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