Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:01

0001 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines various meta classes of instructions that exist in the VM
0010 // representation.  Specific concrete subclasses of these may be found in the
0011 // i*.h files...
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_IR_INSTRTYPES_H
0016 #define LLVM_IR_INSTRTYPES_H
0017 
0018 #include "llvm/ADT/ArrayRef.h"
0019 #include "llvm/ADT/STLExtras.h"
0020 #include "llvm/ADT/Sequence.h"
0021 #include "llvm/ADT/StringMap.h"
0022 #include "llvm/ADT/Twine.h"
0023 #include "llvm/ADT/iterator_range.h"
0024 #include "llvm/IR/Attributes.h"
0025 #include "llvm/IR/CallingConv.h"
0026 #include "llvm/IR/DerivedTypes.h"
0027 #include "llvm/IR/FMF.h"
0028 #include "llvm/IR/Function.h"
0029 #include "llvm/IR/Instruction.h"
0030 #include "llvm/IR/LLVMContext.h"
0031 #include "llvm/IR/OperandTraits.h"
0032 #include "llvm/IR/User.h"
0033 #include <algorithm>
0034 #include <cassert>
0035 #include <cstddef>
0036 #include <cstdint>
0037 #include <iterator>
0038 #include <optional>
0039 #include <string>
0040 #include <vector>
0041 
0042 namespace llvm {
0043 
0044 class StringRef;
0045 class Type;
0046 class Value;
0047 class ConstantRange;
0048 
0049 namespace Intrinsic {
0050 typedef unsigned ID;
0051 }
0052 
0053 //===----------------------------------------------------------------------===//
0054 //                          UnaryInstruction Class
0055 //===----------------------------------------------------------------------===//
0056 
0057 class UnaryInstruction : public Instruction {
0058   constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
0059 
0060 protected:
0061   UnaryInstruction(Type *Ty, unsigned iType, Value *V,
0062                    InsertPosition InsertBefore = nullptr)
0063       : Instruction(Ty, iType, AllocMarker, InsertBefore) {
0064     Op<0>() = V;
0065   }
0066 
0067 public:
0068   // allocate space for exactly one operand
0069   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0070   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0071 
0072   /// Transparently provide more efficient getOperand methods.
0073   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
0074 
0075   // Methods for support type inquiry through isa, cast, and dyn_cast:
0076   static bool classof(const Instruction *I) {
0077     return I->isUnaryOp() || I->getOpcode() == Instruction::Alloca ||
0078            I->getOpcode() == Instruction::Load ||
0079            I->getOpcode() == Instruction::VAArg ||
0080            I->getOpcode() == Instruction::ExtractValue ||
0081            I->getOpcode() == Instruction::Freeze ||
0082            (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd);
0083   }
0084   static bool classof(const Value *V) {
0085     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0086   }
0087 };
0088 
0089 template <>
0090 struct OperandTraits<UnaryInstruction> :
0091   public FixedNumOperandTraits<UnaryInstruction, 1> {
0092 };
0093 
0094 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value)
0095 
0096 //===----------------------------------------------------------------------===//
0097 //                                UnaryOperator Class
0098 //===----------------------------------------------------------------------===//
0099 
0100 class UnaryOperator : public UnaryInstruction {
0101   void AssertOK();
0102 
0103 protected:
0104   UnaryOperator(UnaryOps iType, Value *S, Type *Ty, const Twine &Name,
0105                 InsertPosition InsertBefore);
0106 
0107   // Note: Instruction needs to be a friend here to call cloneImpl.
0108   friend class Instruction;
0109 
0110   UnaryOperator *cloneImpl() const;
0111 
0112 public:
0113   /// Construct a unary instruction, given the opcode and an operand.
0114   /// Optionally (if InstBefore is specified) insert the instruction
0115   /// into a BasicBlock right before the specified instruction.  The specified
0116   /// Instruction is allowed to be a dereferenced end iterator.
0117   ///
0118   static UnaryOperator *Create(UnaryOps Op, Value *S,
0119                                const Twine &Name = Twine(),
0120                                InsertPosition InsertBefore = nullptr);
0121 
0122   /// These methods just forward to Create, and are useful when you
0123   /// statically know what type of instruction you're going to create.  These
0124   /// helpers just save some typing.
0125 #define HANDLE_UNARY_INST(N, OPC, CLASS)                                       \
0126   static UnaryOperator *Create##OPC(Value *V, const Twine &Name = "") {        \
0127     return Create(Instruction::OPC, V, Name);                                  \
0128   }
0129 #include "llvm/IR/Instruction.def"
0130 #define HANDLE_UNARY_INST(N, OPC, CLASS)                                       \
0131   static UnaryOperator *Create##OPC(Value *V, const Twine &Name,               \
0132                                     InsertPosition InsertBefore = nullptr) {   \
0133     return Create(Instruction::OPC, V, Name, InsertBefore);                    \
0134   }
0135 #include "llvm/IR/Instruction.def"
0136 
0137   static UnaryOperator *
0138   CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO,
0139                         const Twine &Name = "",
0140                         InsertPosition InsertBefore = nullptr) {
0141     UnaryOperator *UO = Create(Opc, V, Name, InsertBefore);
0142     UO->copyIRFlags(CopyO);
0143     return UO;
0144   }
0145 
0146   static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource,
0147                                       const Twine &Name = "",
0148                                       InsertPosition InsertBefore = nullptr) {
0149     return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name,
0150                                  InsertBefore);
0151   }
0152 
0153   UnaryOps getOpcode() const {
0154     return static_cast<UnaryOps>(Instruction::getOpcode());
0155   }
0156 
0157   // Methods for support type inquiry through isa, cast, and dyn_cast:
0158   static bool classof(const Instruction *I) {
0159     return I->isUnaryOp();
0160   }
0161   static bool classof(const Value *V) {
0162     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0163   }
0164 };
0165 
0166 //===----------------------------------------------------------------------===//
0167 //                           BinaryOperator Class
0168 //===----------------------------------------------------------------------===//
0169 
0170 class BinaryOperator : public Instruction {
0171   constexpr static IntrusiveOperandsAllocMarker AllocMarker{2};
0172 
0173   void AssertOK();
0174 
0175 protected:
0176   BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty,
0177                  const Twine &Name, InsertPosition InsertBefore);
0178 
0179   // Note: Instruction needs to be a friend here to call cloneImpl.
0180   friend class Instruction;
0181 
0182   BinaryOperator *cloneImpl() const;
0183 
0184 public:
0185   // allocate space for exactly two operands
0186   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0187   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0188 
0189   /// Transparently provide more efficient getOperand methods.
0190   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
0191 
0192   /// Construct a binary instruction, given the opcode and the two
0193   /// operands.  Optionally (if InstBefore is specified) insert the instruction
0194   /// into a BasicBlock right before the specified instruction.  The specified
0195   /// Instruction is allowed to be a dereferenced end iterator.
0196   ///
0197   static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2,
0198                                 const Twine &Name = Twine(),
0199                                 InsertPosition InsertBefore = nullptr);
0200 
0201   /// These methods just forward to Create, and are useful when you
0202   /// statically know what type of instruction you're going to create.  These
0203   /// helpers just save some typing.
0204 #define HANDLE_BINARY_INST(N, OPC, CLASS)                                      \
0205   static BinaryOperator *Create##OPC(Value *V1, Value *V2,                     \
0206                                      const Twine &Name = "") {                 \
0207     return Create(Instruction::OPC, V1, V2, Name);                             \
0208   }
0209 #include "llvm/IR/Instruction.def"
0210 #define HANDLE_BINARY_INST(N, OPC, CLASS)                                      \
0211   static BinaryOperator *Create##OPC(Value *V1, Value *V2, const Twine &Name,  \
0212                                      InsertPosition InsertBefore) {            \
0213     return Create(Instruction::OPC, V1, V2, Name, InsertBefore);               \
0214   }
0215 #include "llvm/IR/Instruction.def"
0216 
0217   static BinaryOperator *
0218   CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO,
0219                         const Twine &Name = "",
0220                         InsertPosition InsertBefore = nullptr) {
0221     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0222     BO->copyIRFlags(CopyO);
0223     return BO;
0224   }
0225 
0226   static BinaryOperator *CreateWithFMF(BinaryOps Opc, Value *V1, Value *V2,
0227                                        FastMathFlags FMF,
0228                                        const Twine &Name = "",
0229                                        InsertPosition InsertBefore = nullptr) {
0230     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0231     BO->setFastMathFlags(FMF);
0232     return BO;
0233   }
0234 
0235   static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF,
0236                                        const Twine &Name = "") {
0237     return CreateWithFMF(Instruction::FAdd, V1, V2, FMF, Name);
0238   }
0239   static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF,
0240                                        const Twine &Name = "") {
0241     return CreateWithFMF(Instruction::FSub, V1, V2, FMF, Name);
0242   }
0243   static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF,
0244                                        const Twine &Name = "") {
0245     return CreateWithFMF(Instruction::FMul, V1, V2, FMF, Name);
0246   }
0247   static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF,
0248                                        const Twine &Name = "") {
0249     return CreateWithFMF(Instruction::FDiv, V1, V2, FMF, Name);
0250   }
0251 
0252   static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2,
0253                                        Instruction *FMFSource,
0254                                        const Twine &Name = "") {
0255     return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name);
0256   }
0257   static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2,
0258                                        Instruction *FMFSource,
0259                                        const Twine &Name = "") {
0260     return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name);
0261   }
0262   static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2,
0263                                        Instruction *FMFSource,
0264                                        const Twine &Name = "") {
0265     return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name);
0266   }
0267   static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2,
0268                                        Instruction *FMFSource,
0269                                        const Twine &Name = "") {
0270     return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name);
0271   }
0272   static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2,
0273                                        Instruction *FMFSource,
0274                                        const Twine &Name = "") {
0275     return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name);
0276   }
0277 
0278   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
0279                                    const Twine &Name = "") {
0280     BinaryOperator *BO = Create(Opc, V1, V2, Name);
0281     BO->setHasNoSignedWrap(true);
0282     return BO;
0283   }
0284 
0285   static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2,
0286                                    const Twine &Name,
0287                                    InsertPosition InsertBefore) {
0288     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0289     BO->setHasNoSignedWrap(true);
0290     return BO;
0291   }
0292 
0293   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
0294                                    const Twine &Name = "") {
0295     BinaryOperator *BO = Create(Opc, V1, V2, Name);
0296     BO->setHasNoUnsignedWrap(true);
0297     return BO;
0298   }
0299 
0300   static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2,
0301                                    const Twine &Name,
0302                                    InsertPosition InsertBefore) {
0303     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0304     BO->setHasNoUnsignedWrap(true);
0305     return BO;
0306   }
0307 
0308   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
0309                                      const Twine &Name = "") {
0310     BinaryOperator *BO = Create(Opc, V1, V2, Name);
0311     BO->setIsExact(true);
0312     return BO;
0313   }
0314 
0315   static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2,
0316                                      const Twine &Name,
0317                                      InsertPosition InsertBefore) {
0318     BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0319     BO->setIsExact(true);
0320     return BO;
0321   }
0322 
0323   static inline BinaryOperator *
0324   CreateDisjoint(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name = "");
0325   static inline BinaryOperator *CreateDisjoint(BinaryOps Opc, Value *V1,
0326                                                Value *V2, const Twine &Name,
0327                                                InsertPosition InsertBefore);
0328 
0329 #define DEFINE_HELPERS(OPC, NUWNSWEXACT)                                       \
0330   static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2,        \
0331                                                   const Twine &Name = "") {    \
0332     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name);                \
0333   }                                                                            \
0334   static BinaryOperator *Create##NUWNSWEXACT##OPC(                             \
0335       Value *V1, Value *V2, const Twine &Name,                                 \
0336       InsertPosition InsertBefore = nullptr) {                                 \
0337     return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, InsertBefore);  \
0338   }
0339 
0340   DEFINE_HELPERS(Add, NSW) // CreateNSWAdd
0341   DEFINE_HELPERS(Add, NUW) // CreateNUWAdd
0342   DEFINE_HELPERS(Sub, NSW) // CreateNSWSub
0343   DEFINE_HELPERS(Sub, NUW) // CreateNUWSub
0344   DEFINE_HELPERS(Mul, NSW) // CreateNSWMul
0345   DEFINE_HELPERS(Mul, NUW) // CreateNUWMul
0346   DEFINE_HELPERS(Shl, NSW) // CreateNSWShl
0347   DEFINE_HELPERS(Shl, NUW) // CreateNUWShl
0348 
0349   DEFINE_HELPERS(SDiv, Exact)  // CreateExactSDiv
0350   DEFINE_HELPERS(UDiv, Exact)  // CreateExactUDiv
0351   DEFINE_HELPERS(AShr, Exact)  // CreateExactAShr
0352   DEFINE_HELPERS(LShr, Exact)  // CreateExactLShr
0353 
0354   DEFINE_HELPERS(Or, Disjoint) // CreateDisjointOr
0355 
0356 #undef DEFINE_HELPERS
0357 
0358   /// Helper functions to construct and inspect unary operations (NEG and NOT)
0359   /// via binary operators SUB and XOR:
0360   ///
0361   /// Create the NEG and NOT instructions out of SUB and XOR instructions.
0362   ///
0363   static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "",
0364                                    InsertPosition InsertBefore = nullptr);
0365   static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "",
0366                                       InsertPosition InsertBefore = nullptr);
0367   static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "",
0368                                    InsertPosition InsertBefore = nullptr);
0369 
0370   BinaryOps getOpcode() const {
0371     return static_cast<BinaryOps>(Instruction::getOpcode());
0372   }
0373 
0374   /// Exchange the two operands to this instruction.
0375   /// This instruction is safe to use on any binary instruction and
0376   /// does not modify the semantics of the instruction.  If the instruction
0377   /// cannot be reversed (ie, it's a Div), then return true.
0378   ///
0379   bool swapOperands();
0380 
0381   // Methods for support type inquiry through isa, cast, and dyn_cast:
0382   static bool classof(const Instruction *I) {
0383     return I->isBinaryOp();
0384   }
0385   static bool classof(const Value *V) {
0386     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0387   }
0388 };
0389 
0390 template <>
0391 struct OperandTraits<BinaryOperator> :
0392   public FixedNumOperandTraits<BinaryOperator, 2> {
0393 };
0394 
0395 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value)
0396 
0397 /// An or instruction, which can be marked as "disjoint", indicating that the
0398 /// inputs don't have a 1 in the same bit position. Meaning this instruction
0399 /// can also be treated as an add.
0400 class PossiblyDisjointInst : public BinaryOperator {
0401 public:
0402   enum { IsDisjoint = (1 << 0) };
0403 
0404   void setIsDisjoint(bool B) {
0405     SubclassOptionalData =
0406         (SubclassOptionalData & ~IsDisjoint) | (B * IsDisjoint);
0407   }
0408 
0409   bool isDisjoint() const { return SubclassOptionalData & IsDisjoint; }
0410 
0411   static bool classof(const Instruction *I) {
0412     return I->getOpcode() == Instruction::Or;
0413   }
0414 
0415   static bool classof(const Value *V) {
0416     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0417   }
0418 };
0419 
0420 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1,
0421                                                Value *V2, const Twine &Name) {
0422   BinaryOperator *BO = Create(Opc, V1, V2, Name);
0423   cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true);
0424   return BO;
0425 }
0426 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1,
0427                                                Value *V2, const Twine &Name,
0428                                                InsertPosition InsertBefore) {
0429   BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore);
0430   cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true);
0431   return BO;
0432 }
0433 
0434 //===----------------------------------------------------------------------===//
0435 //                               CastInst Class
0436 //===----------------------------------------------------------------------===//
0437 
0438 /// This is the base class for all instructions that perform data
0439 /// casts. It is simply provided so that instruction category testing
0440 /// can be performed with code like:
0441 ///
0442 /// if (isa<CastInst>(Instr)) { ... }
0443 /// Base class of casting instructions.
0444 class CastInst : public UnaryInstruction {
0445 protected:
0446   /// Constructor with insert-before-instruction semantics for subclasses
0447   CastInst(Type *Ty, unsigned iType, Value *S, const Twine &NameStr = "",
0448            InsertPosition InsertBefore = nullptr)
0449       : UnaryInstruction(Ty, iType, S, InsertBefore) {
0450     setName(NameStr);
0451   }
0452 
0453 public:
0454   /// Provides a way to construct any of the CastInst subclasses using an
0455   /// opcode instead of the subclass's constructor. The opcode must be in the
0456   /// CastOps category (Instruction::isCast(opcode) returns true). This
0457   /// constructor has insert-before-instruction semantics to automatically
0458   /// insert the new CastInst before InsertBefore (if it is non-null).
0459   /// Construct any of the CastInst subclasses
0460   static CastInst *Create(
0461       Instruction::CastOps,   ///< The opcode of the cast instruction
0462       Value *S,               ///< The value to be casted (operand 0)
0463       Type *Ty,               ///< The type to which cast should be made
0464       const Twine &Name = "", ///< Name for the instruction
0465       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0466   );
0467 
0468   /// Create a ZExt or BitCast cast instruction
0469   static CastInst *CreateZExtOrBitCast(
0470       Value *S,               ///< The value to be casted (operand 0)
0471       Type *Ty,               ///< The type to which cast should be made
0472       const Twine &Name = "", ///< Name for the instruction
0473       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0474   );
0475 
0476   /// Create a SExt or BitCast cast instruction
0477   static CastInst *CreateSExtOrBitCast(
0478       Value *S,               ///< The value to be casted (operand 0)
0479       Type *Ty,               ///< The type to which cast should be made
0480       const Twine &Name = "", ///< Name for the instruction
0481       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0482   );
0483 
0484   /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
0485   static CastInst *CreatePointerCast(
0486       Value *S,               ///< The pointer value to be casted (operand 0)
0487       Type *Ty,               ///< The type to which cast should be made
0488       const Twine &Name = "", ///< Name for the instruction
0489       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0490   );
0491 
0492   /// Create a BitCast or an AddrSpaceCast cast instruction.
0493   static CastInst *CreatePointerBitCastOrAddrSpaceCast(
0494       Value *S,               ///< The pointer value to be casted (operand 0)
0495       Type *Ty,               ///< The type to which cast should be made
0496       const Twine &Name = "", ///< Name for the instruction
0497       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0498   );
0499 
0500   /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
0501   ///
0502   /// If the value is a pointer type and the destination an integer type,
0503   /// creates a PtrToInt cast. If the value is an integer type and the
0504   /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates
0505   /// a bitcast.
0506   static CastInst *CreateBitOrPointerCast(
0507       Value *S,               ///< The pointer value to be casted (operand 0)
0508       Type *Ty,               ///< The type to which cast should be made
0509       const Twine &Name = "", ///< Name for the instruction
0510       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0511   );
0512 
0513   /// Create a ZExt, BitCast, or Trunc for int -> int casts.
0514   static CastInst *CreateIntegerCast(
0515       Value *S,               ///< The pointer value to be casted (operand 0)
0516       Type *Ty,               ///< The type to which cast should be made
0517       bool isSigned,          ///< Whether to regard S as signed or not
0518       const Twine &Name = "", ///< Name for the instruction
0519       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0520   );
0521 
0522   /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts
0523   static CastInst *CreateFPCast(
0524       Value *S,               ///< The floating point value to be casted
0525       Type *Ty,               ///< The floating point type to cast to
0526       const Twine &Name = "", ///< Name for the instruction
0527       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0528   );
0529 
0530   /// Create a Trunc or BitCast cast instruction
0531   static CastInst *CreateTruncOrBitCast(
0532       Value *S,               ///< The value to be casted (operand 0)
0533       Type *Ty,               ///< The type to which cast should be made
0534       const Twine &Name = "", ///< Name for the instruction
0535       InsertPosition InsertBefore = nullptr ///< Place to insert the instruction
0536   );
0537 
0538   /// Check whether a bitcast between these types is valid
0539   static bool isBitCastable(
0540     Type *SrcTy, ///< The Type from which the value should be cast.
0541     Type *DestTy ///< The Type to which the value should be cast.
0542   );
0543 
0544   /// Check whether a bitcast, inttoptr, or ptrtoint cast between these
0545   /// types is valid and a no-op.
0546   ///
0547   /// This ensures that any pointer<->integer cast has enough bits in the
0548   /// integer and any other cast is a bitcast.
0549   static bool isBitOrNoopPointerCastable(
0550       Type *SrcTy,  ///< The Type from which the value should be cast.
0551       Type *DestTy, ///< The Type to which the value should be cast.
0552       const DataLayout &DL);
0553 
0554   /// Returns the opcode necessary to cast Val into Ty using usual casting
0555   /// rules.
0556   /// Infer the opcode for cast operand and type
0557   static Instruction::CastOps getCastOpcode(
0558     const Value *Val, ///< The value to cast
0559     bool SrcIsSigned, ///< Whether to treat the source as signed
0560     Type *Ty,   ///< The Type to which the value should be casted
0561     bool DstIsSigned  ///< Whether to treate the dest. as signed
0562   );
0563 
0564   /// There are several places where we need to know if a cast instruction
0565   /// only deals with integer source and destination types. To simplify that
0566   /// logic, this method is provided.
0567   /// @returns true iff the cast has only integral typed operand and dest type.
0568   /// Determine if this is an integer-only cast.
0569   bool isIntegerCast() const;
0570 
0571   /// A no-op cast is one that can be effected without changing any bits.
0572   /// It implies that the source and destination types are the same size. The
0573   /// DataLayout argument is to determine the pointer size when examining casts
0574   /// involving Integer and Pointer types. They are no-op casts if the integer
0575   /// is the same size as the pointer. However, pointer size varies with
0576   /// platform.  Note that a precondition of this method is that the cast is
0577   /// legal - i.e. the instruction formed with these operands would verify.
0578   static bool isNoopCast(
0579     Instruction::CastOps Opcode, ///< Opcode of cast
0580     Type *SrcTy,         ///< SrcTy of cast
0581     Type *DstTy,         ///< DstTy of cast
0582     const DataLayout &DL ///< DataLayout to get the Int Ptr type from.
0583   );
0584 
0585   /// Determine if this cast is a no-op cast.
0586   ///
0587   /// \param DL is the DataLayout to determine pointer size.
0588   bool isNoopCast(const DataLayout &DL) const;
0589 
0590   /// Determine how a pair of casts can be eliminated, if they can be at all.
0591   /// This is a helper function for both CastInst and ConstantExpr.
0592   /// @returns 0 if the CastInst pair can't be eliminated, otherwise
0593   /// returns Instruction::CastOps value for a cast that can replace
0594   /// the pair, casting SrcTy to DstTy.
0595   /// Determine if a cast pair is eliminable
0596   static unsigned isEliminableCastPair(
0597     Instruction::CastOps firstOpcode,  ///< Opcode of first cast
0598     Instruction::CastOps secondOpcode, ///< Opcode of second cast
0599     Type *SrcTy, ///< SrcTy of 1st cast
0600     Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast
0601     Type *DstTy, ///< DstTy of 2nd cast
0602     Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null
0603     Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null
0604     Type *DstIntPtrTy  ///< Integer type corresponding to Ptr DstTy, or null
0605   );
0606 
0607   /// Return the opcode of this CastInst
0608   Instruction::CastOps getOpcode() const {
0609     return Instruction::CastOps(Instruction::getOpcode());
0610   }
0611 
0612   /// Return the source type, as a convenience
0613   Type* getSrcTy() const { return getOperand(0)->getType(); }
0614   /// Return the destination type, as a convenience
0615   Type* getDestTy() const { return getType(); }
0616 
0617   /// This method can be used to determine if a cast from SrcTy to DstTy using
0618   /// Opcode op is valid or not.
0619   /// @returns true iff the proposed cast is valid.
0620   /// Determine if a cast is valid without creating one.
0621   static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy);
0622   static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
0623     return castIsValid(op, S->getType(), DstTy);
0624   }
0625 
0626   /// Methods for support type inquiry through isa, cast, and dyn_cast:
0627   static bool classof(const Instruction *I) {
0628     return I->isCast();
0629   }
0630   static bool classof(const Value *V) {
0631     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0632   }
0633 };
0634 
0635 /// Instruction that can have a nneg flag (zext/uitofp).
0636 class PossiblyNonNegInst : public CastInst {
0637 public:
0638   enum { NonNeg = (1 << 0) };
0639 
0640   static bool classof(const Instruction *I) {
0641     switch (I->getOpcode()) {
0642     case Instruction::ZExt:
0643     case Instruction::UIToFP:
0644       return true;
0645     default:
0646       return false;
0647     }
0648   }
0649 
0650   static bool classof(const Value *V) {
0651     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0652   }
0653 };
0654 
0655 //===----------------------------------------------------------------------===//
0656 //                               CmpInst Class
0657 //===----------------------------------------------------------------------===//
0658 
0659 /// This class is the base class for the comparison instructions.
0660 /// Abstract base class of comparison instructions.
0661 class CmpInst : public Instruction {
0662   constexpr static IntrusiveOperandsAllocMarker AllocMarker{2};
0663 
0664 public:
0665   /// This enumeration lists the possible predicates for CmpInst subclasses.
0666   /// Values in the range 0-31 are reserved for FCmpInst, while values in the
0667   /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the
0668   /// predicate values are not overlapping between the classes.
0669   ///
0670   /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of
0671   /// FCMP_* values. Changing the bit patterns requires a potential change to
0672   /// those passes.
0673   enum Predicate : unsigned {
0674     // Opcode            U L G E    Intuitive operation
0675     FCMP_FALSE = 0, ///< 0 0 0 0    Always false (always folded)
0676     FCMP_OEQ = 1,   ///< 0 0 0 1    True if ordered and equal
0677     FCMP_OGT = 2,   ///< 0 0 1 0    True if ordered and greater than
0678     FCMP_OGE = 3,   ///< 0 0 1 1    True if ordered and greater than or equal
0679     FCMP_OLT = 4,   ///< 0 1 0 0    True if ordered and less than
0680     FCMP_OLE = 5,   ///< 0 1 0 1    True if ordered and less than or equal
0681     FCMP_ONE = 6,   ///< 0 1 1 0    True if ordered and operands are unequal
0682     FCMP_ORD = 7,   ///< 0 1 1 1    True if ordered (no nans)
0683     FCMP_UNO = 8,   ///< 1 0 0 0    True if unordered: isnan(X) | isnan(Y)
0684     FCMP_UEQ = 9,   ///< 1 0 0 1    True if unordered or equal
0685     FCMP_UGT = 10,  ///< 1 0 1 0    True if unordered or greater than
0686     FCMP_UGE = 11,  ///< 1 0 1 1    True if unordered, greater than, or equal
0687     FCMP_ULT = 12,  ///< 1 1 0 0    True if unordered or less than
0688     FCMP_ULE = 13,  ///< 1 1 0 1    True if unordered, less than, or equal
0689     FCMP_UNE = 14,  ///< 1 1 1 0    True if unordered or not equal
0690     FCMP_TRUE = 15, ///< 1 1 1 1    Always true (always folded)
0691     FIRST_FCMP_PREDICATE = FCMP_FALSE,
0692     LAST_FCMP_PREDICATE = FCMP_TRUE,
0693     BAD_FCMP_PREDICATE = FCMP_TRUE + 1,
0694     ICMP_EQ = 32,  ///< equal
0695     ICMP_NE = 33,  ///< not equal
0696     ICMP_UGT = 34, ///< unsigned greater than
0697     ICMP_UGE = 35, ///< unsigned greater or equal
0698     ICMP_ULT = 36, ///< unsigned less than
0699     ICMP_ULE = 37, ///< unsigned less or equal
0700     ICMP_SGT = 38, ///< signed greater than
0701     ICMP_SGE = 39, ///< signed greater or equal
0702     ICMP_SLT = 40, ///< signed less than
0703     ICMP_SLE = 41, ///< signed less or equal
0704     FIRST_ICMP_PREDICATE = ICMP_EQ,
0705     LAST_ICMP_PREDICATE = ICMP_SLE,
0706     BAD_ICMP_PREDICATE = ICMP_SLE + 1
0707   };
0708   using PredicateField =
0709       Bitfield::Element<Predicate, 0, 6, LAST_ICMP_PREDICATE>;
0710 
0711   /// Returns the sequence of all FCmp predicates.
0712   static auto FCmpPredicates() {
0713     return enum_seq_inclusive(Predicate::FIRST_FCMP_PREDICATE,
0714                               Predicate::LAST_FCMP_PREDICATE,
0715                               force_iteration_on_noniterable_enum);
0716   }
0717 
0718   /// Returns the sequence of all ICmp predicates.
0719   static auto ICmpPredicates() {
0720     return enum_seq_inclusive(Predicate::FIRST_ICMP_PREDICATE,
0721                               Predicate::LAST_ICMP_PREDICATE,
0722                               force_iteration_on_noniterable_enum);
0723   }
0724 
0725 protected:
0726   CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, Value *LHS,
0727           Value *RHS, const Twine &Name = "",
0728           InsertPosition InsertBefore = nullptr,
0729           Instruction *FlagsSource = nullptr);
0730 
0731 public:
0732   // allocate space for exactly two operands
0733   void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
0734   void operator delete(void *Ptr) { User::operator delete(Ptr); }
0735 
0736   /// Construct a compare instruction, given the opcode, the predicate and
0737   /// the two operands.  Optionally (if InstBefore is specified) insert the
0738   /// instruction into a BasicBlock right before the specified instruction.
0739   /// The specified Instruction is allowed to be a dereferenced end iterator.
0740   /// Create a CmpInst
0741   static CmpInst *Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2,
0742                          const Twine &Name = "",
0743                          InsertPosition InsertBefore = nullptr);
0744 
0745   /// Construct a compare instruction, given the opcode, the predicate,
0746   /// the two operands and the instruction to copy the flags from. Optionally
0747   /// (if InstBefore is specified) insert the instruction into a BasicBlock
0748   /// right before the specified instruction. The specified Instruction is
0749   /// allowed to be a dereferenced end iterator.
0750   /// Create a CmpInst
0751   static CmpInst *CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1,
0752                                         Value *S2,
0753                                         const Instruction *FlagsSource,
0754                                         const Twine &Name = "",
0755                                         InsertPosition InsertBefore = nullptr);
0756 
0757   /// Get the opcode casted to the right type
0758   OtherOps getOpcode() const {
0759     return static_cast<OtherOps>(Instruction::getOpcode());
0760   }
0761 
0762   /// Return the predicate for this instruction.
0763   Predicate getPredicate() const { return getSubclassData<PredicateField>(); }
0764 
0765   /// Set the predicate for this instruction to the specified value.
0766   void setPredicate(Predicate P) { setSubclassData<PredicateField>(P); }
0767 
0768   static bool isFPPredicate(Predicate P) {
0769     static_assert(FIRST_FCMP_PREDICATE == 0,
0770                   "FIRST_FCMP_PREDICATE is required to be 0");
0771     return P <= LAST_FCMP_PREDICATE;
0772   }
0773 
0774   static bool isIntPredicate(Predicate P) {
0775     return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE;
0776   }
0777 
0778   static StringRef getPredicateName(Predicate P);
0779 
0780   bool isFPPredicate() const { return isFPPredicate(getPredicate()); }
0781   bool isIntPredicate() const { return isIntPredicate(getPredicate()); }
0782 
0783   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
0784   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
0785   /// @returns the inverse predicate for the instruction's current predicate.
0786   /// Return the inverse of the instruction's predicate.
0787   Predicate getInversePredicate() const {
0788     return getInversePredicate(getPredicate());
0789   }
0790 
0791   /// Returns the ordered variant of a floating point compare.
0792   ///
0793   /// For example, UEQ -> OEQ, ULT -> OLT, OEQ -> OEQ
0794   static Predicate getOrderedPredicate(Predicate Pred) {
0795     return static_cast<Predicate>(Pred & FCMP_ORD);
0796   }
0797 
0798   Predicate getOrderedPredicate() const {
0799     return getOrderedPredicate(getPredicate());
0800   }
0801 
0802   /// Returns the unordered variant of a floating point compare.
0803   ///
0804   /// For example, OEQ -> UEQ, OLT -> ULT, OEQ -> UEQ
0805   static Predicate getUnorderedPredicate(Predicate Pred) {
0806     return static_cast<Predicate>(Pred | FCMP_UNO);
0807   }
0808 
0809   Predicate getUnorderedPredicate() const {
0810     return getUnorderedPredicate(getPredicate());
0811   }
0812 
0813   /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE,
0814   ///              OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
0815   /// @returns the inverse predicate for predicate provided in \p pred.
0816   /// Return the inverse of a given predicate
0817   static Predicate getInversePredicate(Predicate pred);
0818 
0819   /// For example, EQ->EQ, SLE->SGE, ULT->UGT,
0820   ///              OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
0821   /// @returns the predicate that would be the result of exchanging the two
0822   /// operands of the CmpInst instruction without changing the result
0823   /// produced.
0824   /// Return the predicate as if the operands were swapped
0825   Predicate getSwappedPredicate() const {
0826     return getSwappedPredicate(getPredicate());
0827   }
0828 
0829   /// This is a static version that you can use without an instruction
0830   /// available.
0831   /// Return the predicate as if the operands were swapped.
0832   static Predicate getSwappedPredicate(Predicate pred);
0833 
0834   /// This is a static version that you can use without an instruction
0835   /// available.
0836   /// @returns true if the comparison predicate is strict, false otherwise.
0837   static bool isStrictPredicate(Predicate predicate);
0838 
0839   /// @returns true if the comparison predicate is strict, false otherwise.
0840   /// Determine if this instruction is using an strict comparison predicate.
0841   bool isStrictPredicate() const { return isStrictPredicate(getPredicate()); }
0842 
0843   /// This is a static version that you can use without an instruction
0844   /// available.
0845   /// @returns true if the comparison predicate is non-strict, false otherwise.
0846   static bool isNonStrictPredicate(Predicate predicate);
0847 
0848   /// @returns true if the comparison predicate is non-strict, false otherwise.
0849   /// Determine if this instruction is using an non-strict comparison predicate.
0850   bool isNonStrictPredicate() const {
0851     return isNonStrictPredicate(getPredicate());
0852   }
0853 
0854   /// For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
0855   /// Returns the strict version of non-strict comparisons.
0856   Predicate getStrictPredicate() const {
0857     return getStrictPredicate(getPredicate());
0858   }
0859 
0860   /// This is a static version that you can use without an instruction
0861   /// available.
0862   /// @returns the strict version of comparison provided in \p pred.
0863   /// If \p pred is not a strict comparison predicate, returns \p pred.
0864   /// Returns the strict version of non-strict comparisons.
0865   static Predicate getStrictPredicate(Predicate pred);
0866 
0867   /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
0868   /// Returns the non-strict version of strict comparisons.
0869   Predicate getNonStrictPredicate() const {
0870     return getNonStrictPredicate(getPredicate());
0871   }
0872 
0873   /// This is a static version that you can use without an instruction
0874   /// available.
0875   /// @returns the non-strict version of comparison provided in \p pred.
0876   /// If \p pred is not a strict comparison predicate, returns \p pred.
0877   /// Returns the non-strict version of strict comparisons.
0878   static Predicate getNonStrictPredicate(Predicate pred);
0879 
0880   /// This is a static version that you can use without an instruction
0881   /// available.
0882   /// Return the flipped strictness of predicate
0883   static Predicate getFlippedStrictnessPredicate(Predicate pred);
0884 
0885   /// For predicate of kind "is X or equal to 0" returns the predicate "is X".
0886   /// For predicate of kind "is X" returns the predicate "is X or equal to 0".
0887   /// does not support other kind of predicates.
0888   /// @returns the predicate that does not contains is equal to zero if
0889   /// it had and vice versa.
0890   /// Return the flipped strictness of predicate
0891   Predicate getFlippedStrictnessPredicate() const {
0892     return getFlippedStrictnessPredicate(getPredicate());
0893   }
0894 
0895   /// Provide more efficient getOperand methods.
0896   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
0897 
0898   /// This is just a convenience that dispatches to the subclasses.
0899   /// Swap the operands and adjust predicate accordingly to retain
0900   /// the same comparison.
0901   void swapOperands();
0902 
0903   /// This is just a convenience that dispatches to the subclasses.
0904   /// Determine if this CmpInst is commutative.
0905   bool isCommutative() const;
0906 
0907   /// Determine if this is an equals/not equals predicate.
0908   /// This is a static version that you can use without an instruction
0909   /// available.
0910   static bool isEquality(Predicate pred);
0911 
0912   /// Determine if this is an equals/not equals predicate.
0913   bool isEquality() const { return isEquality(getPredicate()); }
0914 
0915   /// Determine if one operand of this compare can always be replaced by the
0916   /// other operand, ignoring provenance considerations. If \p Invert, check for
0917   /// equivalence with the inverse predicate.
0918   bool isEquivalence(bool Invert = false) const;
0919 
0920   /// Return true if the predicate is relational (not EQ or NE).
0921   static bool isRelational(Predicate P) { return !isEquality(P); }
0922 
0923   /// Return true if the predicate is relational (not EQ or NE).
0924   bool isRelational() const { return !isEquality(); }
0925 
0926   /// @returns true if the comparison is signed, false otherwise.
0927   /// Determine if this instruction is using a signed comparison.
0928   bool isSigned() const {
0929     return isSigned(getPredicate());
0930   }
0931 
0932   /// @returns true if the comparison is unsigned, false otherwise.
0933   /// Determine if this instruction is using an unsigned comparison.
0934   bool isUnsigned() const {
0935     return isUnsigned(getPredicate());
0936   }
0937 
0938   /// This is just a convenience.
0939   /// Determine if this is true when both operands are the same.
0940   bool isTrueWhenEqual() const {
0941     return isTrueWhenEqual(getPredicate());
0942   }
0943 
0944   /// This is just a convenience.
0945   /// Determine if this is false when both operands are the same.
0946   bool isFalseWhenEqual() const {
0947     return isFalseWhenEqual(getPredicate());
0948   }
0949 
0950   /// @returns true if the predicate is unsigned, false otherwise.
0951   /// Determine if the predicate is an unsigned operation.
0952   static bool isUnsigned(Predicate predicate);
0953 
0954   /// @returns true if the predicate is signed, false otherwise.
0955   /// Determine if the predicate is an signed operation.
0956   static bool isSigned(Predicate predicate);
0957 
0958   /// Determine if the predicate is an ordered operation.
0959   static bool isOrdered(Predicate predicate);
0960 
0961   /// Determine if the predicate is an unordered operation.
0962   static bool isUnordered(Predicate predicate);
0963 
0964   /// Determine if the predicate is true when comparing a value with itself.
0965   static bool isTrueWhenEqual(Predicate predicate);
0966 
0967   /// Determine if the predicate is false when comparing a value with itself.
0968   static bool isFalseWhenEqual(Predicate predicate);
0969 
0970   /// Methods for support type inquiry through isa, cast, and dyn_cast:
0971   static bool classof(const Instruction *I) {
0972     return I->getOpcode() == Instruction::ICmp ||
0973            I->getOpcode() == Instruction::FCmp;
0974   }
0975   static bool classof(const Value *V) {
0976     return isa<Instruction>(V) && classof(cast<Instruction>(V));
0977   }
0978 
0979   /// Create a result type for fcmp/icmp
0980   static Type* makeCmpResultType(Type* opnd_type) {
0981     if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) {
0982       return VectorType::get(Type::getInt1Ty(opnd_type->getContext()),
0983                              vt->getElementCount());
0984     }
0985     return Type::getInt1Ty(opnd_type->getContext());
0986   }
0987 
0988 private:
0989   // Shadow Value::setValueSubclassData with a private forwarding method so that
0990   // subclasses cannot accidentally use it.
0991   void setValueSubclassData(unsigned short D) {
0992     Value::setValueSubclassData(D);
0993   }
0994 };
0995 
0996 // FIXME: these are redundant if CmpInst < BinaryOperator
0997 template <>
0998 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> {
0999 };
1000 
1001 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value)
1002 
1003 raw_ostream &operator<<(raw_ostream &OS, CmpInst::Predicate Pred);
1004 
1005 /// A lightweight accessor for an operand bundle meant to be passed
1006 /// around by value.
1007 struct OperandBundleUse {
1008   ArrayRef<Use> Inputs;
1009 
1010   OperandBundleUse() = default;
1011   explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs)
1012       : Inputs(Inputs), Tag(Tag) {}
1013 
1014   /// Return true if the operand at index \p Idx in this operand bundle
1015   /// has the attribute A.
1016   bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const {
1017     if (isDeoptOperandBundle())
1018       if (A == Attribute::ReadOnly || A == Attribute::NoCapture)
1019         return Inputs[Idx]->getType()->isPointerTy();
1020 
1021     // Conservative answer:  no operands have any attributes.
1022     return false;
1023   }
1024 
1025   /// Return the tag of this operand bundle as a string.
1026   StringRef getTagName() const {
1027     return Tag->getKey();
1028   }
1029 
1030   /// Return the tag of this operand bundle as an integer.
1031   ///
1032   /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag,
1033   /// and this function returns the unique integer getOrInsertBundleTag
1034   /// associated the tag of this operand bundle to.
1035   uint32_t getTagID() const {
1036     return Tag->getValue();
1037   }
1038 
1039   /// Return true if this is a "deopt" operand bundle.
1040   bool isDeoptOperandBundle() const {
1041     return getTagID() == LLVMContext::OB_deopt;
1042   }
1043 
1044   /// Return true if this is a "funclet" operand bundle.
1045   bool isFuncletOperandBundle() const {
1046     return getTagID() == LLVMContext::OB_funclet;
1047   }
1048 
1049   /// Return true if this is a "cfguardtarget" operand bundle.
1050   bool isCFGuardTargetOperandBundle() const {
1051     return getTagID() == LLVMContext::OB_cfguardtarget;
1052   }
1053 
1054 private:
1055   /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag.
1056   StringMapEntry<uint32_t> *Tag;
1057 };
1058 
1059 /// A container for an operand bundle being viewed as a set of values
1060 /// rather than a set of uses.
1061 ///
1062 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and
1063 /// so it is possible to create and pass around "self-contained" instances of
1064 /// OperandBundleDef and ConstOperandBundleDef.
1065 template <typename InputTy> class OperandBundleDefT {
1066   std::string Tag;
1067   std::vector<InputTy> Inputs;
1068 
1069 public:
1070   explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs)
1071       : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {}
1072   explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs)
1073       : Tag(std::move(Tag)), Inputs(Inputs) {}
1074 
1075   explicit OperandBundleDefT(const OperandBundleUse &OBU) {
1076     Tag = std::string(OBU.getTagName());
1077     llvm::append_range(Inputs, OBU.Inputs);
1078   }
1079 
1080   ArrayRef<InputTy> inputs() const { return Inputs; }
1081 
1082   using input_iterator = typename std::vector<InputTy>::const_iterator;
1083 
1084   size_t input_size() const { return Inputs.size(); }
1085   input_iterator input_begin() const { return Inputs.begin(); }
1086   input_iterator input_end() const { return Inputs.end(); }
1087 
1088   StringRef getTag() const { return Tag; }
1089 };
1090 
1091 using OperandBundleDef = OperandBundleDefT<Value *>;
1092 using ConstOperandBundleDef = OperandBundleDefT<const Value *>;
1093 
1094 //===----------------------------------------------------------------------===//
1095 //                               CallBase Class
1096 //===----------------------------------------------------------------------===//
1097 
1098 /// Base class for all callable instructions (InvokeInst and CallInst)
1099 /// Holds everything related to calling a function.
1100 ///
1101 /// All call-like instructions are required to use a common operand layout:
1102 /// - Zero or more arguments to the call,
1103 /// - Zero or more operand bundles with zero or more operand inputs each
1104 ///   bundle,
1105 /// - Zero or more subclass controlled operands
1106 /// - The called function.
1107 ///
1108 /// This allows this base class to easily access the called function and the
1109 /// start of the arguments without knowing how many other operands a particular
1110 /// subclass requires. Note that accessing the end of the argument list isn't
1111 /// as cheap as most other operations on the base class.
1112 class CallBase : public Instruction {
1113 protected:
1114   // The first two bits are reserved by CallInst for fast retrieval,
1115   using CallInstReservedField = Bitfield::Element<unsigned, 0, 2>;
1116   using CallingConvField =
1117       Bitfield::Element<CallingConv::ID, CallInstReservedField::NextBit, 10,
1118                         CallingConv::MaxID>;
1119   static_assert(
1120       Bitfield::areContiguous<CallInstReservedField, CallingConvField>(),
1121       "Bitfields must be contiguous");
1122 
1123   /// The last operand is the called operand.
1124   static constexpr int CalledOperandOpEndIdx = -1;
1125 
1126   AttributeList Attrs; ///< parameter attributes for callable
1127   FunctionType *FTy;
1128 
1129   template <class... ArgsTy>
1130   CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args)
1131       : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {}
1132 
1133   using Instruction::Instruction;
1134 
1135   bool hasDescriptor() const { return Value::HasDescriptor; }
1136 
1137   unsigned getNumSubclassExtraOperands() const {
1138     switch (getOpcode()) {
1139     case Instruction::Call:
1140       return 0;
1141     case Instruction::Invoke:
1142       return 2;
1143     case Instruction::CallBr:
1144       return getNumSubclassExtraOperandsDynamic();
1145     }
1146     llvm_unreachable("Invalid opcode!");
1147   }
1148 
1149   /// Get the number of extra operands for instructions that don't have a fixed
1150   /// number of extra operands.
1151   unsigned getNumSubclassExtraOperandsDynamic() const;
1152 
1153 public:
1154   using Instruction::getContext;
1155 
1156   /// Create a clone of \p CB with a different set of operand bundles and
1157   /// insert it before \p InsertPt.
1158   ///
1159   /// The returned call instruction is identical \p CB in every way except that
1160   /// the operand bundles for the new instruction are set to the operand bundles
1161   /// in \p Bundles.
1162   static CallBase *Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
1163                           InsertPosition InsertPt = nullptr);
1164 
1165   /// Create a clone of \p CB with the operand bundle with the tag matching
1166   /// \p Bundle's tag replaced with Bundle, and insert it before \p InsertPt.
1167   ///
1168   /// The returned call instruction is identical \p CI in every way except that
1169   /// the specified operand bundle has been replaced.
1170   static CallBase *Create(CallBase *CB, OperandBundleDef Bundle,
1171                           InsertPosition InsertPt = nullptr);
1172 
1173   /// Create a clone of \p CB with operand bundle \p OB added.
1174   static CallBase *addOperandBundle(CallBase *CB, uint32_t ID,
1175                                     OperandBundleDef OB,
1176                                     InsertPosition InsertPt = nullptr);
1177 
1178   /// Create a clone of \p CB with operand bundle \p ID removed.
1179   static CallBase *removeOperandBundle(CallBase *CB, uint32_t ID,
1180                                        InsertPosition InsertPt = nullptr);
1181 
1182   /// Return the convergence control token for this call, if it exists.
1183   Value *getConvergenceControlToken() const {
1184     if (auto Bundle = getOperandBundle(llvm::LLVMContext::OB_convergencectrl)) {
1185       return Bundle->Inputs[0].get();
1186     }
1187     return nullptr;
1188   }
1189 
1190   static bool classof(const Instruction *I) {
1191     return I->getOpcode() == Instruction::Call ||
1192            I->getOpcode() == Instruction::Invoke ||
1193            I->getOpcode() == Instruction::CallBr;
1194   }
1195   static bool classof(const Value *V) {
1196     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1197   }
1198 
1199   FunctionType *getFunctionType() const { return FTy; }
1200 
1201   void mutateFunctionType(FunctionType *FTy) {
1202     Value::mutateType(FTy->getReturnType());
1203     this->FTy = FTy;
1204   }
1205 
1206   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1207 
1208   /// data_operands_begin/data_operands_end - Return iterators iterating over
1209   /// the call / invoke argument list and bundle operands.  For invokes, this is
1210   /// the set of instruction operands except the invoke target and the two
1211   /// successor blocks; and for calls this is the set of instruction operands
1212   /// except the call target.
1213   User::op_iterator data_operands_begin() { return op_begin(); }
1214   User::const_op_iterator data_operands_begin() const {
1215     return const_cast<CallBase *>(this)->data_operands_begin();
1216   }
1217   User::op_iterator data_operands_end() {
1218     // Walk from the end of the operands over the called operand and any
1219     // subclass operands.
1220     return op_end() - getNumSubclassExtraOperands() - 1;
1221   }
1222   User::const_op_iterator data_operands_end() const {
1223     return const_cast<CallBase *>(this)->data_operands_end();
1224   }
1225   iterator_range<User::op_iterator> data_ops() {
1226     return make_range(data_operands_begin(), data_operands_end());
1227   }
1228   iterator_range<User::const_op_iterator> data_ops() const {
1229     return make_range(data_operands_begin(), data_operands_end());
1230   }
1231   bool data_operands_empty() const {
1232     return data_operands_end() == data_operands_begin();
1233   }
1234   unsigned data_operands_size() const {
1235     return std::distance(data_operands_begin(), data_operands_end());
1236   }
1237 
1238   bool isDataOperand(const Use *U) const {
1239     assert(this == U->getUser() &&
1240            "Only valid to query with a use of this instruction!");
1241     return data_operands_begin() <= U && U < data_operands_end();
1242   }
1243   bool isDataOperand(Value::const_user_iterator UI) const {
1244     return isDataOperand(&UI.getUse());
1245   }
1246 
1247   /// Given a value use iterator, return the data operand corresponding to it.
1248   /// Iterator must actually correspond to a data operand.
1249   unsigned getDataOperandNo(Value::const_user_iterator UI) const {
1250     return getDataOperandNo(&UI.getUse());
1251   }
1252 
1253   /// Given a use for a data operand, get the data operand number that
1254   /// corresponds to it.
1255   unsigned getDataOperandNo(const Use *U) const {
1256     assert(isDataOperand(U) && "Data operand # out of range!");
1257     return U - data_operands_begin();
1258   }
1259 
1260   /// Return the iterator pointing to the beginning of the argument list.
1261   User::op_iterator arg_begin() { return op_begin(); }
1262   User::const_op_iterator arg_begin() const {
1263     return const_cast<CallBase *>(this)->arg_begin();
1264   }
1265 
1266   /// Return the iterator pointing to the end of the argument list.
1267   User::op_iterator arg_end() {
1268     // From the end of the data operands, walk backwards past the bundle
1269     // operands.
1270     return data_operands_end() - getNumTotalBundleOperands();
1271   }
1272   User::const_op_iterator arg_end() const {
1273     return const_cast<CallBase *>(this)->arg_end();
1274   }
1275 
1276   /// Iteration adapter for range-for loops.
1277   iterator_range<User::op_iterator> args() {
1278     return make_range(arg_begin(), arg_end());
1279   }
1280   iterator_range<User::const_op_iterator> args() const {
1281     return make_range(arg_begin(), arg_end());
1282   }
1283   bool arg_empty() const { return arg_end() == arg_begin(); }
1284   unsigned arg_size() const { return arg_end() - arg_begin(); }
1285 
1286   Value *getArgOperand(unsigned i) const {
1287     assert(i < arg_size() && "Out of bounds!");
1288     return getOperand(i);
1289   }
1290 
1291   void setArgOperand(unsigned i, Value *v) {
1292     assert(i < arg_size() && "Out of bounds!");
1293     setOperand(i, v);
1294   }
1295 
1296   /// Wrappers for getting the \c Use of a call argument.
1297   const Use &getArgOperandUse(unsigned i) const {
1298     assert(i < arg_size() && "Out of bounds!");
1299     return User::getOperandUse(i);
1300   }
1301   Use &getArgOperandUse(unsigned i) {
1302     assert(i < arg_size() && "Out of bounds!");
1303     return User::getOperandUse(i);
1304   }
1305 
1306   bool isArgOperand(const Use *U) const {
1307     assert(this == U->getUser() &&
1308            "Only valid to query with a use of this instruction!");
1309     return arg_begin() <= U && U < arg_end();
1310   }
1311   bool isArgOperand(Value::const_user_iterator UI) const {
1312     return isArgOperand(&UI.getUse());
1313   }
1314 
1315   /// Given a use for a arg operand, get the arg operand number that
1316   /// corresponds to it.
1317   unsigned getArgOperandNo(const Use *U) const {
1318     assert(isArgOperand(U) && "Arg operand # out of range!");
1319     return U - arg_begin();
1320   }
1321 
1322   /// Given a value use iterator, return the arg operand number corresponding to
1323   /// it. Iterator must actually correspond to a data operand.
1324   unsigned getArgOperandNo(Value::const_user_iterator UI) const {
1325     return getArgOperandNo(&UI.getUse());
1326   }
1327 
1328   /// Returns true if this CallSite passes the given Value* as an argument to
1329   /// the called function.
1330   bool hasArgument(const Value *V) const {
1331     return llvm::is_contained(args(), V);
1332   }
1333 
1334   Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); }
1335 
1336   const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); }
1337   Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); }
1338 
1339   /// Returns the function called, or null if this is an indirect function
1340   /// invocation or the function signature does not match the call signature.
1341   Function *getCalledFunction() const {
1342     if (auto *F = dyn_cast_or_null<Function>(getCalledOperand()))
1343       if (F->getValueType() == getFunctionType())
1344         return F;
1345     return nullptr;
1346   }
1347 
1348   /// Return true if the callsite is an indirect call.
1349   bool isIndirectCall() const;
1350 
1351   /// Determine whether the passed iterator points to the callee operand's Use.
1352   bool isCallee(Value::const_user_iterator UI) const {
1353     return isCallee(&UI.getUse());
1354   }
1355 
1356   /// Determine whether this Use is the callee operand's Use.
1357   bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; }
1358 
1359   /// Helper to get the caller (the parent function).
1360   Function *getCaller();
1361   const Function *getCaller() const {
1362     return const_cast<CallBase *>(this)->getCaller();
1363   }
1364 
1365   /// Tests if this call site must be tail call optimized. Only a CallInst can
1366   /// be tail call optimized.
1367   bool isMustTailCall() const;
1368 
1369   /// Tests if this call site is marked as a tail call.
1370   bool isTailCall() const;
1371 
1372   /// Returns the intrinsic ID of the intrinsic called or
1373   /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if
1374   /// this is an indirect call.
1375   Intrinsic::ID getIntrinsicID() const;
1376 
1377   void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; }
1378 
1379   /// Sets the function called, including updating the function type.
1380   void setCalledFunction(Function *Fn) {
1381     setCalledFunction(Fn->getFunctionType(), Fn);
1382   }
1383 
1384   /// Sets the function called, including updating the function type.
1385   void setCalledFunction(FunctionCallee Fn) {
1386     setCalledFunction(Fn.getFunctionType(), Fn.getCallee());
1387   }
1388 
1389   /// Sets the function called, including updating to the specified function
1390   /// type.
1391   void setCalledFunction(FunctionType *FTy, Value *Fn) {
1392     this->FTy = FTy;
1393     // This function doesn't mutate the return type, only the function
1394     // type. Seems broken, but I'm just gonna stick an assert in for now.
1395     assert(getType() == FTy->getReturnType());
1396     setCalledOperand(Fn);
1397   }
1398 
1399   CallingConv::ID getCallingConv() const {
1400     return getSubclassData<CallingConvField>();
1401   }
1402 
1403   void setCallingConv(CallingConv::ID CC) {
1404     setSubclassData<CallingConvField>(CC);
1405   }
1406 
1407   /// Check if this call is an inline asm statement.
1408   bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); }
1409 
1410   /// \name Attribute API
1411   ///
1412   /// These methods access and modify attributes on this call (including
1413   /// looking through to the attributes on the called function when necessary).
1414   ///@{
1415 
1416   /// Return the attributes for this call.
1417   AttributeList getAttributes() const { return Attrs; }
1418 
1419   /// Set the attributes for this call.
1420   void setAttributes(AttributeList A) { Attrs = A; }
1421 
1422   /// Return the return attributes for this call.
1423   AttributeSet getRetAttributes() const {
1424     return getAttributes().getRetAttrs();
1425   }
1426 
1427   /// Return the param attributes for this call.
1428   AttributeSet getParamAttributes(unsigned ArgNo) const {
1429     return getAttributes().getParamAttrs(ArgNo);
1430   }
1431 
1432   /// Try to intersect the attributes from 'this' CallBase and the
1433   /// 'Other' CallBase. Sets the intersected attributes to 'this' and
1434   /// return true if successful. Doesn't modify 'this' and returns
1435   /// false if unsuccessful.
1436   bool tryIntersectAttributes(const CallBase *Other) {
1437     if (this == Other)
1438       return true;
1439     AttributeList AL = getAttributes();
1440     AttributeList ALOther = Other->getAttributes();
1441     auto Intersected = AL.intersectWith(getContext(), ALOther);
1442     if (!Intersected)
1443       return false;
1444     setAttributes(*Intersected);
1445     return true;
1446   }
1447 
1448   /// Determine whether this call has the given attribute. If it does not
1449   /// then determine if the called function has the attribute, but only if
1450   /// the attribute is allowed for the call.
1451   bool hasFnAttr(Attribute::AttrKind Kind) const {
1452     assert(Kind != Attribute::NoBuiltin &&
1453            "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin");
1454     return hasFnAttrImpl(Kind);
1455   }
1456 
1457   /// Determine whether this call has the given attribute. If it does not
1458   /// then determine if the called function has the attribute, but only if
1459   /// the attribute is allowed for the call.
1460   bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); }
1461 
1462   // TODO: remove non-AtIndex versions of these methods.
1463   /// adds the attribute to the list of attributes.
1464   void addAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
1465     Attrs = Attrs.addAttributeAtIndex(getContext(), i, Kind);
1466   }
1467 
1468   /// adds the attribute to the list of attributes.
1469   void addAttributeAtIndex(unsigned i, Attribute Attr) {
1470     Attrs = Attrs.addAttributeAtIndex(getContext(), i, Attr);
1471   }
1472 
1473   /// Adds the attribute to the function.
1474   void addFnAttr(Attribute::AttrKind Kind) {
1475     Attrs = Attrs.addFnAttribute(getContext(), Kind);
1476   }
1477 
1478   /// Adds the attribute to the function.
1479   void addFnAttr(Attribute Attr) {
1480     Attrs = Attrs.addFnAttribute(getContext(), Attr);
1481   }
1482 
1483   /// Adds the attribute to the return value.
1484   void addRetAttr(Attribute::AttrKind Kind) {
1485     Attrs = Attrs.addRetAttribute(getContext(), Kind);
1486   }
1487 
1488   /// Adds the attribute to the return value.
1489   void addRetAttr(Attribute Attr) {
1490     Attrs = Attrs.addRetAttribute(getContext(), Attr);
1491   }
1492 
1493   /// Adds the attribute to the indicated argument
1494   void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1495     assert(ArgNo < arg_size() && "Out of bounds");
1496     Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Kind);
1497   }
1498 
1499   /// Adds the attribute to the indicated argument
1500   void addParamAttr(unsigned ArgNo, Attribute Attr) {
1501     assert(ArgNo < arg_size() && "Out of bounds");
1502     Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Attr);
1503   }
1504 
1505   /// removes the attribute from the list of attributes.
1506   void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
1507     Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind);
1508   }
1509 
1510   /// removes the attribute from the list of attributes.
1511   void removeAttributeAtIndex(unsigned i, StringRef Kind) {
1512     Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind);
1513   }
1514 
1515   /// Removes the attributes from the function
1516   void removeFnAttrs(const AttributeMask &AttrsToRemove) {
1517     Attrs = Attrs.removeFnAttributes(getContext(), AttrsToRemove);
1518   }
1519 
1520   /// Removes the attribute from the function
1521   void removeFnAttr(Attribute::AttrKind Kind) {
1522     Attrs = Attrs.removeFnAttribute(getContext(), Kind);
1523   }
1524 
1525   /// Removes the attribute from the function
1526   void removeFnAttr(StringRef Kind) {
1527     Attrs = Attrs.removeFnAttribute(getContext(), Kind);
1528   }
1529 
1530   /// Removes the attribute from the return value
1531   void removeRetAttr(Attribute::AttrKind Kind) {
1532     Attrs = Attrs.removeRetAttribute(getContext(), Kind);
1533   }
1534 
1535   /// Removes the attributes from the return value
1536   void removeRetAttrs(const AttributeMask &AttrsToRemove) {
1537     Attrs = Attrs.removeRetAttributes(getContext(), AttrsToRemove);
1538   }
1539 
1540   /// Removes the attribute from the given argument
1541   void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
1542     assert(ArgNo < arg_size() && "Out of bounds");
1543     Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind);
1544   }
1545 
1546   /// Removes the attribute from the given argument
1547   void removeParamAttr(unsigned ArgNo, StringRef Kind) {
1548     assert(ArgNo < arg_size() && "Out of bounds");
1549     Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind);
1550   }
1551 
1552   /// Removes the attributes from the given argument
1553   void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove) {
1554     Attrs = Attrs.removeParamAttributes(getContext(), ArgNo, AttrsToRemove);
1555   }
1556 
1557   /// adds the dereferenceable attribute to the list of attributes.
1558   void addDereferenceableParamAttr(unsigned i, uint64_t Bytes) {
1559     Attrs = Attrs.addDereferenceableParamAttr(getContext(), i, Bytes);
1560   }
1561 
1562   /// adds the dereferenceable attribute to the list of attributes.
1563   void addDereferenceableRetAttr(uint64_t Bytes) {
1564     Attrs = Attrs.addDereferenceableRetAttr(getContext(), Bytes);
1565   }
1566 
1567   /// adds the range attribute to the list of attributes.
1568   void addRangeRetAttr(const ConstantRange &CR) {
1569     Attrs = Attrs.addRangeRetAttr(getContext(), CR);
1570   }
1571 
1572   /// Determine whether the return value has the given attribute.
1573   bool hasRetAttr(Attribute::AttrKind Kind) const {
1574     return hasRetAttrImpl(Kind);
1575   }
1576   /// Determine whether the return value has the given attribute.
1577   bool hasRetAttr(StringRef Kind) const { return hasRetAttrImpl(Kind); }
1578 
1579   /// Return the attribute for the given attribute kind for the return value.
1580   Attribute getRetAttr(Attribute::AttrKind Kind) const {
1581     Attribute RetAttr = Attrs.getRetAttr(Kind);
1582     if (RetAttr.isValid())
1583       return RetAttr;
1584 
1585     // Look at the callee, if available.
1586     if (const Function *F = getCalledFunction())
1587       return F->getRetAttribute(Kind);
1588     return Attribute();
1589   }
1590 
1591   /// Determine whether the argument or parameter has the given attribute.
1592   bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const;
1593 
1594   /// Get the attribute of a given kind at a position.
1595   Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const {
1596     return getAttributes().getAttributeAtIndex(i, Kind);
1597   }
1598 
1599   /// Get the attribute of a given kind at a position.
1600   Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const {
1601     return getAttributes().getAttributeAtIndex(i, Kind);
1602   }
1603 
1604   /// Get the attribute of a given kind for the function.
1605   Attribute getFnAttr(StringRef Kind) const {
1606     Attribute Attr = getAttributes().getFnAttr(Kind);
1607     if (Attr.isValid())
1608       return Attr;
1609     return getFnAttrOnCalledFunction(Kind);
1610   }
1611 
1612   /// Get the attribute of a given kind for the function.
1613   Attribute getFnAttr(Attribute::AttrKind Kind) const {
1614     Attribute A = getAttributes().getFnAttr(Kind);
1615     if (A.isValid())
1616       return A;
1617     return getFnAttrOnCalledFunction(Kind);
1618   }
1619 
1620   /// Get the attribute of a given kind from a given arg
1621   Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
1622     assert(ArgNo < arg_size() && "Out of bounds");
1623     Attribute A = getAttributes().getParamAttr(ArgNo, Kind);
1624     if (A.isValid())
1625       return A;
1626     return getParamAttrOnCalledFunction(ArgNo, Kind);
1627   }
1628 
1629   /// Get the attribute of a given kind from a given arg
1630   Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
1631     assert(ArgNo < arg_size() && "Out of bounds");
1632     Attribute A = getAttributes().getParamAttr(ArgNo, Kind);
1633     if (A.isValid())
1634       return A;
1635     return getParamAttrOnCalledFunction(ArgNo, Kind);
1636   }
1637 
1638   /// Return true if the data operand at index \p i has the attribute \p
1639   /// A.
1640   ///
1641   /// Data operands include call arguments and values used in operand bundles,
1642   /// but does not include the callee operand.
1643   ///
1644   /// The index \p i is interpreted as
1645   ///
1646   ///  \p i in [0, arg_size)  -> argument number (\p i)
1647   ///  \p i in [arg_size, data_operand_size) -> bundle operand at index
1648   ///     (\p i) in the operand list.
1649   bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const {
1650     // Note that we have to add one because `i` isn't zero-indexed.
1651     assert(i < arg_size() + getNumTotalBundleOperands() &&
1652            "Data operand index out of bounds!");
1653 
1654     // The attribute A can either be directly specified, if the operand in
1655     // question is a call argument; or be indirectly implied by the kind of its
1656     // containing operand bundle, if the operand is a bundle operand.
1657 
1658     if (i < arg_size())
1659       return paramHasAttr(i, Kind);
1660 
1661     assert(hasOperandBundles() && i >= getBundleOperandsStartIndex() &&
1662            "Must be either a call argument or an operand bundle!");
1663     return bundleOperandHasAttr(i, Kind);
1664   }
1665 
1666   /// Determine whether this data operand is not captured.
1667   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1668   // better indicate that this may return a conservative answer.
1669   bool doesNotCapture(unsigned OpNo) const {
1670     // If the argument is passed byval, the callee does not have access to the
1671     // original pointer and thus cannot capture it.
1672     if (OpNo < arg_size() && isByValArgument(OpNo))
1673       return true;
1674 
1675     return dataOperandHasImpliedAttr(OpNo, Attribute::NoCapture);
1676   }
1677 
1678   /// Determine whether this argument is passed by value.
1679   bool isByValArgument(unsigned ArgNo) const {
1680     return paramHasAttr(ArgNo, Attribute::ByVal);
1681   }
1682 
1683   /// Determine whether this argument is passed in an alloca.
1684   bool isInAllocaArgument(unsigned ArgNo) const {
1685     return paramHasAttr(ArgNo, Attribute::InAlloca);
1686   }
1687 
1688   /// Determine whether this argument is passed by value, in an alloca, or is
1689   /// preallocated.
1690   bool isPassPointeeByValueArgument(unsigned ArgNo) const {
1691     return paramHasAttr(ArgNo, Attribute::ByVal) ||
1692            paramHasAttr(ArgNo, Attribute::InAlloca) ||
1693            paramHasAttr(ArgNo, Attribute::Preallocated);
1694   }
1695 
1696   /// Determine whether passing undef to this argument is undefined behavior.
1697   /// If passing undef to this argument is UB, passing poison is UB as well
1698   /// because poison is more undefined than undef.
1699   bool isPassingUndefUB(unsigned ArgNo) const {
1700     return paramHasAttr(ArgNo, Attribute::NoUndef) ||
1701            // dereferenceable implies noundef.
1702            paramHasAttr(ArgNo, Attribute::Dereferenceable) ||
1703            // dereferenceable implies noundef, and null is a well-defined value.
1704            paramHasAttr(ArgNo, Attribute::DereferenceableOrNull);
1705   }
1706 
1707   /// Determine if there are is an inalloca argument. Only the last argument can
1708   /// have the inalloca attribute.
1709   bool hasInAllocaArgument() const {
1710     return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca);
1711   }
1712 
1713   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1714   // better indicate that this may return a conservative answer.
1715   bool doesNotAccessMemory(unsigned OpNo) const {
1716     return dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1717   }
1718 
1719   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1720   // better indicate that this may return a conservative answer.
1721   bool onlyReadsMemory(unsigned OpNo) const {
1722     // If the argument is passed byval, the callee does not have access to the
1723     // original pointer and thus cannot write to it.
1724     if (OpNo < arg_size() && isByValArgument(OpNo))
1725       return true;
1726 
1727     return dataOperandHasImpliedAttr(OpNo, Attribute::ReadOnly) ||
1728            dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1729   }
1730 
1731   // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to
1732   // better indicate that this may return a conservative answer.
1733   bool onlyWritesMemory(unsigned OpNo) const {
1734     return dataOperandHasImpliedAttr(OpNo, Attribute::WriteOnly) ||
1735            dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone);
1736   }
1737 
1738   /// Extract the alignment of the return value.
1739   MaybeAlign getRetAlign() const {
1740     if (auto Align = Attrs.getRetAlignment())
1741       return Align;
1742     if (const Function *F = getCalledFunction())
1743       return F->getAttributes().getRetAlignment();
1744     return std::nullopt;
1745   }
1746 
1747   /// Extract the alignment for a call or parameter (0=unknown).
1748   MaybeAlign getParamAlign(unsigned ArgNo) const {
1749     return Attrs.getParamAlignment(ArgNo);
1750   }
1751 
1752   MaybeAlign getParamStackAlign(unsigned ArgNo) const {
1753     return Attrs.getParamStackAlignment(ArgNo);
1754   }
1755 
1756   /// Extract the byref type for a call or parameter.
1757   Type *getParamByRefType(unsigned ArgNo) const {
1758     if (auto *Ty = Attrs.getParamByRefType(ArgNo))
1759       return Ty;
1760     if (const Function *F = getCalledFunction())
1761       return F->getAttributes().getParamByRefType(ArgNo);
1762     return nullptr;
1763   }
1764 
1765   /// Extract the byval type for a call or parameter.
1766   Type *getParamByValType(unsigned ArgNo) const {
1767     if (auto *Ty = Attrs.getParamByValType(ArgNo))
1768       return Ty;
1769     if (const Function *F = getCalledFunction())
1770       return F->getAttributes().getParamByValType(ArgNo);
1771     return nullptr;
1772   }
1773 
1774   /// Extract the preallocated type for a call or parameter.
1775   Type *getParamPreallocatedType(unsigned ArgNo) const {
1776     if (auto *Ty = Attrs.getParamPreallocatedType(ArgNo))
1777       return Ty;
1778     if (const Function *F = getCalledFunction())
1779       return F->getAttributes().getParamPreallocatedType(ArgNo);
1780     return nullptr;
1781   }
1782 
1783   /// Extract the inalloca type for a call or parameter.
1784   Type *getParamInAllocaType(unsigned ArgNo) const {
1785     if (auto *Ty = Attrs.getParamInAllocaType(ArgNo))
1786       return Ty;
1787     if (const Function *F = getCalledFunction())
1788       return F->getAttributes().getParamInAllocaType(ArgNo);
1789     return nullptr;
1790   }
1791 
1792   /// Extract the sret type for a call or parameter.
1793   Type *getParamStructRetType(unsigned ArgNo) const {
1794     if (auto *Ty = Attrs.getParamStructRetType(ArgNo))
1795       return Ty;
1796     if (const Function *F = getCalledFunction())
1797       return F->getAttributes().getParamStructRetType(ArgNo);
1798     return nullptr;
1799   }
1800 
1801   /// Extract the elementtype type for a parameter.
1802   /// Note that elementtype() can only be applied to call arguments, not
1803   /// function declaration parameters.
1804   Type *getParamElementType(unsigned ArgNo) const {
1805     return Attrs.getParamElementType(ArgNo);
1806   }
1807 
1808   /// Extract the number of dereferenceable bytes for a call or
1809   /// parameter (0=unknown).
1810   uint64_t getRetDereferenceableBytes() const {
1811     uint64_t Bytes = Attrs.getRetDereferenceableBytes();
1812     if (const Function *F = getCalledFunction())
1813       Bytes = std::max(Bytes, F->getAttributes().getRetDereferenceableBytes());
1814     return Bytes;
1815   }
1816 
1817   /// Extract the number of dereferenceable bytes for a call or
1818   /// parameter (0=unknown).
1819   uint64_t getParamDereferenceableBytes(unsigned i) const {
1820     return Attrs.getParamDereferenceableBytes(i);
1821   }
1822 
1823   /// Extract the number of dereferenceable_or_null bytes for a call
1824   /// (0=unknown).
1825   uint64_t getRetDereferenceableOrNullBytes() const {
1826     uint64_t Bytes = Attrs.getRetDereferenceableOrNullBytes();
1827     if (const Function *F = getCalledFunction()) {
1828       Bytes = std::max(Bytes,
1829                        F->getAttributes().getRetDereferenceableOrNullBytes());
1830     }
1831 
1832     return Bytes;
1833   }
1834 
1835   /// Extract the number of dereferenceable_or_null bytes for a
1836   /// parameter (0=unknown).
1837   uint64_t getParamDereferenceableOrNullBytes(unsigned i) const {
1838     return Attrs.getParamDereferenceableOrNullBytes(i);
1839   }
1840 
1841   /// Extract a test mask for disallowed floating-point value classes for the
1842   /// return value.
1843   FPClassTest getRetNoFPClass() const;
1844 
1845   /// Extract a test mask for disallowed floating-point value classes for the
1846   /// parameter.
1847   FPClassTest getParamNoFPClass(unsigned i) const;
1848 
1849   /// If this return value has a range attribute, return the value range of the
1850   /// argument. Otherwise, std::nullopt is returned.
1851   std::optional<ConstantRange> getRange() const;
1852 
1853   /// Return true if the return value is known to be not null.
1854   /// This may be because it has the nonnull attribute, or because at least
1855   /// one byte is dereferenceable and the pointer is in addrspace(0).
1856   bool isReturnNonNull() const;
1857 
1858   /// Determine if the return value is marked with NoAlias attribute.
1859   bool returnDoesNotAlias() const {
1860     return Attrs.hasRetAttr(Attribute::NoAlias);
1861   }
1862 
1863   /// If one of the arguments has the 'returned' attribute, returns its
1864   /// operand value. Otherwise, return nullptr.
1865   Value *getReturnedArgOperand() const {
1866     return getArgOperandWithAttribute(Attribute::Returned);
1867   }
1868 
1869   /// If one of the arguments has the specified attribute, returns its
1870   /// operand value. Otherwise, return nullptr.
1871   Value *getArgOperandWithAttribute(Attribute::AttrKind Kind) const;
1872 
1873   /// Return true if the call should not be treated as a call to a
1874   /// builtin.
1875   bool isNoBuiltin() const {
1876     return hasFnAttrImpl(Attribute::NoBuiltin) &&
1877            !hasFnAttrImpl(Attribute::Builtin);
1878   }
1879 
1880   /// Determine if the call requires strict floating point semantics.
1881   bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); }
1882 
1883   /// Return true if the call should not be inlined.
1884   bool isNoInline() const { return hasFnAttr(Attribute::NoInline); }
1885   void setIsNoInline() { addFnAttr(Attribute::NoInline); }
1886 
1887   MemoryEffects getMemoryEffects() const;
1888   void setMemoryEffects(MemoryEffects ME);
1889 
1890   /// Determine if the call does not access memory.
1891   bool doesNotAccessMemory() const;
1892   void setDoesNotAccessMemory();
1893 
1894   /// Determine if the call does not access or only reads memory.
1895   bool onlyReadsMemory() const;
1896   void setOnlyReadsMemory();
1897 
1898   /// Determine if the call does not access or only writes memory.
1899   bool onlyWritesMemory() const;
1900   void setOnlyWritesMemory();
1901 
1902   /// Determine if the call can access memmory only using pointers based
1903   /// on its arguments.
1904   bool onlyAccessesArgMemory() const;
1905   void setOnlyAccessesArgMemory();
1906 
1907   /// Determine if the function may only access memory that is
1908   /// inaccessible from the IR.
1909   bool onlyAccessesInaccessibleMemory() const;
1910   void setOnlyAccessesInaccessibleMemory();
1911 
1912   /// Determine if the function may only access memory that is
1913   /// either inaccessible from the IR or pointed to by its arguments.
1914   bool onlyAccessesInaccessibleMemOrArgMem() const;
1915   void setOnlyAccessesInaccessibleMemOrArgMem();
1916 
1917   /// Determine if the call cannot return.
1918   bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); }
1919   void setDoesNotReturn() { addFnAttr(Attribute::NoReturn); }
1920 
1921   /// Determine if the call should not perform indirect branch tracking.
1922   bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
1923 
1924   /// Determine if the call cannot unwind.
1925   bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
1926   void setDoesNotThrow() { addFnAttr(Attribute::NoUnwind); }
1927 
1928   /// Determine if the invoke cannot be duplicated.
1929   bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); }
1930   void setCannotDuplicate() { addFnAttr(Attribute::NoDuplicate); }
1931 
1932   /// Determine if the call cannot be tail merged.
1933   bool cannotMerge() const { return hasFnAttr(Attribute::NoMerge); }
1934   void setCannotMerge() { addFnAttr(Attribute::NoMerge); }
1935 
1936   /// Determine if the invoke is convergent
1937   bool isConvergent() const { return hasFnAttr(Attribute::Convergent); }
1938   void setConvergent() { addFnAttr(Attribute::Convergent); }
1939   void setNotConvergent() { removeFnAttr(Attribute::Convergent); }
1940 
1941   /// Determine if the call returns a structure through first
1942   /// pointer argument.
1943   bool hasStructRetAttr() const {
1944     if (arg_empty())
1945       return false;
1946 
1947     // Be friendly and also check the callee.
1948     return paramHasAttr(0, Attribute::StructRet);
1949   }
1950 
1951   /// Determine if any call argument is an aggregate passed by value.
1952   bool hasByValArgument() const {
1953     return Attrs.hasAttrSomewhere(Attribute::ByVal);
1954   }
1955 
1956   ///@}
1957   // End of attribute API.
1958 
1959   /// \name Operand Bundle API
1960   ///
1961   /// This group of methods provides the API to access and manipulate operand
1962   /// bundles on this call.
1963   /// @{
1964 
1965   /// Return the number of operand bundles associated with this User.
1966   unsigned getNumOperandBundles() const {
1967     return std::distance(bundle_op_info_begin(), bundle_op_info_end());
1968   }
1969 
1970   /// Return true if this User has any operand bundles.
1971   bool hasOperandBundles() const { return getNumOperandBundles() != 0; }
1972 
1973   /// Return the index of the first bundle operand in the Use array.
1974   unsigned getBundleOperandsStartIndex() const {
1975     assert(hasOperandBundles() && "Don't call otherwise!");
1976     return bundle_op_info_begin()->Begin;
1977   }
1978 
1979   /// Return the index of the last bundle operand in the Use array.
1980   unsigned getBundleOperandsEndIndex() const {
1981     assert(hasOperandBundles() && "Don't call otherwise!");
1982     return bundle_op_info_end()[-1].End;
1983   }
1984 
1985   /// Return true if the operand at index \p Idx is a bundle operand.
1986   bool isBundleOperand(unsigned Idx) const {
1987     return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() &&
1988            Idx < getBundleOperandsEndIndex();
1989   }
1990 
1991   /// Return true if the operand at index \p Idx is a bundle operand that has
1992   /// tag ID \p ID.
1993   bool isOperandBundleOfType(uint32_t ID, unsigned Idx) const {
1994     return isBundleOperand(Idx) &&
1995            getOperandBundleForOperand(Idx).getTagID() == ID;
1996   }
1997 
1998   /// Returns true if the use is a bundle operand.
1999   bool isBundleOperand(const Use *U) const {
2000     assert(this == U->getUser() &&
2001            "Only valid to query with a use of this instruction!");
2002     return hasOperandBundles() && isBundleOperand(U - op_begin());
2003   }
2004   bool isBundleOperand(Value::const_user_iterator UI) const {
2005     return isBundleOperand(&UI.getUse());
2006   }
2007 
2008   /// Return the total number operands (not operand bundles) used by
2009   /// every operand bundle in this OperandBundleUser.
2010   unsigned getNumTotalBundleOperands() const {
2011     if (!hasOperandBundles())
2012       return 0;
2013 
2014     unsigned Begin = getBundleOperandsStartIndex();
2015     unsigned End = getBundleOperandsEndIndex();
2016 
2017     assert(Begin <= End && "Should be!");
2018     return End - Begin;
2019   }
2020 
2021   /// Return the operand bundle at a specific index.
2022   OperandBundleUse getOperandBundleAt(unsigned Index) const {
2023     assert(Index < getNumOperandBundles() && "Index out of bounds!");
2024     return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index));
2025   }
2026 
2027   /// Return the number of operand bundles with the tag Name attached to
2028   /// this instruction.
2029   unsigned countOperandBundlesOfType(StringRef Name) const {
2030     unsigned Count = 0;
2031     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
2032       if (getOperandBundleAt(i).getTagName() == Name)
2033         Count++;
2034 
2035     return Count;
2036   }
2037 
2038   /// Return the number of operand bundles with the tag ID attached to
2039   /// this instruction.
2040   unsigned countOperandBundlesOfType(uint32_t ID) const {
2041     unsigned Count = 0;
2042     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
2043       if (getOperandBundleAt(i).getTagID() == ID)
2044         Count++;
2045 
2046     return Count;
2047   }
2048 
2049   /// Return an operand bundle by name, if present.
2050   ///
2051   /// It is an error to call this for operand bundle types that may have
2052   /// multiple instances of them on the same instruction.
2053   std::optional<OperandBundleUse> getOperandBundle(StringRef Name) const {
2054     assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!");
2055 
2056     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2057       OperandBundleUse U = getOperandBundleAt(i);
2058       if (U.getTagName() == Name)
2059         return U;
2060     }
2061 
2062     return std::nullopt;
2063   }
2064 
2065   /// Return an operand bundle by tag ID, if present.
2066   ///
2067   /// It is an error to call this for operand bundle types that may have
2068   /// multiple instances of them on the same instruction.
2069   std::optional<OperandBundleUse> getOperandBundle(uint32_t ID) const {
2070     assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!");
2071 
2072     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2073       OperandBundleUse U = getOperandBundleAt(i);
2074       if (U.getTagID() == ID)
2075         return U;
2076     }
2077 
2078     return std::nullopt;
2079   }
2080 
2081   /// Return the list of operand bundles attached to this instruction as
2082   /// a vector of OperandBundleDefs.
2083   ///
2084   /// This function copies the OperandBundeUse instances associated with this
2085   /// OperandBundleUser to a vector of OperandBundleDefs.  Note:
2086   /// OperandBundeUses and OperandBundleDefs are non-trivially *different*
2087   /// representations of operand bundles (see documentation above).
2088   void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const;
2089 
2090   /// Return the operand bundle for the operand at index OpIdx.
2091   ///
2092   /// It is an error to call this with an OpIdx that does not correspond to an
2093   /// bundle operand.
2094   OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const {
2095     return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx));
2096   }
2097 
2098   /// Return true if this operand bundle user has operand bundles that
2099   /// may read from the heap.
2100   bool hasReadingOperandBundles() const;
2101 
2102   /// Return true if this operand bundle user has operand bundles that
2103   /// may write to the heap.
2104   bool hasClobberingOperandBundles() const;
2105 
2106   /// Return true if the bundle operand at index \p OpIdx has the
2107   /// attribute \p A.
2108   bool bundleOperandHasAttr(unsigned OpIdx,  Attribute::AttrKind A) const {
2109     auto &BOI = getBundleOpInfoForOperand(OpIdx);
2110     auto OBU = operandBundleFromBundleOpInfo(BOI);
2111     return OBU.operandHasAttr(OpIdx - BOI.Begin, A);
2112   }
2113 
2114   /// Return true if \p Other has the same sequence of operand bundle
2115   /// tags with the same number of operands on each one of them as this
2116   /// OperandBundleUser.
2117   bool hasIdenticalOperandBundleSchema(const CallBase &Other) const {
2118     if (getNumOperandBundles() != Other.getNumOperandBundles())
2119       return false;
2120 
2121     return std::equal(bundle_op_info_begin(), bundle_op_info_end(),
2122                       Other.bundle_op_info_begin());
2123   }
2124 
2125   /// Return true if this operand bundle user contains operand bundles
2126   /// with tags other than those specified in \p IDs.
2127   bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const {
2128     for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) {
2129       uint32_t ID = getOperandBundleAt(i).getTagID();
2130       if (!is_contained(IDs, ID))
2131         return true;
2132     }
2133     return false;
2134   }
2135 
2136   /// Used to keep track of an operand bundle.  See the main comment on
2137   /// OperandBundleUser above.
2138   struct BundleOpInfo {
2139     /// The operand bundle tag, interned by
2140     /// LLVMContextImpl::getOrInsertBundleTag.
2141     StringMapEntry<uint32_t> *Tag;
2142 
2143     /// The index in the Use& vector where operands for this operand
2144     /// bundle starts.
2145     uint32_t Begin;
2146 
2147     /// The index in the Use& vector where operands for this operand
2148     /// bundle ends.
2149     uint32_t End;
2150 
2151     bool operator==(const BundleOpInfo &Other) const {
2152       return Tag == Other.Tag && Begin == Other.Begin && End == Other.End;
2153     }
2154   };
2155 
2156   /// Simple helper function to map a BundleOpInfo to an
2157   /// OperandBundleUse.
2158   OperandBundleUse
2159   operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const {
2160     const auto *begin = op_begin();
2161     ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End);
2162     return OperandBundleUse(BOI.Tag, Inputs);
2163   }
2164 
2165   using bundle_op_iterator = BundleOpInfo *;
2166   using const_bundle_op_iterator = const BundleOpInfo *;
2167 
2168   /// Return the start of the list of BundleOpInfo instances associated
2169   /// with this OperandBundleUser.
2170   ///
2171   /// OperandBundleUser uses the descriptor area co-allocated with the host User
2172   /// to store some meta information about which operands are "normal" operands,
2173   /// and which ones belong to some operand bundle.
2174   ///
2175   /// The layout of an operand bundle user is
2176   ///
2177   ///          +-----------uint32_t End-------------------------------------+
2178   ///          |                                                            |
2179   ///          |  +--------uint32_t Begin--------------------+              |
2180   ///          |  |                                          |              |
2181   ///          ^  ^                                          v              v
2182   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2183   ///  | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un
2184   ///  |------|------|----|----|----|----|----|---------|----|---------|----|-----
2185   ///   v  v                                  ^              ^
2186   ///   |  |                                  |              |
2187   ///   |  +--------uint32_t Begin------------+              |
2188   ///   |                                                    |
2189   ///   +-----------uint32_t End-----------------------------+
2190   ///
2191   ///
2192   /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use
2193   /// list. These descriptions are installed and managed by this class, and
2194   /// they're all instances of OperandBundleUser<T>::BundleOpInfo.
2195   ///
2196   /// DU is an additional descriptor installed by User's 'operator new' to keep
2197   /// track of the 'BOI0 ... BOIN' co-allocation.  OperandBundleUser does not
2198   /// access or modify DU in any way, it's an implementation detail private to
2199   /// User.
2200   ///
2201   /// The regular Use& vector for the User starts at U0.  The operand bundle
2202   /// uses are part of the Use& vector, just like normal uses.  In the diagram
2203   /// above, the operand bundle uses start at BOI0_U0.  Each instance of
2204   /// BundleOpInfo has information about a contiguous set of uses constituting
2205   /// an operand bundle, and the total set of operand bundle uses themselves
2206   /// form a contiguous set of uses (i.e. there are no gaps between uses
2207   /// corresponding to individual operand bundles).
2208   ///
2209   /// This class does not know the location of the set of operand bundle uses
2210   /// within the use list -- that is decided by the User using this class via
2211   /// the BeginIdx argument in populateBundleOperandInfos.
2212   ///
2213   /// Currently operand bundle users with hung-off operands are not supported.
2214   bundle_op_iterator bundle_op_info_begin() {
2215     if (!hasDescriptor())
2216       return nullptr;
2217 
2218     uint8_t *BytesBegin = getDescriptor().begin();
2219     return reinterpret_cast<bundle_op_iterator>(BytesBegin);
2220   }
2221 
2222   /// Return the start of the list of BundleOpInfo instances associated
2223   /// with this OperandBundleUser.
2224   const_bundle_op_iterator bundle_op_info_begin() const {
2225     auto *NonConstThis = const_cast<CallBase *>(this);
2226     return NonConstThis->bundle_op_info_begin();
2227   }
2228 
2229   /// Return the end of the list of BundleOpInfo instances associated
2230   /// with this OperandBundleUser.
2231   bundle_op_iterator bundle_op_info_end() {
2232     if (!hasDescriptor())
2233       return nullptr;
2234 
2235     uint8_t *BytesEnd = getDescriptor().end();
2236     return reinterpret_cast<bundle_op_iterator>(BytesEnd);
2237   }
2238 
2239   /// Return the end of the list of BundleOpInfo instances associated
2240   /// with this OperandBundleUser.
2241   const_bundle_op_iterator bundle_op_info_end() const {
2242     auto *NonConstThis = const_cast<CallBase *>(this);
2243     return NonConstThis->bundle_op_info_end();
2244   }
2245 
2246   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2247   iterator_range<bundle_op_iterator> bundle_op_infos() {
2248     return make_range(bundle_op_info_begin(), bundle_op_info_end());
2249   }
2250 
2251   /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end).
2252   iterator_range<const_bundle_op_iterator> bundle_op_infos() const {
2253     return make_range(bundle_op_info_begin(), bundle_op_info_end());
2254   }
2255 
2256   /// Populate the BundleOpInfo instances and the Use& vector from \p
2257   /// Bundles.  Return the op_iterator pointing to the Use& one past the last
2258   /// last bundle operand use.
2259   ///
2260   /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo
2261   /// instance allocated in this User's descriptor.
2262   op_iterator populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
2263                                          const unsigned BeginIndex);
2264 
2265   /// Return true if the call has deopt state bundle.
2266   bool hasDeoptState() const {
2267     return getOperandBundle(LLVMContext::OB_deopt).has_value();
2268   }
2269 
2270 public:
2271   /// Return the BundleOpInfo for the operand at index OpIdx.
2272   ///
2273   /// It is an error to call this with an OpIdx that does not correspond to an
2274   /// bundle operand.
2275   BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx);
2276   const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const {
2277     return const_cast<CallBase *>(this)->getBundleOpInfoForOperand(OpIdx);
2278   }
2279 
2280 protected:
2281   /// Return the total number of values used in \p Bundles.
2282   static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) {
2283     unsigned Total = 0;
2284     for (const auto &B : Bundles)
2285       Total += B.input_size();
2286     return Total;
2287   }
2288 
2289   /// @}
2290   // End of operand bundle API.
2291 
2292 private:
2293   bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
2294   bool hasFnAttrOnCalledFunction(StringRef Kind) const;
2295 
2296   template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const {
2297     if (Attrs.hasFnAttr(Kind))
2298       return true;
2299 
2300     return hasFnAttrOnCalledFunction(Kind);
2301   }
2302   template <typename AK> Attribute getFnAttrOnCalledFunction(AK Kind) const;
2303   template <typename AK>
2304   Attribute getParamAttrOnCalledFunction(unsigned ArgNo, AK Kind) const;
2305 
2306   /// Determine whether the return value has the given attribute. Supports
2307   /// Attribute::AttrKind and StringRef as \p AttrKind types.
2308   template <typename AttrKind> bool hasRetAttrImpl(AttrKind Kind) const {
2309     if (Attrs.hasRetAttr(Kind))
2310       return true;
2311 
2312     // Look at the callee, if available.
2313     if (const Function *F = getCalledFunction())
2314       return F->getAttributes().hasRetAttr(Kind);
2315     return false;
2316   }
2317 };
2318 
2319 template <>
2320 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase> {};
2321 
2322 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value)
2323 
2324 //===----------------------------------------------------------------------===//
2325 //                           FuncletPadInst Class
2326 //===----------------------------------------------------------------------===//
2327 class FuncletPadInst : public Instruction {
2328 private:
2329   FuncletPadInst(const FuncletPadInst &CPI, AllocInfo AllocInfo);
2330 
2331   explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
2332                           ArrayRef<Value *> Args, AllocInfo AllocInfo,
2333                           const Twine &NameStr, InsertPosition InsertBefore);
2334 
2335   void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr);
2336 
2337 protected:
2338   // Note: Instruction needs to be a friend here to call cloneImpl.
2339   friend class Instruction;
2340   friend class CatchPadInst;
2341   friend class CleanupPadInst;
2342 
2343   FuncletPadInst *cloneImpl() const;
2344 
2345 public:
2346   /// Provide fast operand accessors
2347   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2348 
2349   /// arg_size - Return the number of funcletpad arguments.
2350   ///
2351   unsigned arg_size() const { return getNumOperands() - 1; }
2352 
2353   /// Convenience accessors
2354 
2355   /// Return the outer EH-pad this funclet is nested within.
2356   ///
2357   /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst
2358   /// is a CatchPadInst.
2359   Value *getParentPad() const { return Op<-1>(); }
2360   void setParentPad(Value *ParentPad) {
2361     assert(ParentPad);
2362     Op<-1>() = ParentPad;
2363   }
2364 
2365   /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
2366   ///
2367   Value *getArgOperand(unsigned i) const { return getOperand(i); }
2368   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
2369 
2370   /// arg_operands - iteration adapter for range-for loops.
2371   op_range arg_operands() { return op_range(op_begin(), op_end() - 1); }
2372 
2373   /// arg_operands - iteration adapter for range-for loops.
2374   const_op_range arg_operands() const {
2375     return const_op_range(op_begin(), op_end() - 1);
2376   }
2377 
2378   // Methods for support type inquiry through isa, cast, and dyn_cast:
2379   static bool classof(const Instruction *I) { return I->isFuncletPad(); }
2380   static bool classof(const Value *V) {
2381     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2382   }
2383 };
2384 
2385 template <>
2386 struct OperandTraits<FuncletPadInst>
2387     : public VariadicOperandTraits<FuncletPadInst> {};
2388 
2389 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value)
2390 
2391 } // end namespace llvm
2392 
2393 #endif // LLVM_IR_INSTRTYPES_H