1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines various meta classes of instructions that exist in the VM 10 // representation. Specific concrete subclasses of these may be found in the 11 // i*.h files... 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_IR_INSTRTYPES_H 16 #define LLVM_IR_INSTRTYPES_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/Sequence.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/IR/Attributes.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/FMF.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/OperandTraits.h" 32 #include "llvm/IR/User.h" 33 #include "llvm/Support/Compiler.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstddef> 37 #include <cstdint> 38 #include <iterator> 39 #include <optional> 40 #include <string> 41 #include <vector> 42 43 namespace llvm { 44 45 class StringRef; 46 class Type; 47 class Value; 48 class ConstantRange; 49 50 namespace Intrinsic { 51 typedef unsigned ID; 52 } 53 54 //===----------------------------------------------------------------------===// 55 // UnaryInstruction Class 56 //===----------------------------------------------------------------------===// 57 58 class UnaryInstruction : public Instruction { 59 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1}; 60 61 protected: 62 UnaryInstruction(Type *Ty, unsigned iType, Value *V, 63 InsertPosition InsertBefore = nullptr) Instruction(Ty,iType,AllocMarker,InsertBefore)64 : Instruction(Ty, iType, AllocMarker, InsertBefore) { 65 Op<0>() = V; 66 } 67 68 public: 69 // allocate space for exactly one operand new(size_t S)70 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } delete(void * Ptr)71 void operator delete(void *Ptr) { User::operator delete(Ptr); } 72 73 /// Transparently provide more efficient getOperand methods. 74 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 75 76 // Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Instruction * I)77 static bool classof(const Instruction *I) { 78 return I->isUnaryOp() || I->getOpcode() == Instruction::Alloca || 79 I->getOpcode() == Instruction::Load || 80 I->getOpcode() == Instruction::VAArg || 81 I->getOpcode() == Instruction::ExtractValue || 82 I->getOpcode() == Instruction::Freeze || 83 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd); 84 } classof(const Value * V)85 static bool classof(const Value *V) { 86 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 87 } 88 }; 89 90 template <> 91 struct OperandTraits<UnaryInstruction> : 92 public FixedNumOperandTraits<UnaryInstruction, 1> { 93 }; 94 95 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value) 96 97 //===----------------------------------------------------------------------===// 98 // UnaryOperator Class 99 //===----------------------------------------------------------------------===// 100 101 class UnaryOperator : public UnaryInstruction { 102 void AssertOK(); 103 104 protected: 105 LLVM_ABI UnaryOperator(UnaryOps iType, Value *S, Type *Ty, const Twine &Name, 106 InsertPosition InsertBefore); 107 108 // Note: Instruction needs to be a friend here to call cloneImpl. 109 friend class Instruction; 110 111 LLVM_ABI UnaryOperator *cloneImpl() const; 112 113 public: 114 /// Construct a unary instruction, given the opcode and an operand. 115 /// Optionally (if InstBefore is specified) insert the instruction 116 /// into a BasicBlock right before the specified instruction. The specified 117 /// Instruction is allowed to be a dereferenced end iterator. 118 /// 119 LLVM_ABI static UnaryOperator *Create(UnaryOps Op, Value *S, 120 const Twine &Name = Twine(), 121 InsertPosition InsertBefore = nullptr); 122 123 /// These methods just forward to Create, and are useful when you 124 /// statically know what type of instruction you're going to create. These 125 /// helpers just save some typing. 126 #define HANDLE_UNARY_INST(N, OPC, CLASS) \ 127 static UnaryOperator *Create##OPC(Value *V, const Twine &Name = "") { \ 128 return Create(Instruction::OPC, V, Name); \ 129 } 130 #include "llvm/IR/Instruction.def" 131 #define HANDLE_UNARY_INST(N, OPC, CLASS) \ 132 static UnaryOperator *Create##OPC(Value *V, const Twine &Name, \ 133 InsertPosition InsertBefore = nullptr) { \ 134 return Create(Instruction::OPC, V, Name, InsertBefore); \ 135 } 136 #include "llvm/IR/Instruction.def" 137 138 static UnaryOperator * 139 CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, 140 const Twine &Name = "", 141 InsertPosition InsertBefore = nullptr) { 142 UnaryOperator *UO = Create(Opc, V, Name, InsertBefore); 143 UO->copyIRFlags(CopyO); 144 return UO; 145 } 146 147 static UnaryOperator *CreateFNegFMF(Value *Op, Instruction *FMFSource, 148 const Twine &Name = "", 149 InsertPosition InsertBefore = nullptr) { 150 return CreateWithCopiedFlags(Instruction::FNeg, Op, FMFSource, Name, 151 InsertBefore); 152 } 153 154 UnaryOps getOpcode() const { 155 return static_cast<UnaryOps>(Instruction::getOpcode()); 156 } 157 158 // Methods for support type inquiry through isa, cast, and dyn_cast: 159 static bool classof(const Instruction *I) { 160 return I->isUnaryOp(); 161 } 162 static bool classof(const Value *V) { 163 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 164 } 165 }; 166 167 //===----------------------------------------------------------------------===// 168 // BinaryOperator Class 169 //===----------------------------------------------------------------------===// 170 171 class BinaryOperator : public Instruction { 172 constexpr static IntrusiveOperandsAllocMarker AllocMarker{2}; 173 174 void AssertOK(); 175 176 protected: 177 LLVM_ABI BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, 178 const Twine &Name, InsertPosition InsertBefore); 179 180 // Note: Instruction needs to be a friend here to call cloneImpl. 181 friend class Instruction; 182 183 LLVM_ABI BinaryOperator *cloneImpl() const; 184 185 public: 186 // allocate space for exactly two operands 187 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 188 void operator delete(void *Ptr) { User::operator delete(Ptr); } 189 190 /// Transparently provide more efficient getOperand methods. 191 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 192 193 /// Construct a binary instruction, given the opcode and the two 194 /// operands. Optionally (if InstBefore is specified) insert the instruction 195 /// into a BasicBlock right before the specified instruction. The specified 196 /// Instruction is allowed to be a dereferenced end iterator. 197 /// 198 LLVM_ABI static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, 199 const Twine &Name = Twine(), 200 InsertPosition InsertBefore = nullptr); 201 202 /// These methods just forward to Create, and are useful when you 203 /// statically know what type of instruction you're going to create. These 204 /// helpers just save some typing. 205 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 206 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 207 const Twine &Name = "") { \ 208 return Create(Instruction::OPC, V1, V2, Name); \ 209 } 210 #include "llvm/IR/Instruction.def" 211 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 212 static BinaryOperator *Create##OPC(Value *V1, Value *V2, const Twine &Name, \ 213 InsertPosition InsertBefore) { \ 214 return Create(Instruction::OPC, V1, V2, Name, InsertBefore); \ 215 } 216 #include "llvm/IR/Instruction.def" 217 218 static BinaryOperator * 219 CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, 220 const Twine &Name = "", 221 InsertPosition InsertBefore = nullptr) { 222 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 223 BO->copyIRFlags(CopyO); 224 return BO; 225 } 226 227 static BinaryOperator *CreateWithFMF(BinaryOps Opc, Value *V1, Value *V2, 228 FastMathFlags FMF, 229 const Twine &Name = "", 230 InsertPosition InsertBefore = nullptr) { 231 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 232 BO->setFastMathFlags(FMF); 233 return BO; 234 } 235 236 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, 237 const Twine &Name = "") { 238 return CreateWithFMF(Instruction::FAdd, V1, V2, FMF, Name); 239 } 240 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, 241 const Twine &Name = "") { 242 return CreateWithFMF(Instruction::FSub, V1, V2, FMF, Name); 243 } 244 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, 245 const Twine &Name = "") { 246 return CreateWithFMF(Instruction::FMul, V1, V2, FMF, Name); 247 } 248 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, 249 const Twine &Name = "") { 250 return CreateWithFMF(Instruction::FDiv, V1, V2, FMF, Name); 251 } 252 253 static BinaryOperator *CreateFAddFMF(Value *V1, Value *V2, 254 Instruction *FMFSource, 255 const Twine &Name = "") { 256 return CreateWithCopiedFlags(Instruction::FAdd, V1, V2, FMFSource, Name); 257 } 258 static BinaryOperator *CreateFSubFMF(Value *V1, Value *V2, 259 Instruction *FMFSource, 260 const Twine &Name = "") { 261 return CreateWithCopiedFlags(Instruction::FSub, V1, V2, FMFSource, Name); 262 } 263 static BinaryOperator *CreateFMulFMF(Value *V1, Value *V2, 264 Instruction *FMFSource, 265 const Twine &Name = "") { 266 return CreateWithCopiedFlags(Instruction::FMul, V1, V2, FMFSource, Name); 267 } 268 static BinaryOperator *CreateFDivFMF(Value *V1, Value *V2, 269 Instruction *FMFSource, 270 const Twine &Name = "") { 271 return CreateWithCopiedFlags(Instruction::FDiv, V1, V2, FMFSource, Name); 272 } 273 static BinaryOperator *CreateFRemFMF(Value *V1, Value *V2, 274 Instruction *FMFSource, 275 const Twine &Name = "") { 276 return CreateWithCopiedFlags(Instruction::FRem, V1, V2, FMFSource, Name); 277 } 278 279 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 280 const Twine &Name = "") { 281 BinaryOperator *BO = Create(Opc, V1, V2, Name); 282 BO->setHasNoSignedWrap(true); 283 return BO; 284 } 285 286 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 287 const Twine &Name, 288 InsertPosition InsertBefore) { 289 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 290 BO->setHasNoSignedWrap(true); 291 return BO; 292 } 293 294 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 295 const Twine &Name = "") { 296 BinaryOperator *BO = Create(Opc, V1, V2, Name); 297 BO->setHasNoUnsignedWrap(true); 298 return BO; 299 } 300 301 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 302 const Twine &Name, 303 InsertPosition InsertBefore) { 304 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 305 BO->setHasNoUnsignedWrap(true); 306 return BO; 307 } 308 309 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 310 const Twine &Name = "") { 311 BinaryOperator *BO = Create(Opc, V1, V2, Name); 312 BO->setIsExact(true); 313 return BO; 314 } 315 316 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 317 const Twine &Name, 318 InsertPosition InsertBefore) { 319 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 320 BO->setIsExact(true); 321 return BO; 322 } 323 324 static inline BinaryOperator * 325 CreateDisjoint(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name = ""); 326 static inline BinaryOperator *CreateDisjoint(BinaryOps Opc, Value *V1, 327 Value *V2, const Twine &Name, 328 InsertPosition InsertBefore); 329 330 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \ 331 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \ 332 const Twine &Name = "") { \ 333 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \ 334 } \ 335 static BinaryOperator *Create##NUWNSWEXACT##OPC( \ 336 Value *V1, Value *V2, const Twine &Name, \ 337 InsertPosition InsertBefore = nullptr) { \ 338 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, InsertBefore); \ 339 } 340 341 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd 342 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd 343 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub 344 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub 345 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul 346 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul 347 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl 348 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl 349 350 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv 351 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv 352 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr 353 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr 354 355 DEFINE_HELPERS(Or, Disjoint) // CreateDisjointOr 356 357 #undef DEFINE_HELPERS 358 359 /// Helper functions to construct and inspect unary operations (NEG and NOT) 360 /// via binary operators SUB and XOR: 361 /// 362 /// Create the NEG and NOT instructions out of SUB and XOR instructions. 363 /// 364 LLVM_ABI static BinaryOperator * 365 CreateNeg(Value *Op, const Twine &Name = "", 366 InsertPosition InsertBefore = nullptr); 367 LLVM_ABI static BinaryOperator * 368 CreateNSWNeg(Value *Op, const Twine &Name = "", 369 InsertPosition InsertBefore = nullptr); 370 LLVM_ABI static BinaryOperator * 371 CreateNot(Value *Op, const Twine &Name = "", 372 InsertPosition InsertBefore = nullptr); 373 374 BinaryOps getOpcode() const { 375 return static_cast<BinaryOps>(Instruction::getOpcode()); 376 } 377 378 /// Exchange the two operands to this instruction. 379 /// This instruction is safe to use on any binary instruction and 380 /// does not modify the semantics of the instruction. If the instruction 381 /// cannot be reversed (ie, it's a Div), then return true. 382 /// 383 LLVM_ABI bool swapOperands(); 384 385 // Methods for support type inquiry through isa, cast, and dyn_cast: 386 static bool classof(const Instruction *I) { 387 return I->isBinaryOp(); 388 } 389 static bool classof(const Value *V) { 390 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 391 } 392 }; 393 394 template <> 395 struct OperandTraits<BinaryOperator> : 396 public FixedNumOperandTraits<BinaryOperator, 2> { 397 }; 398 399 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value) 400 401 /// An or instruction, which can be marked as "disjoint", indicating that the 402 /// inputs don't have a 1 in the same bit position. Meaning this instruction 403 /// can also be treated as an add. 404 class PossiblyDisjointInst : public BinaryOperator { 405 public: 406 enum { IsDisjoint = (1 << 0) }; 407 408 void setIsDisjoint(bool B) { 409 SubclassOptionalData = 410 (SubclassOptionalData & ~IsDisjoint) | (B * IsDisjoint); 411 } 412 413 bool isDisjoint() const { return SubclassOptionalData & IsDisjoint; } 414 415 static bool classof(const Instruction *I) { 416 return I->getOpcode() == Instruction::Or; 417 } 418 419 static bool classof(const Value *V) { 420 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 421 } 422 }; 423 424 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1, 425 Value *V2, const Twine &Name) { 426 BinaryOperator *BO = Create(Opc, V1, V2, Name); 427 cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true); 428 return BO; 429 } 430 BinaryOperator *BinaryOperator::CreateDisjoint(BinaryOps Opc, Value *V1, 431 Value *V2, const Twine &Name, 432 InsertPosition InsertBefore) { 433 BinaryOperator *BO = Create(Opc, V1, V2, Name, InsertBefore); 434 cast<PossiblyDisjointInst>(BO)->setIsDisjoint(true); 435 return BO; 436 } 437 438 //===----------------------------------------------------------------------===// 439 // CastInst Class 440 //===----------------------------------------------------------------------===// 441 442 /// This is the base class for all instructions that perform data 443 /// casts. It is simply provided so that instruction category testing 444 /// can be performed with code like: 445 /// 446 /// if (isa<CastInst>(Instr)) { ... } 447 /// Base class of casting instructions. 448 class CastInst : public UnaryInstruction { 449 protected: 450 /// Constructor with insert-before-instruction semantics for subclasses 451 CastInst(Type *Ty, unsigned iType, Value *S, const Twine &NameStr = "", 452 InsertPosition InsertBefore = nullptr) 453 : UnaryInstruction(Ty, iType, S, InsertBefore) { 454 setName(NameStr); 455 } 456 457 public: 458 /// Provides a way to construct any of the CastInst subclasses using an 459 /// opcode instead of the subclass's constructor. The opcode must be in the 460 /// CastOps category (Instruction::isCast(opcode) returns true). This 461 /// constructor has insert-before-instruction semantics to automatically 462 /// insert the new CastInst before InsertBefore (if it is non-null). 463 /// Construct any of the CastInst subclasses 464 LLVM_ABI static CastInst *Create( 465 Instruction::CastOps, ///< The opcode of the cast instruction 466 Value *S, ///< The value to be casted (operand 0) 467 Type *Ty, ///< The type to which cast should be made 468 const Twine &Name = "", ///< Name for the instruction 469 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 470 ); 471 472 /// Create a ZExt or BitCast cast instruction 473 LLVM_ABI static CastInst *CreateZExtOrBitCast( 474 Value *S, ///< The value to be casted (operand 0) 475 Type *Ty, ///< The type to which cast should be made 476 const Twine &Name = "", ///< Name for the instruction 477 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 478 ); 479 480 /// Create a SExt or BitCast cast instruction 481 LLVM_ABI static CastInst *CreateSExtOrBitCast( 482 Value *S, ///< The value to be casted (operand 0) 483 Type *Ty, ///< The type to which cast should be made 484 const Twine &Name = "", ///< Name for the instruction 485 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 486 ); 487 488 /// Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction. 489 LLVM_ABI static CastInst *CreatePointerCast( 490 Value *S, ///< The pointer value to be casted (operand 0) 491 Type *Ty, ///< The type to which cast should be made 492 const Twine &Name = "", ///< Name for the instruction 493 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 494 ); 495 496 /// Create a BitCast or an AddrSpaceCast cast instruction. 497 LLVM_ABI static CastInst *CreatePointerBitCastOrAddrSpaceCast( 498 Value *S, ///< The pointer value to be casted (operand 0) 499 Type *Ty, ///< The type to which cast should be made 500 const Twine &Name = "", ///< Name for the instruction 501 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 502 ); 503 504 /// Create a BitCast, a PtrToInt, or an IntToPTr cast instruction. 505 /// 506 /// If the value is a pointer type and the destination an integer type, 507 /// creates a PtrToInt cast. If the value is an integer type and the 508 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates 509 /// a bitcast. 510 LLVM_ABI static CastInst *CreateBitOrPointerCast( 511 Value *S, ///< The pointer value to be casted (operand 0) 512 Type *Ty, ///< The type to which cast should be made 513 const Twine &Name = "", ///< Name for the instruction 514 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 515 ); 516 517 /// Create a ZExt, BitCast, or Trunc for int -> int casts. 518 LLVM_ABI static CastInst *CreateIntegerCast( 519 Value *S, ///< The pointer value to be casted (operand 0) 520 Type *Ty, ///< The type to which cast should be made 521 bool isSigned, ///< Whether to regard S as signed or not 522 const Twine &Name = "", ///< Name for the instruction 523 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 524 ); 525 526 /// Create an FPExt, BitCast, or FPTrunc for fp -> fp casts 527 LLVM_ABI static CastInst *CreateFPCast( 528 Value *S, ///< The floating point value to be casted 529 Type *Ty, ///< The floating point type to cast to 530 const Twine &Name = "", ///< Name for the instruction 531 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 532 ); 533 534 /// Create a Trunc or BitCast cast instruction 535 LLVM_ABI static CastInst *CreateTruncOrBitCast( 536 Value *S, ///< The value to be casted (operand 0) 537 Type *Ty, ///< The type to which cast should be made 538 const Twine &Name = "", ///< Name for the instruction 539 InsertPosition InsertBefore = nullptr ///< Place to insert the instruction 540 ); 541 542 /// Check whether a bitcast between these types is valid 543 LLVM_ABI static bool 544 isBitCastable(Type *SrcTy, ///< The Type from which the value should be cast. 545 Type *DestTy ///< The Type to which the value should be cast. 546 ); 547 548 /// Check whether a bitcast, inttoptr, or ptrtoint cast between these 549 /// types is valid and a no-op. 550 /// 551 /// This ensures that any pointer<->integer cast has enough bits in the 552 /// integer and any other cast is a bitcast. 553 LLVM_ABI static bool isBitOrNoopPointerCastable( 554 Type *SrcTy, ///< The Type from which the value should be cast. 555 Type *DestTy, ///< The Type to which the value should be cast. 556 const DataLayout &DL); 557 558 /// Returns the opcode necessary to cast Val into Ty using usual casting 559 /// rules. 560 /// Infer the opcode for cast operand and type 561 LLVM_ABI static Instruction::CastOps 562 getCastOpcode(const Value *Val, ///< The value to cast 563 bool SrcIsSigned, ///< Whether to treat the source as signed 564 Type *Ty, ///< The Type to which the value should be casted 565 bool DstIsSigned ///< Whether to treate the dest. as signed 566 ); 567 568 /// There are several places where we need to know if a cast instruction 569 /// only deals with integer source and destination types. To simplify that 570 /// logic, this method is provided. 571 /// @returns true iff the cast has only integral typed operand and dest type. 572 /// Determine if this is an integer-only cast. 573 LLVM_ABI bool isIntegerCast() const; 574 575 /// A no-op cast is one that can be effected without changing any bits. 576 /// It implies that the source and destination types are the same size. The 577 /// DataLayout argument is to determine the pointer size when examining casts 578 /// involving Integer and Pointer types. They are no-op casts if the integer 579 /// is the same size as the pointer. However, pointer size varies with 580 /// platform. Note that a precondition of this method is that the cast is 581 /// legal - i.e. the instruction formed with these operands would verify. 582 LLVM_ABI static bool 583 isNoopCast(Instruction::CastOps Opcode, ///< Opcode of cast 584 Type *SrcTy, ///< SrcTy of cast 585 Type *DstTy, ///< DstTy of cast 586 const DataLayout &DL ///< DataLayout to get the Int Ptr type from. 587 ); 588 589 /// Determine if this cast is a no-op cast. 590 /// 591 /// \param DL is the DataLayout to determine pointer size. 592 LLVM_ABI bool isNoopCast(const DataLayout &DL) const; 593 594 /// Determine how a pair of casts can be eliminated, if they can be at all. 595 /// This is a helper function for both CastInst and ConstantExpr. 596 /// @returns 0 if the CastInst pair can't be eliminated, otherwise 597 /// returns Instruction::CastOps value for a cast that can replace 598 /// the pair, casting SrcTy to DstTy. 599 /// Determine if a cast pair is eliminable 600 LLVM_ABI static unsigned isEliminableCastPair( 601 Instruction::CastOps firstOpcode, ///< Opcode of first cast 602 Instruction::CastOps secondOpcode, ///< Opcode of second cast 603 Type *SrcTy, ///< SrcTy of 1st cast 604 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast 605 Type *DstTy, ///< DstTy of 2nd cast 606 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null 607 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null 608 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null 609 ); 610 611 /// Return the opcode of this CastInst 612 Instruction::CastOps getOpcode() const { 613 return Instruction::CastOps(Instruction::getOpcode()); 614 } 615 616 /// Return the source type, as a convenience 617 Type* getSrcTy() const { return getOperand(0)->getType(); } 618 /// Return the destination type, as a convenience 619 Type* getDestTy() const { return getType(); } 620 621 /// This method can be used to determine if a cast from SrcTy to DstTy using 622 /// Opcode op is valid or not. 623 /// @returns true iff the proposed cast is valid. 624 /// Determine if a cast is valid without creating one. 625 LLVM_ABI static bool castIsValid(Instruction::CastOps op, Type *SrcTy, 626 Type *DstTy); 627 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 628 return castIsValid(op, S->getType(), DstTy); 629 } 630 631 /// Methods for support type inquiry through isa, cast, and dyn_cast: 632 static bool classof(const Instruction *I) { 633 return I->isCast(); 634 } 635 static bool classof(const Value *V) { 636 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 637 } 638 }; 639 640 /// Instruction that can have a nneg flag (zext/uitofp). 641 class PossiblyNonNegInst : public CastInst { 642 public: 643 enum { NonNeg = (1 << 0) }; 644 645 static bool classof(const Instruction *I) { 646 switch (I->getOpcode()) { 647 case Instruction::ZExt: 648 case Instruction::UIToFP: 649 return true; 650 default: 651 return false; 652 } 653 } 654 655 static bool classof(const Value *V) { 656 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 657 } 658 }; 659 660 //===----------------------------------------------------------------------===// 661 // CmpInst Class 662 //===----------------------------------------------------------------------===// 663 664 /// This class is the base class for the comparison instructions. 665 /// Abstract base class of comparison instructions. 666 class CmpInst : public Instruction { 667 constexpr static IntrusiveOperandsAllocMarker AllocMarker{2}; 668 669 public: 670 /// This enumeration lists the possible predicates for CmpInst subclasses. 671 /// Values in the range 0-31 are reserved for FCmpInst, while values in the 672 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the 673 /// predicate values are not overlapping between the classes. 674 /// 675 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of 676 /// FCMP_* values. Changing the bit patterns requires a potential change to 677 /// those passes. 678 enum Predicate : unsigned { 679 // Opcode U L G E Intuitive operation 680 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded) 681 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal 682 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than 683 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal 684 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than 685 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal 686 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal 687 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans) 688 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y) 689 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal 690 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than 691 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal 692 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than 693 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal 694 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal 695 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded) 696 FIRST_FCMP_PREDICATE = FCMP_FALSE, 697 LAST_FCMP_PREDICATE = FCMP_TRUE, 698 BAD_FCMP_PREDICATE = FCMP_TRUE + 1, 699 ICMP_EQ = 32, ///< equal 700 ICMP_NE = 33, ///< not equal 701 ICMP_UGT = 34, ///< unsigned greater than 702 ICMP_UGE = 35, ///< unsigned greater or equal 703 ICMP_ULT = 36, ///< unsigned less than 704 ICMP_ULE = 37, ///< unsigned less or equal 705 ICMP_SGT = 38, ///< signed greater than 706 ICMP_SGE = 39, ///< signed greater or equal 707 ICMP_SLT = 40, ///< signed less than 708 ICMP_SLE = 41, ///< signed less or equal 709 FIRST_ICMP_PREDICATE = ICMP_EQ, 710 LAST_ICMP_PREDICATE = ICMP_SLE, 711 BAD_ICMP_PREDICATE = ICMP_SLE + 1 712 }; 713 using PredicateField = 714 Bitfield::Element<Predicate, 0, 6, LAST_ICMP_PREDICATE>; 715 716 /// Returns the sequence of all FCmp predicates. 717 static auto FCmpPredicates() { 718 return enum_seq_inclusive(Predicate::FIRST_FCMP_PREDICATE, 719 Predicate::LAST_FCMP_PREDICATE, 720 force_iteration_on_noniterable_enum); 721 } 722 723 /// Returns the sequence of all ICmp predicates. 724 static auto ICmpPredicates() { 725 return enum_seq_inclusive(Predicate::FIRST_ICMP_PREDICATE, 726 Predicate::LAST_ICMP_PREDICATE, 727 force_iteration_on_noniterable_enum); 728 } 729 730 protected: 731 LLVM_ABI CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, 732 Value *LHS, Value *RHS, const Twine &Name = "", 733 InsertPosition InsertBefore = nullptr, 734 Instruction *FlagsSource = nullptr); 735 736 public: 737 // allocate space for exactly two operands 738 void *operator new(size_t S) { return User::operator new(S, AllocMarker); } 739 void operator delete(void *Ptr) { User::operator delete(Ptr); } 740 741 /// Construct a compare instruction, given the opcode, the predicate and 742 /// the two operands. Optionally (if InstBefore is specified) insert the 743 /// instruction into a BasicBlock right before the specified instruction. 744 /// The specified Instruction is allowed to be a dereferenced end iterator. 745 /// Create a CmpInst 746 LLVM_ABI static CmpInst *Create(OtherOps Op, Predicate Pred, Value *S1, 747 Value *S2, const Twine &Name = "", 748 InsertPosition InsertBefore = nullptr); 749 750 /// Construct a compare instruction, given the opcode, the predicate, 751 /// the two operands and the instruction to copy the flags from. Optionally 752 /// (if InstBefore is specified) insert the instruction into a BasicBlock 753 /// right before the specified instruction. The specified Instruction is 754 /// allowed to be a dereferenced end iterator. 755 /// Create a CmpInst 756 LLVM_ABI static CmpInst * 757 CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, 758 const Instruction *FlagsSource, const Twine &Name = "", 759 InsertPosition InsertBefore = nullptr); 760 761 /// Get the opcode casted to the right type 762 OtherOps getOpcode() const { 763 return static_cast<OtherOps>(Instruction::getOpcode()); 764 } 765 766 /// Return the predicate for this instruction. 767 Predicate getPredicate() const { return getSubclassData<PredicateField>(); } 768 769 /// Set the predicate for this instruction to the specified value. 770 void setPredicate(Predicate P) { setSubclassData<PredicateField>(P); } 771 772 static bool isFPPredicate(Predicate P) { 773 static_assert(FIRST_FCMP_PREDICATE == 0, 774 "FIRST_FCMP_PREDICATE is required to be 0"); 775 return P <= LAST_FCMP_PREDICATE; 776 } 777 778 static bool isIntPredicate(Predicate P) { 779 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE; 780 } 781 782 LLVM_ABI static StringRef getPredicateName(Predicate P); 783 784 bool isFPPredicate() const { return isFPPredicate(getPredicate()); } 785 bool isIntPredicate() const { return isIntPredicate(getPredicate()); } 786 787 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 788 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 789 /// @returns the inverse predicate for the instruction's current predicate. 790 /// Return the inverse of the instruction's predicate. 791 Predicate getInversePredicate() const { 792 return getInversePredicate(getPredicate()); 793 } 794 795 /// Returns the ordered variant of a floating point compare. 796 /// 797 /// For example, UEQ -> OEQ, ULT -> OLT, OEQ -> OEQ 798 static Predicate getOrderedPredicate(Predicate Pred) { 799 return static_cast<Predicate>(Pred & FCMP_ORD); 800 } 801 802 Predicate getOrderedPredicate() const { 803 return getOrderedPredicate(getPredicate()); 804 } 805 806 /// Returns the unordered variant of a floating point compare. 807 /// 808 /// For example, OEQ -> UEQ, OLT -> ULT, OEQ -> UEQ 809 static Predicate getUnorderedPredicate(Predicate Pred) { 810 return static_cast<Predicate>(Pred | FCMP_UNO); 811 } 812 813 Predicate getUnorderedPredicate() const { 814 return getUnorderedPredicate(getPredicate()); 815 } 816 817 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 818 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 819 /// @returns the inverse predicate for predicate provided in \p pred. 820 /// Return the inverse of a given predicate 821 LLVM_ABI static Predicate getInversePredicate(Predicate pred); 822 823 /// For example, EQ->EQ, SLE->SGE, ULT->UGT, 824 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc. 825 /// @returns the predicate that would be the result of exchanging the two 826 /// operands of the CmpInst instruction without changing the result 827 /// produced. 828 /// Return the predicate as if the operands were swapped 829 Predicate getSwappedPredicate() const { 830 return getSwappedPredicate(getPredicate()); 831 } 832 833 /// This is a static version that you can use without an instruction 834 /// available. 835 /// Return the predicate as if the operands were swapped. 836 LLVM_ABI static Predicate getSwappedPredicate(Predicate pred); 837 838 /// This is a static version that you can use without an instruction 839 /// available. 840 /// @returns true if the comparison predicate is strict, false otherwise. 841 LLVM_ABI static bool isStrictPredicate(Predicate predicate); 842 843 /// @returns true if the comparison predicate is strict, false otherwise. 844 /// Determine if this instruction is using an strict comparison predicate. 845 bool isStrictPredicate() const { return isStrictPredicate(getPredicate()); } 846 847 /// This is a static version that you can use without an instruction 848 /// available. 849 /// @returns true if the comparison predicate is non-strict, false otherwise. 850 LLVM_ABI static bool isNonStrictPredicate(Predicate predicate); 851 852 /// @returns true if the comparison predicate is non-strict, false otherwise. 853 /// Determine if this instruction is using an non-strict comparison predicate. 854 bool isNonStrictPredicate() const { 855 return isNonStrictPredicate(getPredicate()); 856 } 857 858 /// For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT. 859 /// Returns the strict version of non-strict comparisons. 860 Predicate getStrictPredicate() const { 861 return getStrictPredicate(getPredicate()); 862 } 863 864 /// This is a static version that you can use without an instruction 865 /// available. 866 /// @returns the strict version of comparison provided in \p pred. 867 /// If \p pred is not a strict comparison predicate, returns \p pred. 868 /// Returns the strict version of non-strict comparisons. 869 LLVM_ABI static Predicate getStrictPredicate(Predicate pred); 870 871 /// For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE. 872 /// Returns the non-strict version of strict comparisons. 873 Predicate getNonStrictPredicate() const { 874 return getNonStrictPredicate(getPredicate()); 875 } 876 877 /// This is a static version that you can use without an instruction 878 /// available. 879 /// @returns the non-strict version of comparison provided in \p pred. 880 /// If \p pred is not a strict comparison predicate, returns \p pred. 881 /// Returns the non-strict version of strict comparisons. 882 LLVM_ABI static Predicate getNonStrictPredicate(Predicate pred); 883 884 /// This is a static version that you can use without an instruction 885 /// available. 886 /// Return the flipped strictness of predicate 887 LLVM_ABI static Predicate getFlippedStrictnessPredicate(Predicate pred); 888 889 /// For predicate of kind "is X or equal to 0" returns the predicate "is X". 890 /// For predicate of kind "is X" returns the predicate "is X or equal to 0". 891 /// does not support other kind of predicates. 892 /// @returns the predicate that does not contains is equal to zero if 893 /// it had and vice versa. 894 /// Return the flipped strictness of predicate 895 Predicate getFlippedStrictnessPredicate() const { 896 return getFlippedStrictnessPredicate(getPredicate()); 897 } 898 899 /// Provide more efficient getOperand methods. 900 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 901 902 /// This is just a convenience that dispatches to the subclasses. 903 /// Swap the operands and adjust predicate accordingly to retain 904 /// the same comparison. 905 LLVM_ABI void swapOperands(); 906 907 /// This is just a convenience that dispatches to the subclasses. 908 /// Determine if this CmpInst is commutative. 909 LLVM_ABI bool isCommutative() const; 910 911 /// Determine if this is an equals/not equals predicate. 912 /// This is a static version that you can use without an instruction 913 /// available. 914 LLVM_ABI static bool isEquality(Predicate pred); 915 916 /// Determine if this is an equals/not equals predicate. 917 bool isEquality() const { return isEquality(getPredicate()); } 918 919 /// Determine if one operand of this compare can always be replaced by the 920 /// other operand, ignoring provenance considerations. If \p Invert, check for 921 /// equivalence with the inverse predicate. 922 LLVM_ABI bool isEquivalence(bool Invert = false) const; 923 924 /// Return true if the predicate is relational (not EQ or NE). 925 static bool isRelational(Predicate P) { return !isEquality(P); } 926 927 /// Return true if the predicate is relational (not EQ or NE). 928 bool isRelational() const { return !isEquality(); } 929 930 /// @returns true if the comparison is signed, false otherwise. 931 /// Determine if this instruction is using a signed comparison. 932 bool isSigned() const { 933 return isSigned(getPredicate()); 934 } 935 936 /// @returns true if the comparison is unsigned, false otherwise. 937 /// Determine if this instruction is using an unsigned comparison. 938 bool isUnsigned() const { 939 return isUnsigned(getPredicate()); 940 } 941 942 /// This is just a convenience. 943 /// Determine if this is true when both operands are the same. 944 bool isTrueWhenEqual() const { 945 return isTrueWhenEqual(getPredicate()); 946 } 947 948 /// This is just a convenience. 949 /// Determine if this is false when both operands are the same. 950 bool isFalseWhenEqual() const { 951 return isFalseWhenEqual(getPredicate()); 952 } 953 954 /// @returns true if the predicate is unsigned, false otherwise. 955 /// Determine if the predicate is an unsigned operation. 956 LLVM_ABI static bool isUnsigned(Predicate predicate); 957 958 /// @returns true if the predicate is signed, false otherwise. 959 /// Determine if the predicate is an signed operation. 960 LLVM_ABI static bool isSigned(Predicate predicate); 961 962 /// Determine if the predicate is an ordered operation. 963 LLVM_ABI static bool isOrdered(Predicate predicate); 964 965 /// Determine if the predicate is an unordered operation. 966 LLVM_ABI static bool isUnordered(Predicate predicate); 967 968 /// Determine if the predicate is true when comparing a value with itself. 969 LLVM_ABI static bool isTrueWhenEqual(Predicate predicate); 970 971 /// Determine if the predicate is false when comparing a value with itself. 972 LLVM_ABI static bool isFalseWhenEqual(Predicate predicate); 973 974 /// Methods for support type inquiry through isa, cast, and dyn_cast: 975 static bool classof(const Instruction *I) { 976 return I->getOpcode() == Instruction::ICmp || 977 I->getOpcode() == Instruction::FCmp; 978 } 979 static bool classof(const Value *V) { 980 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 981 } 982 983 /// Create a result type for fcmp/icmp 984 static Type* makeCmpResultType(Type* opnd_type) { 985 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) { 986 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()), 987 vt->getElementCount()); 988 } 989 return Type::getInt1Ty(opnd_type->getContext()); 990 } 991 992 private: 993 // Shadow Value::setValueSubclassData with a private forwarding method so that 994 // subclasses cannot accidentally use it. 995 void setValueSubclassData(unsigned short D) { 996 Value::setValueSubclassData(D); 997 } 998 }; 999 1000 // FIXME: these are redundant if CmpInst < BinaryOperator 1001 template <> 1002 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> { 1003 }; 1004 1005 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value) 1006 1007 LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, CmpInst::Predicate Pred); 1008 1009 /// A lightweight accessor for an operand bundle meant to be passed 1010 /// around by value. 1011 struct OperandBundleUse { 1012 ArrayRef<Use> Inputs; 1013 1014 OperandBundleUse() = default; 1015 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs) 1016 : Inputs(Inputs), Tag(Tag) {} 1017 1018 /// Return true if the operand at index \p Idx in this operand bundle 1019 /// has the attribute A. 1020 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const { 1021 if (isDeoptOperandBundle()) 1022 if (A == Attribute::ReadOnly) 1023 return Inputs[Idx]->getType()->isPointerTy(); 1024 1025 // Conservative answer: no operands have any attributes. 1026 return false; 1027 } 1028 1029 /// Return the tag of this operand bundle as a string. 1030 StringRef getTagName() const { 1031 return Tag->getKey(); 1032 } 1033 1034 /// Return the tag of this operand bundle as an integer. 1035 /// 1036 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag, 1037 /// and this function returns the unique integer getOrInsertBundleTag 1038 /// associated the tag of this operand bundle to. 1039 uint32_t getTagID() const { 1040 return Tag->getValue(); 1041 } 1042 1043 /// Return true if this is a "deopt" operand bundle. 1044 bool isDeoptOperandBundle() const { 1045 return getTagID() == LLVMContext::OB_deopt; 1046 } 1047 1048 /// Return true if this is a "funclet" operand bundle. 1049 bool isFuncletOperandBundle() const { 1050 return getTagID() == LLVMContext::OB_funclet; 1051 } 1052 1053 /// Return true if this is a "cfguardtarget" operand bundle. 1054 bool isCFGuardTargetOperandBundle() const { 1055 return getTagID() == LLVMContext::OB_cfguardtarget; 1056 } 1057 1058 private: 1059 /// Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag. 1060 StringMapEntry<uint32_t> *Tag; 1061 }; 1062 1063 /// A container for an operand bundle being viewed as a set of values 1064 /// rather than a set of uses. 1065 /// 1066 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and 1067 /// so it is possible to create and pass around "self-contained" instances of 1068 /// OperandBundleDef and ConstOperandBundleDef. 1069 template <typename InputTy> class OperandBundleDefT { 1070 std::string Tag; 1071 std::vector<InputTy> Inputs; 1072 1073 public: 1074 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs) 1075 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {} 1076 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs) 1077 : Tag(std::move(Tag)), Inputs(Inputs) {} 1078 1079 explicit OperandBundleDefT(const OperandBundleUse &OBU) { 1080 Tag = std::string(OBU.getTagName()); 1081 llvm::append_range(Inputs, OBU.Inputs); 1082 } 1083 1084 ArrayRef<InputTy> inputs() const { return Inputs; } 1085 1086 using input_iterator = typename std::vector<InputTy>::const_iterator; 1087 1088 size_t input_size() const { return Inputs.size(); } 1089 input_iterator input_begin() const { return Inputs.begin(); } 1090 input_iterator input_end() const { return Inputs.end(); } 1091 1092 StringRef getTag() const { return Tag; } 1093 }; 1094 1095 using OperandBundleDef = OperandBundleDefT<Value *>; 1096 using ConstOperandBundleDef = OperandBundleDefT<const Value *>; 1097 1098 //===----------------------------------------------------------------------===// 1099 // CallBase Class 1100 //===----------------------------------------------------------------------===// 1101 1102 /// Base class for all callable instructions (InvokeInst and CallInst) 1103 /// Holds everything related to calling a function. 1104 /// 1105 /// All call-like instructions are required to use a common operand layout: 1106 /// - Zero or more arguments to the call, 1107 /// - Zero or more operand bundles with zero or more operand inputs each 1108 /// bundle, 1109 /// - Zero or more subclass controlled operands 1110 /// - The called function. 1111 /// 1112 /// This allows this base class to easily access the called function and the 1113 /// start of the arguments without knowing how many other operands a particular 1114 /// subclass requires. Note that accessing the end of the argument list isn't 1115 /// as cheap as most other operations on the base class. 1116 class CallBase : public Instruction { 1117 protected: 1118 // The first two bits are reserved by CallInst for fast retrieval, 1119 using CallInstReservedField = Bitfield::Element<unsigned, 0, 2>; 1120 using CallingConvField = 1121 Bitfield::Element<CallingConv::ID, CallInstReservedField::NextBit, 10, 1122 CallingConv::MaxID>; 1123 static_assert( 1124 Bitfield::areContiguous<CallInstReservedField, CallingConvField>(), 1125 "Bitfields must be contiguous"); 1126 1127 /// The last operand is the called operand. 1128 static constexpr int CalledOperandOpEndIdx = -1; 1129 1130 AttributeList Attrs; ///< parameter attributes for callable 1131 FunctionType *FTy; 1132 1133 template <class... ArgsTy> 1134 CallBase(AttributeList const &A, FunctionType *FT, ArgsTy &&... Args) 1135 : Instruction(std::forward<ArgsTy>(Args)...), Attrs(A), FTy(FT) {} 1136 1137 using Instruction::Instruction; 1138 1139 bool hasDescriptor() const { return Value::HasDescriptor; } 1140 1141 unsigned getNumSubclassExtraOperands() const { 1142 switch (getOpcode()) { 1143 case Instruction::Call: 1144 return 0; 1145 case Instruction::Invoke: 1146 return 2; 1147 case Instruction::CallBr: 1148 return getNumSubclassExtraOperandsDynamic(); 1149 } 1150 llvm_unreachable("Invalid opcode!"); 1151 } 1152 1153 /// Get the number of extra operands for instructions that don't have a fixed 1154 /// number of extra operands. 1155 LLVM_ABI unsigned getNumSubclassExtraOperandsDynamic() const; 1156 1157 public: 1158 using Instruction::getContext; 1159 1160 /// Create a clone of \p CB with a different set of operand bundles and 1161 /// insert it before \p InsertPt. 1162 /// 1163 /// The returned call instruction is identical \p CB in every way except that 1164 /// the operand bundles for the new instruction are set to the operand bundles 1165 /// in \p Bundles. 1166 LLVM_ABI static CallBase *Create(CallBase *CB, 1167 ArrayRef<OperandBundleDef> Bundles, 1168 InsertPosition InsertPt = nullptr); 1169 1170 /// Create a clone of \p CB with the operand bundle with the tag matching 1171 /// \p Bundle's tag replaced with Bundle, and insert it before \p InsertPt. 1172 /// 1173 /// The returned call instruction is identical \p CI in every way except that 1174 /// the specified operand bundle has been replaced. 1175 LLVM_ABI static CallBase *Create(CallBase *CB, OperandBundleDef Bundle, 1176 InsertPosition InsertPt = nullptr); 1177 1178 /// Create a clone of \p CB with operand bundle \p OB added. 1179 LLVM_ABI static CallBase *addOperandBundle(CallBase *CB, uint32_t ID, 1180 OperandBundleDef OB, 1181 InsertPosition InsertPt = nullptr); 1182 1183 /// Create a clone of \p CB with operand bundle \p ID removed. 1184 LLVM_ABI static CallBase * 1185 removeOperandBundle(CallBase *CB, uint32_t ID, 1186 InsertPosition InsertPt = nullptr); 1187 1188 /// Return the convergence control token for this call, if it exists. 1189 Value *getConvergenceControlToken() const { 1190 if (auto Bundle = getOperandBundle(llvm::LLVMContext::OB_convergencectrl)) { 1191 return Bundle->Inputs[0].get(); 1192 } 1193 return nullptr; 1194 } 1195 1196 static bool classof(const Instruction *I) { 1197 return I->getOpcode() == Instruction::Call || 1198 I->getOpcode() == Instruction::Invoke || 1199 I->getOpcode() == Instruction::CallBr; 1200 } 1201 static bool classof(const Value *V) { 1202 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1203 } 1204 1205 FunctionType *getFunctionType() const { return FTy; } 1206 1207 void mutateFunctionType(FunctionType *FTy) { 1208 Value::mutateType(FTy->getReturnType()); 1209 this->FTy = FTy; 1210 } 1211 1212 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 1213 1214 /// data_operands_begin/data_operands_end - Return iterators iterating over 1215 /// the call / invoke argument list and bundle operands. For invokes, this is 1216 /// the set of instruction operands except the invoke target and the two 1217 /// successor blocks; and for calls this is the set of instruction operands 1218 /// except the call target. 1219 User::op_iterator data_operands_begin() { return op_begin(); } 1220 User::const_op_iterator data_operands_begin() const { 1221 return const_cast<CallBase *>(this)->data_operands_begin(); 1222 } 1223 User::op_iterator data_operands_end() { 1224 // Walk from the end of the operands over the called operand and any 1225 // subclass operands. 1226 return op_end() - getNumSubclassExtraOperands() - 1; 1227 } 1228 User::const_op_iterator data_operands_end() const { 1229 return const_cast<CallBase *>(this)->data_operands_end(); 1230 } 1231 iterator_range<User::op_iterator> data_ops() { 1232 return make_range(data_operands_begin(), data_operands_end()); 1233 } 1234 iterator_range<User::const_op_iterator> data_ops() const { 1235 return make_range(data_operands_begin(), data_operands_end()); 1236 } 1237 bool data_operands_empty() const { 1238 return data_operands_end() == data_operands_begin(); 1239 } 1240 unsigned data_operands_size() const { 1241 return std::distance(data_operands_begin(), data_operands_end()); 1242 } 1243 1244 bool isDataOperand(const Use *U) const { 1245 assert(this == U->getUser() && 1246 "Only valid to query with a use of this instruction!"); 1247 return data_operands_begin() <= U && U < data_operands_end(); 1248 } 1249 bool isDataOperand(Value::const_user_iterator UI) const { 1250 return isDataOperand(&UI.getUse()); 1251 } 1252 1253 /// Given a value use iterator, return the data operand corresponding to it. 1254 /// Iterator must actually correspond to a data operand. 1255 unsigned getDataOperandNo(Value::const_user_iterator UI) const { 1256 return getDataOperandNo(&UI.getUse()); 1257 } 1258 1259 /// Given a use for a data operand, get the data operand number that 1260 /// corresponds to it. 1261 unsigned getDataOperandNo(const Use *U) const { 1262 assert(isDataOperand(U) && "Data operand # out of range!"); 1263 return U - data_operands_begin(); 1264 } 1265 1266 /// Return the iterator pointing to the beginning of the argument list. 1267 User::op_iterator arg_begin() { return op_begin(); } 1268 User::const_op_iterator arg_begin() const { 1269 return const_cast<CallBase *>(this)->arg_begin(); 1270 } 1271 1272 /// Return the iterator pointing to the end of the argument list. 1273 User::op_iterator arg_end() { 1274 // From the end of the data operands, walk backwards past the bundle 1275 // operands. 1276 return data_operands_end() - getNumTotalBundleOperands(); 1277 } 1278 User::const_op_iterator arg_end() const { 1279 return const_cast<CallBase *>(this)->arg_end(); 1280 } 1281 1282 /// Iteration adapter for range-for loops. 1283 iterator_range<User::op_iterator> args() { 1284 return make_range(arg_begin(), arg_end()); 1285 } 1286 iterator_range<User::const_op_iterator> args() const { 1287 return make_range(arg_begin(), arg_end()); 1288 } 1289 bool arg_empty() const { return arg_end() == arg_begin(); } 1290 unsigned arg_size() const { return arg_end() - arg_begin(); } 1291 1292 Value *getArgOperand(unsigned i) const { 1293 assert(i < arg_size() && "Out of bounds!"); 1294 return getOperand(i); 1295 } 1296 1297 void setArgOperand(unsigned i, Value *v) { 1298 assert(i < arg_size() && "Out of bounds!"); 1299 setOperand(i, v); 1300 } 1301 1302 /// Wrappers for getting the \c Use of a call argument. 1303 const Use &getArgOperandUse(unsigned i) const { 1304 assert(i < arg_size() && "Out of bounds!"); 1305 return User::getOperandUse(i); 1306 } 1307 Use &getArgOperandUse(unsigned i) { 1308 assert(i < arg_size() && "Out of bounds!"); 1309 return User::getOperandUse(i); 1310 } 1311 1312 bool isArgOperand(const Use *U) const { 1313 assert(this == U->getUser() && 1314 "Only valid to query with a use of this instruction!"); 1315 return arg_begin() <= U && U < arg_end(); 1316 } 1317 bool isArgOperand(Value::const_user_iterator UI) const { 1318 return isArgOperand(&UI.getUse()); 1319 } 1320 1321 /// Given a use for a arg operand, get the arg operand number that 1322 /// corresponds to it. 1323 unsigned getArgOperandNo(const Use *U) const { 1324 assert(isArgOperand(U) && "Arg operand # out of range!"); 1325 return U - arg_begin(); 1326 } 1327 1328 /// Given a value use iterator, return the arg operand number corresponding to 1329 /// it. Iterator must actually correspond to a data operand. 1330 unsigned getArgOperandNo(Value::const_user_iterator UI) const { 1331 return getArgOperandNo(&UI.getUse()); 1332 } 1333 1334 /// Returns true if this CallSite passes the given Value* as an argument to 1335 /// the called function. 1336 bool hasArgument(const Value *V) const { 1337 return llvm::is_contained(args(), V); 1338 } 1339 1340 Value *getCalledOperand() const { return Op<CalledOperandOpEndIdx>(); } 1341 1342 const Use &getCalledOperandUse() const { return Op<CalledOperandOpEndIdx>(); } 1343 Use &getCalledOperandUse() { return Op<CalledOperandOpEndIdx>(); } 1344 1345 /// Returns the function called, or null if this is an indirect function 1346 /// invocation or the function signature does not match the call signature, or 1347 /// the call target is an alias. 1348 Function *getCalledFunction() const { 1349 if (auto *F = dyn_cast_or_null<Function>(getCalledOperand())) 1350 if (F->getValueType() == getFunctionType()) 1351 return F; 1352 return nullptr; 1353 } 1354 1355 /// Return true if the callsite is an indirect call. 1356 LLVM_ABI bool isIndirectCall() const; 1357 1358 /// Determine whether the passed iterator points to the callee operand's Use. 1359 bool isCallee(Value::const_user_iterator UI) const { 1360 return isCallee(&UI.getUse()); 1361 } 1362 1363 /// Determine whether this Use is the callee operand's Use. 1364 bool isCallee(const Use *U) const { return &getCalledOperandUse() == U; } 1365 1366 /// Helper to get the caller (the parent function). 1367 LLVM_ABI Function *getCaller(); 1368 const Function *getCaller() const { 1369 return const_cast<CallBase *>(this)->getCaller(); 1370 } 1371 1372 /// Tests if this call site must be tail call optimized. Only a CallInst can 1373 /// be tail call optimized. 1374 LLVM_ABI bool isMustTailCall() const; 1375 1376 /// Tests if this call site is marked as a tail call. 1377 LLVM_ABI bool isTailCall() const; 1378 1379 /// Returns the intrinsic ID of the intrinsic called or 1380 /// Intrinsic::not_intrinsic if the called function is not an intrinsic, or if 1381 /// this is an indirect call. 1382 LLVM_ABI Intrinsic::ID getIntrinsicID() const; 1383 1384 void setCalledOperand(Value *V) { Op<CalledOperandOpEndIdx>() = V; } 1385 1386 /// Sets the function called, including updating the function type. 1387 void setCalledFunction(Function *Fn) { 1388 setCalledFunction(Fn->getFunctionType(), Fn); 1389 } 1390 1391 /// Sets the function called, including updating the function type. 1392 void setCalledFunction(FunctionCallee Fn) { 1393 setCalledFunction(Fn.getFunctionType(), Fn.getCallee()); 1394 } 1395 1396 /// Sets the function called, including updating to the specified function 1397 /// type. 1398 void setCalledFunction(FunctionType *FTy, Value *Fn) { 1399 this->FTy = FTy; 1400 // This function doesn't mutate the return type, only the function 1401 // type. Seems broken, but I'm just gonna stick an assert in for now. 1402 assert(getType() == FTy->getReturnType()); 1403 setCalledOperand(Fn); 1404 } 1405 1406 CallingConv::ID getCallingConv() const { 1407 return getSubclassData<CallingConvField>(); 1408 } 1409 1410 void setCallingConv(CallingConv::ID CC) { 1411 setSubclassData<CallingConvField>(CC); 1412 } 1413 1414 /// Check if this call is an inline asm statement. 1415 bool isInlineAsm() const { return isa<InlineAsm>(getCalledOperand()); } 1416 1417 /// \name Attribute API 1418 /// 1419 /// These methods access and modify attributes on this call (including 1420 /// looking through to the attributes on the called function when necessary). 1421 ///@{ 1422 1423 /// Return the attributes for this call. 1424 AttributeList getAttributes() const { return Attrs; } 1425 1426 /// Set the attributes for this call. 1427 void setAttributes(AttributeList A) { Attrs = A; } 1428 1429 /// Return the return attributes for this call. 1430 AttributeSet getRetAttributes() const { 1431 return getAttributes().getRetAttrs(); 1432 } 1433 1434 /// Return the param attributes for this call. 1435 AttributeSet getParamAttributes(unsigned ArgNo) const { 1436 return getAttributes().getParamAttrs(ArgNo); 1437 } 1438 1439 /// Try to intersect the attributes from 'this' CallBase and the 1440 /// 'Other' CallBase. Sets the intersected attributes to 'this' and 1441 /// return true if successful. Doesn't modify 'this' and returns 1442 /// false if unsuccessful. 1443 bool tryIntersectAttributes(const CallBase *Other) { 1444 if (this == Other) 1445 return true; 1446 AttributeList AL = getAttributes(); 1447 AttributeList ALOther = Other->getAttributes(); 1448 auto Intersected = AL.intersectWith(getContext(), ALOther); 1449 if (!Intersected) 1450 return false; 1451 setAttributes(*Intersected); 1452 return true; 1453 } 1454 1455 /// Determine whether this call has the given attribute. If it does not 1456 /// then determine if the called function has the attribute, but only if 1457 /// the attribute is allowed for the call. 1458 bool hasFnAttr(Attribute::AttrKind Kind) const { 1459 assert(Kind != Attribute::NoBuiltin && 1460 "Use CallBase::isNoBuiltin() to check for Attribute::NoBuiltin"); 1461 return hasFnAttrImpl(Kind); 1462 } 1463 1464 /// Determine whether this call has the given attribute. If it does not 1465 /// then determine if the called function has the attribute, but only if 1466 /// the attribute is allowed for the call. 1467 bool hasFnAttr(StringRef Kind) const { return hasFnAttrImpl(Kind); } 1468 1469 // TODO: remove non-AtIndex versions of these methods. 1470 /// adds the attribute to the list of attributes. 1471 void addAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 1472 Attrs = Attrs.addAttributeAtIndex(getContext(), i, Kind); 1473 } 1474 1475 /// adds the attribute to the list of attributes. 1476 void addAttributeAtIndex(unsigned i, Attribute Attr) { 1477 Attrs = Attrs.addAttributeAtIndex(getContext(), i, Attr); 1478 } 1479 1480 /// Adds the attribute to the function. 1481 void addFnAttr(Attribute::AttrKind Kind) { 1482 Attrs = Attrs.addFnAttribute(getContext(), Kind); 1483 } 1484 1485 /// Adds the attribute to the function. 1486 void addFnAttr(Attribute Attr) { 1487 Attrs = Attrs.addFnAttribute(getContext(), Attr); 1488 } 1489 1490 /// Adds the attribute to the return value. 1491 void addRetAttr(Attribute::AttrKind Kind) { 1492 Attrs = Attrs.addRetAttribute(getContext(), Kind); 1493 } 1494 1495 /// Adds the attribute to the return value. 1496 void addRetAttr(Attribute Attr) { 1497 Attrs = Attrs.addRetAttribute(getContext(), Attr); 1498 } 1499 1500 /// Adds attributes to the return value. 1501 void addRetAttrs(const AttrBuilder &B) { 1502 Attrs = Attrs.addRetAttributes(getContext(), B); 1503 } 1504 1505 /// Adds the attribute to the indicated argument 1506 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 1507 assert(ArgNo < arg_size() && "Out of bounds"); 1508 Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Kind); 1509 } 1510 1511 /// Adds the attribute to the indicated argument 1512 void addParamAttr(unsigned ArgNo, Attribute Attr) { 1513 assert(ArgNo < arg_size() && "Out of bounds"); 1514 Attrs = Attrs.addParamAttribute(getContext(), ArgNo, Attr); 1515 } 1516 1517 /// Adds attributes to the indicated argument 1518 void addParamAttrs(unsigned ArgNo, const AttrBuilder &B) { 1519 assert(ArgNo < arg_size() && "Out of bounds"); 1520 Attrs = Attrs.addParamAttributes(getContext(), ArgNo, B); 1521 } 1522 1523 /// removes the attribute from the list of attributes. 1524 void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) { 1525 Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind); 1526 } 1527 1528 /// removes the attribute from the list of attributes. 1529 void removeAttributeAtIndex(unsigned i, StringRef Kind) { 1530 Attrs = Attrs.removeAttributeAtIndex(getContext(), i, Kind); 1531 } 1532 1533 /// Removes the attributes from the function 1534 void removeFnAttrs(const AttributeMask &AttrsToRemove) { 1535 Attrs = Attrs.removeFnAttributes(getContext(), AttrsToRemove); 1536 } 1537 1538 /// Removes the attribute from the function 1539 void removeFnAttr(Attribute::AttrKind Kind) { 1540 Attrs = Attrs.removeFnAttribute(getContext(), Kind); 1541 } 1542 1543 /// Removes the attribute from the function 1544 void removeFnAttr(StringRef Kind) { 1545 Attrs = Attrs.removeFnAttribute(getContext(), Kind); 1546 } 1547 1548 /// Removes the attribute from the return value 1549 void removeRetAttr(Attribute::AttrKind Kind) { 1550 Attrs = Attrs.removeRetAttribute(getContext(), Kind); 1551 } 1552 1553 /// Removes the attributes from the return value 1554 void removeRetAttrs(const AttributeMask &AttrsToRemove) { 1555 Attrs = Attrs.removeRetAttributes(getContext(), AttrsToRemove); 1556 } 1557 1558 /// Removes the attribute from the given argument 1559 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 1560 assert(ArgNo < arg_size() && "Out of bounds"); 1561 Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind); 1562 } 1563 1564 /// Removes the attribute from the given argument 1565 void removeParamAttr(unsigned ArgNo, StringRef Kind) { 1566 assert(ArgNo < arg_size() && "Out of bounds"); 1567 Attrs = Attrs.removeParamAttribute(getContext(), ArgNo, Kind); 1568 } 1569 1570 /// Removes the attributes from the given argument 1571 void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove) { 1572 Attrs = Attrs.removeParamAttributes(getContext(), ArgNo, AttrsToRemove); 1573 } 1574 1575 /// adds the dereferenceable attribute to the list of attributes. 1576 void addDereferenceableParamAttr(unsigned i, uint64_t Bytes) { 1577 Attrs = Attrs.addDereferenceableParamAttr(getContext(), i, Bytes); 1578 } 1579 1580 /// adds the dereferenceable attribute to the list of attributes. 1581 void addDereferenceableRetAttr(uint64_t Bytes) { 1582 Attrs = Attrs.addDereferenceableRetAttr(getContext(), Bytes); 1583 } 1584 1585 /// adds the range attribute to the list of attributes. 1586 void addRangeRetAttr(const ConstantRange &CR) { 1587 Attrs = Attrs.addRangeRetAttr(getContext(), CR); 1588 } 1589 1590 /// Determine whether the return value has the given attribute. 1591 bool hasRetAttr(Attribute::AttrKind Kind) const { 1592 return hasRetAttrImpl(Kind); 1593 } 1594 /// Determine whether the return value has the given attribute. 1595 bool hasRetAttr(StringRef Kind) const { return hasRetAttrImpl(Kind); } 1596 1597 /// Return the attribute for the given attribute kind for the return value. 1598 Attribute getRetAttr(Attribute::AttrKind Kind) const { 1599 Attribute RetAttr = Attrs.getRetAttr(Kind); 1600 if (RetAttr.isValid()) 1601 return RetAttr; 1602 1603 // Look at the callee, if available. 1604 if (const Function *F = getCalledFunction()) 1605 return F->getRetAttribute(Kind); 1606 return Attribute(); 1607 } 1608 1609 /// Determine whether the argument or parameter has the given attribute. 1610 LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const; 1611 1612 /// Return true if this argument has the nonnull attribute on either the 1613 /// CallBase instruction or the called function. Also returns true if at least 1614 /// one byte is known to be dereferenceable and the pointer is in 1615 /// addrspace(0). If \p AllowUndefOrPoison is true, respect the semantics of 1616 /// nonnull attribute and return true even if the argument can be undef or 1617 /// poison. 1618 LLVM_ABI bool paramHasNonNullAttr(unsigned ArgNo, 1619 bool AllowUndefOrPoison) const; 1620 1621 /// Get the attribute of a given kind at a position. 1622 Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const { 1623 return getAttributes().getAttributeAtIndex(i, Kind); 1624 } 1625 1626 /// Get the attribute of a given kind at a position. 1627 Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const { 1628 return getAttributes().getAttributeAtIndex(i, Kind); 1629 } 1630 1631 /// Get the attribute of a given kind for the function. 1632 Attribute getFnAttr(StringRef Kind) const { 1633 Attribute Attr = getAttributes().getFnAttr(Kind); 1634 if (Attr.isValid()) 1635 return Attr; 1636 return getFnAttrOnCalledFunction(Kind); 1637 } 1638 1639 /// Get the attribute of a given kind for the function. 1640 Attribute getFnAttr(Attribute::AttrKind Kind) const { 1641 Attribute A = getAttributes().getFnAttr(Kind); 1642 if (A.isValid()) 1643 return A; 1644 return getFnAttrOnCalledFunction(Kind); 1645 } 1646 1647 /// Get the attribute of a given kind from a given arg 1648 Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { 1649 assert(ArgNo < arg_size() && "Out of bounds"); 1650 Attribute A = getAttributes().getParamAttr(ArgNo, Kind); 1651 if (A.isValid()) 1652 return A; 1653 return getParamAttrOnCalledFunction(ArgNo, Kind); 1654 } 1655 1656 /// Get the attribute of a given kind from a given arg 1657 Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const { 1658 assert(ArgNo < arg_size() && "Out of bounds"); 1659 Attribute A = getAttributes().getParamAttr(ArgNo, Kind); 1660 if (A.isValid()) 1661 return A; 1662 return getParamAttrOnCalledFunction(ArgNo, Kind); 1663 } 1664 1665 /// Return true if the data operand at index \p i has the attribute \p 1666 /// A. 1667 /// 1668 /// Data operands include call arguments and values used in operand bundles, 1669 /// but does not include the callee operand. 1670 /// 1671 /// The index \p i is interpreted as 1672 /// 1673 /// \p i in [0, arg_size) -> argument number (\p i) 1674 /// \p i in [arg_size, data_operand_size) -> bundle operand at index 1675 /// (\p i) in the operand list. 1676 bool dataOperandHasImpliedAttr(unsigned i, Attribute::AttrKind Kind) const { 1677 // Note that we have to add one because `i` isn't zero-indexed. 1678 assert(i < arg_size() + getNumTotalBundleOperands() && 1679 "Data operand index out of bounds!"); 1680 1681 // The attribute A can either be directly specified, if the operand in 1682 // question is a call argument; or be indirectly implied by the kind of its 1683 // containing operand bundle, if the operand is a bundle operand. 1684 1685 if (i < arg_size()) 1686 return paramHasAttr(i, Kind); 1687 1688 assert(hasOperandBundles() && i >= getBundleOperandsStartIndex() && 1689 "Must be either a call argument or an operand bundle!"); 1690 return bundleOperandHasAttr(i, Kind); 1691 } 1692 1693 /// Return which pointer components this operand may capture. 1694 LLVM_ABI CaptureInfo getCaptureInfo(unsigned OpNo) const; 1695 1696 /// Determine whether this data operand is not captured. 1697 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1698 // better indicate that this may return a conservative answer. 1699 bool doesNotCapture(unsigned OpNo) const { 1700 return capturesNothing(getCaptureInfo(OpNo)); 1701 } 1702 1703 /// Returns whether the call has an argument that has an attribute like 1704 /// captures(ret: address, provenance), where the return capture components 1705 /// are not a subset of the other capture components. 1706 LLVM_ABI bool hasArgumentWithAdditionalReturnCaptureComponents() const; 1707 1708 /// Determine whether this argument is passed by value. 1709 bool isByValArgument(unsigned ArgNo) const { 1710 return paramHasAttr(ArgNo, Attribute::ByVal); 1711 } 1712 1713 /// Determine whether this argument is passed in an alloca. 1714 bool isInAllocaArgument(unsigned ArgNo) const { 1715 return paramHasAttr(ArgNo, Attribute::InAlloca); 1716 } 1717 1718 /// Determine whether this argument is passed by value, in an alloca, or is 1719 /// preallocated. 1720 bool isPassPointeeByValueArgument(unsigned ArgNo) const { 1721 return paramHasAttr(ArgNo, Attribute::ByVal) || 1722 paramHasAttr(ArgNo, Attribute::InAlloca) || 1723 paramHasAttr(ArgNo, Attribute::Preallocated); 1724 } 1725 1726 /// Determine whether passing undef to this argument is undefined behavior. 1727 /// If passing undef to this argument is UB, passing poison is UB as well 1728 /// because poison is more undefined than undef. 1729 bool isPassingUndefUB(unsigned ArgNo) const { 1730 return paramHasAttr(ArgNo, Attribute::NoUndef) || 1731 // dereferenceable implies noundef. 1732 paramHasAttr(ArgNo, Attribute::Dereferenceable) || 1733 // dereferenceable implies noundef, and null is a well-defined value. 1734 paramHasAttr(ArgNo, Attribute::DereferenceableOrNull); 1735 } 1736 1737 /// Determine if there are is an inalloca argument. Only the last argument can 1738 /// have the inalloca attribute. 1739 bool hasInAllocaArgument() const { 1740 return !arg_empty() && paramHasAttr(arg_size() - 1, Attribute::InAlloca); 1741 } 1742 1743 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1744 // better indicate that this may return a conservative answer. 1745 bool doesNotAccessMemory(unsigned OpNo) const { 1746 return dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1747 } 1748 1749 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1750 // better indicate that this may return a conservative answer. 1751 bool onlyReadsMemory(unsigned OpNo) const { 1752 // If the argument is passed byval, the callee does not have access to the 1753 // original pointer and thus cannot write to it. 1754 if (OpNo < arg_size() && isByValArgument(OpNo)) 1755 return true; 1756 1757 return dataOperandHasImpliedAttr(OpNo, Attribute::ReadOnly) || 1758 dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1759 } 1760 1761 // FIXME: Once this API is no longer duplicated in `CallSite`, rename this to 1762 // better indicate that this may return a conservative answer. 1763 bool onlyWritesMemory(unsigned OpNo) const { 1764 return dataOperandHasImpliedAttr(OpNo, Attribute::WriteOnly) || 1765 dataOperandHasImpliedAttr(OpNo, Attribute::ReadNone); 1766 } 1767 1768 /// Extract the alignment of the return value. 1769 MaybeAlign getRetAlign() const { 1770 if (auto Align = Attrs.getRetAlignment()) 1771 return Align; 1772 if (const Function *F = getCalledFunction()) 1773 return F->getAttributes().getRetAlignment(); 1774 return std::nullopt; 1775 } 1776 1777 /// Extract the alignment for a call or parameter (0=unknown). 1778 MaybeAlign getParamAlign(unsigned ArgNo) const { 1779 return Attrs.getParamAlignment(ArgNo); 1780 } 1781 1782 MaybeAlign getParamStackAlign(unsigned ArgNo) const { 1783 return Attrs.getParamStackAlignment(ArgNo); 1784 } 1785 1786 /// Extract the byref type for a call or parameter. 1787 Type *getParamByRefType(unsigned ArgNo) const { 1788 if (auto *Ty = Attrs.getParamByRefType(ArgNo)) 1789 return Ty; 1790 if (const Function *F = getCalledFunction()) 1791 return F->getAttributes().getParamByRefType(ArgNo); 1792 return nullptr; 1793 } 1794 1795 /// Extract the byval type for a call or parameter. 1796 Type *getParamByValType(unsigned ArgNo) const { 1797 if (auto *Ty = Attrs.getParamByValType(ArgNo)) 1798 return Ty; 1799 if (const Function *F = getCalledFunction()) 1800 return F->getAttributes().getParamByValType(ArgNo); 1801 return nullptr; 1802 } 1803 1804 /// Extract the preallocated type for a call or parameter. 1805 Type *getParamPreallocatedType(unsigned ArgNo) const { 1806 if (auto *Ty = Attrs.getParamPreallocatedType(ArgNo)) 1807 return Ty; 1808 if (const Function *F = getCalledFunction()) 1809 return F->getAttributes().getParamPreallocatedType(ArgNo); 1810 return nullptr; 1811 } 1812 1813 /// Extract the inalloca type for a call or parameter. 1814 Type *getParamInAllocaType(unsigned ArgNo) const { 1815 if (auto *Ty = Attrs.getParamInAllocaType(ArgNo)) 1816 return Ty; 1817 if (const Function *F = getCalledFunction()) 1818 return F->getAttributes().getParamInAllocaType(ArgNo); 1819 return nullptr; 1820 } 1821 1822 /// Extract the sret type for a call or parameter. 1823 Type *getParamStructRetType(unsigned ArgNo) const { 1824 if (auto *Ty = Attrs.getParamStructRetType(ArgNo)) 1825 return Ty; 1826 if (const Function *F = getCalledFunction()) 1827 return F->getAttributes().getParamStructRetType(ArgNo); 1828 return nullptr; 1829 } 1830 1831 /// Extract the elementtype type for a parameter. 1832 /// Note that elementtype() can only be applied to call arguments, not 1833 /// function declaration parameters. 1834 Type *getParamElementType(unsigned ArgNo) const { 1835 return Attrs.getParamElementType(ArgNo); 1836 } 1837 1838 /// Extract the number of dereferenceable bytes for a call or 1839 /// parameter (0=unknown). 1840 uint64_t getRetDereferenceableBytes() const { 1841 uint64_t Bytes = Attrs.getRetDereferenceableBytes(); 1842 if (const Function *F = getCalledFunction()) 1843 Bytes = std::max(Bytes, F->getAttributes().getRetDereferenceableBytes()); 1844 return Bytes; 1845 } 1846 1847 /// Extract the number of dereferenceable bytes for a call or 1848 /// parameter (0=unknown). 1849 uint64_t getParamDereferenceableBytes(unsigned i) const { 1850 return Attrs.getParamDereferenceableBytes(i); 1851 } 1852 1853 /// Extract the number of dereferenceable_or_null bytes for a call 1854 /// (0=unknown). 1855 uint64_t getRetDereferenceableOrNullBytes() const { 1856 uint64_t Bytes = Attrs.getRetDereferenceableOrNullBytes(); 1857 if (const Function *F = getCalledFunction()) { 1858 Bytes = std::max(Bytes, 1859 F->getAttributes().getRetDereferenceableOrNullBytes()); 1860 } 1861 1862 return Bytes; 1863 } 1864 1865 /// Extract the number of dereferenceable_or_null bytes for a 1866 /// parameter (0=unknown). 1867 uint64_t getParamDereferenceableOrNullBytes(unsigned i) const { 1868 return Attrs.getParamDereferenceableOrNullBytes(i); 1869 } 1870 1871 /// Extract a test mask for disallowed floating-point value classes for the 1872 /// return value. 1873 LLVM_ABI FPClassTest getRetNoFPClass() const; 1874 1875 /// Extract a test mask for disallowed floating-point value classes for the 1876 /// parameter. 1877 LLVM_ABI FPClassTest getParamNoFPClass(unsigned i) const; 1878 1879 /// If this return value has a range attribute, return the value range of the 1880 /// argument. Otherwise, std::nullopt is returned. 1881 LLVM_ABI std::optional<ConstantRange> getRange() const; 1882 1883 /// Return true if the return value is known to be not null. 1884 /// This may be because it has the nonnull attribute, or because at least 1885 /// one byte is dereferenceable and the pointer is in addrspace(0). 1886 LLVM_ABI bool isReturnNonNull() const; 1887 1888 /// Determine if the return value is marked with NoAlias attribute. 1889 bool returnDoesNotAlias() const { 1890 return Attrs.hasRetAttr(Attribute::NoAlias); 1891 } 1892 1893 /// If one of the arguments has the 'returned' attribute, returns its 1894 /// operand value. Otherwise, return nullptr. 1895 Value *getReturnedArgOperand() const { 1896 return getArgOperandWithAttribute(Attribute::Returned); 1897 } 1898 1899 /// If one of the arguments has the specified attribute, returns its 1900 /// operand value. Otherwise, return nullptr. 1901 LLVM_ABI Value *getArgOperandWithAttribute(Attribute::AttrKind Kind) const; 1902 1903 /// Return true if the call should not be treated as a call to a 1904 /// builtin. 1905 bool isNoBuiltin() const { 1906 return hasFnAttrImpl(Attribute::NoBuiltin) && 1907 !hasFnAttrImpl(Attribute::Builtin); 1908 } 1909 1910 /// Determine if the call requires strict floating point semantics. 1911 bool isStrictFP() const { return hasFnAttr(Attribute::StrictFP); } 1912 1913 /// Return true if the call should not be inlined. 1914 bool isNoInline() const { return hasFnAttr(Attribute::NoInline); } 1915 void setIsNoInline() { addFnAttr(Attribute::NoInline); } 1916 1917 LLVM_ABI MemoryEffects getMemoryEffects() const; 1918 LLVM_ABI void setMemoryEffects(MemoryEffects ME); 1919 1920 /// Determine if the call does not access memory. 1921 LLVM_ABI bool doesNotAccessMemory() const; 1922 LLVM_ABI void setDoesNotAccessMemory(); 1923 1924 /// Determine if the call does not access or only reads memory. 1925 LLVM_ABI bool onlyReadsMemory() const; 1926 LLVM_ABI void setOnlyReadsMemory(); 1927 1928 /// Determine if the call does not access or only writes memory. 1929 LLVM_ABI bool onlyWritesMemory() const; 1930 LLVM_ABI void setOnlyWritesMemory(); 1931 1932 /// Determine if the call can access memmory only using pointers based 1933 /// on its arguments. 1934 LLVM_ABI bool onlyAccessesArgMemory() const; 1935 LLVM_ABI void setOnlyAccessesArgMemory(); 1936 1937 /// Determine if the function may only access memory that is 1938 /// inaccessible from the IR. 1939 LLVM_ABI bool onlyAccessesInaccessibleMemory() const; 1940 LLVM_ABI void setOnlyAccessesInaccessibleMemory(); 1941 1942 /// Determine if the function may only access memory that is 1943 /// either inaccessible from the IR or pointed to by its arguments. 1944 LLVM_ABI bool onlyAccessesInaccessibleMemOrArgMem() const; 1945 LLVM_ABI void setOnlyAccessesInaccessibleMemOrArgMem(); 1946 1947 /// Determine if the call cannot return. 1948 bool doesNotReturn() const { return hasFnAttr(Attribute::NoReturn); } 1949 void setDoesNotReturn() { addFnAttr(Attribute::NoReturn); } 1950 1951 /// Determine if the call should not perform indirect branch tracking. 1952 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); } 1953 1954 /// Determine if the call cannot unwind. 1955 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); } 1956 void setDoesNotThrow() { addFnAttr(Attribute::NoUnwind); } 1957 1958 /// Determine if the invoke cannot be duplicated. 1959 bool cannotDuplicate() const { return hasFnAttr(Attribute::NoDuplicate); } 1960 void setCannotDuplicate() { addFnAttr(Attribute::NoDuplicate); } 1961 1962 /// Determine if the call cannot be tail merged. 1963 bool cannotMerge() const { return hasFnAttr(Attribute::NoMerge); } 1964 void setCannotMerge() { addFnAttr(Attribute::NoMerge); } 1965 1966 /// Determine if the invoke is convergent 1967 bool isConvergent() const { return hasFnAttr(Attribute::Convergent); } 1968 void setConvergent() { addFnAttr(Attribute::Convergent); } 1969 void setNotConvergent() { removeFnAttr(Attribute::Convergent); } 1970 1971 /// Determine if the call returns a structure through first 1972 /// pointer argument. 1973 bool hasStructRetAttr() const { 1974 if (arg_empty()) 1975 return false; 1976 1977 // Be friendly and also check the callee. 1978 return paramHasAttr(0, Attribute::StructRet); 1979 } 1980 1981 /// Determine if any call argument is an aggregate passed by value. 1982 bool hasByValArgument() const { 1983 return Attrs.hasAttrSomewhere(Attribute::ByVal); 1984 } 1985 1986 ///@} 1987 // End of attribute API. 1988 1989 /// \name Operand Bundle API 1990 /// 1991 /// This group of methods provides the API to access and manipulate operand 1992 /// bundles on this call. 1993 /// @{ 1994 1995 /// Return the number of operand bundles associated with this User. 1996 unsigned getNumOperandBundles() const { 1997 return std::distance(bundle_op_info_begin(), bundle_op_info_end()); 1998 } 1999 2000 /// Return true if this User has any operand bundles. 2001 bool hasOperandBundles() const { return getNumOperandBundles() != 0; } 2002 2003 /// Return the index of the first bundle operand in the Use array. 2004 unsigned getBundleOperandsStartIndex() const { 2005 assert(hasOperandBundles() && "Don't call otherwise!"); 2006 return bundle_op_info_begin()->Begin; 2007 } 2008 2009 /// Return the index of the last bundle operand in the Use array. 2010 unsigned getBundleOperandsEndIndex() const { 2011 assert(hasOperandBundles() && "Don't call otherwise!"); 2012 return bundle_op_info_end()[-1].End; 2013 } 2014 2015 /// Return true if the operand at index \p Idx is a bundle operand. 2016 bool isBundleOperand(unsigned Idx) const { 2017 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() && 2018 Idx < getBundleOperandsEndIndex(); 2019 } 2020 2021 /// Return true if the operand at index \p Idx is a bundle operand that has 2022 /// tag ID \p ID. 2023 bool isOperandBundleOfType(uint32_t ID, unsigned Idx) const { 2024 return isBundleOperand(Idx) && 2025 getOperandBundleForOperand(Idx).getTagID() == ID; 2026 } 2027 2028 /// Returns true if the use is a bundle operand. 2029 bool isBundleOperand(const Use *U) const { 2030 assert(this == U->getUser() && 2031 "Only valid to query with a use of this instruction!"); 2032 return hasOperandBundles() && isBundleOperand(U - op_begin()); 2033 } 2034 bool isBundleOperand(Value::const_user_iterator UI) const { 2035 return isBundleOperand(&UI.getUse()); 2036 } 2037 2038 /// Return the total number operands (not operand bundles) used by 2039 /// every operand bundle in this OperandBundleUser. 2040 unsigned getNumTotalBundleOperands() const { 2041 if (!hasOperandBundles()) 2042 return 0; 2043 2044 unsigned Begin = getBundleOperandsStartIndex(); 2045 unsigned End = getBundleOperandsEndIndex(); 2046 2047 assert(Begin <= End && "Should be!"); 2048 return End - Begin; 2049 } 2050 2051 /// Return the operand bundle at a specific index. 2052 OperandBundleUse getOperandBundleAt(unsigned Index) const { 2053 assert(Index < getNumOperandBundles() && "Index out of bounds!"); 2054 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index)); 2055 } 2056 2057 /// Return the number of operand bundles with the tag Name attached to 2058 /// this instruction. 2059 unsigned countOperandBundlesOfType(StringRef Name) const { 2060 unsigned Count = 0; 2061 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 2062 if (getOperandBundleAt(i).getTagName() == Name) 2063 Count++; 2064 2065 return Count; 2066 } 2067 2068 /// Return the number of operand bundles with the tag ID attached to 2069 /// this instruction. 2070 unsigned countOperandBundlesOfType(uint32_t ID) const { 2071 unsigned Count = 0; 2072 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 2073 if (getOperandBundleAt(i).getTagID() == ID) 2074 Count++; 2075 2076 return Count; 2077 } 2078 2079 /// Return an operand bundle by name, if present. 2080 /// 2081 /// It is an error to call this for operand bundle types that may have 2082 /// multiple instances of them on the same instruction. 2083 std::optional<OperandBundleUse> getOperandBundle(StringRef Name) const { 2084 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!"); 2085 2086 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2087 OperandBundleUse U = getOperandBundleAt(i); 2088 if (U.getTagName() == Name) 2089 return U; 2090 } 2091 2092 return std::nullopt; 2093 } 2094 2095 /// Return an operand bundle by tag ID, if present. 2096 /// 2097 /// It is an error to call this for operand bundle types that may have 2098 /// multiple instances of them on the same instruction. 2099 std::optional<OperandBundleUse> getOperandBundle(uint32_t ID) const { 2100 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!"); 2101 2102 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2103 OperandBundleUse U = getOperandBundleAt(i); 2104 if (U.getTagID() == ID) 2105 return U; 2106 } 2107 2108 return std::nullopt; 2109 } 2110 2111 /// Return the list of operand bundles attached to this instruction as 2112 /// a vector of OperandBundleDefs. 2113 /// 2114 /// This function copies the OperandBundeUse instances associated with this 2115 /// OperandBundleUser to a vector of OperandBundleDefs. Note: 2116 /// OperandBundeUses and OperandBundleDefs are non-trivially *different* 2117 /// representations of operand bundles (see documentation above). 2118 LLVM_ABI void 2119 getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const; 2120 2121 /// Return the operand bundle for the operand at index OpIdx. 2122 /// 2123 /// It is an error to call this with an OpIdx that does not correspond to an 2124 /// bundle operand. 2125 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const { 2126 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx)); 2127 } 2128 2129 /// Return true if this operand bundle user has operand bundles that 2130 /// may read from the heap. 2131 LLVM_ABI bool hasReadingOperandBundles() const; 2132 2133 /// Return true if this operand bundle user has operand bundles that 2134 /// may write to the heap. 2135 LLVM_ABI bool hasClobberingOperandBundles() const; 2136 2137 /// Return true if the bundle operand at index \p OpIdx has the 2138 /// attribute \p A. 2139 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const { 2140 auto &BOI = getBundleOpInfoForOperand(OpIdx); 2141 auto OBU = operandBundleFromBundleOpInfo(BOI); 2142 return OBU.operandHasAttr(OpIdx - BOI.Begin, A); 2143 } 2144 2145 /// Return true if \p Other has the same sequence of operand bundle 2146 /// tags with the same number of operands on each one of them as this 2147 /// OperandBundleUser. 2148 bool hasIdenticalOperandBundleSchema(const CallBase &Other) const { 2149 if (getNumOperandBundles() != Other.getNumOperandBundles()) 2150 return false; 2151 2152 return std::equal(bundle_op_info_begin(), bundle_op_info_end(), 2153 Other.bundle_op_info_begin()); 2154 } 2155 2156 /// Return true if this operand bundle user contains operand bundles 2157 /// with tags other than those specified in \p IDs. 2158 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const { 2159 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 2160 uint32_t ID = getOperandBundleAt(i).getTagID(); 2161 if (!is_contained(IDs, ID)) 2162 return true; 2163 } 2164 return false; 2165 } 2166 2167 /// Used to keep track of an operand bundle. See the main comment on 2168 /// OperandBundleUser above. 2169 struct BundleOpInfo { 2170 /// The operand bundle tag, interned by 2171 /// LLVMContextImpl::getOrInsertBundleTag. 2172 StringMapEntry<uint32_t> *Tag; 2173 2174 /// The index in the Use& vector where operands for this operand 2175 /// bundle starts. 2176 uint32_t Begin; 2177 2178 /// The index in the Use& vector where operands for this operand 2179 /// bundle ends. 2180 uint32_t End; 2181 2182 bool operator==(const BundleOpInfo &Other) const { 2183 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End; 2184 } 2185 }; 2186 2187 /// Simple helper function to map a BundleOpInfo to an 2188 /// OperandBundleUse. 2189 OperandBundleUse 2190 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const { 2191 const auto *begin = op_begin(); 2192 ArrayRef<Use> Inputs(begin + BOI.Begin, begin + BOI.End); 2193 return OperandBundleUse(BOI.Tag, Inputs); 2194 } 2195 2196 using bundle_op_iterator = BundleOpInfo *; 2197 using const_bundle_op_iterator = const BundleOpInfo *; 2198 2199 /// Return the start of the list of BundleOpInfo instances associated 2200 /// with this OperandBundleUser. 2201 /// 2202 /// OperandBundleUser uses the descriptor area co-allocated with the host User 2203 /// to store some meta information about which operands are "normal" operands, 2204 /// and which ones belong to some operand bundle. 2205 /// 2206 /// The layout of an operand bundle user is 2207 /// 2208 /// +-----------uint32_t End-------------------------------------+ 2209 /// | | 2210 /// | +--------uint32_t Begin--------------------+ | 2211 /// | | | | 2212 /// ^ ^ v v 2213 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 2214 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un 2215 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 2216 /// v v ^ ^ 2217 /// | | | | 2218 /// | +--------uint32_t Begin------------+ | 2219 /// | | 2220 /// +-----------uint32_t End-----------------------------+ 2221 /// 2222 /// 2223 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use 2224 /// list. These descriptions are installed and managed by this class, and 2225 /// they're all instances of OperandBundleUser<T>::BundleOpInfo. 2226 /// 2227 /// DU is an additional descriptor installed by User's 'operator new' to keep 2228 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not 2229 /// access or modify DU in any way, it's an implementation detail private to 2230 /// User. 2231 /// 2232 /// The regular Use& vector for the User starts at U0. The operand bundle 2233 /// uses are part of the Use& vector, just like normal uses. In the diagram 2234 /// above, the operand bundle uses start at BOI0_U0. Each instance of 2235 /// BundleOpInfo has information about a contiguous set of uses constituting 2236 /// an operand bundle, and the total set of operand bundle uses themselves 2237 /// form a contiguous set of uses (i.e. there are no gaps between uses 2238 /// corresponding to individual operand bundles). 2239 /// 2240 /// This class does not know the location of the set of operand bundle uses 2241 /// within the use list -- that is decided by the User using this class via 2242 /// the BeginIdx argument in populateBundleOperandInfos. 2243 /// 2244 /// Currently operand bundle users with hung-off operands are not supported. 2245 bundle_op_iterator bundle_op_info_begin() { 2246 if (!hasDescriptor()) 2247 return nullptr; 2248 2249 uint8_t *BytesBegin = getDescriptor().begin(); 2250 return reinterpret_cast<bundle_op_iterator>(BytesBegin); 2251 } 2252 2253 /// Return the start of the list of BundleOpInfo instances associated 2254 /// with this OperandBundleUser. 2255 const_bundle_op_iterator bundle_op_info_begin() const { 2256 auto *NonConstThis = const_cast<CallBase *>(this); 2257 return NonConstThis->bundle_op_info_begin(); 2258 } 2259 2260 /// Return the end of the list of BundleOpInfo instances associated 2261 /// with this OperandBundleUser. 2262 bundle_op_iterator bundle_op_info_end() { 2263 if (!hasDescriptor()) 2264 return nullptr; 2265 2266 uint8_t *BytesEnd = getDescriptor().end(); 2267 return reinterpret_cast<bundle_op_iterator>(BytesEnd); 2268 } 2269 2270 /// Return the end of the list of BundleOpInfo instances associated 2271 /// with this OperandBundleUser. 2272 const_bundle_op_iterator bundle_op_info_end() const { 2273 auto *NonConstThis = const_cast<CallBase *>(this); 2274 return NonConstThis->bundle_op_info_end(); 2275 } 2276 2277 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 2278 iterator_range<bundle_op_iterator> bundle_op_infos() { 2279 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 2280 } 2281 2282 /// Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 2283 iterator_range<const_bundle_op_iterator> bundle_op_infos() const { 2284 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 2285 } 2286 2287 /// Populate the BundleOpInfo instances and the Use& vector from \p 2288 /// Bundles. Return the op_iterator pointing to the Use& one past the last 2289 /// last bundle operand use. 2290 /// 2291 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo 2292 /// instance allocated in this User's descriptor. 2293 LLVM_ABI op_iterator populateBundleOperandInfos( 2294 ArrayRef<OperandBundleDef> Bundles, const unsigned BeginIndex); 2295 2296 /// Return true if the call has deopt state bundle. 2297 bool hasDeoptState() const { 2298 return getOperandBundle(LLVMContext::OB_deopt).has_value(); 2299 } 2300 2301 public: 2302 /// Return the BundleOpInfo for the operand at index OpIdx. 2303 /// 2304 /// It is an error to call this with an OpIdx that does not correspond to an 2305 /// bundle operand. 2306 LLVM_ABI BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx); 2307 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const { 2308 return const_cast<CallBase *>(this)->getBundleOpInfoForOperand(OpIdx); 2309 } 2310 2311 protected: 2312 /// Return the total number of values used in \p Bundles. 2313 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) { 2314 unsigned Total = 0; 2315 for (const auto &B : Bundles) 2316 Total += B.input_size(); 2317 return Total; 2318 } 2319 2320 /// @} 2321 // End of operand bundle API. 2322 2323 private: 2324 LLVM_ABI bool hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const; 2325 LLVM_ABI bool hasFnAttrOnCalledFunction(StringRef Kind) const; 2326 2327 template <typename AttrKind> bool hasFnAttrImpl(AttrKind Kind) const { 2328 if (Attrs.hasFnAttr(Kind)) 2329 return true; 2330 2331 return hasFnAttrOnCalledFunction(Kind); 2332 } 2333 template <typename AK> Attribute getFnAttrOnCalledFunction(AK Kind) const; 2334 template <typename AK> 2335 Attribute getParamAttrOnCalledFunction(unsigned ArgNo, AK Kind) const; 2336 2337 /// Determine whether the return value has the given attribute. Supports 2338 /// Attribute::AttrKind and StringRef as \p AttrKind types. 2339 template <typename AttrKind> bool hasRetAttrImpl(AttrKind Kind) const { 2340 if (Attrs.hasRetAttr(Kind)) 2341 return true; 2342 2343 // Look at the callee, if available. 2344 if (const Function *F = getCalledFunction()) 2345 return F->getAttributes().hasRetAttr(Kind); 2346 return false; 2347 } 2348 }; 2349 2350 template <> 2351 struct OperandTraits<CallBase> : public VariadicOperandTraits<CallBase> {}; 2352 2353 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallBase, Value) 2354 2355 //===----------------------------------------------------------------------===// 2356 // FuncletPadInst Class 2357 //===----------------------------------------------------------------------===// 2358 class FuncletPadInst : public Instruction { 2359 private: 2360 FuncletPadInst(const FuncletPadInst &CPI, AllocInfo AllocInfo); 2361 2362 LLVM_ABI explicit FuncletPadInst(Instruction::FuncletPadOps Op, 2363 Value *ParentPad, ArrayRef<Value *> Args, 2364 AllocInfo AllocInfo, const Twine &NameStr, 2365 InsertPosition InsertBefore); 2366 2367 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr); 2368 2369 protected: 2370 // Note: Instruction needs to be a friend here to call cloneImpl. 2371 friend class Instruction; 2372 friend class CatchPadInst; 2373 friend class CleanupPadInst; 2374 2375 LLVM_ABI FuncletPadInst *cloneImpl() const; 2376 2377 public: 2378 /// Provide fast operand accessors 2379 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 2380 2381 /// arg_size - Return the number of funcletpad arguments. 2382 /// 2383 unsigned arg_size() const { return getNumOperands() - 1; } 2384 2385 /// Convenience accessors 2386 2387 /// Return the outer EH-pad this funclet is nested within. 2388 /// 2389 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst 2390 /// is a CatchPadInst. 2391 Value *getParentPad() const { return Op<-1>(); } 2392 void setParentPad(Value *ParentPad) { 2393 assert(ParentPad); 2394 Op<-1>() = ParentPad; 2395 } 2396 2397 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument. 2398 /// 2399 Value *getArgOperand(unsigned i) const { return getOperand(i); } 2400 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); } 2401 2402 /// arg_operands - iteration adapter for range-for loops. 2403 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); } 2404 2405 /// arg_operands - iteration adapter for range-for loops. 2406 const_op_range arg_operands() const { 2407 return const_op_range(op_begin(), op_end() - 1); 2408 } 2409 2410 // Methods for support type inquiry through isa, cast, and dyn_cast: 2411 static bool classof(const Instruction *I) { return I->isFuncletPad(); } 2412 static bool classof(const Value *V) { 2413 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 2414 } 2415 }; 2416 2417 template <> 2418 struct OperandTraits<FuncletPadInst> 2419 : public VariadicOperandTraits<FuncletPadInst> {}; 2420 2421 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value) 2422 2423 } // end namespace llvm 2424 2425 #endif // LLVM_IR_INSTRTYPES_H 2426