1 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the declaration of the Instruction class, which is the 10 // base class for all of the LLVM instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_IR_INSTRUCTION_H 15 #define LLVM_IR_INSTRUCTION_H 16 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/Bitfields.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/ilist_node.h" 21 #include "llvm/IR/DebugLoc.h" 22 #include "llvm/IR/SymbolTableListTraits.h" 23 #include "llvm/IR/User.h" 24 #include "llvm/IR/Value.h" 25 #include "llvm/Support/AtomicOrdering.h" 26 #include <cstdint> 27 #include <utility> 28 29 namespace llvm { 30 31 class BasicBlock; 32 class DPMarker; 33 class FastMathFlags; 34 class MDNode; 35 class Module; 36 struct AAMDNodes; 37 class DPMarker; 38 class DbgRecord; 39 40 template <> struct ilist_alloc_traits<Instruction> { 41 static inline void deleteNode(Instruction *V); 42 }; 43 44 iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange(DPMarker *); 45 46 class Instruction : public User, 47 public ilist_node_with_parent<Instruction, BasicBlock, 48 ilist_iterator_bits<true>> { 49 public: 50 using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>>; 51 private: 52 BasicBlock *Parent; 53 DebugLoc DbgLoc; // 'dbg' Metadata cache. 54 55 /// Relative order of this instruction in its parent basic block. Used for 56 /// O(1) local dominance checks between instructions. 57 mutable unsigned Order = 0; 58 59 public: 60 /// Optional marker recording the position for debugging information that 61 /// takes effect immediately before this instruction. Null unless there is 62 /// debugging information present. 63 DPMarker *DbgMarker = nullptr; 64 65 /// Clone any debug-info attached to \p From onto this instruction. Used to 66 /// copy debugging information from one block to another, when copying entire 67 /// blocks. \see DebugProgramInstruction.h , because the ordering of 68 /// DbgRecords is still important, fine grain control of which instructions 69 /// are moved and where they go is necessary. 70 /// \p From The instruction to clone debug-info from. 71 /// \p from_here Optional iterator to limit DbgRecords cloned to be a range 72 /// from 73 /// from_here to end(). 74 /// \p InsertAtHead Whether the cloned DbgRecords should be placed at the end 75 /// or the beginning of existing DbgRecords attached to this. 76 /// \returns A range over the newly cloned DbgRecords. 77 iterator_range<simple_ilist<DbgRecord>::iterator> cloneDebugInfoFrom( 78 const Instruction *From, 79 std::optional<simple_ilist<DbgRecord>::iterator> FromHere = std::nullopt, 80 bool InsertAtHead = false); 81 82 /// Return a range over the DbgRecords attached to this instruction. 83 iterator_range<simple_ilist<DbgRecord>::iterator> getDbgRecordRange() const { 84 return llvm::getDbgRecordRange(DbgMarker); 85 } 86 87 /// Return an iterator to the position of the "Next" DbgRecord after this 88 /// instruction, or std::nullopt. This is the position to pass to 89 /// BasicBlock::reinsertInstInDbgRecords when re-inserting an instruction. 90 std::optional<simple_ilist<DbgRecord>::iterator> getDbgReinsertionPosition(); 91 92 /// Returns true if any DbgRecords are attached to this instruction. 93 bool hasDbgRecords() const; 94 95 /// Transfer any DbgRecords on the position \p It onto this instruction, 96 /// by simply adopting the sequence of DbgRecords (which is efficient) if 97 /// possible, by merging two sequences otherwise. 98 void adoptDbgRecords(BasicBlock *BB, InstListType::iterator It, 99 bool InsertAtHead); 100 101 /// Erase any DbgRecords attached to this instruction. 102 void dropDbgRecords(); 103 104 /// Erase a single DbgRecord \p I that is attached to this instruction. 105 void dropOneDbgRecord(DbgRecord *I); 106 107 /// Handle the debug-info implications of this instruction being removed. Any 108 /// attached DbgRecords need to "fall" down onto the next instruction. 109 void handleMarkerRemoval(); 110 111 protected: 112 // The 15 first bits of `Value::SubclassData` are available for subclasses of 113 // `Instruction` to use. 114 using OpaqueField = Bitfield::Element<uint16_t, 0, 15>; 115 116 // Template alias so that all Instruction storing alignment use the same 117 // definiton. 118 // Valid alignments are powers of two from 2^0 to 2^MaxAlignmentExponent = 119 // 2^32. We store them as Log2(Alignment), so we need 6 bits to encode the 33 120 // possible values. 121 template <unsigned Offset> 122 using AlignmentBitfieldElementT = 123 typename Bitfield::Element<unsigned, Offset, 6, 124 Value::MaxAlignmentExponent>; 125 126 template <unsigned Offset> 127 using BoolBitfieldElementT = typename Bitfield::Element<bool, Offset, 1>; 128 129 template <unsigned Offset> 130 using AtomicOrderingBitfieldElementT = 131 typename Bitfield::Element<AtomicOrdering, Offset, 3, 132 AtomicOrdering::LAST>; 133 134 private: 135 // The last bit is used to store whether the instruction has metadata attached 136 // or not. 137 using HasMetadataField = Bitfield::Element<bool, 15, 1>; 138 139 protected: 140 ~Instruction(); // Use deleteValue() to delete a generic Instruction. 141 142 public: 143 Instruction(const Instruction &) = delete; 144 Instruction &operator=(const Instruction &) = delete; 145 146 /// Specialize the methods defined in Value, as we know that an instruction 147 /// can only be used by other instructions. 148 Instruction *user_back() { return cast<Instruction>(*user_begin());} 149 const Instruction *user_back() const { return cast<Instruction>(*user_begin());} 150 151 inline const BasicBlock *getParent() const { return Parent; } 152 inline BasicBlock *getParent() { return Parent; } 153 154 /// Return the module owning the function this instruction belongs to 155 /// or nullptr it the function does not have a module. 156 /// 157 /// Note: this is undefined behavior if the instruction does not have a 158 /// parent, or the parent basic block does not have a parent function. 159 const Module *getModule() const; 160 Module *getModule() { 161 return const_cast<Module *>( 162 static_cast<const Instruction *>(this)->getModule()); 163 } 164 165 /// Return the function this instruction belongs to. 166 /// 167 /// Note: it is undefined behavior to call this on an instruction not 168 /// currently inserted into a function. 169 const Function *getFunction() const; 170 Function *getFunction() { 171 return const_cast<Function *>( 172 static_cast<const Instruction *>(this)->getFunction()); 173 } 174 175 /// This method unlinks 'this' from the containing basic block, but does not 176 /// delete it. 177 void removeFromParent(); 178 179 /// This method unlinks 'this' from the containing basic block and deletes it. 180 /// 181 /// \returns an iterator pointing to the element after the erased one 182 InstListType::iterator eraseFromParent(); 183 184 /// Insert an unlinked instruction into a basic block immediately before 185 /// the specified instruction. 186 void insertBefore(Instruction *InsertPos); 187 void insertBefore(InstListType::iterator InsertPos); 188 189 /// Insert an unlinked instruction into a basic block immediately after the 190 /// specified instruction. 191 void insertAfter(Instruction *InsertPos); 192 193 /// Inserts an unlinked instruction into \p ParentBB at position \p It and 194 /// returns the iterator of the inserted instruction. 195 InstListType::iterator insertInto(BasicBlock *ParentBB, 196 InstListType::iterator It); 197 198 void insertBefore(BasicBlock &BB, InstListType::iterator InsertPos); 199 200 /// Unlink this instruction from its current basic block and insert it into 201 /// the basic block that MovePos lives in, right before MovePos. 202 void moveBefore(Instruction *MovePos); 203 204 /// Perform a \ref moveBefore operation, while signalling that the caller 205 /// intends to preserve the original ordering of instructions. This implicitly 206 /// means that any adjacent debug-info should move with this instruction. 207 /// This method is currently a no-op placeholder, but it will become meaningful 208 /// when the "RemoveDIs" project is enabled. 209 void moveBeforePreserving(Instruction *MovePos); 210 211 private: 212 /// RemoveDIs project: all other moves implemented with this method, 213 /// centralising debug-info updates into one place. 214 void moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve); 215 216 public: 217 /// Unlink this instruction and insert into BB before I. 218 /// 219 /// \pre I is a valid iterator into BB. 220 void moveBefore(BasicBlock &BB, InstListType::iterator I); 221 222 /// (See other overload for moveBeforePreserving). 223 void moveBeforePreserving(BasicBlock &BB, InstListType::iterator I); 224 225 /// Unlink this instruction from its current basic block and insert it into 226 /// the basic block that MovePos lives in, right after MovePos. 227 void moveAfter(Instruction *MovePos); 228 229 /// See \ref moveBeforePreserving . 230 void moveAfterPreserving(Instruction *MovePos); 231 232 /// Given an instruction Other in the same basic block as this instruction, 233 /// return true if this instruction comes before Other. In this worst case, 234 /// this takes linear time in the number of instructions in the block. The 235 /// results are cached, so in common cases when the block remains unmodified, 236 /// it takes constant time. 237 bool comesBefore(const Instruction *Other) const; 238 239 /// Get the first insertion point at which the result of this instruction 240 /// is defined. This is *not* the directly following instruction in a number 241 /// of cases, e.g. phi nodes or terminators that return values. This function 242 /// may return null if the insertion after the definition is not possible, 243 /// e.g. due to a catchswitch terminator. 244 std::optional<InstListType::iterator> getInsertionPointAfterDef(); 245 246 //===--------------------------------------------------------------------===// 247 // Subclass classification. 248 //===--------------------------------------------------------------------===// 249 250 /// Returns a member of one of the enums like Instruction::Add. 251 unsigned getOpcode() const { return getValueID() - InstructionVal; } 252 253 const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } 254 bool isTerminator() const { return isTerminator(getOpcode()); } 255 bool isUnaryOp() const { return isUnaryOp(getOpcode()); } 256 bool isBinaryOp() const { return isBinaryOp(getOpcode()); } 257 bool isIntDivRem() const { return isIntDivRem(getOpcode()); } 258 bool isShift() const { return isShift(getOpcode()); } 259 bool isCast() const { return isCast(getOpcode()); } 260 bool isFuncletPad() const { return isFuncletPad(getOpcode()); } 261 bool isSpecialTerminator() const { return isSpecialTerminator(getOpcode()); } 262 263 /// It checks if this instruction is the only user of at least one of 264 /// its operands. 265 bool isOnlyUserOfAnyOperand(); 266 267 static const char *getOpcodeName(unsigned Opcode); 268 269 static inline bool isTerminator(unsigned Opcode) { 270 return Opcode >= TermOpsBegin && Opcode < TermOpsEnd; 271 } 272 273 static inline bool isUnaryOp(unsigned Opcode) { 274 return Opcode >= UnaryOpsBegin && Opcode < UnaryOpsEnd; 275 } 276 static inline bool isBinaryOp(unsigned Opcode) { 277 return Opcode >= BinaryOpsBegin && Opcode < BinaryOpsEnd; 278 } 279 280 static inline bool isIntDivRem(unsigned Opcode) { 281 return Opcode == UDiv || Opcode == SDiv || Opcode == URem || Opcode == SRem; 282 } 283 284 /// Determine if the Opcode is one of the shift instructions. 285 static inline bool isShift(unsigned Opcode) { 286 return Opcode >= Shl && Opcode <= AShr; 287 } 288 289 /// Return true if this is a logical shift left or a logical shift right. 290 inline bool isLogicalShift() const { 291 return getOpcode() == Shl || getOpcode() == LShr; 292 } 293 294 /// Return true if this is an arithmetic shift right. 295 inline bool isArithmeticShift() const { 296 return getOpcode() == AShr; 297 } 298 299 /// Determine if the Opcode is and/or/xor. 300 static inline bool isBitwiseLogicOp(unsigned Opcode) { 301 return Opcode == And || Opcode == Or || Opcode == Xor; 302 } 303 304 /// Return true if this is and/or/xor. 305 inline bool isBitwiseLogicOp() const { 306 return isBitwiseLogicOp(getOpcode()); 307 } 308 309 /// Determine if the Opcode is one of the CastInst instructions. 310 static inline bool isCast(unsigned Opcode) { 311 return Opcode >= CastOpsBegin && Opcode < CastOpsEnd; 312 } 313 314 /// Determine if the Opcode is one of the FuncletPadInst instructions. 315 static inline bool isFuncletPad(unsigned Opcode) { 316 return Opcode >= FuncletPadOpsBegin && Opcode < FuncletPadOpsEnd; 317 } 318 319 /// Returns true if the Opcode is a "special" terminator that does more than 320 /// branch to a successor (e.g. have a side effect or return a value). 321 static inline bool isSpecialTerminator(unsigned Opcode) { 322 switch (Opcode) { 323 case Instruction::CatchSwitch: 324 case Instruction::CatchRet: 325 case Instruction::CleanupRet: 326 case Instruction::Invoke: 327 case Instruction::Resume: 328 case Instruction::CallBr: 329 return true; 330 default: 331 return false; 332 } 333 } 334 335 //===--------------------------------------------------------------------===// 336 // Metadata manipulation. 337 //===--------------------------------------------------------------------===// 338 339 /// Return true if this instruction has any metadata attached to it. 340 bool hasMetadata() const { return DbgLoc || Value::hasMetadata(); } 341 342 /// Return true if this instruction has metadata attached to it other than a 343 /// debug location. 344 bool hasMetadataOtherThanDebugLoc() const { return Value::hasMetadata(); } 345 346 /// Return true if this instruction has the given type of metadata attached. 347 bool hasMetadata(unsigned KindID) const { 348 return getMetadata(KindID) != nullptr; 349 } 350 351 /// Return true if this instruction has the given type of metadata attached. 352 bool hasMetadata(StringRef Kind) const { 353 return getMetadata(Kind) != nullptr; 354 } 355 356 /// Get the metadata of given kind attached to this Instruction. 357 /// If the metadata is not found then return null. 358 MDNode *getMetadata(unsigned KindID) const { 359 // Handle 'dbg' as a special case since it is not stored in the hash table. 360 if (KindID == LLVMContext::MD_dbg) 361 return DbgLoc.getAsMDNode(); 362 return Value::getMetadata(KindID); 363 } 364 365 /// Get the metadata of given kind attached to this Instruction. 366 /// If the metadata is not found then return null. 367 MDNode *getMetadata(StringRef Kind) const { 368 if (!hasMetadata()) return nullptr; 369 return getMetadataImpl(Kind); 370 } 371 372 /// Get all metadata attached to this Instruction. The first element of each 373 /// pair returned is the KindID, the second element is the metadata value. 374 /// This list is returned sorted by the KindID. 375 void 376 getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 377 if (hasMetadata()) 378 getAllMetadataImpl(MDs); 379 } 380 381 /// This does the same thing as getAllMetadata, except that it filters out the 382 /// debug location. 383 void getAllMetadataOtherThanDebugLoc( 384 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const { 385 Value::getAllMetadata(MDs); 386 } 387 388 /// Set the metadata of the specified kind to the specified node. This updates 389 /// or replaces metadata if already present, or removes it if Node is null. 390 void setMetadata(unsigned KindID, MDNode *Node); 391 void setMetadata(StringRef Kind, MDNode *Node); 392 393 /// Copy metadata from \p SrcInst to this instruction. \p WL, if not empty, 394 /// specifies the list of meta data that needs to be copied. If \p WL is 395 /// empty, all meta data will be copied. 396 void copyMetadata(const Instruction &SrcInst, 397 ArrayRef<unsigned> WL = ArrayRef<unsigned>()); 398 399 /// Erase all metadata that matches the predicate. 400 void eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred); 401 402 /// If the instruction has "branch_weights" MD_prof metadata and the MDNode 403 /// has three operands (including name string), swap the order of the 404 /// metadata. 405 void swapProfMetadata(); 406 407 /// Drop all unknown metadata except for debug locations. 408 /// @{ 409 /// Passes are required to drop metadata they don't understand. This is a 410 /// convenience method for passes to do so. 411 /// dropUBImplyingAttrsAndUnknownMetadata should be used instead of 412 /// this API if the Instruction being modified is a call. 413 void dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs); 414 void dropUnknownNonDebugMetadata() { 415 return dropUnknownNonDebugMetadata(std::nullopt); 416 } 417 void dropUnknownNonDebugMetadata(unsigned ID1) { 418 return dropUnknownNonDebugMetadata(ArrayRef(ID1)); 419 } 420 void dropUnknownNonDebugMetadata(unsigned ID1, unsigned ID2) { 421 unsigned IDs[] = {ID1, ID2}; 422 return dropUnknownNonDebugMetadata(IDs); 423 } 424 /// @} 425 426 /// Adds an !annotation metadata node with \p Annotation to this instruction. 427 /// If this instruction already has !annotation metadata, append \p Annotation 428 /// to the existing node. 429 void addAnnotationMetadata(StringRef Annotation); 430 /// Adds an !annotation metadata node with an array of \p Annotations 431 /// as a tuple to this instruction. If this instruction already has 432 /// !annotation metadata, append the tuple to 433 /// the existing node. 434 void addAnnotationMetadata(SmallVector<StringRef> Annotations); 435 /// Returns the AA metadata for this instruction. 436 AAMDNodes getAAMetadata() const; 437 438 /// Sets the AA metadata on this instruction from the AAMDNodes structure. 439 void setAAMetadata(const AAMDNodes &N); 440 441 /// Sets the nosanitize metadata on this instruction. 442 void setNoSanitizeMetadata(); 443 444 /// Retrieve total raw weight values of a branch. 445 /// Returns true on success with profile total weights filled in. 446 /// Returns false if no metadata was found. 447 bool extractProfTotalWeight(uint64_t &TotalVal) const; 448 449 /// Set the debug location information for this instruction. 450 void setDebugLoc(DebugLoc Loc) { DbgLoc = std::move(Loc); } 451 452 /// Return the debug location for this node as a DebugLoc. 453 const DebugLoc &getDebugLoc() const { return DbgLoc; } 454 455 /// Fetch the debug location for this node, unless this is a debug intrinsic, 456 /// in which case fetch the debug location of the next non-debug node. 457 const DebugLoc &getStableDebugLoc() const; 458 459 /// Set or clear the nuw flag on this instruction, which must be an operator 460 /// which supports this flag. See LangRef.html for the meaning of this flag. 461 void setHasNoUnsignedWrap(bool b = true); 462 463 /// Set or clear the nsw flag on this instruction, which must be an operator 464 /// which supports this flag. See LangRef.html for the meaning of this flag. 465 void setHasNoSignedWrap(bool b = true); 466 467 /// Set or clear the exact flag on this instruction, which must be an operator 468 /// which supports this flag. See LangRef.html for the meaning of this flag. 469 void setIsExact(bool b = true); 470 471 /// Set or clear the nneg flag on this instruction, which must be a zext 472 /// instruction. 473 void setNonNeg(bool b = true); 474 475 /// Determine whether the no unsigned wrap flag is set. 476 bool hasNoUnsignedWrap() const LLVM_READONLY; 477 478 /// Determine whether the no signed wrap flag is set. 479 bool hasNoSignedWrap() const LLVM_READONLY; 480 481 /// Determine whether the the nneg flag is set. 482 bool hasNonNeg() const LLVM_READONLY; 483 484 /// Return true if this operator has flags which may cause this instruction 485 /// to evaluate to poison despite having non-poison inputs. 486 bool hasPoisonGeneratingFlags() const LLVM_READONLY; 487 488 /// Drops flags that may cause this instruction to evaluate to poison despite 489 /// having non-poison inputs. 490 void dropPoisonGeneratingFlags(); 491 492 /// Return true if this instruction has poison-generating metadata. 493 bool hasPoisonGeneratingMetadata() const LLVM_READONLY; 494 495 /// Drops metadata that may generate poison. 496 void dropPoisonGeneratingMetadata(); 497 498 /// Return true if this instruction has poison-generating flags or metadata. 499 bool hasPoisonGeneratingFlagsOrMetadata() const { 500 return hasPoisonGeneratingFlags() || hasPoisonGeneratingMetadata(); 501 } 502 503 /// Drops flags and metadata that may generate poison. 504 void dropPoisonGeneratingFlagsAndMetadata() { 505 dropPoisonGeneratingFlags(); 506 dropPoisonGeneratingMetadata(); 507 } 508 509 /// This function drops non-debug unknown metadata (through 510 /// dropUnknownNonDebugMetadata). For calls, it also drops parameter and 511 /// return attributes that can cause undefined behaviour. Both of these should 512 /// be done by passes which move instructions in IR. 513 void dropUBImplyingAttrsAndUnknownMetadata(ArrayRef<unsigned> KnownIDs = {}); 514 515 /// Drop any attributes or metadata that can cause immediate undefined 516 /// behavior. Retain other attributes/metadata on a best-effort basis. 517 /// This should be used when speculating instructions. 518 void dropUBImplyingAttrsAndMetadata(); 519 520 /// Determine whether the exact flag is set. 521 bool isExact() const LLVM_READONLY; 522 523 /// Set or clear all fast-math-flags on this instruction, which must be an 524 /// operator which supports this flag. See LangRef.html for the meaning of 525 /// this flag. 526 void setFast(bool B); 527 528 /// Set or clear the reassociation flag on this instruction, which must be 529 /// an operator which supports this flag. See LangRef.html for the meaning of 530 /// this flag. 531 void setHasAllowReassoc(bool B); 532 533 /// Set or clear the no-nans flag on this instruction, which must be an 534 /// operator which supports this flag. See LangRef.html for the meaning of 535 /// this flag. 536 void setHasNoNaNs(bool B); 537 538 /// Set or clear the no-infs flag on this instruction, which must be an 539 /// operator which supports this flag. See LangRef.html for the meaning of 540 /// this flag. 541 void setHasNoInfs(bool B); 542 543 /// Set or clear the no-signed-zeros flag on this instruction, which must be 544 /// an operator which supports this flag. See LangRef.html for the meaning of 545 /// this flag. 546 void setHasNoSignedZeros(bool B); 547 548 /// Set or clear the allow-reciprocal flag on this instruction, which must be 549 /// an operator which supports this flag. See LangRef.html for the meaning of 550 /// this flag. 551 void setHasAllowReciprocal(bool B); 552 553 /// Set or clear the allow-contract flag on this instruction, which must be 554 /// an operator which supports this flag. See LangRef.html for the meaning of 555 /// this flag. 556 void setHasAllowContract(bool B); 557 558 /// Set or clear the approximate-math-functions flag on this instruction, 559 /// which must be an operator which supports this flag. See LangRef.html for 560 /// the meaning of this flag. 561 void setHasApproxFunc(bool B); 562 563 /// Convenience function for setting multiple fast-math flags on this 564 /// instruction, which must be an operator which supports these flags. See 565 /// LangRef.html for the meaning of these flags. 566 void setFastMathFlags(FastMathFlags FMF); 567 568 /// Convenience function for transferring all fast-math flag values to this 569 /// instruction, which must be an operator which supports these flags. See 570 /// LangRef.html for the meaning of these flags. 571 void copyFastMathFlags(FastMathFlags FMF); 572 573 /// Determine whether all fast-math-flags are set. 574 bool isFast() const LLVM_READONLY; 575 576 /// Determine whether the allow-reassociation flag is set. 577 bool hasAllowReassoc() const LLVM_READONLY; 578 579 /// Determine whether the no-NaNs flag is set. 580 bool hasNoNaNs() const LLVM_READONLY; 581 582 /// Determine whether the no-infs flag is set. 583 bool hasNoInfs() const LLVM_READONLY; 584 585 /// Determine whether the no-signed-zeros flag is set. 586 bool hasNoSignedZeros() const LLVM_READONLY; 587 588 /// Determine whether the allow-reciprocal flag is set. 589 bool hasAllowReciprocal() const LLVM_READONLY; 590 591 /// Determine whether the allow-contract flag is set. 592 bool hasAllowContract() const LLVM_READONLY; 593 594 /// Determine whether the approximate-math-functions flag is set. 595 bool hasApproxFunc() const LLVM_READONLY; 596 597 /// Convenience function for getting all the fast-math flags, which must be an 598 /// operator which supports these flags. See LangRef.html for the meaning of 599 /// these flags. 600 FastMathFlags getFastMathFlags() const LLVM_READONLY; 601 602 /// Copy I's fast-math flags 603 void copyFastMathFlags(const Instruction *I); 604 605 /// Convenience method to copy supported exact, fast-math, and (optionally) 606 /// wrapping flags from V to this instruction. 607 void copyIRFlags(const Value *V, bool IncludeWrapFlags = true); 608 609 /// Logical 'and' of any supported wrapping, exact, and fast-math flags of 610 /// V and this instruction. 611 void andIRFlags(const Value *V); 612 613 /// Merge 2 debug locations and apply it to the Instruction. If the 614 /// instruction is a CallIns, we need to traverse the inline chain to find 615 /// the common scope. This is not efficient for N-way merging as each time 616 /// you merge 2 iterations, you need to rebuild the hashmap to find the 617 /// common scope. However, we still choose this API because: 618 /// 1) Simplicity: it takes 2 locations instead of a list of locations. 619 /// 2) In worst case, it increases the complexity from O(N*I) to 620 /// O(2*N*I), where N is # of Instructions to merge, and I is the 621 /// maximum level of inline stack. So it is still linear. 622 /// 3) Merging of call instructions should be extremely rare in real 623 /// applications, thus the N-way merging should be in code path. 624 /// The DebugLoc attached to this instruction will be overwritten by the 625 /// merged DebugLoc. 626 void applyMergedLocation(DILocation *LocA, DILocation *LocB); 627 628 /// Updates the debug location given that the instruction has been hoisted 629 /// from a block to a predecessor of that block. 630 /// Note: it is undefined behavior to call this on an instruction not 631 /// currently inserted into a function. 632 void updateLocationAfterHoist(); 633 634 /// Drop the instruction's debug location. This does not guarantee removal 635 /// of the !dbg source location attachment, as it must set a line 0 location 636 /// with scope information attached on call instructions. To guarantee 637 /// removal of the !dbg attachment, use the \ref setDebugLoc() API. 638 /// Note: it is undefined behavior to call this on an instruction not 639 /// currently inserted into a function. 640 void dropLocation(); 641 642 /// Merge the DIAssignID metadata from this instruction and those attached to 643 /// instructions in \p SourceInstructions. This process performs a RAUW on 644 /// the MetadataAsValue uses of the merged DIAssignID nodes. Not every 645 /// instruction in \p SourceInstructions needs to have DIAssignID 646 /// metadata. If none of them do then nothing happens. If this instruction 647 /// does not have a DIAssignID attachment but at least one in \p 648 /// SourceInstructions does then the merged one will be attached to 649 /// it. However, instructions without attachments in \p SourceInstructions 650 /// are not modified. 651 void mergeDIAssignID(ArrayRef<const Instruction *> SourceInstructions); 652 653 private: 654 // These are all implemented in Metadata.cpp. 655 MDNode *getMetadataImpl(StringRef Kind) const; 656 void 657 getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned, MDNode *>> &) const; 658 659 /// Update the LLVMContext ID-to-Instruction(s) mapping. If \p ID is nullptr 660 /// then clear the mapping for this instruction. 661 void updateDIAssignIDMapping(DIAssignID *ID); 662 663 public: 664 //===--------------------------------------------------------------------===// 665 // Predicates and helper methods. 666 //===--------------------------------------------------------------------===// 667 668 /// Return true if the instruction is associative: 669 /// 670 /// Associative operators satisfy: x op (y op z) === (x op y) op z 671 /// 672 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative. 673 /// 674 bool isAssociative() const LLVM_READONLY; 675 static bool isAssociative(unsigned Opcode) { 676 return Opcode == And || Opcode == Or || Opcode == Xor || 677 Opcode == Add || Opcode == Mul; 678 } 679 680 /// Return true if the instruction is commutative: 681 /// 682 /// Commutative operators satisfy: (x op y) === (y op x) 683 /// 684 /// In LLVM, these are the commutative operators, plus SetEQ and SetNE, when 685 /// applied to any type. 686 /// 687 bool isCommutative() const LLVM_READONLY; 688 static bool isCommutative(unsigned Opcode) { 689 switch (Opcode) { 690 case Add: case FAdd: 691 case Mul: case FMul: 692 case And: case Or: case Xor: 693 return true; 694 default: 695 return false; 696 } 697 } 698 699 /// Return true if the instruction is idempotent: 700 /// 701 /// Idempotent operators satisfy: x op x === x 702 /// 703 /// In LLVM, the And and Or operators are idempotent. 704 /// 705 bool isIdempotent() const { return isIdempotent(getOpcode()); } 706 static bool isIdempotent(unsigned Opcode) { 707 return Opcode == And || Opcode == Or; 708 } 709 710 /// Return true if the instruction is nilpotent: 711 /// 712 /// Nilpotent operators satisfy: x op x === Id, 713 /// 714 /// where Id is the identity for the operator, i.e. a constant such that 715 /// x op Id === x and Id op x === x for all x. 716 /// 717 /// In LLVM, the Xor operator is nilpotent. 718 /// 719 bool isNilpotent() const { return isNilpotent(getOpcode()); } 720 static bool isNilpotent(unsigned Opcode) { 721 return Opcode == Xor; 722 } 723 724 /// Return true if this instruction may modify memory. 725 bool mayWriteToMemory() const LLVM_READONLY; 726 727 /// Return true if this instruction may read memory. 728 bool mayReadFromMemory() const LLVM_READONLY; 729 730 /// Return true if this instruction may read or write memory. 731 bool mayReadOrWriteMemory() const { 732 return mayReadFromMemory() || mayWriteToMemory(); 733 } 734 735 /// Return true if this instruction has an AtomicOrdering of unordered or 736 /// higher. 737 bool isAtomic() const LLVM_READONLY; 738 739 /// Return true if this atomic instruction loads from memory. 740 bool hasAtomicLoad() const LLVM_READONLY; 741 742 /// Return true if this atomic instruction stores to memory. 743 bool hasAtomicStore() const LLVM_READONLY; 744 745 /// Return true if this instruction has a volatile memory access. 746 bool isVolatile() const LLVM_READONLY; 747 748 /// Return the type this instruction accesses in memory, if any. 749 Type *getAccessType() const LLVM_READONLY; 750 751 /// Return true if this instruction may throw an exception. 752 /// 753 /// If IncludePhaseOneUnwind is set, this will also include cases where 754 /// phase one unwinding may unwind past this frame due to skipping of 755 /// cleanup landingpads. 756 bool mayThrow(bool IncludePhaseOneUnwind = false) const LLVM_READONLY; 757 758 /// Return true if this instruction behaves like a memory fence: it can load 759 /// or store to memory location without being given a memory location. 760 bool isFenceLike() const { 761 switch (getOpcode()) { 762 default: 763 return false; 764 // This list should be kept in sync with the list in mayWriteToMemory for 765 // all opcodes which don't have a memory location. 766 case Instruction::Fence: 767 case Instruction::CatchPad: 768 case Instruction::CatchRet: 769 case Instruction::Call: 770 case Instruction::Invoke: 771 return true; 772 } 773 } 774 775 /// Return true if the instruction may have side effects. 776 /// 777 /// Side effects are: 778 /// * Writing to memory. 779 /// * Unwinding. 780 /// * Not returning (e.g. an infinite loop). 781 /// 782 /// Note that this does not consider malloc and alloca to have side 783 /// effects because the newly allocated memory is completely invisible to 784 /// instructions which don't use the returned value. For cases where this 785 /// matters, isSafeToSpeculativelyExecute may be more appropriate. 786 bool mayHaveSideEffects() const LLVM_READONLY; 787 788 /// Return true if the instruction can be removed if the result is unused. 789 /// 790 /// When constant folding some instructions cannot be removed even if their 791 /// results are unused. Specifically terminator instructions and calls that 792 /// may have side effects cannot be removed without semantically changing the 793 /// generated program. 794 bool isSafeToRemove() const LLVM_READONLY; 795 796 /// Return true if the instruction will return (unwinding is considered as 797 /// a form of returning control flow here). 798 bool willReturn() const LLVM_READONLY; 799 800 /// Return true if the instruction is a variety of EH-block. 801 bool isEHPad() const { 802 switch (getOpcode()) { 803 case Instruction::CatchSwitch: 804 case Instruction::CatchPad: 805 case Instruction::CleanupPad: 806 case Instruction::LandingPad: 807 return true; 808 default: 809 return false; 810 } 811 } 812 813 /// Return true if the instruction is a llvm.lifetime.start or 814 /// llvm.lifetime.end marker. 815 bool isLifetimeStartOrEnd() const LLVM_READONLY; 816 817 /// Return true if the instruction is a llvm.launder.invariant.group or 818 /// llvm.strip.invariant.group. 819 bool isLaunderOrStripInvariantGroup() const LLVM_READONLY; 820 821 /// Return true if the instruction is a DbgInfoIntrinsic or PseudoProbeInst. 822 bool isDebugOrPseudoInst() const LLVM_READONLY; 823 824 /// Return a pointer to the next non-debug instruction in the same basic 825 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 826 /// operations if \c SkipPseudoOp is true. 827 const Instruction * 828 getNextNonDebugInstruction(bool SkipPseudoOp = false) const; 829 Instruction *getNextNonDebugInstruction(bool SkipPseudoOp = false) { 830 return const_cast<Instruction *>( 831 static_cast<const Instruction *>(this)->getNextNonDebugInstruction( 832 SkipPseudoOp)); 833 } 834 835 /// Return a pointer to the previous non-debug instruction in the same basic 836 /// block as 'this', or nullptr if no such instruction exists. Skip any pseudo 837 /// operations if \c SkipPseudoOp is true. 838 const Instruction * 839 getPrevNonDebugInstruction(bool SkipPseudoOp = false) const; 840 Instruction *getPrevNonDebugInstruction(bool SkipPseudoOp = false) { 841 return const_cast<Instruction *>( 842 static_cast<const Instruction *>(this)->getPrevNonDebugInstruction( 843 SkipPseudoOp)); 844 } 845 846 /// Create a copy of 'this' instruction that is identical in all ways except 847 /// the following: 848 /// * The instruction has no parent 849 /// * The instruction has no name 850 /// 851 Instruction *clone() const; 852 853 /// Return true if the specified instruction is exactly identical to the 854 /// current one. This means that all operands match and any extra information 855 /// (e.g. load is volatile) agree. 856 bool isIdenticalTo(const Instruction *I) const LLVM_READONLY; 857 858 /// This is like isIdenticalTo, except that it ignores the 859 /// SubclassOptionalData flags, which may specify conditions under which the 860 /// instruction's result is undefined. 861 bool isIdenticalToWhenDefined(const Instruction *I) const LLVM_READONLY; 862 863 /// When checking for operation equivalence (using isSameOperationAs) it is 864 /// sometimes useful to ignore certain attributes. 865 enum OperationEquivalenceFlags { 866 /// Check for equivalence ignoring load/store alignment. 867 CompareIgnoringAlignment = 1<<0, 868 /// Check for equivalence treating a type and a vector of that type 869 /// as equivalent. 870 CompareUsingScalarTypes = 1<<1 871 }; 872 873 /// This function determines if the specified instruction executes the same 874 /// operation as the current one. This means that the opcodes, type, operand 875 /// types and any other factors affecting the operation must be the same. This 876 /// is similar to isIdenticalTo except the operands themselves don't have to 877 /// be identical. 878 /// @returns true if the specified instruction is the same operation as 879 /// the current one. 880 /// Determine if one instruction is the same operation as another. 881 bool isSameOperationAs(const Instruction *I, unsigned flags = 0) const LLVM_READONLY; 882 883 /// This function determines if the speficied instruction has the same 884 /// "special" characteristics as the current one. This means that opcode 885 /// specific details are the same. As a common example, if we are comparing 886 /// loads, then hasSameSpecialState would compare the alignments (among 887 /// other things). 888 /// @returns true if the specific instruction has the same opcde specific 889 /// characteristics as the current one. Determine if one instruction has the 890 /// same state as another. 891 bool hasSameSpecialState(const Instruction *I2, 892 bool IgnoreAlignment = false) const LLVM_READONLY; 893 894 /// Return true if there are any uses of this instruction in blocks other than 895 /// the specified block. Note that PHI nodes are considered to evaluate their 896 /// operands in the corresponding predecessor block. 897 bool isUsedOutsideOfBlock(const BasicBlock *BB) const LLVM_READONLY; 898 899 /// Return the number of successors that this instruction has. The instruction 900 /// must be a terminator. 901 unsigned getNumSuccessors() const LLVM_READONLY; 902 903 /// Return the specified successor. This instruction must be a terminator. 904 BasicBlock *getSuccessor(unsigned Idx) const LLVM_READONLY; 905 906 /// Update the specified successor to point at the provided block. This 907 /// instruction must be a terminator. 908 void setSuccessor(unsigned Idx, BasicBlock *BB); 909 910 /// Replace specified successor OldBB to point at the provided block. 911 /// This instruction must be a terminator. 912 void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB); 913 914 /// Methods for support type inquiry through isa, cast, and dyn_cast: 915 static bool classof(const Value *V) { 916 return V->getValueID() >= Value::InstructionVal; 917 } 918 919 //---------------------------------------------------------------------- 920 // Exported enumerations. 921 // 922 enum TermOps { // These terminate basic blocks 923 #define FIRST_TERM_INST(N) TermOpsBegin = N, 924 #define HANDLE_TERM_INST(N, OPC, CLASS) OPC = N, 925 #define LAST_TERM_INST(N) TermOpsEnd = N+1 926 #include "llvm/IR/Instruction.def" 927 }; 928 929 enum UnaryOps { 930 #define FIRST_UNARY_INST(N) UnaryOpsBegin = N, 931 #define HANDLE_UNARY_INST(N, OPC, CLASS) OPC = N, 932 #define LAST_UNARY_INST(N) UnaryOpsEnd = N+1 933 #include "llvm/IR/Instruction.def" 934 }; 935 936 enum BinaryOps { 937 #define FIRST_BINARY_INST(N) BinaryOpsBegin = N, 938 #define HANDLE_BINARY_INST(N, OPC, CLASS) OPC = N, 939 #define LAST_BINARY_INST(N) BinaryOpsEnd = N+1 940 #include "llvm/IR/Instruction.def" 941 }; 942 943 enum MemoryOps { 944 #define FIRST_MEMORY_INST(N) MemoryOpsBegin = N, 945 #define HANDLE_MEMORY_INST(N, OPC, CLASS) OPC = N, 946 #define LAST_MEMORY_INST(N) MemoryOpsEnd = N+1 947 #include "llvm/IR/Instruction.def" 948 }; 949 950 enum CastOps { 951 #define FIRST_CAST_INST(N) CastOpsBegin = N, 952 #define HANDLE_CAST_INST(N, OPC, CLASS) OPC = N, 953 #define LAST_CAST_INST(N) CastOpsEnd = N+1 954 #include "llvm/IR/Instruction.def" 955 }; 956 957 enum FuncletPadOps { 958 #define FIRST_FUNCLETPAD_INST(N) FuncletPadOpsBegin = N, 959 #define HANDLE_FUNCLETPAD_INST(N, OPC, CLASS) OPC = N, 960 #define LAST_FUNCLETPAD_INST(N) FuncletPadOpsEnd = N+1 961 #include "llvm/IR/Instruction.def" 962 }; 963 964 enum OtherOps { 965 #define FIRST_OTHER_INST(N) OtherOpsBegin = N, 966 #define HANDLE_OTHER_INST(N, OPC, CLASS) OPC = N, 967 #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 968 #include "llvm/IR/Instruction.def" 969 }; 970 971 private: 972 friend class SymbolTableListTraits<Instruction, ilist_iterator_bits<true>>; 973 friend class BasicBlock; // For renumbering. 974 975 // Shadow Value::setValueSubclassData with a private forwarding method so that 976 // subclasses cannot accidentally use it. 977 void setValueSubclassData(unsigned short D) { 978 Value::setValueSubclassData(D); 979 } 980 981 unsigned short getSubclassDataFromValue() const { 982 return Value::getSubclassDataFromValue(); 983 } 984 985 void setParent(BasicBlock *P); 986 987 protected: 988 // Instruction subclasses can stick up to 15 bits of stuff into the 989 // SubclassData field of instruction with these members. 990 991 template <typename BitfieldElement> 992 typename BitfieldElement::Type getSubclassData() const { 993 static_assert( 994 std::is_same<BitfieldElement, HasMetadataField>::value || 995 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 996 "Must not overlap with the metadata bit"); 997 return Bitfield::get<BitfieldElement>(getSubclassDataFromValue()); 998 } 999 1000 template <typename BitfieldElement> 1001 void setSubclassData(typename BitfieldElement::Type Value) { 1002 static_assert( 1003 std::is_same<BitfieldElement, HasMetadataField>::value || 1004 !Bitfield::isOverlapping<BitfieldElement, HasMetadataField>(), 1005 "Must not overlap with the metadata bit"); 1006 auto Storage = getSubclassDataFromValue(); 1007 Bitfield::set<BitfieldElement>(Storage, Value); 1008 setValueSubclassData(Storage); 1009 } 1010 1011 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 1012 InstListType::iterator InsertBefore); 1013 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 1014 Instruction *InsertBefore = nullptr); 1015 Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, 1016 BasicBlock *InsertAtEnd); 1017 1018 private: 1019 /// Create a copy of this instruction. 1020 Instruction *cloneImpl() const; 1021 }; 1022 1023 inline void ilist_alloc_traits<Instruction>::deleteNode(Instruction *V) { 1024 V->deleteValue(); 1025 } 1026 1027 } // end namespace llvm 1028 1029 #endif // LLVM_IR_INSTRUCTION_H 1030