xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/Instruction.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the Instruction class, which is the
10 // base class for all of the LLVM instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_INSTRUCTION_H
15 #define LLVM_IR_INSTRUCTION_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Bitfields.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/ilist_node.h"
21 #include "llvm/IR/DebugLoc.h"
22 #include "llvm/IR/SymbolTableListTraits.h"
23 #include "llvm/IR/User.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/AtomicOrdering.h"
26 #include <cstdint>
27 #include <utility>
28 
29 namespace llvm {
30 
31 class BasicBlock;
32 class DataLayout;
33 class DbgMarker;
34 class FastMathFlags;
35 class MDNode;
36 class Module;
37 struct AAMDNodes;
38 class DbgMarker;
39 class DbgRecord;
40 
41 template <> struct ilist_alloc_traits<Instruction> {
42   static inline void deleteNode(Instruction *V);
43 };
44 
45 iterator_range<simple_ilist<DbgRecord>::iterator>
46 getDbgRecordRange(DbgMarker *);
47 
48 class InsertPosition {
49   using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>,
50                                        ilist_parent<BasicBlock>>;
51   InstListType::iterator InsertAt;
52 
53 public:
54   InsertPosition(std::nullptr_t) : InsertAt() {}
55   // LLVM_DEPRECATED("Use BasicBlock::iterators for insertion instead",
56   // "BasicBlock::iterator")
57   InsertPosition(Instruction *InsertBefore);
58   InsertPosition(BasicBlock *InsertAtEnd);
59   InsertPosition(InstListType::iterator InsertAt) : InsertAt(InsertAt) {}
60   operator InstListType::iterator() const { return InsertAt; }
61   bool isValid() const { return InsertAt.isValid(); }
62   BasicBlock *getBasicBlock() { return InsertAt.getNodeParent(); }
63 };
64 
65 class Instruction : public User,
66                     public ilist_node_with_parent<Instruction, BasicBlock,
67                                                   ilist_iterator_bits<true>,
68                                                   ilist_parent<BasicBlock>> {
69 public:
70   using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>,
71                                        ilist_parent<BasicBlock>>;
72 
73 private:
74   DebugLoc DbgLoc;                         // 'dbg' Metadata cache.
75 
76   /// Relative order of this instruction in its parent basic block. Used for
77   /// O(1) local dominance checks between instructions.
78   mutable unsigned Order = 0;
79 
80 public:
81   /// Optional marker recording the position for debugging information that
82   /// takes effect immediately before this instruction. Null unless there is
83   /// debugging information present.
84   DbgMarker *DebugMarker = nullptr;
85 
86   /// Clone any debug-info attached to \p From onto this instruction. Used to
87   /// copy debugging information from one block to another, when copying entire
88   /// blocks. \see DebugProgramInstruction.h , because the ordering of
89   /// DbgRecords is still important, fine grain control of which instructions
90   /// are moved and where they go is necessary.
91   /// \p From The instruction to clone debug-info from.
92   /// \p from_here Optional iterator to limit DbgRecords cloned to be a range
93   /// from
94   ///    from_here to end().
95   /// \p InsertAtHead Whether the cloned DbgRecords should be placed at the end
96   ///    or the beginning of existing DbgRecords attached to this.
97   /// \returns A range over the newly cloned DbgRecords.
98   iterator_range<simple_ilist<DbgRecord>::iterator> cloneDebugInfoFrom(
99       const Instruction *From,
100       std::optional<simple_ilist<DbgRecord>::iterator> FromHere = std::nullopt,
101       bool InsertAtHead = false);
102 
103   /// Return a range over the DbgRecords attached to this instruction.
104   iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange() const {
105     return llvm::getDbgRecordRange(DebugMarker);
106   }
107 
108   /// Return an iterator to the position of the "Next" DbgRecord after this
109   /// instruction, or std::nullopt. This is the position to pass to
110   /// BasicBlock::reinsertInstInDbgRecords when re-inserting an instruction.
111   std::optional<simple_ilist<DbgRecord>::iterator> getDbgReinsertionPosition();
112 
113   /// Returns true if any DbgRecords are attached to this instruction.
114   bool hasDbgRecords() const;
115 
116   /// Transfer any DbgRecords on the position \p It onto this instruction,
117   /// by simply adopting the sequence of DbgRecords (which is efficient) if
118   /// possible, by merging two sequences otherwise.
119   void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It,
120                        bool InsertAtHead);
121 
122   /// Erase any DbgRecords attached to this instruction.
123   void dropDbgRecords();
124 
125   /// Erase a single DbgRecord \p I that is attached to this instruction.
126   void dropOneDbgRecord(DbgRecord *I);
127 
128   /// Handle the debug-info implications of this instruction being removed. Any
129   /// attached DbgRecords need to "fall" down onto the next instruction.
130   void handleMarkerRemoval();
131 
132 protected:
133   // The 15 first bits of `Value::SubclassData` are available for subclasses of
134   // `Instruction` to use.
135   using OpaqueField = Bitfield::Element<uint16_t, 0, 15>;
136 
137   // Template alias so that all Instruction storing alignment use the same
138   // definiton.
139   // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent =
140   // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33
141   // possible values.
142   template <unsigned Offset>
143   using AlignmentBitfieldElementT =
144       typename Bitfield::Element<unsigned, Offset, 6,
145                                  Value::MaxAlignmentExponent>;
146 
147   template <unsigned Offset>
148   using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>;
149 
150   template <unsigned Offset>
151   using AtomicOrderingBitfieldElementT =
152       typename Bitfield::Element<AtomicOrdering, Offset, 3,
153                                  AtomicOrdering::LAST>;
154 
155 private:
156   // The last bit is used to store whether the instruction has metadata attached
157   // or not.
158   using HasMetadataField = Bitfield::Element<bool, 15, 1>;
159 
160 protected:
161   ~Instruction(); // Use deleteValue() to delete a generic Instruction.
162 
163 public:
164   Instruction(const Instruction &) = delete;
165   Instruction &operator=(const Instruction &) = delete;
166 
167   /// Specialize the methods defined in Value, as we know that an instruction
168   /// can only be used by other instructions.
169   Instruction       *user_back()       { return cast<Instruction>(*user_begin());}
170   const Instruction *user_back() const { return cast<Instruction>(*user_begin());}
171 
172   /// Return the module owning the function this instruction belongs to
173   /// or nullptr it the function does not have a module.
174   ///
175   /// Note: this is undefined behavior if the instruction does not have a
176   /// parent, or the parent basic block does not have a parent function.
177   const Module *getModule() const;
178   Module *getModule() {
179     return const_cast<Module *>(
180                            static_cast<const Instruction *>(this)->getModule());
181   }
182 
183   /// Return the function this instruction belongs to.
184   ///
185   /// Note: it is undefined behavior to call this on an instruction not
186   /// currently inserted into a function.
187   const Function *getFunction() const;
188   Function *getFunction() {
189     return const_cast<Function *>(
190                          static_cast<const Instruction *>(this)->getFunction());
191   }
192 
193   /// Get the data layout of the module this instruction belongs to.
194   ///
195   /// Requires the instruction to have a parent module.
196   const DataLayout &getDataLayout() const;
197 
198   /// This method unlinks 'this' from the containing basic block, but does not
199   /// delete it.
200   void removeFromParent();
201 
202   /// This method unlinks 'this' from the containing basic block and deletes it.
203   ///
204   /// \returns an iterator pointing to the element after the erased one
205   InstListType::iterator eraseFromParent();
206 
207   /// Insert an unlinked instruction into a basic block immediately before
208   /// the specified instruction.
209   void insertBefore(Instruction *InsertPos);
210   void insertBefore(InstListType::iterator InsertPos);
211 
212   /// Insert an unlinked instruction into a basic block immediately after the
213   /// specified instruction.
214   void insertAfter(Instruction *InsertPos);
215 
216   /// Inserts an unlinked instruction into \p ParentBB at position \p It and
217   /// returns the iterator of the inserted instruction.
218   InstListType::iterator insertInto(BasicBlock *ParentBB,
219                                     InstListType::iterator It);
220 
221   void insertBefore(BasicBlock &BB, InstListType::iterator InsertPos);
222 
223   /// Unlink this instruction from its current basic block and insert it into
224   /// the basic block that MovePos lives in, right before MovePos.
225   void moveBefore(Instruction *MovePos);
226 
227   /// Perform a \ref moveBefore operation, while signalling that the caller
228   /// intends to preserve the original ordering of instructions. This implicitly
229   /// means that any adjacent debug-info should move with this instruction.
230   /// This method is currently a no-op placeholder, but it will become meaningful
231   /// when the "RemoveDIs" project is enabled.
232   void moveBeforePreserving(Instruction *MovePos);
233 
234 private:
235   /// RemoveDIs project: all other moves implemented with this method,
236   /// centralising debug-info updates into one place.
237   void moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve);
238 
239 public:
240   /// Unlink this instruction and insert into BB before I.
241   ///
242   /// \pre I is a valid iterator into BB.
243   void moveBefore(BasicBlock &BB, InstListType::iterator I);
244 
245   /// (See other overload for moveBeforePreserving).
246   void moveBeforePreserving(BasicBlock &BB, InstListType::iterator I);
247 
248   /// Unlink this instruction from its current basic block and insert it into
249   /// the basic block that MovePos lives in, right after MovePos.
250   void moveAfter(Instruction *MovePos);
251 
252   /// See \ref moveBeforePreserving .
253   void moveAfterPreserving(Instruction *MovePos);
254 
255   /// Given an instruction Other in the same basic block as this instruction,
256   /// return true if this instruction comes before Other. In this worst case,
257   /// this takes linear time in the number of instructions in the block. The
258   /// results are cached, so in common cases when the block remains unmodified,
259   /// it takes constant time.
260   bool comesBefore(const Instruction *Other) const;
261 
262   /// Get the first insertion point at which the result of this instruction
263   /// is defined. This is *not* the directly following instruction in a number
264   /// of cases, e.g. phi nodes or terminators that return values. This function
265   /// may return null if the insertion after the definition is not possible,
266   /// e.g. due to a catchswitch terminator.
267   std::optional<InstListType::iterator> getInsertionPointAfterDef();
268 
269   //===--------------------------------------------------------------------===//
270   // Subclass classification.
271   //===--------------------------------------------------------------------===//
272 
273   /// Returns a member of one of the enums like Instruction::Add.
274   unsigned getOpcode() const { return getValueID() - InstructionVal; }
275 
276   const char *getOpcodeName() const { return getOpcodeName(getOpcode()); }
277   bool isTerminator() const { return isTerminator(getOpcode()); }
278   bool isUnaryOp() const { return isUnaryOp(getOpcode()); }
279   bool isBinaryOp() const { return isBinaryOp(getOpcode()); }
280   bool isIntDivRem() const { return isIntDivRem(getOpcode()); }
281   bool isShift() const { return isShift(getOpcode()); }
282   bool isCast() const { return isCast(getOpcode()); }
283   bool isFuncletPad() const { return isFuncletPad(getOpcode()); }
284   bool isSpecialTerminator() const { return isSpecialTerminator(getOpcode()); }
285 
286   /// It checks if this instruction is the only user of at least one of
287   /// its operands.
288   bool isOnlyUserOfAnyOperand();
289 
290   static const char *getOpcodeName(unsigned Opcode);
291 
292   static inline bool isTerminator(unsigned Opcode) {
293     return Opcode >= TermOpsBegin && Opcode < TermOpsEnd;
294   }
295 
296   static inline bool isUnaryOp(unsigned Opcode) {
297     return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd;
298   }
299   static inline bool isBinaryOp(unsigned Opcode) {
300     return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd;
301   }
302 
303   static inline bool isIntDivRem(unsigned Opcode) {
304     return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem;
305   }
306 
307   /// Determine if the Opcode is one of the shift instructions.
308   static inline bool isShift(unsigned Opcode) {
309     return Opcode >= Shl && Opcode <= AShr;
310   }
311 
312   /// Return true if this is a logical shift left or a logical shift right.
313   inline bool isLogicalShift() const {
314     return getOpcode() == Shl || getOpcode() == LShr;
315   }
316 
317   /// Return true if this is an arithmetic shift right.
318   inline bool isArithmeticShift() const {
319     return getOpcode() == AShr;
320   }
321 
322   /// Determine if the Opcode is and/or/xor.
323   static inline bool isBitwiseLogicOp(unsigned Opcode) {
324     return Opcode == And || Opcode == Or || Opcode == Xor;
325   }
326 
327   /// Return true if this is and/or/xor.
328   inline bool isBitwiseLogicOp() const {
329     return isBitwiseLogicOp(getOpcode());
330   }
331 
332   /// Determine if the Opcode is one of the CastInst instructions.
333   static inline bool isCast(unsigned Opcode) {
334     return Opcode >= CastOpsBegin && Opcode < CastOpsEnd;
335   }
336 
337   /// Determine if the Opcode is one of the FuncletPadInst instructions.
338   static inline bool isFuncletPad(unsigned Opcode) {
339     return Opcode >= FuncletPadOpsBegin && Opcode < FuncletPadOpsEnd;
340   }
341 
342   /// Returns true if the Opcode is a "special" terminator that does more than
343   /// branch to a successor (e.g. have a side effect or return a value).
344   static inline bool isSpecialTerminator(unsigned Opcode) {
345     switch (Opcode) {
346     case Instruction::CatchSwitch:
347     case Instruction::CatchRet:
348     case Instruction::CleanupRet:
349     case Instruction::Invoke:
350     case Instruction::Resume:
351     case Instruction::CallBr:
352       return true;
353     default:
354       return false;
355     }
356   }
357 
358   //===--------------------------------------------------------------------===//
359   // Metadata manipulation.
360   //===--------------------------------------------------------------------===//
361 
362   /// Return true if this instruction has any metadata attached to it.
363   bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); }
364 
365   /// Return true if this instruction has metadata attached to it other than a
366   /// debug location.
367   bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); }
368 
369   /// Return true if this instruction has the given type of metadata attached.
370   bool hasMetadata(unsigned KindID) const {
371     return getMetadata(KindID) != nullptr;
372   }
373 
374   /// Return true if this instruction has the given type of metadata attached.
375   bool hasMetadata(StringRef Kind) const {
376     return getMetadata(Kind) != nullptr;
377   }
378 
379   /// Get the metadata of given kind attached to this Instruction.
380   /// If the metadata is not found then return null.
381   MDNode *getMetadata(unsigned KindID) const {
382     // Handle 'dbg' as a special case since it is not stored in the hash table.
383     if (KindID == LLVMContext::MD_dbg)
384       return DbgLoc.getAsMDNode();
385     return Value::getMetadata(KindID);
386   }
387 
388   /// Get the metadata of given kind attached to this Instruction.
389   /// If the metadata is not found then return null.
390   MDNode *getMetadata(StringRef Kind) const {
391     if (!hasMetadata()) return nullptr;
392     return getMetadataImpl(Kind);
393   }
394 
395   /// Get all metadata attached to this Instruction. The first element of each
396   /// pair returned is the KindID, the second element is the metadata value.
397   /// This list is returned sorted by the KindID.
398   void
399   getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
400     if (hasMetadata())
401       getAllMetadataImpl(MDs);
402   }
403 
404   /// This does the same thing as getAllMetadata, except that it filters out the
405   /// debug location.
406   void getAllMetadataOtherThanDebugLoc(
407       SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
408     Value::getAllMetadata(MDs);
409   }
410 
411   /// Set the metadata of the specified kind to the specified node. This updates
412   /// or replaces metadata if already present, or removes it if Node is null.
413   void setMetadata(unsigned KindID, MDNode *Node);
414   void setMetadata(StringRef Kind, MDNode *Node);
415 
416   /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty,
417   /// specifies the list of meta data that needs to be copied. If \p WL is
418   /// empty, all meta data will be copied.
419   void copyMetadata(const Instruction &SrcInst,
420                     ArrayRef<unsigned> WL = ArrayRef<unsigned>());
421 
422   /// Erase all metadata that matches the predicate.
423   void eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred);
424 
425   /// If the instruction has "branch_weights" MD_prof metadata and the MDNode
426   /// has three operands (including name string), swap the order of the
427   /// metadata.
428   void swapProfMetadata();
429 
430   /// Drop all unknown metadata except for debug locations.
431   /// @{
432   /// Passes are required to drop metadata they don't understand. This is a
433   /// convenience method for passes to do so.
434   /// dropUBImplyingAttrsAndUnknownMetadata should be used instead of
435   /// this API if the Instruction being modified is a call.
436   void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs = std::nullopt);
437   /// @}
438 
439   /// Adds an !annotation metadata node with \p Annotation to this instruction.
440   /// If this instruction already has !annotation metadata, append \p Annotation
441   /// to the existing node.
442   void addAnnotationMetadata(StringRef Annotation);
443   /// Adds an !annotation metadata node with an array of \p Annotations
444   /// as a tuple to this instruction. If this instruction already has
445   /// !annotation metadata, append the tuple to
446   /// the existing node.
447   void addAnnotationMetadata(SmallVector<StringRef> Annotations);
448   /// Returns the AA metadata for this instruction.
449   AAMDNodes getAAMetadata() const;
450 
451   /// Sets the AA metadata on this instruction from the AAMDNodes structure.
452   void setAAMetadata(const AAMDNodes &N);
453 
454   /// Sets the nosanitize metadata on this instruction.
455   void setNoSanitizeMetadata();
456 
457   /// Retrieve total raw weight values of a branch.
458   /// Returns true on success with profile total weights filled in.
459   /// Returns false if no metadata was found.
460   bool extractProfTotalWeight(uint64_t &TotalVal) const;
461 
462   /// Set the debug location information for this instruction.
463   void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); }
464 
465   /// Return the debug location for this node as a DebugLoc.
466   const DebugLoc &getDebugLoc() const { return DbgLoc; }
467 
468   /// Fetch the debug location for this node, unless this is a debug intrinsic,
469   /// in which case fetch the debug location of the next non-debug node.
470   const DebugLoc &getStableDebugLoc() const;
471 
472   /// Set or clear the nuw flag on this instruction, which must be an operator
473   /// which supports this flag. See LangRef.html for the meaning of this flag.
474   void setHasNoUnsignedWrap(bool b = true);
475 
476   /// Set or clear the nsw flag on this instruction, which must be an operator
477   /// which supports this flag. See LangRef.html for the meaning of this flag.
478   void setHasNoSignedWrap(bool b = true);
479 
480   /// Set or clear the exact flag on this instruction, which must be an operator
481   /// which supports this flag. See LangRef.html for the meaning of this flag.
482   void setIsExact(bool b = true);
483 
484   /// Set or clear the nneg flag on this instruction, which must be a zext
485   /// instruction.
486   void setNonNeg(bool b = true);
487 
488   /// Determine whether the no unsigned wrap flag is set.
489   bool hasNoUnsignedWrap() const LLVM_READONLY;
490 
491   /// Determine whether the no signed wrap flag is set.
492   bool hasNoSignedWrap() const LLVM_READONLY;
493 
494   /// Determine whether the the nneg flag is set.
495   bool hasNonNeg() const LLVM_READONLY;
496 
497   /// Return true if this operator has flags which may cause this instruction
498   /// to evaluate to poison despite having non-poison inputs.
499   bool hasPoisonGeneratingFlags() const LLVM_READONLY;
500 
501   /// Drops flags that may cause this instruction to evaluate to poison despite
502   /// having non-poison inputs.
503   void dropPoisonGeneratingFlags();
504 
505   /// Return true if this instruction has poison-generating metadata.
506   bool hasPoisonGeneratingMetadata() const LLVM_READONLY;
507 
508   /// Drops metadata that may generate poison.
509   void dropPoisonGeneratingMetadata();
510 
511   /// Return true if this instruction has poison-generating attribute.
512   bool hasPoisonGeneratingReturnAttributes() const LLVM_READONLY;
513 
514   /// Drops return attributes that may generate poison.
515   void dropPoisonGeneratingReturnAttributes();
516 
517   /// Return true if this instruction has poison-generating flags,
518   /// return attributes or metadata.
519   bool hasPoisonGeneratingAnnotations() const {
520     return hasPoisonGeneratingFlags() ||
521            hasPoisonGeneratingReturnAttributes() ||
522            hasPoisonGeneratingMetadata();
523   }
524 
525   /// Drops flags, return attributes and metadata that may generate poison.
526   void dropPoisonGeneratingAnnotations() {
527     dropPoisonGeneratingFlags();
528     dropPoisonGeneratingReturnAttributes();
529     dropPoisonGeneratingMetadata();
530   }
531 
532   /// This function drops non-debug unknown metadata (through
533   /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and
534   /// return attributes that can cause undefined behaviour. Both of these should
535   /// be done by passes which move instructions in IR.
536   void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {});
537 
538   /// Drop any attributes or metadata that can cause immediate undefined
539   /// behavior. Retain other attributes/metadata on a best-effort basis.
540   /// This should be used when speculating instructions.
541   void dropUBImplyingAttrsAndMetadata();
542 
543   /// Determine whether the exact flag is set.
544   bool isExact() const LLVM_READONLY;
545 
546   /// Set or clear all fast-math-flags on this instruction, which must be an
547   /// operator which supports this flag. See LangRef.html for the meaning of
548   /// this flag.
549   void setFast(bool B);
550 
551   /// Set or clear the reassociation flag on this instruction, which must be
552   /// an operator which supports this flag. See LangRef.html for the meaning of
553   /// this flag.
554   void setHasAllowReassoc(bool B);
555 
556   /// Set or clear the no-nans flag on this instruction, which must be an
557   /// operator which supports this flag. See LangRef.html for the meaning of
558   /// this flag.
559   void setHasNoNaNs(bool B);
560 
561   /// Set or clear the no-infs flag on this instruction, which must be an
562   /// operator which supports this flag. See LangRef.html for the meaning of
563   /// this flag.
564   void setHasNoInfs(bool B);
565 
566   /// Set or clear the no-signed-zeros flag on this instruction, which must be
567   /// an operator which supports this flag. See LangRef.html for the meaning of
568   /// this flag.
569   void setHasNoSignedZeros(bool B);
570 
571   /// Set or clear the allow-reciprocal flag on this instruction, which must be
572   /// an operator which supports this flag. See LangRef.html for the meaning of
573   /// this flag.
574   void setHasAllowReciprocal(bool B);
575 
576   /// Set or clear the allow-contract flag on this instruction, which must be
577   /// an operator which supports this flag. See LangRef.html for the meaning of
578   /// this flag.
579   void setHasAllowContract(bool B);
580 
581   /// Set or clear the approximate-math-functions flag on this instruction,
582   /// which must be an operator which supports this flag. See LangRef.html for
583   /// the meaning of this flag.
584   void setHasApproxFunc(bool B);
585 
586   /// Convenience function for setting multiple fast-math flags on this
587   /// instruction, which must be an operator which supports these flags. See
588   /// LangRef.html for the meaning of these flags.
589   void setFastMathFlags(FastMathFlags FMF);
590 
591   /// Convenience function for transferring all fast-math flag values to this
592   /// instruction, which must be an operator which supports these flags. See
593   /// LangRef.html for the meaning of these flags.
594   void copyFastMathFlags(FastMathFlags FMF);
595 
596   /// Determine whether all fast-math-flags are set.
597   bool isFast() const LLVM_READONLY;
598 
599   /// Determine whether the allow-reassociation flag is set.
600   bool hasAllowReassoc() const LLVM_READONLY;
601 
602   /// Determine whether the no-NaNs flag is set.
603   bool hasNoNaNs() const LLVM_READONLY;
604 
605   /// Determine whether the no-infs flag is set.
606   bool hasNoInfs() const LLVM_READONLY;
607 
608   /// Determine whether the no-signed-zeros flag is set.
609   bool hasNoSignedZeros() const LLVM_READONLY;
610 
611   /// Determine whether the allow-reciprocal flag is set.
612   bool hasAllowReciprocal() const LLVM_READONLY;
613 
614   /// Determine whether the allow-contract flag is set.
615   bool hasAllowContract() const LLVM_READONLY;
616 
617   /// Determine whether the approximate-math-functions flag is set.
618   bool hasApproxFunc() const LLVM_READONLY;
619 
620   /// Convenience function for getting all the fast-math flags, which must be an
621   /// operator which supports these flags. See LangRef.html for the meaning of
622   /// these flags.
623   FastMathFlags getFastMathFlags() const LLVM_READONLY;
624 
625   /// Copy I's fast-math flags
626   void copyFastMathFlags(const Instruction *I);
627 
628   /// Convenience method to copy supported exact, fast-math, and (optionally)
629   /// wrapping flags from V to this instruction.
630   void copyIRFlags(const Value *V, bool IncludeWrapFlags = true);
631 
632   /// Logical 'and' of any supported wrapping, exact, and fast-math flags of
633   /// V and this instruction.
634   void andIRFlags(const Value *V);
635 
636   /// Merge 2 debug locations and apply it to the Instruction. If the
637   /// instruction is a CallIns, we need to traverse the inline chain to find
638   /// the common scope. This is not efficient for N-way merging as each time
639   /// you merge 2 iterations, you need to rebuild the hashmap to find the
640   /// common scope. However, we still choose this API because:
641   ///  1) Simplicity: it takes 2 locations instead of a list of locations.
642   ///  2) In worst case, it increases the complexity from O(N*I) to
643   ///     O(2*N*I), where N is # of Instructions to merge, and I is the
644   ///     maximum level of inline stack. So it is still linear.
645   ///  3) Merging of call instructions should be extremely rare in real
646   ///     applications, thus the N-way merging should be in code path.
647   /// The DebugLoc attached to this instruction will be overwritten by the
648   /// merged DebugLoc.
649   void applyMergedLocation(DILocation *LocA, DILocation *LocB);
650 
651   /// Updates the debug location given that the instruction has been hoisted
652   /// from a block to a predecessor of that block.
653   /// Note: it is undefined behavior to call this on an instruction not
654   /// currently inserted into a function.
655   void updateLocationAfterHoist();
656 
657   /// Drop the instruction's debug location. This does not guarantee removal
658   /// of the !dbg source location attachment, as it must set a line 0 location
659   /// with scope information attached on call instructions. To guarantee
660   /// removal of the !dbg attachment, use the \ref setDebugLoc() API.
661   /// Note: it is undefined behavior to call this on an instruction not
662   /// currently inserted into a function.
663   void dropLocation();
664 
665   /// Merge the DIAssignID metadata from this instruction and those attached to
666   /// instructions in \p SourceInstructions. This process performs a RAUW on
667   /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every
668   /// instruction in \p SourceInstructions needs to have DIAssignID
669   /// metadata. If none of them do then nothing happens. If this instruction
670   /// does not have a DIAssignID attachment but at least one in \p
671   /// SourceInstructions does then the merged one will be attached to
672   /// it. However, instructions without attachments in \p SourceInstructions
673   /// are not modified.
674   void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions);
675 
676 private:
677   // These are all implemented in Metadata.cpp.
678   MDNode *getMetadataImpl(StringRef Kind) const;
679   void
680   getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const;
681 
682   /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr
683   /// then clear the mapping for this instruction.
684   void updateDIAssignIDMapping(DIAssignID *ID);
685 
686 public:
687   //===--------------------------------------------------------------------===//
688   // Predicates and helper methods.
689   //===--------------------------------------------------------------------===//
690 
691   /// Return true if the instruction is associative:
692   ///
693   ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
694   ///
695   /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
696   ///
697   bool isAssociative() const LLVM_READONLY;
698   static bool isAssociative(unsigned Opcode) {
699     return Opcode == And || Opcode == Or || Opcode == Xor ||
700            Opcode == Add || Opcode == Mul;
701   }
702 
703   /// Return true if the instruction is commutative:
704   ///
705   ///   Commutative operators satisfy: (x op y) === (y op x)
706   ///
707   /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when
708   /// applied to any type.
709   ///
710   bool isCommutative() const LLVM_READONLY;
711   static bool isCommutative(unsigned Opcode) {
712     switch (Opcode) {
713     case Add: case FAdd:
714     case Mul: case FMul:
715     case And: case Or: case Xor:
716       return true;
717     default:
718       return false;
719   }
720   }
721 
722   /// Return true if the instruction is idempotent:
723   ///
724   ///   Idempotent operators satisfy:  x op x === x
725   ///
726   /// In LLVM, the And and Or operators are idempotent.
727   ///
728   bool isIdempotent() const { return isIdempotent(getOpcode()); }
729   static bool isIdempotent(unsigned Opcode) {
730     return Opcode == And || Opcode == Or;
731   }
732 
733   /// Return true if the instruction is nilpotent:
734   ///
735   ///   Nilpotent operators satisfy:  x op x === Id,
736   ///
737   ///   where Id is the identity for the operator, i.e. a constant such that
738   ///     x op Id === x and Id op x === x for all x.
739   ///
740   /// In LLVM, the Xor operator is nilpotent.
741   ///
742   bool isNilpotent() const { return isNilpotent(getOpcode()); }
743   static bool isNilpotent(unsigned Opcode) {
744     return Opcode == Xor;
745   }
746 
747   /// Return true if this instruction may modify memory.
748   bool mayWriteToMemory() const LLVM_READONLY;
749 
750   /// Return true if this instruction may read memory.
751   bool mayReadFromMemory() const LLVM_READONLY;
752 
753   /// Return true if this instruction may read or write memory.
754   bool mayReadOrWriteMemory() const {
755     return mayReadFromMemory() || mayWriteToMemory();
756   }
757 
758   /// Return true if this instruction has an AtomicOrdering of unordered or
759   /// higher.
760   bool isAtomic() const LLVM_READONLY;
761 
762   /// Return true if this atomic instruction loads from memory.
763   bool hasAtomicLoad() const LLVM_READONLY;
764 
765   /// Return true if this atomic instruction stores to memory.
766   bool hasAtomicStore() const LLVM_READONLY;
767 
768   /// Return true if this instruction has a volatile memory access.
769   bool isVolatile() const LLVM_READONLY;
770 
771   /// Return the type this instruction accesses in memory, if any.
772   Type *getAccessType() const LLVM_READONLY;
773 
774   /// Return true if this instruction may throw an exception.
775   ///
776   /// If IncludePhaseOneUnwind is set, this will also include cases where
777   /// phase one unwinding may unwind past this frame due to skipping of
778   /// cleanup landingpads.
779   bool mayThrow(bool IncludePhaseOneUnwind = false) const LLVM_READONLY;
780 
781   /// Return true if this instruction behaves like a memory fence: it can load
782   /// or store to memory location without being given a memory location.
783   bool isFenceLike() const {
784     switch (getOpcode()) {
785     default:
786       return false;
787     // This list should be kept in sync with the list in mayWriteToMemory for
788     // all opcodes which don't have a memory location.
789     case Instruction::Fence:
790     case Instruction::CatchPad:
791     case Instruction::CatchRet:
792     case Instruction::Call:
793     case Instruction::Invoke:
794       return true;
795     }
796   }
797 
798   /// Return true if the instruction may have side effects.
799   ///
800   /// Side effects are:
801   ///  * Writing to memory.
802   ///  * Unwinding.
803   ///  * Not returning (e.g. an infinite loop).
804   ///
805   /// Note that this does not consider malloc and alloca to have side
806   /// effects because the newly allocated memory is completely invisible to
807   /// instructions which don't use the returned value.  For cases where this
808   /// matters, isSafeToSpeculativelyExecute may be more appropriate.
809   bool mayHaveSideEffects() const LLVM_READONLY;
810 
811   /// Return true if the instruction can be removed if the result is unused.
812   ///
813   /// When constant folding some instructions cannot be removed even if their
814   /// results are unused. Specifically terminator instructions and calls that
815   /// may have side effects cannot be removed without semantically changing the
816   /// generated program.
817   bool isSafeToRemove() const LLVM_READONLY;
818 
819   /// Return true if the instruction will return (unwinding is considered as
820   /// a form of returning control flow here).
821   bool willReturn() const LLVM_READONLY;
822 
823   /// Return true if the instruction is a variety of EH-block.
824   bool isEHPad() const {
825     switch (getOpcode()) {
826     case Instruction::CatchSwitch:
827     case Instruction::CatchPad:
828     case Instruction::CleanupPad:
829     case Instruction::LandingPad:
830       return true;
831     default:
832       return false;
833     }
834   }
835 
836   /// Return true if the instruction is a llvm.lifetime.start or
837   /// llvm.lifetime.end marker.
838   bool isLifetimeStartOrEnd() const LLVM_READONLY;
839 
840   /// Return true if the instruction is a llvm.launder.invariant.group or
841   /// llvm.strip.invariant.group.
842   bool isLaunderOrStripInvariantGroup() const LLVM_READONLY;
843 
844   /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst.
845   bool isDebugOrPseudoInst() const LLVM_READONLY;
846 
847   /// Return a pointer to the next non-debug instruction in the same basic
848   /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
849   /// operations if \c SkipPseudoOp is true.
850   const Instruction *
851   getNextNonDebugInstruction(bool SkipPseudoOp = false) const;
852   Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) {
853     return const_cast<Instruction *>(
854         static_cast<const Instruction *>(this)->getNextNonDebugInstruction(
855             SkipPseudoOp));
856   }
857 
858   /// Return a pointer to the previous non-debug instruction in the same basic
859   /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo
860   /// operations if \c SkipPseudoOp is true.
861   const Instruction *
862   getPrevNonDebugInstruction(bool SkipPseudoOp = false) const;
863   Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) {
864     return const_cast<Instruction *>(
865         static_cast<const Instruction *>(this)->getPrevNonDebugInstruction(
866             SkipPseudoOp));
867   }
868 
869   /// Create a copy of 'this' instruction that is identical in all ways except
870   /// the following:
871   ///   * The instruction has no parent
872   ///   * The instruction has no name
873   ///
874   Instruction *clone() const;
875 
876   /// Return true if the specified instruction is exactly identical to the
877   /// current one. This means that all operands match and any extra information
878   /// (e.g. load is volatile) agree.
879   bool isIdenticalTo(const Instruction *I) const LLVM_READONLY;
880 
881   /// This is like isIdenticalTo, except that it ignores the
882   /// SubclassOptionalData flags, which may specify conditions under which the
883   /// instruction's result is undefined.
884   bool isIdenticalToWhenDefined(const Instruction *I) const LLVM_READONLY;
885 
886   /// When checking for operation equivalence (using isSameOperationAs) it is
887   /// sometimes useful to ignore certain attributes.
888   enum OperationEquivalenceFlags {
889     /// Check for equivalence ignoring load/store alignment.
890     CompareIgnoringAlignment = 1<<0,
891     /// Check for equivalence treating a type and a vector of that type
892     /// as equivalent.
893     CompareUsingScalarTypes = 1<<1
894   };
895 
896   /// This function determines if the specified instruction executes the same
897   /// operation as the current one. This means that the opcodes, type, operand
898   /// types and any other factors affecting the operation must be the same. This
899   /// is similar to isIdenticalTo except the operands themselves don't have to
900   /// be identical.
901   /// @returns true if the specified instruction is the same operation as
902   /// the current one.
903   /// Determine if one instruction is the same operation as another.
904   bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY;
905 
906   /// This function determines if the speficied instruction has the same
907   /// "special" characteristics as the current one. This means that opcode
908   /// specific details are the same. As a common example, if we are comparing
909   /// loads, then hasSameSpecialState would compare the alignments (among
910   /// other things).
911   /// @returns true if the specific instruction has the same opcde specific
912   /// characteristics as the current one. Determine if one instruction has the
913   /// same state as another.
914   bool hasSameSpecialState(const Instruction *I2,
915                            bool IgnoreAlignment = false) const LLVM_READONLY;
916 
917   /// Return true if there are any uses of this instruction in blocks other than
918   /// the specified block. Note that PHI nodes are considered to evaluate their
919   /// operands in the corresponding predecessor block.
920   bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY;
921 
922   /// Return the number of successors that this instruction has. The instruction
923   /// must be a terminator.
924   unsigned getNumSuccessors() const LLVM_READONLY;
925 
926   /// Return the specified successor. This instruction must be a terminator.
927   BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY;
928 
929   /// Update the specified successor to point at the provided block. This
930   /// instruction must be a terminator.
931   void setSuccessor(unsigned Idx, BasicBlock *BB);
932 
933   /// Replace specified successor OldBB to point at the provided block.
934   /// This instruction must be a terminator.
935   void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB);
936 
937   /// Methods for support type inquiry through isa, cast, and dyn_cast:
938   static bool classof(const Value *V) {
939     return V->getValueID() >= Value::InstructionVal;
940   }
941 
942   //----------------------------------------------------------------------
943   // Exported enumerations.
944   //
945   enum TermOps {       // These terminate basic blocks
946 #define  FIRST_TERM_INST(N)             TermOpsBegin = N,
947 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N,
948 #define   LAST_TERM_INST(N)             TermOpsEnd = N+1
949 #include "llvm/IR/Instruction.def"
950   };
951 
952   enum UnaryOps {
953 #define  FIRST_UNARY_INST(N)             UnaryOpsBegin = N,
954 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N,
955 #define   LAST_UNARY_INST(N)             UnaryOpsEnd = N+1
956 #include "llvm/IR/Instruction.def"
957   };
958 
959   enum BinaryOps {
960 #define  FIRST_BINARY_INST(N)             BinaryOpsBegin = N,
961 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N,
962 #define   LAST_BINARY_INST(N)             BinaryOpsEnd = N+1
963 #include "llvm/IR/Instruction.def"
964   };
965 
966   enum MemoryOps {
967 #define  FIRST_MEMORY_INST(N)             MemoryOpsBegin = N,
968 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N,
969 #define   LAST_MEMORY_INST(N)             MemoryOpsEnd = N+1
970 #include "llvm/IR/Instruction.def"
971   };
972 
973   enum CastOps {
974 #define  FIRST_CAST_INST(N)             CastOpsBegin = N,
975 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N,
976 #define   LAST_CAST_INST(N)             CastOpsEnd = N+1
977 #include "llvm/IR/Instruction.def"
978   };
979 
980   enum FuncletPadOps {
981 #define  FIRST_FUNCLETPAD_INST(N)             FuncletPadOpsBegin = N,
982 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N,
983 #define   LAST_FUNCLETPAD_INST(N)             FuncletPadOpsEnd = N+1
984 #include "llvm/IR/Instruction.def"
985   };
986 
987   enum OtherOps {
988 #define  FIRST_OTHER_INST(N)             OtherOpsBegin = N,
989 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N,
990 #define   LAST_OTHER_INST(N)             OtherOpsEnd = N+1
991 #include "llvm/IR/Instruction.def"
992   };
993 
994 private:
995   friend class SymbolTableListTraits<Instruction, ilist_iterator_bits<true>,
996                                      ilist_parent<BasicBlock>>;
997   friend class BasicBlock; // For renumbering.
998 
999   // Shadow Value::setValueSubclassData with a private forwarding method so that
1000   // subclasses cannot accidentally use it.
1001   void setValueSubclassData(unsigned short D) {
1002     Value::setValueSubclassData(D);
1003   }
1004 
1005   unsigned short getSubclassDataFromValue() const {
1006     return Value::getSubclassDataFromValue();
1007   }
1008 
1009 protected:
1010   // Instruction subclasses can stick up to 15 bits of stuff into the
1011   // SubclassData field of instruction with these members.
1012 
1013   template <typename BitfieldElement>
1014   typename BitfieldElement::Type getSubclassData() const {
1015     static_assert(
1016         std::is_same<BitfieldElement, HasMetadataField>::value ||
1017             !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
1018         "Must not overlap with the metadata bit");
1019     return Bitfield::get<BitfieldElement>(getSubclassDataFromValue());
1020   }
1021 
1022   template <typename BitfieldElement>
1023   void setSubclassData(typename BitfieldElement::Type Value) {
1024     static_assert(
1025         std::is_same<BitfieldElement, HasMetadataField>::value ||
1026             !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(),
1027         "Must not overlap with the metadata bit");
1028     auto Storage = getSubclassDataFromValue();
1029     Bitfield::set<BitfieldElement>(Storage, Value);
1030     setValueSubclassData(Storage);
1031   }
1032 
1033   Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps,
1034               InsertPosition InsertBefore = nullptr);
1035 
1036 private:
1037   /// Create a copy of this instruction.
1038   Instruction *cloneImpl() const;
1039 };
1040 
1041 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) {
1042   V->deleteValue();
1043 }
1044 
1045 } // end namespace llvm
1046 
1047 #endif // LLVM_IR_INSTRUCTION_H
1048