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