1 //===- llvm/InstrTypes.h - Important Instruction subclasses -----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines various meta classes of instructions that exist in the VM 11 // representation. Specific concrete subclasses of these may be found in the 12 // i*.h files... 13 // 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_IR_INSTRTYPES_H 17 #define LLVM_IR_INSTRTYPES_H 18 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/ADT/iterator_range.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/OperandTraits.h" 32 #include "llvm/IR/Type.h" 33 #include "llvm/IR/User.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include <algorithm> 38 #include <cassert> 39 #include <cstddef> 40 #include <cstdint> 41 #include <iterator> 42 #include <string> 43 #include <vector> 44 45 namespace llvm { 46 47 //===----------------------------------------------------------------------===// 48 // TerminatorInst Class 49 //===----------------------------------------------------------------------===// 50 51 /// Subclasses of this class are all able to terminate a basic 52 /// block. Thus, these are all the flow control type of operations. 53 /// 54 class TerminatorInst : public Instruction { 55 protected: 56 TerminatorInst(Type *Ty, Instruction::TermOps iType, 57 Use *Ops, unsigned NumOps, 58 Instruction *InsertBefore = nullptr) 59 : Instruction(Ty, iType, Ops, NumOps, InsertBefore) {} 60 61 TerminatorInst(Type *Ty, Instruction::TermOps iType, 62 Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd) 63 : Instruction(Ty, iType, Ops, NumOps, InsertAtEnd) {} 64 65 public: 66 /// Return the number of successors that this terminator has. 67 unsigned getNumSuccessors() const; 68 69 /// Return the specified successor. 70 BasicBlock *getSuccessor(unsigned idx) const; 71 72 /// Update the specified successor to point at the provided block. 73 void setSuccessor(unsigned idx, BasicBlock *B); 74 75 // Methods for support type inquiry through isa, cast, and dyn_cast: 76 static inline bool classof(const Instruction *I) { 77 return I->isTerminator(); 78 } 79 static inline bool classof(const Value *V) { 80 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 81 } 82 83 // \brief Returns true if this terminator relates to exception handling. 84 bool isExceptional() const { 85 switch (getOpcode()) { 86 case Instruction::CatchSwitch: 87 case Instruction::CatchRet: 88 case Instruction::CleanupRet: 89 case Instruction::Invoke: 90 case Instruction::Resume: 91 return true; 92 default: 93 return false; 94 } 95 } 96 97 //===--------------------------------------------------------------------===// 98 // succ_iterator definition 99 //===--------------------------------------------------------------------===// 100 101 template <class Term, class BB> // Successor Iterator 102 class SuccIterator : public std::iterator<std::random_access_iterator_tag, BB, 103 int, BB *, BB *> { 104 using super = 105 std::iterator<std::random_access_iterator_tag, BB, int, BB *, BB *>; 106 107 public: 108 using pointer = typename super::pointer; 109 using reference = typename super::reference; 110 111 private: 112 Term TermInst; 113 unsigned idx; 114 using Self = SuccIterator<Term, BB>; 115 116 inline bool index_is_valid(unsigned idx) { 117 return idx < TermInst->getNumSuccessors(); 118 } 119 120 /// \brief Proxy object to allow write access in operator[] 121 class SuccessorProxy { 122 Self it; 123 124 public: 125 explicit SuccessorProxy(const Self &it) : it(it) {} 126 127 SuccessorProxy(const SuccessorProxy &) = default; 128 129 SuccessorProxy &operator=(SuccessorProxy r) { 130 *this = reference(r); 131 return *this; 132 } 133 134 SuccessorProxy &operator=(reference r) { 135 it.TermInst->setSuccessor(it.idx, r); 136 return *this; 137 } 138 139 operator reference() const { return *it; } 140 }; 141 142 public: 143 // begin iterator 144 explicit inline SuccIterator(Term T) : TermInst(T), idx(0) {} 145 // end iterator 146 inline SuccIterator(Term T, bool) : TermInst(T) { 147 if (TermInst) 148 idx = TermInst->getNumSuccessors(); 149 else 150 // Term == NULL happens, if a basic block is not fully constructed and 151 // consequently getTerminator() returns NULL. In this case we construct 152 // a SuccIterator which describes a basic block that has zero 153 // successors. 154 // Defining SuccIterator for incomplete and malformed CFGs is especially 155 // useful for debugging. 156 idx = 0; 157 } 158 159 /// This is used to interface between code that wants to 160 /// operate on terminator instructions directly. 161 unsigned getSuccessorIndex() const { return idx; } 162 163 inline bool operator==(const Self &x) const { return idx == x.idx; } 164 inline bool operator!=(const Self &x) const { return !operator==(x); } 165 166 inline reference operator*() const { return TermInst->getSuccessor(idx); } 167 inline pointer operator->() const { return operator*(); } 168 169 inline Self &operator++() { 170 ++idx; 171 return *this; 172 } // Preincrement 173 174 inline Self operator++(int) { // Postincrement 175 Self tmp = *this; 176 ++*this; 177 return tmp; 178 } 179 180 inline Self &operator--() { 181 --idx; 182 return *this; 183 } // Predecrement 184 inline Self operator--(int) { // Postdecrement 185 Self tmp = *this; 186 --*this; 187 return tmp; 188 } 189 190 inline bool operator<(const Self &x) const { 191 assert(TermInst == x.TermInst && 192 "Cannot compare iterators of different blocks!"); 193 return idx < x.idx; 194 } 195 196 inline bool operator<=(const Self &x) const { 197 assert(TermInst == x.TermInst && 198 "Cannot compare iterators of different blocks!"); 199 return idx <= x.idx; 200 } 201 inline bool operator>=(const Self &x) const { 202 assert(TermInst == x.TermInst && 203 "Cannot compare iterators of different blocks!"); 204 return idx >= x.idx; 205 } 206 207 inline bool operator>(const Self &x) const { 208 assert(TermInst == x.TermInst && 209 "Cannot compare iterators of different blocks!"); 210 return idx > x.idx; 211 } 212 213 inline Self &operator+=(int Right) { 214 unsigned new_idx = idx + Right; 215 assert(index_is_valid(new_idx) && "Iterator index out of bound"); 216 idx = new_idx; 217 return *this; 218 } 219 220 inline Self operator+(int Right) const { 221 Self tmp = *this; 222 tmp += Right; 223 return tmp; 224 } 225 226 inline Self &operator-=(int Right) { return operator+=(-Right); } 227 228 inline Self operator-(int Right) const { return operator+(-Right); } 229 230 inline int operator-(const Self &x) const { 231 assert(TermInst == x.TermInst && 232 "Cannot work on iterators of different blocks!"); 233 int distance = idx - x.idx; 234 return distance; 235 } 236 237 inline SuccessorProxy operator[](int offset) { 238 Self tmp = *this; 239 tmp += offset; 240 return SuccessorProxy(tmp); 241 } 242 243 /// Get the source BB of this iterator. 244 inline BB *getSource() { 245 assert(TermInst && "Source not available, if basic block was malformed"); 246 return TermInst->getParent(); 247 } 248 }; 249 250 using succ_iterator = SuccIterator<TerminatorInst *, BasicBlock>; 251 using succ_const_iterator = 252 SuccIterator<const TerminatorInst *, const BasicBlock>; 253 using succ_range = iterator_range<succ_iterator>; 254 using succ_const_range = iterator_range<succ_const_iterator>; 255 256 private: 257 inline succ_iterator succ_begin() { return succ_iterator(this); } 258 inline succ_const_iterator succ_begin() const { 259 return succ_const_iterator(this); 260 } 261 inline succ_iterator succ_end() { return succ_iterator(this, true); } 262 inline succ_const_iterator succ_end() const { 263 return succ_const_iterator(this, true); 264 } 265 266 public: 267 inline succ_range successors() { 268 return succ_range(succ_begin(), succ_end()); 269 } 270 inline succ_const_range successors() const { 271 return succ_const_range(succ_begin(), succ_end()); 272 } 273 }; 274 275 //===----------------------------------------------------------------------===// 276 // UnaryInstruction Class 277 //===----------------------------------------------------------------------===// 278 279 class UnaryInstruction : public Instruction { 280 protected: 281 UnaryInstruction(Type *Ty, unsigned iType, Value *V, 282 Instruction *IB = nullptr) 283 : Instruction(Ty, iType, &Op<0>(), 1, IB) { 284 Op<0>() = V; 285 } 286 UnaryInstruction(Type *Ty, unsigned iType, Value *V, BasicBlock *IAE) 287 : Instruction(Ty, iType, &Op<0>(), 1, IAE) { 288 Op<0>() = V; 289 } 290 291 public: 292 // allocate space for exactly one operand 293 void *operator new(size_t s) { 294 return User::operator new(s, 1); 295 } 296 297 /// Transparently provide more efficient getOperand methods. 298 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 299 300 // Methods for support type inquiry through isa, cast, and dyn_cast: 301 static inline bool classof(const Instruction *I) { 302 return I->getOpcode() == Instruction::Alloca || 303 I->getOpcode() == Instruction::Load || 304 I->getOpcode() == Instruction::VAArg || 305 I->getOpcode() == Instruction::ExtractValue || 306 (I->getOpcode() >= CastOpsBegin && I->getOpcode() < CastOpsEnd); 307 } 308 static inline bool classof(const Value *V) { 309 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 310 } 311 }; 312 313 template <> 314 struct OperandTraits<UnaryInstruction> : 315 public FixedNumOperandTraits<UnaryInstruction, 1> { 316 }; 317 318 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryInstruction, Value) 319 320 //===----------------------------------------------------------------------===// 321 // BinaryOperator Class 322 //===----------------------------------------------------------------------===// 323 324 class BinaryOperator : public Instruction { 325 protected: 326 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, 327 const Twine &Name, Instruction *InsertBefore); 328 BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, 329 const Twine &Name, BasicBlock *InsertAtEnd); 330 331 void init(BinaryOps iType); 332 333 // Note: Instruction needs to be a friend here to call cloneImpl. 334 friend class Instruction; 335 336 BinaryOperator *cloneImpl() const; 337 338 public: 339 // allocate space for exactly two operands 340 void *operator new(size_t s) { 341 return User::operator new(s, 2); 342 } 343 344 /// Transparently provide more efficient getOperand methods. 345 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 346 347 /// Construct a binary instruction, given the opcode and the two 348 /// operands. Optionally (if InstBefore is specified) insert the instruction 349 /// into a BasicBlock right before the specified instruction. The specified 350 /// Instruction is allowed to be a dereferenced end iterator. 351 /// 352 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, 353 const Twine &Name = Twine(), 354 Instruction *InsertBefore = nullptr); 355 356 /// Construct a binary instruction, given the opcode and the two 357 /// operands. Also automatically insert this instruction to the end of the 358 /// BasicBlock specified. 359 /// 360 static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, 361 const Twine &Name, BasicBlock *InsertAtEnd); 362 363 /// These methods just forward to Create, and are useful when you 364 /// statically know what type of instruction you're going to create. These 365 /// helpers just save some typing. 366 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 367 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 368 const Twine &Name = "") {\ 369 return Create(Instruction::OPC, V1, V2, Name);\ 370 } 371 #include "llvm/IR/Instruction.def" 372 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 373 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 374 const Twine &Name, BasicBlock *BB) {\ 375 return Create(Instruction::OPC, V1, V2, Name, BB);\ 376 } 377 #include "llvm/IR/Instruction.def" 378 #define HANDLE_BINARY_INST(N, OPC, CLASS) \ 379 static BinaryOperator *Create##OPC(Value *V1, Value *V2, \ 380 const Twine &Name, Instruction *I) {\ 381 return Create(Instruction::OPC, V1, V2, Name, I);\ 382 } 383 #include "llvm/IR/Instruction.def" 384 385 static BinaryOperator *CreateWithCopiedFlags(BinaryOps Opc, 386 Value *V1, Value *V2, 387 BinaryOperator *CopyBO, 388 const Twine &Name = "") { 389 BinaryOperator *BO = Create(Opc, V1, V2, Name); 390 BO->copyIRFlags(CopyBO); 391 return BO; 392 } 393 394 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 395 const Twine &Name = "") { 396 BinaryOperator *BO = Create(Opc, V1, V2, Name); 397 BO->setHasNoSignedWrap(true); 398 return BO; 399 } 400 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 401 const Twine &Name, BasicBlock *BB) { 402 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 403 BO->setHasNoSignedWrap(true); 404 return BO; 405 } 406 static BinaryOperator *CreateNSW(BinaryOps Opc, Value *V1, Value *V2, 407 const Twine &Name, Instruction *I) { 408 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 409 BO->setHasNoSignedWrap(true); 410 return BO; 411 } 412 413 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 414 const Twine &Name = "") { 415 BinaryOperator *BO = Create(Opc, V1, V2, Name); 416 BO->setHasNoUnsignedWrap(true); 417 return BO; 418 } 419 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 420 const Twine &Name, BasicBlock *BB) { 421 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 422 BO->setHasNoUnsignedWrap(true); 423 return BO; 424 } 425 static BinaryOperator *CreateNUW(BinaryOps Opc, Value *V1, Value *V2, 426 const Twine &Name, Instruction *I) { 427 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 428 BO->setHasNoUnsignedWrap(true); 429 return BO; 430 } 431 432 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 433 const Twine &Name = "") { 434 BinaryOperator *BO = Create(Opc, V1, V2, Name); 435 BO->setIsExact(true); 436 return BO; 437 } 438 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 439 const Twine &Name, BasicBlock *BB) { 440 BinaryOperator *BO = Create(Opc, V1, V2, Name, BB); 441 BO->setIsExact(true); 442 return BO; 443 } 444 static BinaryOperator *CreateExact(BinaryOps Opc, Value *V1, Value *V2, 445 const Twine &Name, Instruction *I) { 446 BinaryOperator *BO = Create(Opc, V1, V2, Name, I); 447 BO->setIsExact(true); 448 return BO; 449 } 450 451 #define DEFINE_HELPERS(OPC, NUWNSWEXACT) \ 452 static BinaryOperator *Create##NUWNSWEXACT##OPC(Value *V1, Value *V2, \ 453 const Twine &Name = "") { \ 454 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name); \ 455 } \ 456 static BinaryOperator *Create##NUWNSWEXACT##OPC( \ 457 Value *V1, Value *V2, const Twine &Name, BasicBlock *BB) { \ 458 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, BB); \ 459 } \ 460 static BinaryOperator *Create##NUWNSWEXACT##OPC( \ 461 Value *V1, Value *V2, const Twine &Name, Instruction *I) { \ 462 return Create##NUWNSWEXACT(Instruction::OPC, V1, V2, Name, I); \ 463 } 464 465 DEFINE_HELPERS(Add, NSW) // CreateNSWAdd 466 DEFINE_HELPERS(Add, NUW) // CreateNUWAdd 467 DEFINE_HELPERS(Sub, NSW) // CreateNSWSub 468 DEFINE_HELPERS(Sub, NUW) // CreateNUWSub 469 DEFINE_HELPERS(Mul, NSW) // CreateNSWMul 470 DEFINE_HELPERS(Mul, NUW) // CreateNUWMul 471 DEFINE_HELPERS(Shl, NSW) // CreateNSWShl 472 DEFINE_HELPERS(Shl, NUW) // CreateNUWShl 473 474 DEFINE_HELPERS(SDiv, Exact) // CreateExactSDiv 475 DEFINE_HELPERS(UDiv, Exact) // CreateExactUDiv 476 DEFINE_HELPERS(AShr, Exact) // CreateExactAShr 477 DEFINE_HELPERS(LShr, Exact) // CreateExactLShr 478 479 #undef DEFINE_HELPERS 480 481 /// Helper functions to construct and inspect unary operations (NEG and NOT) 482 /// via binary operators SUB and XOR: 483 /// 484 /// Create the NEG and NOT instructions out of SUB and XOR instructions. 485 /// 486 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name = "", 487 Instruction *InsertBefore = nullptr); 488 static BinaryOperator *CreateNeg(Value *Op, const Twine &Name, 489 BasicBlock *InsertAtEnd); 490 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name = "", 491 Instruction *InsertBefore = nullptr); 492 static BinaryOperator *CreateNSWNeg(Value *Op, const Twine &Name, 493 BasicBlock *InsertAtEnd); 494 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name = "", 495 Instruction *InsertBefore = nullptr); 496 static BinaryOperator *CreateNUWNeg(Value *Op, const Twine &Name, 497 BasicBlock *InsertAtEnd); 498 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name = "", 499 Instruction *InsertBefore = nullptr); 500 static BinaryOperator *CreateFNeg(Value *Op, const Twine &Name, 501 BasicBlock *InsertAtEnd); 502 static BinaryOperator *CreateNot(Value *Op, const Twine &Name = "", 503 Instruction *InsertBefore = nullptr); 504 static BinaryOperator *CreateNot(Value *Op, const Twine &Name, 505 BasicBlock *InsertAtEnd); 506 507 /// Check if the given Value is a NEG, FNeg, or NOT instruction. 508 /// 509 static bool isNeg(const Value *V); 510 static bool isFNeg(const Value *V, bool IgnoreZeroSign=false); 511 static bool isNot(const Value *V); 512 513 /// Helper functions to extract the unary argument of a NEG, FNEG or NOT 514 /// operation implemented via Sub, FSub, or Xor. 515 /// 516 static const Value *getNegArgument(const Value *BinOp); 517 static Value *getNegArgument( Value *BinOp); 518 static const Value *getFNegArgument(const Value *BinOp); 519 static Value *getFNegArgument( Value *BinOp); 520 static const Value *getNotArgument(const Value *BinOp); 521 static Value *getNotArgument( Value *BinOp); 522 523 BinaryOps getOpcode() const { 524 return static_cast<BinaryOps>(Instruction::getOpcode()); 525 } 526 527 /// Exchange the two operands to this instruction. 528 /// This instruction is safe to use on any binary instruction and 529 /// does not modify the semantics of the instruction. If the instruction 530 /// cannot be reversed (ie, it's a Div), then return true. 531 /// 532 bool swapOperands(); 533 534 // Methods for support type inquiry through isa, cast, and dyn_cast: 535 static inline bool classof(const Instruction *I) { 536 return I->isBinaryOp(); 537 } 538 static inline bool classof(const Value *V) { 539 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 540 } 541 }; 542 543 template <> 544 struct OperandTraits<BinaryOperator> : 545 public FixedNumOperandTraits<BinaryOperator, 2> { 546 }; 547 548 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryOperator, Value) 549 550 //===----------------------------------------------------------------------===// 551 // CastInst Class 552 //===----------------------------------------------------------------------===// 553 554 /// This is the base class for all instructions that perform data 555 /// casts. It is simply provided so that instruction category testing 556 /// can be performed with code like: 557 /// 558 /// if (isa<CastInst>(Instr)) { ... } 559 /// @brief Base class of casting instructions. 560 class CastInst : public UnaryInstruction { 561 protected: 562 /// @brief Constructor with insert-before-instruction semantics for subclasses 563 CastInst(Type *Ty, unsigned iType, Value *S, 564 const Twine &NameStr = "", Instruction *InsertBefore = nullptr) 565 : UnaryInstruction(Ty, iType, S, InsertBefore) { 566 setName(NameStr); 567 } 568 /// @brief Constructor with insert-at-end-of-block semantics for subclasses 569 CastInst(Type *Ty, unsigned iType, Value *S, 570 const Twine &NameStr, BasicBlock *InsertAtEnd) 571 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 572 setName(NameStr); 573 } 574 575 public: 576 /// Provides a way to construct any of the CastInst subclasses using an 577 /// opcode instead of the subclass's constructor. The opcode must be in the 578 /// CastOps category (Instruction::isCast(opcode) returns true). This 579 /// constructor has insert-before-instruction semantics to automatically 580 /// insert the new CastInst before InsertBefore (if it is non-null). 581 /// @brief Construct any of the CastInst subclasses 582 static CastInst *Create( 583 Instruction::CastOps, ///< The opcode of the cast instruction 584 Value *S, ///< The value to be casted (operand 0) 585 Type *Ty, ///< The type to which cast should be made 586 const Twine &Name = "", ///< Name for the instruction 587 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 588 ); 589 /// Provides a way to construct any of the CastInst subclasses using an 590 /// opcode instead of the subclass's constructor. The opcode must be in the 591 /// CastOps category. This constructor has insert-at-end-of-block semantics 592 /// to automatically insert the new CastInst at the end of InsertAtEnd (if 593 /// its non-null). 594 /// @brief Construct any of the CastInst subclasses 595 static CastInst *Create( 596 Instruction::CastOps, ///< The opcode for the cast instruction 597 Value *S, ///< The value to be casted (operand 0) 598 Type *Ty, ///< The type to which operand is casted 599 const Twine &Name, ///< The name for the instruction 600 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 601 ); 602 603 /// @brief Create a ZExt or BitCast cast instruction 604 static CastInst *CreateZExtOrBitCast( 605 Value *S, ///< The value to be casted (operand 0) 606 Type *Ty, ///< The type to which cast should be made 607 const Twine &Name = "", ///< Name for the instruction 608 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 609 ); 610 611 /// @brief Create a ZExt or BitCast cast instruction 612 static CastInst *CreateZExtOrBitCast( 613 Value *S, ///< The value to be casted (operand 0) 614 Type *Ty, ///< The type to which operand is casted 615 const Twine &Name, ///< The name for the instruction 616 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 617 ); 618 619 /// @brief Create a SExt or BitCast cast instruction 620 static CastInst *CreateSExtOrBitCast( 621 Value *S, ///< The value to be casted (operand 0) 622 Type *Ty, ///< The type to which cast should be made 623 const Twine &Name = "", ///< Name for the instruction 624 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 625 ); 626 627 /// @brief Create a SExt or BitCast cast instruction 628 static CastInst *CreateSExtOrBitCast( 629 Value *S, ///< The value to be casted (operand 0) 630 Type *Ty, ///< The type to which operand is casted 631 const Twine &Name, ///< The name for the instruction 632 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 633 ); 634 635 /// @brief Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction. 636 static CastInst *CreatePointerCast( 637 Value *S, ///< The pointer value to be casted (operand 0) 638 Type *Ty, ///< The type to which operand is casted 639 const Twine &Name, ///< The name for the instruction 640 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 641 ); 642 643 /// @brief Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction. 644 static CastInst *CreatePointerCast( 645 Value *S, ///< The pointer value to be casted (operand 0) 646 Type *Ty, ///< The type to which cast should be made 647 const Twine &Name = "", ///< Name for the instruction 648 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 649 ); 650 651 /// @brief Create a BitCast or an AddrSpaceCast cast instruction. 652 static CastInst *CreatePointerBitCastOrAddrSpaceCast( 653 Value *S, ///< The pointer value to be casted (operand 0) 654 Type *Ty, ///< The type to which operand is casted 655 const Twine &Name, ///< The name for the instruction 656 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 657 ); 658 659 /// @brief Create a BitCast or an AddrSpaceCast cast instruction. 660 static CastInst *CreatePointerBitCastOrAddrSpaceCast( 661 Value *S, ///< The pointer value to be casted (operand 0) 662 Type *Ty, ///< The type to which cast should be made 663 const Twine &Name = "", ///< Name for the instruction 664 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 665 ); 666 667 /// @brief Create a BitCast, a PtrToInt, or an IntToPTr cast instruction. 668 /// 669 /// If the value is a pointer type and the destination an integer type, 670 /// creates a PtrToInt cast. If the value is an integer type and the 671 /// destination a pointer type, creates an IntToPtr cast. Otherwise, creates 672 /// a bitcast. 673 static CastInst *CreateBitOrPointerCast( 674 Value *S, ///< The pointer value to be casted (operand 0) 675 Type *Ty, ///< The type to which cast should be made 676 const Twine &Name = "", ///< Name for the instruction 677 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 678 ); 679 680 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts. 681 static CastInst *CreateIntegerCast( 682 Value *S, ///< The pointer value to be casted (operand 0) 683 Type *Ty, ///< The type to which cast should be made 684 bool isSigned, ///< Whether to regard S as signed or not 685 const Twine &Name = "", ///< Name for the instruction 686 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 687 ); 688 689 /// @brief Create a ZExt, BitCast, or Trunc for int -> int casts. 690 static CastInst *CreateIntegerCast( 691 Value *S, ///< The integer value to be casted (operand 0) 692 Type *Ty, ///< The integer type to which operand is casted 693 bool isSigned, ///< Whether to regard S as signed or not 694 const Twine &Name, ///< The name for the instruction 695 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 696 ); 697 698 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts 699 static CastInst *CreateFPCast( 700 Value *S, ///< The floating point value to be casted 701 Type *Ty, ///< The floating point type to cast to 702 const Twine &Name = "", ///< Name for the instruction 703 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 704 ); 705 706 /// @brief Create an FPExt, BitCast, or FPTrunc for fp -> fp casts 707 static CastInst *CreateFPCast( 708 Value *S, ///< The floating point value to be casted 709 Type *Ty, ///< The floating point type to cast to 710 const Twine &Name, ///< The name for the instruction 711 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 712 ); 713 714 /// @brief Create a Trunc or BitCast cast instruction 715 static CastInst *CreateTruncOrBitCast( 716 Value *S, ///< The value to be casted (operand 0) 717 Type *Ty, ///< The type to which cast should be made 718 const Twine &Name = "", ///< Name for the instruction 719 Instruction *InsertBefore = nullptr ///< Place to insert the instruction 720 ); 721 722 /// @brief Create a Trunc or BitCast cast instruction 723 static CastInst *CreateTruncOrBitCast( 724 Value *S, ///< The value to be casted (operand 0) 725 Type *Ty, ///< The type to which operand is casted 726 const Twine &Name, ///< The name for the instruction 727 BasicBlock *InsertAtEnd ///< The block to insert the instruction into 728 ); 729 730 /// @brief Check whether it is valid to call getCastOpcode for these types. 731 static bool isCastable( 732 Type *SrcTy, ///< The Type from which the value should be cast. 733 Type *DestTy ///< The Type to which the value should be cast. 734 ); 735 736 /// @brief Check whether a bitcast between these types is valid 737 static bool isBitCastable( 738 Type *SrcTy, ///< The Type from which the value should be cast. 739 Type *DestTy ///< The Type to which the value should be cast. 740 ); 741 742 /// @brief Check whether a bitcast, inttoptr, or ptrtoint cast between these 743 /// types is valid and a no-op. 744 /// 745 /// This ensures that any pointer<->integer cast has enough bits in the 746 /// integer and any other cast is a bitcast. 747 static bool isBitOrNoopPointerCastable( 748 Type *SrcTy, ///< The Type from which the value should be cast. 749 Type *DestTy, ///< The Type to which the value should be cast. 750 const DataLayout &DL); 751 752 /// Returns the opcode necessary to cast Val into Ty using usual casting 753 /// rules. 754 /// @brief Infer the opcode for cast operand and type 755 static Instruction::CastOps getCastOpcode( 756 const Value *Val, ///< The value to cast 757 bool SrcIsSigned, ///< Whether to treat the source as signed 758 Type *Ty, ///< The Type to which the value should be casted 759 bool DstIsSigned ///< Whether to treate the dest. as signed 760 ); 761 762 /// There are several places where we need to know if a cast instruction 763 /// only deals with integer source and destination types. To simplify that 764 /// logic, this method is provided. 765 /// @returns true iff the cast has only integral typed operand and dest type. 766 /// @brief Determine if this is an integer-only cast. 767 bool isIntegerCast() const; 768 769 /// A lossless cast is one that does not alter the basic value. It implies 770 /// a no-op cast but is more stringent, preventing things like int->float, 771 /// long->double, or int->ptr. 772 /// @returns true iff the cast is lossless. 773 /// @brief Determine if this is a lossless cast. 774 bool isLosslessCast() const; 775 776 /// A no-op cast is one that can be effected without changing any bits. 777 /// It implies that the source and destination types are the same size. The 778 /// IntPtrTy argument is used to make accurate determinations for casts 779 /// involving Integer and Pointer types. They are no-op casts if the integer 780 /// is the same size as the pointer. However, pointer size varies with 781 /// platform. Generally, the result of DataLayout::getIntPtrType() should be 782 /// passed in. If that's not available, use Type::Int64Ty, which will make 783 /// the isNoopCast call conservative. 784 /// @brief Determine if the described cast is a no-op cast. 785 static bool isNoopCast( 786 Instruction::CastOps Opcode, ///< Opcode of cast 787 Type *SrcTy, ///< SrcTy of cast 788 Type *DstTy, ///< DstTy of cast 789 Type *IntPtrTy ///< Integer type corresponding to Ptr types 790 ); 791 792 /// @brief Determine if this cast is a no-op cast. 793 bool isNoopCast( 794 Type *IntPtrTy ///< Integer type corresponding to pointer 795 ) const; 796 797 /// @brief Determine if this cast is a no-op cast. 798 /// 799 /// \param DL is the DataLayout to get the Int Ptr type from. 800 bool isNoopCast(const DataLayout &DL) const; 801 802 /// Determine how a pair of casts can be eliminated, if they can be at all. 803 /// This is a helper function for both CastInst and ConstantExpr. 804 /// @returns 0 if the CastInst pair can't be eliminated, otherwise 805 /// returns Instruction::CastOps value for a cast that can replace 806 /// the pair, casting SrcTy to DstTy. 807 /// @brief Determine if a cast pair is eliminable 808 static unsigned isEliminableCastPair( 809 Instruction::CastOps firstOpcode, ///< Opcode of first cast 810 Instruction::CastOps secondOpcode, ///< Opcode of second cast 811 Type *SrcTy, ///< SrcTy of 1st cast 812 Type *MidTy, ///< DstTy of 1st cast & SrcTy of 2nd cast 813 Type *DstTy, ///< DstTy of 2nd cast 814 Type *SrcIntPtrTy, ///< Integer type corresponding to Ptr SrcTy, or null 815 Type *MidIntPtrTy, ///< Integer type corresponding to Ptr MidTy, or null 816 Type *DstIntPtrTy ///< Integer type corresponding to Ptr DstTy, or null 817 ); 818 819 /// @brief Return the opcode of this CastInst 820 Instruction::CastOps getOpcode() const { 821 return Instruction::CastOps(Instruction::getOpcode()); 822 } 823 824 /// @brief Return the source type, as a convenience 825 Type* getSrcTy() const { return getOperand(0)->getType(); } 826 /// @brief Return the destination type, as a convenience 827 Type* getDestTy() const { return getType(); } 828 829 /// This method can be used to determine if a cast from S to DstTy using 830 /// Opcode op is valid or not. 831 /// @returns true iff the proposed cast is valid. 832 /// @brief Determine if a cast is valid without creating one. 833 static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy); 834 835 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast: 836 static inline bool classof(const Instruction *I) { 837 return I->isCast(); 838 } 839 static inline bool classof(const Value *V) { 840 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 841 } 842 }; 843 844 //===----------------------------------------------------------------------===// 845 // CmpInst Class 846 //===----------------------------------------------------------------------===// 847 848 /// This class is the base class for the comparison instructions. 849 /// @brief Abstract base class of comparison instructions. 850 class CmpInst : public Instruction { 851 public: 852 /// This enumeration lists the possible predicates for CmpInst subclasses. 853 /// Values in the range 0-31 are reserved for FCmpInst, while values in the 854 /// range 32-64 are reserved for ICmpInst. This is necessary to ensure the 855 /// predicate values are not overlapping between the classes. 856 /// 857 /// Some passes (e.g. InstCombine) depend on the bit-wise characteristics of 858 /// FCMP_* values. Changing the bit patterns requires a potential change to 859 /// those passes. 860 enum Predicate { 861 // Opcode U L G E Intuitive operation 862 FCMP_FALSE = 0, ///< 0 0 0 0 Always false (always folded) 863 FCMP_OEQ = 1, ///< 0 0 0 1 True if ordered and equal 864 FCMP_OGT = 2, ///< 0 0 1 0 True if ordered and greater than 865 FCMP_OGE = 3, ///< 0 0 1 1 True if ordered and greater than or equal 866 FCMP_OLT = 4, ///< 0 1 0 0 True if ordered and less than 867 FCMP_OLE = 5, ///< 0 1 0 1 True if ordered and less than or equal 868 FCMP_ONE = 6, ///< 0 1 1 0 True if ordered and operands are unequal 869 FCMP_ORD = 7, ///< 0 1 1 1 True if ordered (no nans) 870 FCMP_UNO = 8, ///< 1 0 0 0 True if unordered: isnan(X) | isnan(Y) 871 FCMP_UEQ = 9, ///< 1 0 0 1 True if unordered or equal 872 FCMP_UGT = 10, ///< 1 0 1 0 True if unordered or greater than 873 FCMP_UGE = 11, ///< 1 0 1 1 True if unordered, greater than, or equal 874 FCMP_ULT = 12, ///< 1 1 0 0 True if unordered or less than 875 FCMP_ULE = 13, ///< 1 1 0 1 True if unordered, less than, or equal 876 FCMP_UNE = 14, ///< 1 1 1 0 True if unordered or not equal 877 FCMP_TRUE = 15, ///< 1 1 1 1 Always true (always folded) 878 FIRST_FCMP_PREDICATE = FCMP_FALSE, 879 LAST_FCMP_PREDICATE = FCMP_TRUE, 880 BAD_FCMP_PREDICATE = FCMP_TRUE + 1, 881 ICMP_EQ = 32, ///< equal 882 ICMP_NE = 33, ///< not equal 883 ICMP_UGT = 34, ///< unsigned greater than 884 ICMP_UGE = 35, ///< unsigned greater or equal 885 ICMP_ULT = 36, ///< unsigned less than 886 ICMP_ULE = 37, ///< unsigned less or equal 887 ICMP_SGT = 38, ///< signed greater than 888 ICMP_SGE = 39, ///< signed greater or equal 889 ICMP_SLT = 40, ///< signed less than 890 ICMP_SLE = 41, ///< signed less or equal 891 FIRST_ICMP_PREDICATE = ICMP_EQ, 892 LAST_ICMP_PREDICATE = ICMP_SLE, 893 BAD_ICMP_PREDICATE = ICMP_SLE + 1 894 }; 895 896 protected: 897 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, 898 Value *LHS, Value *RHS, const Twine &Name = "", 899 Instruction *InsertBefore = nullptr); 900 901 CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, 902 Value *LHS, Value *RHS, const Twine &Name, 903 BasicBlock *InsertAtEnd); 904 905 public: 906 // allocate space for exactly two operands 907 void *operator new(size_t s) { 908 return User::operator new(s, 2); 909 } 910 911 /// Construct a compare instruction, given the opcode, the predicate and 912 /// the two operands. Optionally (if InstBefore is specified) insert the 913 /// instruction into a BasicBlock right before the specified instruction. 914 /// The specified Instruction is allowed to be a dereferenced end iterator. 915 /// @brief Create a CmpInst 916 static CmpInst *Create(OtherOps Op, 917 Predicate predicate, Value *S1, 918 Value *S2, const Twine &Name = "", 919 Instruction *InsertBefore = nullptr); 920 921 /// Construct a compare instruction, given the opcode, the predicate and the 922 /// two operands. Also automatically insert this instruction to the end of 923 /// the BasicBlock specified. 924 /// @brief Create a CmpInst 925 static CmpInst *Create(OtherOps Op, Predicate predicate, Value *S1, 926 Value *S2, const Twine &Name, BasicBlock *InsertAtEnd); 927 928 /// @brief Get the opcode casted to the right type 929 OtherOps getOpcode() const { 930 return static_cast<OtherOps>(Instruction::getOpcode()); 931 } 932 933 /// @brief Return the predicate for this instruction. 934 Predicate getPredicate() const { 935 return Predicate(getSubclassDataFromInstruction()); 936 } 937 938 /// @brief Set the predicate for this instruction to the specified value. 939 void setPredicate(Predicate P) { setInstructionSubclassData(P); } 940 941 static bool isFPPredicate(Predicate P) { 942 return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE; 943 } 944 945 static bool isIntPredicate(Predicate P) { 946 return P >= FIRST_ICMP_PREDICATE && P <= LAST_ICMP_PREDICATE; 947 } 948 949 static StringRef getPredicateName(Predicate P); 950 951 bool isFPPredicate() const { return isFPPredicate(getPredicate()); } 952 bool isIntPredicate() const { return isIntPredicate(getPredicate()); } 953 954 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 955 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 956 /// @returns the inverse predicate for the instruction's current predicate. 957 /// @brief Return the inverse of the instruction's predicate. 958 Predicate getInversePredicate() const { 959 return getInversePredicate(getPredicate()); 960 } 961 962 /// For example, EQ -> NE, UGT -> ULE, SLT -> SGE, 963 /// OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc. 964 /// @returns the inverse predicate for predicate provided in \p pred. 965 /// @brief Return the inverse of a given predicate 966 static Predicate getInversePredicate(Predicate pred); 967 968 /// For example, EQ->EQ, SLE->SGE, ULT->UGT, 969 /// OEQ->OEQ, ULE->UGE, OLT->OGT, etc. 970 /// @returns the predicate that would be the result of exchanging the two 971 /// operands of the CmpInst instruction without changing the result 972 /// produced. 973 /// @brief Return the predicate as if the operands were swapped 974 Predicate getSwappedPredicate() const { 975 return getSwappedPredicate(getPredicate()); 976 } 977 978 /// This is a static version that you can use without an instruction 979 /// available. 980 /// @brief Return the predicate as if the operands were swapped. 981 static Predicate getSwappedPredicate(Predicate pred); 982 983 /// @brief Provide more efficient getOperand methods. 984 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 985 986 /// This is just a convenience that dispatches to the subclasses. 987 /// @brief Swap the operands and adjust predicate accordingly to retain 988 /// the same comparison. 989 void swapOperands(); 990 991 /// This is just a convenience that dispatches to the subclasses. 992 /// @brief Determine if this CmpInst is commutative. 993 bool isCommutative() const; 994 995 /// This is just a convenience that dispatches to the subclasses. 996 /// @brief Determine if this is an equals/not equals predicate. 997 bool isEquality() const; 998 999 /// @returns true if the comparison is signed, false otherwise. 1000 /// @brief Determine if this instruction is using a signed comparison. 1001 bool isSigned() const { 1002 return isSigned(getPredicate()); 1003 } 1004 1005 /// @returns true if the comparison is unsigned, false otherwise. 1006 /// @brief Determine if this instruction is using an unsigned comparison. 1007 bool isUnsigned() const { 1008 return isUnsigned(getPredicate()); 1009 } 1010 1011 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert 1012 /// @returns the signed version of the unsigned predicate pred. 1013 /// @brief return the signed version of a predicate 1014 static Predicate getSignedPredicate(Predicate pred); 1015 1016 /// For example, ULT->SLT, ULE->SLE, UGT->SGT, UGE->SGE, SLT->Failed assert 1017 /// @returns the signed version of the predicate for this instruction (which 1018 /// has to be an unsigned predicate). 1019 /// @brief return the signed version of a predicate 1020 Predicate getSignedPredicate() { 1021 return getSignedPredicate(getPredicate()); 1022 } 1023 1024 /// This is just a convenience. 1025 /// @brief Determine if this is true when both operands are the same. 1026 bool isTrueWhenEqual() const { 1027 return isTrueWhenEqual(getPredicate()); 1028 } 1029 1030 /// This is just a convenience. 1031 /// @brief Determine if this is false when both operands are the same. 1032 bool isFalseWhenEqual() const { 1033 return isFalseWhenEqual(getPredicate()); 1034 } 1035 1036 /// @returns true if the predicate is unsigned, false otherwise. 1037 /// @brief Determine if the predicate is an unsigned operation. 1038 static bool isUnsigned(Predicate predicate); 1039 1040 /// @returns true if the predicate is signed, false otherwise. 1041 /// @brief Determine if the predicate is an signed operation. 1042 static bool isSigned(Predicate predicate); 1043 1044 /// @brief Determine if the predicate is an ordered operation. 1045 static bool isOrdered(Predicate predicate); 1046 1047 /// @brief Determine if the predicate is an unordered operation. 1048 static bool isUnordered(Predicate predicate); 1049 1050 /// Determine if the predicate is true when comparing a value with itself. 1051 static bool isTrueWhenEqual(Predicate predicate); 1052 1053 /// Determine if the predicate is false when comparing a value with itself. 1054 static bool isFalseWhenEqual(Predicate predicate); 1055 1056 /// Determine if Pred1 implies Pred2 is true when two compares have matching 1057 /// operands. 1058 static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2); 1059 1060 /// Determine if Pred1 implies Pred2 is false when two compares have matching 1061 /// operands. 1062 static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2); 1063 1064 /// @brief Methods for support type inquiry through isa, cast, and dyn_cast: 1065 static inline bool classof(const Instruction *I) { 1066 return I->getOpcode() == Instruction::ICmp || 1067 I->getOpcode() == Instruction::FCmp; 1068 } 1069 static inline bool classof(const Value *V) { 1070 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1071 } 1072 1073 /// @brief Create a result type for fcmp/icmp 1074 static Type* makeCmpResultType(Type* opnd_type) { 1075 if (VectorType* vt = dyn_cast<VectorType>(opnd_type)) { 1076 return VectorType::get(Type::getInt1Ty(opnd_type->getContext()), 1077 vt->getNumElements()); 1078 } 1079 return Type::getInt1Ty(opnd_type->getContext()); 1080 } 1081 1082 private: 1083 // Shadow Value::setValueSubclassData with a private forwarding method so that 1084 // subclasses cannot accidentally use it. 1085 void setValueSubclassData(unsigned short D) { 1086 Value::setValueSubclassData(D); 1087 } 1088 }; 1089 1090 // FIXME: these are redundant if CmpInst < BinaryOperator 1091 template <> 1092 struct OperandTraits<CmpInst> : public FixedNumOperandTraits<CmpInst, 2> { 1093 }; 1094 1095 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CmpInst, Value) 1096 1097 //===----------------------------------------------------------------------===// 1098 // FuncletPadInst Class 1099 //===----------------------------------------------------------------------===// 1100 class FuncletPadInst : public Instruction { 1101 private: 1102 FuncletPadInst(const FuncletPadInst &CPI); 1103 1104 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1105 ArrayRef<Value *> Args, unsigned Values, 1106 const Twine &NameStr, Instruction *InsertBefore); 1107 explicit FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1108 ArrayRef<Value *> Args, unsigned Values, 1109 const Twine &NameStr, BasicBlock *InsertAtEnd); 1110 1111 void init(Value *ParentPad, ArrayRef<Value *> Args, const Twine &NameStr); 1112 1113 protected: 1114 // Note: Instruction needs to be a friend here to call cloneImpl. 1115 friend class Instruction; 1116 friend class CatchPadInst; 1117 friend class CleanupPadInst; 1118 1119 FuncletPadInst *cloneImpl() const; 1120 1121 public: 1122 /// Provide fast operand accessors 1123 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 1124 1125 /// getNumArgOperands - Return the number of funcletpad arguments. 1126 /// 1127 unsigned getNumArgOperands() const { return getNumOperands() - 1; } 1128 1129 /// Convenience accessors 1130 1131 /// \brief Return the outer EH-pad this funclet is nested within. 1132 /// 1133 /// Note: This returns the associated CatchSwitchInst if this FuncletPadInst 1134 /// is a CatchPadInst. 1135 Value *getParentPad() const { return Op<-1>(); } 1136 void setParentPad(Value *ParentPad) { 1137 assert(ParentPad); 1138 Op<-1>() = ParentPad; 1139 } 1140 1141 /// getArgOperand/setArgOperand - Return/set the i-th funcletpad argument. 1142 /// 1143 Value *getArgOperand(unsigned i) const { return getOperand(i); } 1144 void setArgOperand(unsigned i, Value *v) { setOperand(i, v); } 1145 1146 /// arg_operands - iteration adapter for range-for loops. 1147 op_range arg_operands() { return op_range(op_begin(), op_end() - 1); } 1148 1149 /// arg_operands - iteration adapter for range-for loops. 1150 const_op_range arg_operands() const { 1151 return const_op_range(op_begin(), op_end() - 1); 1152 } 1153 1154 // Methods for support type inquiry through isa, cast, and dyn_cast: 1155 static inline bool classof(const Instruction *I) { return I->isFuncletPad(); } 1156 static inline bool classof(const Value *V) { 1157 return isa<Instruction>(V) && classof(cast<Instruction>(V)); 1158 } 1159 }; 1160 1161 template <> 1162 struct OperandTraits<FuncletPadInst> 1163 : public VariadicOperandTraits<FuncletPadInst, /*MINARITY=*/1> {}; 1164 1165 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(FuncletPadInst, Value) 1166 1167 /// \brief A lightweight accessor for an operand bundle meant to be passed 1168 /// around by value. 1169 struct OperandBundleUse { 1170 ArrayRef<Use> Inputs; 1171 1172 OperandBundleUse() = default; 1173 explicit OperandBundleUse(StringMapEntry<uint32_t> *Tag, ArrayRef<Use> Inputs) 1174 : Inputs(Inputs), Tag(Tag) {} 1175 1176 /// \brief Return true if the operand at index \p Idx in this operand bundle 1177 /// has the attribute A. 1178 bool operandHasAttr(unsigned Idx, Attribute::AttrKind A) const { 1179 if (isDeoptOperandBundle()) 1180 if (A == Attribute::ReadOnly || A == Attribute::NoCapture) 1181 return Inputs[Idx]->getType()->isPointerTy(); 1182 1183 // Conservative answer: no operands have any attributes. 1184 return false; 1185 } 1186 1187 /// \brief Return the tag of this operand bundle as a string. 1188 StringRef getTagName() const { 1189 return Tag->getKey(); 1190 } 1191 1192 /// \brief Return the tag of this operand bundle as an integer. 1193 /// 1194 /// Operand bundle tags are interned by LLVMContextImpl::getOrInsertBundleTag, 1195 /// and this function returns the unique integer getOrInsertBundleTag 1196 /// associated the tag of this operand bundle to. 1197 uint32_t getTagID() const { 1198 return Tag->getValue(); 1199 } 1200 1201 /// \brief Return true if this is a "deopt" operand bundle. 1202 bool isDeoptOperandBundle() const { 1203 return getTagID() == LLVMContext::OB_deopt; 1204 } 1205 1206 /// \brief Return true if this is a "funclet" operand bundle. 1207 bool isFuncletOperandBundle() const { 1208 return getTagID() == LLVMContext::OB_funclet; 1209 } 1210 1211 private: 1212 /// \brief Pointer to an entry in LLVMContextImpl::getOrInsertBundleTag. 1213 StringMapEntry<uint32_t> *Tag; 1214 }; 1215 1216 /// \brief A container for an operand bundle being viewed as a set of values 1217 /// rather than a set of uses. 1218 /// 1219 /// Unlike OperandBundleUse, OperandBundleDefT owns the memory it carries, and 1220 /// so it is possible to create and pass around "self-contained" instances of 1221 /// OperandBundleDef and ConstOperandBundleDef. 1222 template <typename InputTy> class OperandBundleDefT { 1223 std::string Tag; 1224 std::vector<InputTy> Inputs; 1225 1226 public: 1227 explicit OperandBundleDefT(std::string Tag, std::vector<InputTy> Inputs) 1228 : Tag(std::move(Tag)), Inputs(std::move(Inputs)) {} 1229 explicit OperandBundleDefT(std::string Tag, ArrayRef<InputTy> Inputs) 1230 : Tag(std::move(Tag)), Inputs(Inputs) {} 1231 1232 explicit OperandBundleDefT(const OperandBundleUse &OBU) { 1233 Tag = OBU.getTagName(); 1234 Inputs.insert(Inputs.end(), OBU.Inputs.begin(), OBU.Inputs.end()); 1235 } 1236 1237 ArrayRef<InputTy> inputs() const { return Inputs; } 1238 1239 using input_iterator = typename std::vector<InputTy>::const_iterator; 1240 1241 size_t input_size() const { return Inputs.size(); } 1242 input_iterator input_begin() const { return Inputs.begin(); } 1243 input_iterator input_end() const { return Inputs.end(); } 1244 1245 StringRef getTag() const { return Tag; } 1246 }; 1247 1248 using OperandBundleDef = OperandBundleDefT<Value *>; 1249 using ConstOperandBundleDef = OperandBundleDefT<const Value *>; 1250 1251 /// \brief A mixin to add operand bundle functionality to llvm instruction 1252 /// classes. 1253 /// 1254 /// OperandBundleUser uses the descriptor area co-allocated with the host User 1255 /// to store some meta information about which operands are "normal" operands, 1256 /// and which ones belong to some operand bundle. 1257 /// 1258 /// The layout of an operand bundle user is 1259 /// 1260 /// +-----------uint32_t End-------------------------------------+ 1261 /// | | 1262 /// | +--------uint32_t Begin--------------------+ | 1263 /// | | | | 1264 /// ^ ^ v v 1265 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 1266 /// | BOI0 | BOI1 | .. | DU | U0 | U1 | .. | BOI0_U0 | .. | BOI1_U0 | .. | Un 1267 /// |------|------|----|----|----|----|----|---------|----|---------|----|----- 1268 /// v v ^ ^ 1269 /// | | | | 1270 /// | +--------uint32_t Begin------------+ | 1271 /// | | 1272 /// +-----------uint32_t End-----------------------------+ 1273 /// 1274 /// 1275 /// BOI0, BOI1 ... are descriptions of operand bundles in this User's use list. 1276 /// These descriptions are installed and managed by this class, and they're all 1277 /// instances of OperandBundleUser<T>::BundleOpInfo. 1278 /// 1279 /// DU is an additional descriptor installed by User's 'operator new' to keep 1280 /// track of the 'BOI0 ... BOIN' co-allocation. OperandBundleUser does not 1281 /// access or modify DU in any way, it's an implementation detail private to 1282 /// User. 1283 /// 1284 /// The regular Use& vector for the User starts at U0. The operand bundle uses 1285 /// are part of the Use& vector, just like normal uses. In the diagram above, 1286 /// the operand bundle uses start at BOI0_U0. Each instance of BundleOpInfo has 1287 /// information about a contiguous set of uses constituting an operand bundle, 1288 /// and the total set of operand bundle uses themselves form a contiguous set of 1289 /// uses (i.e. there are no gaps between uses corresponding to individual 1290 /// operand bundles). 1291 /// 1292 /// This class does not know the location of the set of operand bundle uses 1293 /// within the use list -- that is decided by the User using this class via the 1294 /// BeginIdx argument in populateBundleOperandInfos. 1295 /// 1296 /// Currently operand bundle users with hung-off operands are not supported. 1297 template <typename InstrTy, typename OpIteratorTy> class OperandBundleUser { 1298 public: 1299 /// \brief Return the number of operand bundles associated with this User. 1300 unsigned getNumOperandBundles() const { 1301 return std::distance(bundle_op_info_begin(), bundle_op_info_end()); 1302 } 1303 1304 /// \brief Return true if this User has any operand bundles. 1305 bool hasOperandBundles() const { return getNumOperandBundles() != 0; } 1306 1307 /// \brief Return the index of the first bundle operand in the Use array. 1308 unsigned getBundleOperandsStartIndex() const { 1309 assert(hasOperandBundles() && "Don't call otherwise!"); 1310 return bundle_op_info_begin()->Begin; 1311 } 1312 1313 /// \brief Return the index of the last bundle operand in the Use array. 1314 unsigned getBundleOperandsEndIndex() const { 1315 assert(hasOperandBundles() && "Don't call otherwise!"); 1316 return bundle_op_info_end()[-1].End; 1317 } 1318 1319 /// Return true if the operand at index \p Idx is a bundle operand. 1320 bool isBundleOperand(unsigned Idx) const { 1321 return hasOperandBundles() && Idx >= getBundleOperandsStartIndex() && 1322 Idx < getBundleOperandsEndIndex(); 1323 } 1324 1325 /// \brief Return the total number operands (not operand bundles) used by 1326 /// every operand bundle in this OperandBundleUser. 1327 unsigned getNumTotalBundleOperands() const { 1328 if (!hasOperandBundles()) 1329 return 0; 1330 1331 unsigned Begin = getBundleOperandsStartIndex(); 1332 unsigned End = getBundleOperandsEndIndex(); 1333 1334 assert(Begin <= End && "Should be!"); 1335 return End - Begin; 1336 } 1337 1338 /// \brief Return the operand bundle at a specific index. 1339 OperandBundleUse getOperandBundleAt(unsigned Index) const { 1340 assert(Index < getNumOperandBundles() && "Index out of bounds!"); 1341 return operandBundleFromBundleOpInfo(*(bundle_op_info_begin() + Index)); 1342 } 1343 1344 /// \brief Return the number of operand bundles with the tag Name attached to 1345 /// this instruction. 1346 unsigned countOperandBundlesOfType(StringRef Name) const { 1347 unsigned Count = 0; 1348 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 1349 if (getOperandBundleAt(i).getTagName() == Name) 1350 Count++; 1351 1352 return Count; 1353 } 1354 1355 /// \brief Return the number of operand bundles with the tag ID attached to 1356 /// this instruction. 1357 unsigned countOperandBundlesOfType(uint32_t ID) const { 1358 unsigned Count = 0; 1359 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 1360 if (getOperandBundleAt(i).getTagID() == ID) 1361 Count++; 1362 1363 return Count; 1364 } 1365 1366 /// \brief Return an operand bundle by name, if present. 1367 /// 1368 /// It is an error to call this for operand bundle types that may have 1369 /// multiple instances of them on the same instruction. 1370 Optional<OperandBundleUse> getOperandBundle(StringRef Name) const { 1371 assert(countOperandBundlesOfType(Name) < 2 && "Precondition violated!"); 1372 1373 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 1374 OperandBundleUse U = getOperandBundleAt(i); 1375 if (U.getTagName() == Name) 1376 return U; 1377 } 1378 1379 return None; 1380 } 1381 1382 /// \brief Return an operand bundle by tag ID, if present. 1383 /// 1384 /// It is an error to call this for operand bundle types that may have 1385 /// multiple instances of them on the same instruction. 1386 Optional<OperandBundleUse> getOperandBundle(uint32_t ID) const { 1387 assert(countOperandBundlesOfType(ID) < 2 && "Precondition violated!"); 1388 1389 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 1390 OperandBundleUse U = getOperandBundleAt(i); 1391 if (U.getTagID() == ID) 1392 return U; 1393 } 1394 1395 return None; 1396 } 1397 1398 /// \brief Return the list of operand bundles attached to this instruction as 1399 /// a vector of OperandBundleDefs. 1400 /// 1401 /// This function copies the OperandBundeUse instances associated with this 1402 /// OperandBundleUser to a vector of OperandBundleDefs. Note: 1403 /// OperandBundeUses and OperandBundleDefs are non-trivially *different* 1404 /// representations of operand bundles (see documentation above). 1405 void getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> &Defs) const { 1406 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) 1407 Defs.emplace_back(getOperandBundleAt(i)); 1408 } 1409 1410 /// \brief Return the operand bundle for the operand at index OpIdx. 1411 /// 1412 /// It is an error to call this with an OpIdx that does not correspond to an 1413 /// bundle operand. 1414 OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const { 1415 return operandBundleFromBundleOpInfo(getBundleOpInfoForOperand(OpIdx)); 1416 } 1417 1418 /// \brief Return true if this operand bundle user has operand bundles that 1419 /// may read from the heap. 1420 bool hasReadingOperandBundles() const { 1421 // Implementation note: this is a conservative implementation of operand 1422 // bundle semantics, where *any* operand bundle forces a callsite to be at 1423 // least readonly. 1424 return hasOperandBundles(); 1425 } 1426 1427 /// \brief Return true if this operand bundle user has operand bundles that 1428 /// may write to the heap. 1429 bool hasClobberingOperandBundles() const { 1430 for (auto &BOI : bundle_op_infos()) { 1431 if (BOI.Tag->second == LLVMContext::OB_deopt || 1432 BOI.Tag->second == LLVMContext::OB_funclet) 1433 continue; 1434 1435 // This instruction has an operand bundle that is not known to us. 1436 // Assume the worst. 1437 return true; 1438 } 1439 1440 return false; 1441 } 1442 1443 /// \brief Return true if the bundle operand at index \p OpIdx has the 1444 /// attribute \p A. 1445 bool bundleOperandHasAttr(unsigned OpIdx, Attribute::AttrKind A) const { 1446 auto &BOI = getBundleOpInfoForOperand(OpIdx); 1447 auto OBU = operandBundleFromBundleOpInfo(BOI); 1448 return OBU.operandHasAttr(OpIdx - BOI.Begin, A); 1449 } 1450 1451 /// \brief Return true if \p Other has the same sequence of operand bundle 1452 /// tags with the same number of operands on each one of them as this 1453 /// OperandBundleUser. 1454 bool hasIdenticalOperandBundleSchema( 1455 const OperandBundleUser<InstrTy, OpIteratorTy> &Other) const { 1456 if (getNumOperandBundles() != Other.getNumOperandBundles()) 1457 return false; 1458 1459 return std::equal(bundle_op_info_begin(), bundle_op_info_end(), 1460 Other.bundle_op_info_begin()); 1461 } 1462 1463 /// \brief Return true if this operand bundle user contains operand bundles 1464 /// with tags other than those specified in \p IDs. 1465 bool hasOperandBundlesOtherThan(ArrayRef<uint32_t> IDs) const { 1466 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i) { 1467 uint32_t ID = getOperandBundleAt(i).getTagID(); 1468 if (!is_contained(IDs, ID)) 1469 return true; 1470 } 1471 return false; 1472 } 1473 1474 protected: 1475 /// \brief Is the function attribute S disallowed by some operand bundle on 1476 /// this operand bundle user? 1477 bool isFnAttrDisallowedByOpBundle(StringRef S) const { 1478 // Operand bundles only possibly disallow readnone, readonly and argmenonly 1479 // attributes. All String attributes are fine. 1480 return false; 1481 } 1482 1483 /// \brief Is the function attribute A disallowed by some operand bundle on 1484 /// this operand bundle user? 1485 bool isFnAttrDisallowedByOpBundle(Attribute::AttrKind A) const { 1486 switch (A) { 1487 default: 1488 return false; 1489 1490 case Attribute::ArgMemOnly: 1491 return hasReadingOperandBundles(); 1492 1493 case Attribute::ReadNone: 1494 return hasReadingOperandBundles(); 1495 1496 case Attribute::ReadOnly: 1497 return hasClobberingOperandBundles(); 1498 } 1499 1500 llvm_unreachable("switch has a default case!"); 1501 } 1502 1503 /// \brief Used to keep track of an operand bundle. See the main comment on 1504 /// OperandBundleUser above. 1505 struct BundleOpInfo { 1506 /// \brief The operand bundle tag, interned by 1507 /// LLVMContextImpl::getOrInsertBundleTag. 1508 StringMapEntry<uint32_t> *Tag; 1509 1510 /// \brief The index in the Use& vector where operands for this operand 1511 /// bundle starts. 1512 uint32_t Begin; 1513 1514 /// \brief The index in the Use& vector where operands for this operand 1515 /// bundle ends. 1516 uint32_t End; 1517 1518 bool operator==(const BundleOpInfo &Other) const { 1519 return Tag == Other.Tag && Begin == Other.Begin && End == Other.End; 1520 } 1521 }; 1522 1523 /// \brief Simple helper function to map a BundleOpInfo to an 1524 /// OperandBundleUse. 1525 OperandBundleUse 1526 operandBundleFromBundleOpInfo(const BundleOpInfo &BOI) const { 1527 auto op_begin = static_cast<const InstrTy *>(this)->op_begin(); 1528 ArrayRef<Use> Inputs(op_begin + BOI.Begin, op_begin + BOI.End); 1529 return OperandBundleUse(BOI.Tag, Inputs); 1530 } 1531 1532 using bundle_op_iterator = BundleOpInfo *; 1533 using const_bundle_op_iterator = const BundleOpInfo *; 1534 1535 /// \brief Return the start of the list of BundleOpInfo instances associated 1536 /// with this OperandBundleUser. 1537 bundle_op_iterator bundle_op_info_begin() { 1538 if (!static_cast<InstrTy *>(this)->hasDescriptor()) 1539 return nullptr; 1540 1541 uint8_t *BytesBegin = static_cast<InstrTy *>(this)->getDescriptor().begin(); 1542 return reinterpret_cast<bundle_op_iterator>(BytesBegin); 1543 } 1544 1545 /// \brief Return the start of the list of BundleOpInfo instances associated 1546 /// with this OperandBundleUser. 1547 const_bundle_op_iterator bundle_op_info_begin() const { 1548 auto *NonConstThis = 1549 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this); 1550 return NonConstThis->bundle_op_info_begin(); 1551 } 1552 1553 /// \brief Return the end of the list of BundleOpInfo instances associated 1554 /// with this OperandBundleUser. 1555 bundle_op_iterator bundle_op_info_end() { 1556 if (!static_cast<InstrTy *>(this)->hasDescriptor()) 1557 return nullptr; 1558 1559 uint8_t *BytesEnd = static_cast<InstrTy *>(this)->getDescriptor().end(); 1560 return reinterpret_cast<bundle_op_iterator>(BytesEnd); 1561 } 1562 1563 /// \brief Return the end of the list of BundleOpInfo instances associated 1564 /// with this OperandBundleUser. 1565 const_bundle_op_iterator bundle_op_info_end() const { 1566 auto *NonConstThis = 1567 const_cast<OperandBundleUser<InstrTy, OpIteratorTy> *>(this); 1568 return NonConstThis->bundle_op_info_end(); 1569 } 1570 1571 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 1572 iterator_range<bundle_op_iterator> bundle_op_infos() { 1573 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 1574 } 1575 1576 /// \brief Return the range [\p bundle_op_info_begin, \p bundle_op_info_end). 1577 iterator_range<const_bundle_op_iterator> bundle_op_infos() const { 1578 return make_range(bundle_op_info_begin(), bundle_op_info_end()); 1579 } 1580 1581 /// \brief Populate the BundleOpInfo instances and the Use& vector from \p 1582 /// Bundles. Return the op_iterator pointing to the Use& one past the last 1583 /// last bundle operand use. 1584 /// 1585 /// Each \p OperandBundleDef instance is tracked by a OperandBundleInfo 1586 /// instance allocated in this User's descriptor. 1587 OpIteratorTy populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, 1588 const unsigned BeginIndex) { 1589 auto It = static_cast<InstrTy *>(this)->op_begin() + BeginIndex; 1590 for (auto &B : Bundles) 1591 It = std::copy(B.input_begin(), B.input_end(), It); 1592 1593 auto *ContextImpl = static_cast<InstrTy *>(this)->getContext().pImpl; 1594 auto BI = Bundles.begin(); 1595 unsigned CurrentIndex = BeginIndex; 1596 1597 for (auto &BOI : bundle_op_infos()) { 1598 assert(BI != Bundles.end() && "Incorrect allocation?"); 1599 1600 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag()); 1601 BOI.Begin = CurrentIndex; 1602 BOI.End = CurrentIndex + BI->input_size(); 1603 CurrentIndex = BOI.End; 1604 BI++; 1605 } 1606 1607 assert(BI == Bundles.end() && "Incorrect allocation?"); 1608 1609 return It; 1610 } 1611 1612 /// \brief Return the BundleOpInfo for the operand at index OpIdx. 1613 /// 1614 /// It is an error to call this with an OpIdx that does not correspond to an 1615 /// bundle operand. 1616 const BundleOpInfo &getBundleOpInfoForOperand(unsigned OpIdx) const { 1617 for (auto &BOI : bundle_op_infos()) 1618 if (BOI.Begin <= OpIdx && OpIdx < BOI.End) 1619 return BOI; 1620 1621 llvm_unreachable("Did not find operand bundle for operand!"); 1622 } 1623 1624 /// \brief Return the total number of values used in \p Bundles. 1625 static unsigned CountBundleInputs(ArrayRef<OperandBundleDef> Bundles) { 1626 unsigned Total = 0; 1627 for (auto &B : Bundles) 1628 Total += B.input_size(); 1629 return Total; 1630 } 1631 }; 1632 1633 } // end namespace llvm 1634 1635 #endif // LLVM_IR_INSTRTYPES_H 1636