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