1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- 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 MachineInstr class, which is the 10 // basic representation for all target dependent machine instructions used by 11 // the back end. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CODEGEN_MACHINEINSTR_H 16 #define LLVM_CODEGEN_MACHINEINSTR_H 17 18 #include "llvm/ADT/DenseMapInfo.h" 19 #include "llvm/ADT/PointerSumType.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/ilist.h" 22 #include "llvm/ADT/ilist_node.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/CodeGen/MachineMemOperand.h" 25 #include "llvm/CodeGen/MachineOperand.h" 26 #include "llvm/CodeGen/TargetOpcodes.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/InlineAsm.h" 29 #include "llvm/MC/MCInstrDesc.h" 30 #include "llvm/MC/MCSymbol.h" 31 #include "llvm/Support/ArrayRecycler.h" 32 #include "llvm/Support/TrailingObjects.h" 33 #include <algorithm> 34 #include <cassert> 35 #include <cstdint> 36 #include <utility> 37 38 namespace llvm { 39 40 class DILabel; 41 class Instruction; 42 class MDNode; 43 class AAResults; 44 template <typename T> class ArrayRef; 45 class DIExpression; 46 class DILocalVariable; 47 class MachineBasicBlock; 48 class MachineFunction; 49 class MachineRegisterInfo; 50 class ModuleSlotTracker; 51 class raw_ostream; 52 template <typename T> class SmallVectorImpl; 53 class SmallBitVector; 54 class StringRef; 55 class TargetInstrInfo; 56 class TargetRegisterClass; 57 class TargetRegisterInfo; 58 59 //===----------------------------------------------------------------------===// 60 /// Representation of each machine instruction. 61 /// 62 /// This class isn't a POD type, but it must have a trivial destructor. When a 63 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated 64 /// without having their destructor called. 65 /// 66 class MachineInstr 67 : public ilist_node_with_parent<MachineInstr, MachineBasicBlock, 68 ilist_sentinel_tracking<true>> { 69 public: 70 using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator; 71 72 /// Flags to specify different kinds of comments to output in 73 /// assembly code. These flags carry semantic information not 74 /// otherwise easily derivable from the IR text. 75 /// 76 enum CommentFlag { 77 ReloadReuse = 0x1, // higher bits are reserved for target dep comments. 78 NoSchedComment = 0x2, 79 TAsmComments = 0x4 // Target Asm comments should start from this value. 80 }; 81 82 enum MIFlag { 83 NoFlags = 0, 84 FrameSetup = 1 << 0, // Instruction is used as a part of 85 // function frame setup code. 86 FrameDestroy = 1 << 1, // Instruction is used as a part of 87 // function frame destruction code. 88 BundledPred = 1 << 2, // Instruction has bundled predecessors. 89 BundledSucc = 1 << 3, // Instruction has bundled successors. 90 FmNoNans = 1 << 4, // Instruction does not support Fast 91 // math nan values. 92 FmNoInfs = 1 << 5, // Instruction does not support Fast 93 // math infinity values. 94 FmNsz = 1 << 6, // Instruction is not required to retain 95 // signed zero values. 96 FmArcp = 1 << 7, // Instruction supports Fast math 97 // reciprocal approximations. 98 FmContract = 1 << 8, // Instruction supports Fast math 99 // contraction operations like fma. 100 FmAfn = 1 << 9, // Instruction may map to Fast math 101 // intrinsic approximation. 102 FmReassoc = 1 << 10, // Instruction supports Fast math 103 // reassociation of operand order. 104 NoUWrap = 1 << 11, // Instruction supports binary operator 105 // no unsigned wrap. 106 NoSWrap = 1 << 12, // Instruction supports binary operator 107 // no signed wrap. 108 IsExact = 1 << 13, // Instruction supports division is 109 // known to be exact. 110 NoFPExcept = 1 << 14, // Instruction does not raise 111 // floatint-point exceptions. 112 NoMerge = 1 << 15, // Passes that drop source location info 113 // (e.g. branch folding) should skip 114 // this instruction. 115 }; 116 117 private: 118 const MCInstrDesc *MCID; // Instruction descriptor. 119 MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block. 120 121 // Operands are allocated by an ArrayRecycler. 122 MachineOperand *Operands = nullptr; // Pointer to the first operand. 123 unsigned NumOperands = 0; // Number of operands on instruction. 124 125 uint16_t Flags = 0; // Various bits of additional 126 // information about machine 127 // instruction. 128 129 uint8_t AsmPrinterFlags = 0; // Various bits of information used by 130 // the AsmPrinter to emit helpful 131 // comments. This is *not* semantic 132 // information. Do not use this for 133 // anything other than to convey comment 134 // information to AsmPrinter. 135 136 // OperandCapacity has uint8_t size, so it should be next to AsmPrinterFlags 137 // to properly pack. 138 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity; 139 OperandCapacity CapOperands; // Capacity of the Operands array. 140 141 /// Internal implementation detail class that provides out-of-line storage for 142 /// extra info used by the machine instruction when this info cannot be stored 143 /// in-line within the instruction itself. 144 /// 145 /// This has to be defined eagerly due to the implementation constraints of 146 /// `PointerSumType` where it is used. 147 class ExtraInfo final 148 : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> { 149 public: 150 static ExtraInfo *create(BumpPtrAllocator &Allocator, 151 ArrayRef<MachineMemOperand *> MMOs, 152 MCSymbol *PreInstrSymbol = nullptr, 153 MCSymbol *PostInstrSymbol = nullptr, 154 MDNode *HeapAllocMarker = nullptr) { 155 bool HasPreInstrSymbol = PreInstrSymbol != nullptr; 156 bool HasPostInstrSymbol = PostInstrSymbol != nullptr; 157 bool HasHeapAllocMarker = HeapAllocMarker != nullptr; 158 auto *Result = new (Allocator.Allocate( 159 totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>( 160 MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol, 161 HasHeapAllocMarker), 162 alignof(ExtraInfo))) 163 ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol, 164 HasHeapAllocMarker); 165 166 // Copy the actual data into the trailing objects. 167 std::copy(MMOs.begin(), MMOs.end(), 168 Result->getTrailingObjects<MachineMemOperand *>()); 169 170 if (HasPreInstrSymbol) 171 Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol; 172 if (HasPostInstrSymbol) 173 Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] = 174 PostInstrSymbol; 175 if (HasHeapAllocMarker) 176 Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker; 177 178 return Result; 179 } 180 181 ArrayRef<MachineMemOperand *> getMMOs() const { 182 return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs); 183 } 184 185 MCSymbol *getPreInstrSymbol() const { 186 return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr; 187 } 188 189 MCSymbol *getPostInstrSymbol() const { 190 return HasPostInstrSymbol 191 ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] 192 : nullptr; 193 } 194 195 MDNode *getHeapAllocMarker() const { 196 return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr; 197 } 198 199 private: 200 friend TrailingObjects; 201 202 // Description of the extra info, used to interpret the actual optional 203 // data appended. 204 // 205 // Note that this is not terribly space optimized. This leaves a great deal 206 // of flexibility to fit more in here later. 207 const int NumMMOs; 208 const bool HasPreInstrSymbol; 209 const bool HasPostInstrSymbol; 210 const bool HasHeapAllocMarker; 211 212 // Implement the `TrailingObjects` internal API. 213 size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const { 214 return NumMMOs; 215 } 216 size_t numTrailingObjects(OverloadToken<MCSymbol *>) const { 217 return HasPreInstrSymbol + HasPostInstrSymbol; 218 } 219 size_t numTrailingObjects(OverloadToken<MDNode *>) const { 220 return HasHeapAllocMarker; 221 } 222 223 // Just a boring constructor to allow us to initialize the sizes. Always use 224 // the `create` routine above. 225 ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol, 226 bool HasHeapAllocMarker) 227 : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol), 228 HasPostInstrSymbol(HasPostInstrSymbol), 229 HasHeapAllocMarker(HasHeapAllocMarker) {} 230 }; 231 232 /// Enumeration of the kinds of inline extra info available. It is important 233 /// that the `MachineMemOperand` inline kind has a tag value of zero to make 234 /// it accessible as an `ArrayRef`. 235 enum ExtraInfoInlineKinds { 236 EIIK_MMO = 0, 237 EIIK_PreInstrSymbol, 238 EIIK_PostInstrSymbol, 239 EIIK_OutOfLine 240 }; 241 242 // We store extra information about the instruction here. The common case is 243 // expected to be nothing or a single pointer (typically a MMO or a symbol). 244 // We work to optimize this common case by storing it inline here rather than 245 // requiring a separate allocation, but we fall back to an allocation when 246 // multiple pointers are needed. 247 PointerSumType<ExtraInfoInlineKinds, 248 PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>, 249 PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>, 250 PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>, 251 PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>> 252 Info; 253 254 DebugLoc DbgLoc; // Source line information. 255 256 /// Unique instruction number. Used by DBG_INSTR_REFs to refer to the values 257 /// defined by this instruction. 258 unsigned DebugInstrNum; 259 260 // Intrusive list support 261 friend struct ilist_traits<MachineInstr>; 262 friend struct ilist_callback_traits<MachineBasicBlock>; 263 void setParent(MachineBasicBlock *P) { Parent = P; } 264 265 /// This constructor creates a copy of the given 266 /// MachineInstr in the given MachineFunction. 267 MachineInstr(MachineFunction &, const MachineInstr &); 268 269 /// This constructor create a MachineInstr and add the implicit operands. 270 /// It reserves space for number of operands specified by 271 /// MCInstrDesc. An explicit DebugLoc is supplied. 272 MachineInstr(MachineFunction &, const MCInstrDesc &TID, DebugLoc DL, 273 bool NoImp = false); 274 275 // MachineInstrs are pool-allocated and owned by MachineFunction. 276 friend class MachineFunction; 277 278 void 279 dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth, 280 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const; 281 282 public: 283 MachineInstr(const MachineInstr &) = delete; 284 MachineInstr &operator=(const MachineInstr &) = delete; 285 // Use MachineFunction::DeleteMachineInstr() instead. 286 ~MachineInstr() = delete; 287 288 const MachineBasicBlock* getParent() const { return Parent; } 289 MachineBasicBlock* getParent() { return Parent; } 290 291 /// Move the instruction before \p MovePos. 292 void moveBefore(MachineInstr *MovePos); 293 294 /// Return the function that contains the basic block that this instruction 295 /// belongs to. 296 /// 297 /// Note: this is undefined behaviour if the instruction does not have a 298 /// parent. 299 const MachineFunction *getMF() const; 300 MachineFunction *getMF() { 301 return const_cast<MachineFunction *>( 302 static_cast<const MachineInstr *>(this)->getMF()); 303 } 304 305 /// Return the asm printer flags bitvector. 306 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; } 307 308 /// Clear the AsmPrinter bitvector. 309 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; } 310 311 /// Return whether an AsmPrinter flag is set. 312 bool getAsmPrinterFlag(CommentFlag Flag) const { 313 return AsmPrinterFlags & Flag; 314 } 315 316 /// Set a flag for the AsmPrinter. 317 void setAsmPrinterFlag(uint8_t Flag) { 318 AsmPrinterFlags |= Flag; 319 } 320 321 /// Clear specific AsmPrinter flags. 322 void clearAsmPrinterFlag(CommentFlag Flag) { 323 AsmPrinterFlags &= ~Flag; 324 } 325 326 /// Return the MI flags bitvector. 327 uint16_t getFlags() const { 328 return Flags; 329 } 330 331 /// Return whether an MI flag is set. 332 bool getFlag(MIFlag Flag) const { 333 return Flags & Flag; 334 } 335 336 /// Set a MI flag. 337 void setFlag(MIFlag Flag) { 338 Flags |= (uint16_t)Flag; 339 } 340 341 void setFlags(unsigned flags) { 342 // Filter out the automatically maintained flags. 343 unsigned Mask = BundledPred | BundledSucc; 344 Flags = (Flags & Mask) | (flags & ~Mask); 345 } 346 347 /// clearFlag - Clear a MI flag. 348 void clearFlag(MIFlag Flag) { 349 Flags &= ~((uint16_t)Flag); 350 } 351 352 /// Return true if MI is in a bundle (but not the first MI in a bundle). 353 /// 354 /// A bundle looks like this before it's finalized: 355 /// ---------------- 356 /// | MI | 357 /// ---------------- 358 /// | 359 /// ---------------- 360 /// | MI * | 361 /// ---------------- 362 /// | 363 /// ---------------- 364 /// | MI * | 365 /// ---------------- 366 /// In this case, the first MI starts a bundle but is not inside a bundle, the 367 /// next 2 MIs are considered "inside" the bundle. 368 /// 369 /// After a bundle is finalized, it looks like this: 370 /// ---------------- 371 /// | Bundle | 372 /// ---------------- 373 /// | 374 /// ---------------- 375 /// | MI * | 376 /// ---------------- 377 /// | 378 /// ---------------- 379 /// | MI * | 380 /// ---------------- 381 /// | 382 /// ---------------- 383 /// | MI * | 384 /// ---------------- 385 /// The first instruction has the special opcode "BUNDLE". It's not "inside" 386 /// a bundle, but the next three MIs are. 387 bool isInsideBundle() const { 388 return getFlag(BundledPred); 389 } 390 391 /// Return true if this instruction part of a bundle. This is true 392 /// if either itself or its following instruction is marked "InsideBundle". 393 bool isBundled() const { 394 return isBundledWithPred() || isBundledWithSucc(); 395 } 396 397 /// Return true if this instruction is part of a bundle, and it is not the 398 /// first instruction in the bundle. 399 bool isBundledWithPred() const { return getFlag(BundledPred); } 400 401 /// Return true if this instruction is part of a bundle, and it is not the 402 /// last instruction in the bundle. 403 bool isBundledWithSucc() const { return getFlag(BundledSucc); } 404 405 /// Bundle this instruction with its predecessor. This can be an unbundled 406 /// instruction, or it can be the first instruction in a bundle. 407 void bundleWithPred(); 408 409 /// Bundle this instruction with its successor. This can be an unbundled 410 /// instruction, or it can be the last instruction in a bundle. 411 void bundleWithSucc(); 412 413 /// Break bundle above this instruction. 414 void unbundleFromPred(); 415 416 /// Break bundle below this instruction. 417 void unbundleFromSucc(); 418 419 /// Returns the debug location id of this MachineInstr. 420 const DebugLoc &getDebugLoc() const { return DbgLoc; } 421 422 /// Return the operand containing the offset to be used if this DBG_VALUE 423 /// instruction is indirect; will be an invalid register if this value is 424 /// not indirect, and an immediate with value 0 otherwise. 425 const MachineOperand &getDebugOffset() const { 426 assert(isNonListDebugValue() && "not a DBG_VALUE"); 427 return getOperand(1); 428 } 429 MachineOperand &getDebugOffset() { 430 assert(isNonListDebugValue() && "not a DBG_VALUE"); 431 return getOperand(1); 432 } 433 434 /// Return the operand for the debug variable referenced by 435 /// this DBG_VALUE instruction. 436 const MachineOperand &getDebugVariableOp() const; 437 MachineOperand &getDebugVariableOp(); 438 439 /// Return the debug variable referenced by 440 /// this DBG_VALUE instruction. 441 const DILocalVariable *getDebugVariable() const; 442 443 /// Return the operand for the complex address expression referenced by 444 /// this DBG_VALUE instruction. 445 const MachineOperand &getDebugExpressionOp() const; 446 MachineOperand &getDebugExpressionOp(); 447 448 /// Return the complex address expression referenced by 449 /// this DBG_VALUE instruction. 450 const DIExpression *getDebugExpression() const; 451 452 /// Return the debug label referenced by 453 /// this DBG_LABEL instruction. 454 const DILabel *getDebugLabel() const; 455 456 /// Fetch the instruction number of this MachineInstr. If it does not have 457 /// one already, a new and unique number will be assigned. 458 unsigned getDebugInstrNum(); 459 460 /// Fetch instruction number of this MachineInstr -- but before it's inserted 461 /// into \p MF. Needed for transformations that create an instruction but 462 /// don't immediately insert them. 463 unsigned getDebugInstrNum(MachineFunction &MF); 464 465 /// Examine the instruction number of this MachineInstr. May be zero if 466 /// it hasn't been assigned a number yet. 467 unsigned peekDebugInstrNum() const { return DebugInstrNum; } 468 469 /// Set instruction number of this MachineInstr. Avoid using unless you're 470 /// deserializing this information. 471 void setDebugInstrNum(unsigned Num) { DebugInstrNum = Num; } 472 473 /// Drop any variable location debugging information associated with this 474 /// instruction. Use when an instruction is modified in such a way that it no 475 /// longer defines the value it used to. Variable locations using that value 476 /// will be dropped. 477 void dropDebugNumber() { DebugInstrNum = 0; } 478 479 /// Emit an error referring to the source location of this instruction. 480 /// This should only be used for inline assembly that is somehow 481 /// impossible to compile. Other errors should have been handled much 482 /// earlier. 483 /// 484 /// If this method returns, the caller should try to recover from the error. 485 void emitError(StringRef Msg) const; 486 487 /// Returns the target instruction descriptor of this MachineInstr. 488 const MCInstrDesc &getDesc() const { return *MCID; } 489 490 /// Returns the opcode of this MachineInstr. 491 unsigned getOpcode() const { return MCID->Opcode; } 492 493 /// Retuns the total number of operands. 494 unsigned getNumOperands() const { return NumOperands; } 495 496 /// Returns the total number of operands which are debug locations. 497 unsigned getNumDebugOperands() const { 498 return std::distance(debug_operands().begin(), debug_operands().end()); 499 } 500 501 const MachineOperand& getOperand(unsigned i) const { 502 assert(i < getNumOperands() && "getOperand() out of range!"); 503 return Operands[i]; 504 } 505 MachineOperand& getOperand(unsigned i) { 506 assert(i < getNumOperands() && "getOperand() out of range!"); 507 return Operands[i]; 508 } 509 510 MachineOperand &getDebugOperand(unsigned Index) { 511 assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!"); 512 return *(debug_operands().begin() + Index); 513 } 514 const MachineOperand &getDebugOperand(unsigned Index) const { 515 assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!"); 516 return *(debug_operands().begin() + Index); 517 } 518 519 SmallSet<Register, 4> getUsedDebugRegs() const { 520 assert(isDebugValue() && "not a DBG_VALUE*"); 521 SmallSet<Register, 4> UsedRegs; 522 for (const auto &MO : debug_operands()) 523 if (MO.isReg() && MO.getReg()) 524 UsedRegs.insert(MO.getReg()); 525 return UsedRegs; 526 } 527 528 /// Returns whether this debug value has at least one debug operand with the 529 /// register \p Reg. 530 bool hasDebugOperandForReg(Register Reg) const { 531 return any_of(debug_operands(), [Reg](const MachineOperand &Op) { 532 return Op.isReg() && Op.getReg() == Reg; 533 }); 534 } 535 536 /// Returns a range of all of the operands that correspond to a debug use of 537 /// \p Reg. 538 template <typename Operand, typename Instruction> 539 static iterator_range< 540 filter_iterator<Operand *, std::function<bool(Operand &Op)>>> 541 getDebugOperandsForReg(Instruction *MI, Register Reg) { 542 std::function<bool(Operand & Op)> OpUsesReg( 543 [Reg](Operand &Op) { return Op.isReg() && Op.getReg() == Reg; }); 544 return make_filter_range(MI->debug_operands(), OpUsesReg); 545 } 546 iterator_range<filter_iterator<const MachineOperand *, 547 std::function<bool(const MachineOperand &Op)>>> 548 getDebugOperandsForReg(Register Reg) const { 549 return MachineInstr::getDebugOperandsForReg<const MachineOperand, 550 const MachineInstr>(this, Reg); 551 } 552 iterator_range<filter_iterator<MachineOperand *, 553 std::function<bool(MachineOperand &Op)>>> 554 getDebugOperandsForReg(Register Reg) { 555 return MachineInstr::getDebugOperandsForReg<MachineOperand, MachineInstr>( 556 this, Reg); 557 } 558 559 bool isDebugOperand(const MachineOperand *Op) const { 560 return Op >= adl_begin(debug_operands()) && Op <= adl_end(debug_operands()); 561 } 562 563 unsigned getDebugOperandIndex(const MachineOperand *Op) const { 564 assert(isDebugOperand(Op) && "Expected a debug operand."); 565 return std::distance(adl_begin(debug_operands()), Op); 566 } 567 568 /// Returns the total number of definitions. 569 unsigned getNumDefs() const { 570 return getNumExplicitDefs() + MCID->getNumImplicitDefs(); 571 } 572 573 /// Returns true if the instruction has implicit definition. 574 bool hasImplicitDef() const { 575 for (unsigned I = getNumExplicitOperands(), E = getNumOperands(); 576 I != E; ++I) { 577 const MachineOperand &MO = getOperand(I); 578 if (MO.isDef() && MO.isImplicit()) 579 return true; 580 } 581 return false; 582 } 583 584 /// Returns the implicit operands number. 585 unsigned getNumImplicitOperands() const { 586 return getNumOperands() - getNumExplicitOperands(); 587 } 588 589 /// Return true if operand \p OpIdx is a subregister index. 590 bool isOperandSubregIdx(unsigned OpIdx) const { 591 assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate && 592 "Expected MO_Immediate operand type."); 593 if (isExtractSubreg() && OpIdx == 2) 594 return true; 595 if (isInsertSubreg() && OpIdx == 3) 596 return true; 597 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0) 598 return true; 599 if (isSubregToReg() && OpIdx == 3) 600 return true; 601 return false; 602 } 603 604 /// Returns the number of non-implicit operands. 605 unsigned getNumExplicitOperands() const; 606 607 /// Returns the number of non-implicit definitions. 608 unsigned getNumExplicitDefs() const; 609 610 /// iterator/begin/end - Iterate over all operands of a machine instruction. 611 using mop_iterator = MachineOperand *; 612 using const_mop_iterator = const MachineOperand *; 613 614 mop_iterator operands_begin() { return Operands; } 615 mop_iterator operands_end() { return Operands + NumOperands; } 616 617 const_mop_iterator operands_begin() const { return Operands; } 618 const_mop_iterator operands_end() const { return Operands + NumOperands; } 619 620 iterator_range<mop_iterator> operands() { 621 return make_range(operands_begin(), operands_end()); 622 } 623 iterator_range<const_mop_iterator> operands() const { 624 return make_range(operands_begin(), operands_end()); 625 } 626 iterator_range<mop_iterator> explicit_operands() { 627 return make_range(operands_begin(), 628 operands_begin() + getNumExplicitOperands()); 629 } 630 iterator_range<const_mop_iterator> explicit_operands() const { 631 return make_range(operands_begin(), 632 operands_begin() + getNumExplicitOperands()); 633 } 634 iterator_range<mop_iterator> implicit_operands() { 635 return make_range(explicit_operands().end(), operands_end()); 636 } 637 iterator_range<const_mop_iterator> implicit_operands() const { 638 return make_range(explicit_operands().end(), operands_end()); 639 } 640 /// Returns a range over all operands that are used to determine the variable 641 /// location for this DBG_VALUE instruction. 642 iterator_range<mop_iterator> debug_operands() { 643 assert(isDebugValue() && "Must be a debug value instruction."); 644 return isDebugValueList() 645 ? make_range(operands_begin() + 2, operands_end()) 646 : make_range(operands_begin(), operands_begin() + 1); 647 } 648 /// \copydoc debug_operands() 649 iterator_range<const_mop_iterator> debug_operands() const { 650 assert(isDebugValue() && "Must be a debug value instruction."); 651 return isDebugValueList() 652 ? make_range(operands_begin() + 2, operands_end()) 653 : make_range(operands_begin(), operands_begin() + 1); 654 } 655 /// Returns a range over all explicit operands that are register definitions. 656 /// Implicit definition are not included! 657 iterator_range<mop_iterator> defs() { 658 return make_range(operands_begin(), 659 operands_begin() + getNumExplicitDefs()); 660 } 661 /// \copydoc defs() 662 iterator_range<const_mop_iterator> defs() const { 663 return make_range(operands_begin(), 664 operands_begin() + getNumExplicitDefs()); 665 } 666 /// Returns a range that includes all operands that are register uses. 667 /// This may include unrelated operands which are not register uses. 668 iterator_range<mop_iterator> uses() { 669 return make_range(operands_begin() + getNumExplicitDefs(), operands_end()); 670 } 671 /// \copydoc uses() 672 iterator_range<const_mop_iterator> uses() const { 673 return make_range(operands_begin() + getNumExplicitDefs(), operands_end()); 674 } 675 iterator_range<mop_iterator> explicit_uses() { 676 return make_range(operands_begin() + getNumExplicitDefs(), 677 operands_begin() + getNumExplicitOperands()); 678 } 679 iterator_range<const_mop_iterator> explicit_uses() const { 680 return make_range(operands_begin() + getNumExplicitDefs(), 681 operands_begin() + getNumExplicitOperands()); 682 } 683 684 /// Returns the number of the operand iterator \p I points to. 685 unsigned getOperandNo(const_mop_iterator I) const { 686 return I - operands_begin(); 687 } 688 689 /// Access to memory operands of the instruction. If there are none, that does 690 /// not imply anything about whether the function accesses memory. Instead, 691 /// the caller must behave conservatively. 692 ArrayRef<MachineMemOperand *> memoperands() const { 693 if (!Info) 694 return {}; 695 696 if (Info.is<EIIK_MMO>()) 697 return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1); 698 699 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 700 return EI->getMMOs(); 701 702 return {}; 703 } 704 705 /// Access to memory operands of the instruction. 706 /// 707 /// If `memoperands_begin() == memoperands_end()`, that does not imply 708 /// anything about whether the function accesses memory. Instead, the caller 709 /// must behave conservatively. 710 mmo_iterator memoperands_begin() const { return memoperands().begin(); } 711 712 /// Access to memory operands of the instruction. 713 /// 714 /// If `memoperands_begin() == memoperands_end()`, that does not imply 715 /// anything about whether the function accesses memory. Instead, the caller 716 /// must behave conservatively. 717 mmo_iterator memoperands_end() const { return memoperands().end(); } 718 719 /// Return true if we don't have any memory operands which described the 720 /// memory access done by this instruction. If this is true, calling code 721 /// must be conservative. 722 bool memoperands_empty() const { return memoperands().empty(); } 723 724 /// Return true if this instruction has exactly one MachineMemOperand. 725 bool hasOneMemOperand() const { return memoperands().size() == 1; } 726 727 /// Return the number of memory operands. 728 unsigned getNumMemOperands() const { return memoperands().size(); } 729 730 /// Helper to extract a pre-instruction symbol if one has been added. 731 MCSymbol *getPreInstrSymbol() const { 732 if (!Info) 733 return nullptr; 734 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>()) 735 return S; 736 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 737 return EI->getPreInstrSymbol(); 738 739 return nullptr; 740 } 741 742 /// Helper to extract a post-instruction symbol if one has been added. 743 MCSymbol *getPostInstrSymbol() const { 744 if (!Info) 745 return nullptr; 746 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>()) 747 return S; 748 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 749 return EI->getPostInstrSymbol(); 750 751 return nullptr; 752 } 753 754 /// Helper to extract a heap alloc marker if one has been added. 755 MDNode *getHeapAllocMarker() const { 756 if (!Info) 757 return nullptr; 758 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 759 return EI->getHeapAllocMarker(); 760 761 return nullptr; 762 } 763 764 /// API for querying MachineInstr properties. They are the same as MCInstrDesc 765 /// queries but they are bundle aware. 766 767 enum QueryType { 768 IgnoreBundle, // Ignore bundles 769 AnyInBundle, // Return true if any instruction in bundle has property 770 AllInBundle // Return true if all instructions in bundle have property 771 }; 772 773 /// Return true if the instruction (or in the case of a bundle, 774 /// the instructions inside the bundle) has the specified property. 775 /// The first argument is the property being queried. 776 /// The second argument indicates whether the query should look inside 777 /// instruction bundles. 778 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const { 779 assert(MCFlag < 64 && 780 "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."); 781 // Inline the fast path for unbundled or bundle-internal instructions. 782 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred()) 783 return getDesc().getFlags() & (1ULL << MCFlag); 784 785 // If this is the first instruction in a bundle, take the slow path. 786 return hasPropertyInBundle(1ULL << MCFlag, Type); 787 } 788 789 /// Return true if this is an instruction that should go through the usual 790 /// legalization steps. 791 bool isPreISelOpcode(QueryType Type = IgnoreBundle) const { 792 return hasProperty(MCID::PreISelOpcode, Type); 793 } 794 795 /// Return true if this instruction can have a variable number of operands. 796 /// In this case, the variable operands will be after the normal 797 /// operands but before the implicit definitions and uses (if any are 798 /// present). 799 bool isVariadic(QueryType Type = IgnoreBundle) const { 800 return hasProperty(MCID::Variadic, Type); 801 } 802 803 /// Set if this instruction has an optional definition, e.g. 804 /// ARM instructions which can set condition code if 's' bit is set. 805 bool hasOptionalDef(QueryType Type = IgnoreBundle) const { 806 return hasProperty(MCID::HasOptionalDef, Type); 807 } 808 809 /// Return true if this is a pseudo instruction that doesn't 810 /// correspond to a real machine instruction. 811 bool isPseudo(QueryType Type = IgnoreBundle) const { 812 return hasProperty(MCID::Pseudo, Type); 813 } 814 815 /// Return true if this instruction doesn't produce any output in the form of 816 /// executable instructions. 817 bool isMetaInstruction(QueryType Type = IgnoreBundle) const { 818 return hasProperty(MCID::Meta, Type); 819 } 820 821 bool isReturn(QueryType Type = AnyInBundle) const { 822 return hasProperty(MCID::Return, Type); 823 } 824 825 /// Return true if this is an instruction that marks the end of an EH scope, 826 /// i.e., a catchpad or a cleanuppad instruction. 827 bool isEHScopeReturn(QueryType Type = AnyInBundle) const { 828 return hasProperty(MCID::EHScopeReturn, Type); 829 } 830 831 bool isCall(QueryType Type = AnyInBundle) const { 832 return hasProperty(MCID::Call, Type); 833 } 834 835 /// Return true if this is a call instruction that may have an associated 836 /// call site entry in the debug info. 837 bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const; 838 /// Return true if copying, moving, or erasing this instruction requires 839 /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo, 840 /// \ref eraseCallSiteInfo). 841 bool shouldUpdateCallSiteInfo() const; 842 843 /// Returns true if the specified instruction stops control flow 844 /// from executing the instruction immediately following it. Examples include 845 /// unconditional branches and return instructions. 846 bool isBarrier(QueryType Type = AnyInBundle) const { 847 return hasProperty(MCID::Barrier, Type); 848 } 849 850 /// Returns true if this instruction part of the terminator for a basic block. 851 /// Typically this is things like return and branch instructions. 852 /// 853 /// Various passes use this to insert code into the bottom of a basic block, 854 /// but before control flow occurs. 855 bool isTerminator(QueryType Type = AnyInBundle) const { 856 return hasProperty(MCID::Terminator, Type); 857 } 858 859 /// Returns true if this is a conditional, unconditional, or indirect branch. 860 /// Predicates below can be used to discriminate between 861 /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to 862 /// get more information. 863 bool isBranch(QueryType Type = AnyInBundle) const { 864 return hasProperty(MCID::Branch, Type); 865 } 866 867 /// Return true if this is an indirect branch, such as a 868 /// branch through a register. 869 bool isIndirectBranch(QueryType Type = AnyInBundle) const { 870 return hasProperty(MCID::IndirectBranch, Type); 871 } 872 873 /// Return true if this is a branch which may fall 874 /// through to the next instruction or may transfer control flow to some other 875 /// block. The TargetInstrInfo::analyzeBranch method can be used to get more 876 /// information about this branch. 877 bool isConditionalBranch(QueryType Type = AnyInBundle) const { 878 return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type); 879 } 880 881 /// Return true if this is a branch which always 882 /// transfers control flow to some other block. The 883 /// TargetInstrInfo::analyzeBranch method can be used to get more information 884 /// about this branch. 885 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const { 886 return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type); 887 } 888 889 /// Return true if this instruction has a predicate operand that 890 /// controls execution. It may be set to 'always', or may be set to other 891 /// values. There are various methods in TargetInstrInfo that can be used to 892 /// control and modify the predicate in this instruction. 893 bool isPredicable(QueryType Type = AllInBundle) const { 894 // If it's a bundle than all bundled instructions must be predicable for this 895 // to return true. 896 return hasProperty(MCID::Predicable, Type); 897 } 898 899 /// Return true if this instruction is a comparison. 900 bool isCompare(QueryType Type = IgnoreBundle) const { 901 return hasProperty(MCID::Compare, Type); 902 } 903 904 /// Return true if this instruction is a move immediate 905 /// (including conditional moves) instruction. 906 bool isMoveImmediate(QueryType Type = IgnoreBundle) const { 907 return hasProperty(MCID::MoveImm, Type); 908 } 909 910 /// Return true if this instruction is a register move. 911 /// (including moving values from subreg to reg) 912 bool isMoveReg(QueryType Type = IgnoreBundle) const { 913 return hasProperty(MCID::MoveReg, Type); 914 } 915 916 /// Return true if this instruction is a bitcast instruction. 917 bool isBitcast(QueryType Type = IgnoreBundle) const { 918 return hasProperty(MCID::Bitcast, Type); 919 } 920 921 /// Return true if this instruction is a select instruction. 922 bool isSelect(QueryType Type = IgnoreBundle) const { 923 return hasProperty(MCID::Select, Type); 924 } 925 926 /// Return true if this instruction cannot be safely duplicated. 927 /// For example, if the instruction has a unique labels attached 928 /// to it, duplicating it would cause multiple definition errors. 929 bool isNotDuplicable(QueryType Type = AnyInBundle) const { 930 return hasProperty(MCID::NotDuplicable, Type); 931 } 932 933 /// Return true if this instruction is convergent. 934 /// Convergent instructions can not be made control-dependent on any 935 /// additional values. 936 bool isConvergent(QueryType Type = AnyInBundle) const { 937 if (isInlineAsm()) { 938 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 939 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 940 return true; 941 } 942 return hasProperty(MCID::Convergent, Type); 943 } 944 945 /// Returns true if the specified instruction has a delay slot 946 /// which must be filled by the code generator. 947 bool hasDelaySlot(QueryType Type = AnyInBundle) const { 948 return hasProperty(MCID::DelaySlot, Type); 949 } 950 951 /// Return true for instructions that can be folded as 952 /// memory operands in other instructions. The most common use for this 953 /// is instructions that are simple loads from memory that don't modify 954 /// the loaded value in any way, but it can also be used for instructions 955 /// that can be expressed as constant-pool loads, such as V_SETALLONES 956 /// on x86, to allow them to be folded when it is beneficial. 957 /// This should only be set on instructions that return a value in their 958 /// only virtual register definition. 959 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const { 960 return hasProperty(MCID::FoldableAsLoad, Type); 961 } 962 963 /// Return true if this instruction behaves 964 /// the same way as the generic REG_SEQUENCE instructions. 965 /// E.g., on ARM, 966 /// dX VMOVDRR rY, rZ 967 /// is equivalent to 968 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1. 969 /// 970 /// Note that for the optimizers to be able to take advantage of 971 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be 972 /// override accordingly. 973 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const { 974 return hasProperty(MCID::RegSequence, Type); 975 } 976 977 /// Return true if this instruction behaves 978 /// the same way as the generic EXTRACT_SUBREG instructions. 979 /// E.g., on ARM, 980 /// rX, rY VMOVRRD dZ 981 /// is equivalent to two EXTRACT_SUBREG: 982 /// rX = EXTRACT_SUBREG dZ, ssub_0 983 /// rY = EXTRACT_SUBREG dZ, ssub_1 984 /// 985 /// Note that for the optimizers to be able to take advantage of 986 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be 987 /// override accordingly. 988 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const { 989 return hasProperty(MCID::ExtractSubreg, Type); 990 } 991 992 /// Return true if this instruction behaves 993 /// the same way as the generic INSERT_SUBREG instructions. 994 /// E.g., on ARM, 995 /// dX = VSETLNi32 dY, rZ, Imm 996 /// is equivalent to a INSERT_SUBREG: 997 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm) 998 /// 999 /// Note that for the optimizers to be able to take advantage of 1000 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be 1001 /// override accordingly. 1002 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const { 1003 return hasProperty(MCID::InsertSubreg, Type); 1004 } 1005 1006 //===--------------------------------------------------------------------===// 1007 // Side Effect Analysis 1008 //===--------------------------------------------------------------------===// 1009 1010 /// Return true if this instruction could possibly read memory. 1011 /// Instructions with this flag set are not necessarily simple load 1012 /// instructions, they may load a value and modify it, for example. 1013 bool mayLoad(QueryType Type = AnyInBundle) const { 1014 if (isInlineAsm()) { 1015 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1016 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1017 return true; 1018 } 1019 return hasProperty(MCID::MayLoad, Type); 1020 } 1021 1022 /// Return true if this instruction could possibly modify memory. 1023 /// Instructions with this flag set are not necessarily simple store 1024 /// instructions, they may store a modified value based on their operands, or 1025 /// may not actually modify anything, for example. 1026 bool mayStore(QueryType Type = AnyInBundle) const { 1027 if (isInlineAsm()) { 1028 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1029 if (ExtraInfo & InlineAsm::Extra_MayStore) 1030 return true; 1031 } 1032 return hasProperty(MCID::MayStore, Type); 1033 } 1034 1035 /// Return true if this instruction could possibly read or modify memory. 1036 bool mayLoadOrStore(QueryType Type = AnyInBundle) const { 1037 return mayLoad(Type) || mayStore(Type); 1038 } 1039 1040 /// Return true if this instruction could possibly raise a floating-point 1041 /// exception. This is the case if the instruction is a floating-point 1042 /// instruction that can in principle raise an exception, as indicated 1043 /// by the MCID::MayRaiseFPException property, *and* at the same time, 1044 /// the instruction is used in a context where we expect floating-point 1045 /// exceptions are not disabled, as indicated by the NoFPExcept MI flag. 1046 bool mayRaiseFPException() const { 1047 return hasProperty(MCID::MayRaiseFPException) && 1048 !getFlag(MachineInstr::MIFlag::NoFPExcept); 1049 } 1050 1051 //===--------------------------------------------------------------------===// 1052 // Flags that indicate whether an instruction can be modified by a method. 1053 //===--------------------------------------------------------------------===// 1054 1055 /// Return true if this may be a 2- or 3-address 1056 /// instruction (of the form "X = op Y, Z, ..."), which produces the same 1057 /// result if Y and Z are exchanged. If this flag is set, then the 1058 /// TargetInstrInfo::commuteInstruction method may be used to hack on the 1059 /// instruction. 1060 /// 1061 /// Note that this flag may be set on instructions that are only commutable 1062 /// sometimes. In these cases, the call to commuteInstruction will fail. 1063 /// Also note that some instructions require non-trivial modification to 1064 /// commute them. 1065 bool isCommutable(QueryType Type = IgnoreBundle) const { 1066 return hasProperty(MCID::Commutable, Type); 1067 } 1068 1069 /// Return true if this is a 2-address instruction 1070 /// which can be changed into a 3-address instruction if needed. Doing this 1071 /// transformation can be profitable in the register allocator, because it 1072 /// means that the instruction can use a 2-address form if possible, but 1073 /// degrade into a less efficient form if the source and dest register cannot 1074 /// be assigned to the same register. For example, this allows the x86 1075 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which 1076 /// is the same speed as the shift but has bigger code size. 1077 /// 1078 /// If this returns true, then the target must implement the 1079 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which 1080 /// is allowed to fail if the transformation isn't valid for this specific 1081 /// instruction (e.g. shl reg, 4 on x86). 1082 /// 1083 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const { 1084 return hasProperty(MCID::ConvertibleTo3Addr, Type); 1085 } 1086 1087 /// Return true if this instruction requires 1088 /// custom insertion support when the DAG scheduler is inserting it into a 1089 /// machine basic block. If this is true for the instruction, it basically 1090 /// means that it is a pseudo instruction used at SelectionDAG time that is 1091 /// expanded out into magic code by the target when MachineInstrs are formed. 1092 /// 1093 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method 1094 /// is used to insert this into the MachineBasicBlock. 1095 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const { 1096 return hasProperty(MCID::UsesCustomInserter, Type); 1097 } 1098 1099 /// Return true if this instruction requires *adjustment* 1100 /// after instruction selection by calling a target hook. For example, this 1101 /// can be used to fill in ARM 's' optional operand depending on whether 1102 /// the conditional flag register is used. 1103 bool hasPostISelHook(QueryType Type = IgnoreBundle) const { 1104 return hasProperty(MCID::HasPostISelHook, Type); 1105 } 1106 1107 /// Returns true if this instruction is a candidate for remat. 1108 /// This flag is deprecated, please don't use it anymore. If this 1109 /// flag is set, the isReallyTriviallyReMaterializable() method is called to 1110 /// verify the instruction is really rematable. 1111 bool isRematerializable(QueryType Type = AllInBundle) const { 1112 // It's only possible to re-mat a bundle if all bundled instructions are 1113 // re-materializable. 1114 return hasProperty(MCID::Rematerializable, Type); 1115 } 1116 1117 /// Returns true if this instruction has the same cost (or less) than a move 1118 /// instruction. This is useful during certain types of optimizations 1119 /// (e.g., remat during two-address conversion or machine licm) 1120 /// where we would like to remat or hoist the instruction, but not if it costs 1121 /// more than moving the instruction into the appropriate register. Note, we 1122 /// are not marking copies from and to the same register class with this flag. 1123 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const { 1124 // Only returns true for a bundle if all bundled instructions are cheap. 1125 return hasProperty(MCID::CheapAsAMove, Type); 1126 } 1127 1128 /// Returns true if this instruction source operands 1129 /// have special register allocation requirements that are not captured by the 1130 /// operand register classes. e.g. ARM::STRD's two source registers must be an 1131 /// even / odd pair, ARM::STM registers have to be in ascending order. 1132 /// Post-register allocation passes should not attempt to change allocations 1133 /// for sources of instructions with this flag. 1134 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const { 1135 return hasProperty(MCID::ExtraSrcRegAllocReq, Type); 1136 } 1137 1138 /// Returns true if this instruction def operands 1139 /// have special register allocation requirements that are not captured by the 1140 /// operand register classes. e.g. ARM::LDRD's two def registers must be an 1141 /// even / odd pair, ARM::LDM registers have to be in ascending order. 1142 /// Post-register allocation passes should not attempt to change allocations 1143 /// for definitions of instructions with this flag. 1144 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const { 1145 return hasProperty(MCID::ExtraDefRegAllocReq, Type); 1146 } 1147 1148 enum MICheckType { 1149 CheckDefs, // Check all operands for equality 1150 CheckKillDead, // Check all operands including kill / dead markers 1151 IgnoreDefs, // Ignore all definitions 1152 IgnoreVRegDefs // Ignore virtual register definitions 1153 }; 1154 1155 /// Return true if this instruction is identical to \p Other. 1156 /// Two instructions are identical if they have the same opcode and all their 1157 /// operands are identical (with respect to MachineOperand::isIdenticalTo()). 1158 /// Note that this means liveness related flags (dead, undef, kill) do not 1159 /// affect the notion of identical. 1160 bool isIdenticalTo(const MachineInstr &Other, 1161 MICheckType Check = CheckDefs) const; 1162 1163 /// Unlink 'this' from the containing basic block, and return it without 1164 /// deleting it. 1165 /// 1166 /// This function can not be used on bundled instructions, use 1167 /// removeFromBundle() to remove individual instructions from a bundle. 1168 MachineInstr *removeFromParent(); 1169 1170 /// Unlink this instruction from its basic block and return it without 1171 /// deleting it. 1172 /// 1173 /// If the instruction is part of a bundle, the other instructions in the 1174 /// bundle remain bundled. 1175 MachineInstr *removeFromBundle(); 1176 1177 /// Unlink 'this' from the containing basic block and delete it. 1178 /// 1179 /// If this instruction is the header of a bundle, the whole bundle is erased. 1180 /// This function can not be used for instructions inside a bundle, use 1181 /// eraseFromBundle() to erase individual bundled instructions. 1182 void eraseFromParent(); 1183 1184 /// Unlink 'this' form its basic block and delete it. 1185 /// 1186 /// If the instruction is part of a bundle, the other instructions in the 1187 /// bundle remain bundled. 1188 void eraseFromBundle(); 1189 1190 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; } 1191 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; } 1192 bool isAnnotationLabel() const { 1193 return getOpcode() == TargetOpcode::ANNOTATION_LABEL; 1194 } 1195 1196 /// Returns true if the MachineInstr represents a label. 1197 bool isLabel() const { 1198 return isEHLabel() || isGCLabel() || isAnnotationLabel(); 1199 } 1200 1201 bool isCFIInstruction() const { 1202 return getOpcode() == TargetOpcode::CFI_INSTRUCTION; 1203 } 1204 1205 bool isPseudoProbe() const { 1206 return getOpcode() == TargetOpcode::PSEUDO_PROBE; 1207 } 1208 1209 // True if the instruction represents a position in the function. 1210 bool isPosition() const { return isLabel() || isCFIInstruction(); } 1211 1212 bool isNonListDebugValue() const { 1213 return getOpcode() == TargetOpcode::DBG_VALUE; 1214 } 1215 bool isDebugValueList() const { 1216 return getOpcode() == TargetOpcode::DBG_VALUE_LIST; 1217 } 1218 bool isDebugValue() const { 1219 return isNonListDebugValue() || isDebugValueList(); 1220 } 1221 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; } 1222 bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; } 1223 bool isDebugPHI() const { return getOpcode() == TargetOpcode::DBG_PHI; } 1224 bool isDebugInstr() const { 1225 return isDebugValue() || isDebugLabel() || isDebugRef() || isDebugPHI(); 1226 } 1227 bool isDebugOrPseudoInstr() const { 1228 return isDebugInstr() || isPseudoProbe(); 1229 } 1230 1231 bool isDebugOffsetImm() const { 1232 return isNonListDebugValue() && getDebugOffset().isImm(); 1233 } 1234 1235 /// A DBG_VALUE is indirect iff the location operand is a register and 1236 /// the offset operand is an immediate. 1237 bool isIndirectDebugValue() const { 1238 return isDebugOffsetImm() && getDebugOperand(0).isReg(); 1239 } 1240 1241 /// A DBG_VALUE is an entry value iff its debug expression contains the 1242 /// DW_OP_LLVM_entry_value operation. 1243 bool isDebugEntryValue() const; 1244 1245 /// Return true if the instruction is a debug value which describes a part of 1246 /// a variable as unavailable. 1247 bool isUndefDebugValue() const { 1248 if (!isDebugValue()) 1249 return false; 1250 // If any $noreg locations are given, this DV is undef. 1251 for (const MachineOperand &Op : debug_operands()) 1252 if (Op.isReg() && !Op.getReg().isValid()) 1253 return true; 1254 return false; 1255 } 1256 1257 bool isPHI() const { 1258 return getOpcode() == TargetOpcode::PHI || 1259 getOpcode() == TargetOpcode::G_PHI; 1260 } 1261 bool isKill() const { return getOpcode() == TargetOpcode::KILL; } 1262 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; } 1263 bool isInlineAsm() const { 1264 return getOpcode() == TargetOpcode::INLINEASM || 1265 getOpcode() == TargetOpcode::INLINEASM_BR; 1266 } 1267 1268 /// FIXME: Seems like a layering violation that the AsmDialect, which is X86 1269 /// specific, be attached to a generic MachineInstr. 1270 bool isMSInlineAsm() const { 1271 return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel; 1272 } 1273 1274 bool isStackAligningInlineAsm() const; 1275 InlineAsm::AsmDialect getInlineAsmDialect() const; 1276 1277 bool isInsertSubreg() const { 1278 return getOpcode() == TargetOpcode::INSERT_SUBREG; 1279 } 1280 1281 bool isSubregToReg() const { 1282 return getOpcode() == TargetOpcode::SUBREG_TO_REG; 1283 } 1284 1285 bool isRegSequence() const { 1286 return getOpcode() == TargetOpcode::REG_SEQUENCE; 1287 } 1288 1289 bool isBundle() const { 1290 return getOpcode() == TargetOpcode::BUNDLE; 1291 } 1292 1293 bool isCopy() const { 1294 return getOpcode() == TargetOpcode::COPY; 1295 } 1296 1297 bool isFullCopy() const { 1298 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg(); 1299 } 1300 1301 bool isExtractSubreg() const { 1302 return getOpcode() == TargetOpcode::EXTRACT_SUBREG; 1303 } 1304 1305 /// Return true if the instruction behaves like a copy. 1306 /// This does not include native copy instructions. 1307 bool isCopyLike() const { 1308 return isCopy() || isSubregToReg(); 1309 } 1310 1311 /// Return true is the instruction is an identity copy. 1312 bool isIdentityCopy() const { 1313 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() && 1314 getOperand(0).getSubReg() == getOperand(1).getSubReg(); 1315 } 1316 1317 /// Return true if this is a transient instruction that is either very likely 1318 /// to be eliminated during register allocation (such as copy-like 1319 /// instructions), or if this instruction doesn't have an execution-time cost. 1320 bool isTransient() const { 1321 switch (getOpcode()) { 1322 default: 1323 return isMetaInstruction(); 1324 // Copy-like instructions are usually eliminated during register allocation. 1325 case TargetOpcode::PHI: 1326 case TargetOpcode::G_PHI: 1327 case TargetOpcode::COPY: 1328 case TargetOpcode::INSERT_SUBREG: 1329 case TargetOpcode::SUBREG_TO_REG: 1330 case TargetOpcode::REG_SEQUENCE: 1331 return true; 1332 } 1333 } 1334 1335 /// Return the number of instructions inside the MI bundle, excluding the 1336 /// bundle header. 1337 /// 1338 /// This is the number of instructions that MachineBasicBlock::iterator 1339 /// skips, 0 for unbundled instructions. 1340 unsigned getBundleSize() const; 1341 1342 /// Return true if the MachineInstr reads the specified register. 1343 /// If TargetRegisterInfo is passed, then it also checks if there 1344 /// is a read of a super-register. 1345 /// This does not count partial redefines of virtual registers as reads: 1346 /// %reg1024:6 = OP. 1347 bool readsRegister(Register Reg, 1348 const TargetRegisterInfo *TRI = nullptr) const { 1349 return findRegisterUseOperandIdx(Reg, false, TRI) != -1; 1350 } 1351 1352 /// Return true if the MachineInstr reads the specified virtual register. 1353 /// Take into account that a partial define is a 1354 /// read-modify-write operation. 1355 bool readsVirtualRegister(Register Reg) const { 1356 return readsWritesVirtualRegister(Reg).first; 1357 } 1358 1359 /// Return a pair of bools (reads, writes) indicating if this instruction 1360 /// reads or writes Reg. This also considers partial defines. 1361 /// If Ops is not null, all operand indices for Reg are added. 1362 std::pair<bool,bool> readsWritesVirtualRegister(Register Reg, 1363 SmallVectorImpl<unsigned> *Ops = nullptr) const; 1364 1365 /// Return true if the MachineInstr kills the specified register. 1366 /// If TargetRegisterInfo is passed, then it also checks if there is 1367 /// a kill of a super-register. 1368 bool killsRegister(Register Reg, 1369 const TargetRegisterInfo *TRI = nullptr) const { 1370 return findRegisterUseOperandIdx(Reg, true, TRI) != -1; 1371 } 1372 1373 /// Return true if the MachineInstr fully defines the specified register. 1374 /// If TargetRegisterInfo is passed, then it also checks 1375 /// if there is a def of a super-register. 1376 /// NOTE: It's ignoring subreg indices on virtual registers. 1377 bool definesRegister(Register Reg, 1378 const TargetRegisterInfo *TRI = nullptr) const { 1379 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1; 1380 } 1381 1382 /// Return true if the MachineInstr modifies (fully define or partially 1383 /// define) the specified register. 1384 /// NOTE: It's ignoring subreg indices on virtual registers. 1385 bool modifiesRegister(Register Reg, 1386 const TargetRegisterInfo *TRI = nullptr) const { 1387 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1; 1388 } 1389 1390 /// Returns true if the register is dead in this machine instruction. 1391 /// If TargetRegisterInfo is passed, then it also checks 1392 /// if there is a dead def of a super-register. 1393 bool registerDefIsDead(Register Reg, 1394 const TargetRegisterInfo *TRI = nullptr) const { 1395 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1; 1396 } 1397 1398 /// Returns true if the MachineInstr has an implicit-use operand of exactly 1399 /// the given register (not considering sub/super-registers). 1400 bool hasRegisterImplicitUseOperand(Register Reg) const; 1401 1402 /// Returns the operand index that is a use of the specific register or -1 1403 /// if it is not found. It further tightens the search criteria to a use 1404 /// that kills the register if isKill is true. 1405 int findRegisterUseOperandIdx(Register Reg, bool isKill = false, 1406 const TargetRegisterInfo *TRI = nullptr) const; 1407 1408 /// Wrapper for findRegisterUseOperandIdx, it returns 1409 /// a pointer to the MachineOperand rather than an index. 1410 MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false, 1411 const TargetRegisterInfo *TRI = nullptr) { 1412 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI); 1413 return (Idx == -1) ? nullptr : &getOperand(Idx); 1414 } 1415 1416 const MachineOperand *findRegisterUseOperand( 1417 Register Reg, bool isKill = false, 1418 const TargetRegisterInfo *TRI = nullptr) const { 1419 return const_cast<MachineInstr *>(this)-> 1420 findRegisterUseOperand(Reg, isKill, TRI); 1421 } 1422 1423 /// Returns the operand index that is a def of the specified register or 1424 /// -1 if it is not found. If isDead is true, defs that are not dead are 1425 /// skipped. If Overlap is true, then it also looks for defs that merely 1426 /// overlap the specified register. If TargetRegisterInfo is non-null, 1427 /// then it also checks if there is a def of a super-register. 1428 /// This may also return a register mask operand when Overlap is true. 1429 int findRegisterDefOperandIdx(Register Reg, 1430 bool isDead = false, bool Overlap = false, 1431 const TargetRegisterInfo *TRI = nullptr) const; 1432 1433 /// Wrapper for findRegisterDefOperandIdx, it returns 1434 /// a pointer to the MachineOperand rather than an index. 1435 MachineOperand * 1436 findRegisterDefOperand(Register Reg, bool isDead = false, 1437 bool Overlap = false, 1438 const TargetRegisterInfo *TRI = nullptr) { 1439 int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI); 1440 return (Idx == -1) ? nullptr : &getOperand(Idx); 1441 } 1442 1443 const MachineOperand * 1444 findRegisterDefOperand(Register Reg, bool isDead = false, 1445 bool Overlap = false, 1446 const TargetRegisterInfo *TRI = nullptr) const { 1447 return const_cast<MachineInstr *>(this)->findRegisterDefOperand( 1448 Reg, isDead, Overlap, TRI); 1449 } 1450 1451 /// Find the index of the first operand in the 1452 /// operand list that is used to represent the predicate. It returns -1 if 1453 /// none is found. 1454 int findFirstPredOperandIdx() const; 1455 1456 /// Find the index of the flag word operand that 1457 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if 1458 /// getOperand(OpIdx) does not belong to an inline asm operand group. 1459 /// 1460 /// If GroupNo is not NULL, it will receive the number of the operand group 1461 /// containing OpIdx. 1462 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const; 1463 1464 /// Compute the static register class constraint for operand OpIdx. 1465 /// For normal instructions, this is derived from the MCInstrDesc. 1466 /// For inline assembly it is derived from the flag words. 1467 /// 1468 /// Returns NULL if the static register class constraint cannot be 1469 /// determined. 1470 const TargetRegisterClass* 1471 getRegClassConstraint(unsigned OpIdx, 1472 const TargetInstrInfo *TII, 1473 const TargetRegisterInfo *TRI) const; 1474 1475 /// Applies the constraints (def/use) implied by this MI on \p Reg to 1476 /// the given \p CurRC. 1477 /// If \p ExploreBundle is set and MI is part of a bundle, all the 1478 /// instructions inside the bundle will be taken into account. In other words, 1479 /// this method accumulates all the constraints of the operand of this MI and 1480 /// the related bundle if MI is a bundle or inside a bundle. 1481 /// 1482 /// Returns the register class that satisfies both \p CurRC and the 1483 /// constraints set by MI. Returns NULL if such a register class does not 1484 /// exist. 1485 /// 1486 /// \pre CurRC must not be NULL. 1487 const TargetRegisterClass *getRegClassConstraintEffectForVReg( 1488 Register Reg, const TargetRegisterClass *CurRC, 1489 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, 1490 bool ExploreBundle = false) const; 1491 1492 /// Applies the constraints (def/use) implied by the \p OpIdx operand 1493 /// to the given \p CurRC. 1494 /// 1495 /// Returns the register class that satisfies both \p CurRC and the 1496 /// constraints set by \p OpIdx MI. Returns NULL if such a register class 1497 /// does not exist. 1498 /// 1499 /// \pre CurRC must not be NULL. 1500 /// \pre The operand at \p OpIdx must be a register. 1501 const TargetRegisterClass * 1502 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC, 1503 const TargetInstrInfo *TII, 1504 const TargetRegisterInfo *TRI) const; 1505 1506 /// Add a tie between the register operands at DefIdx and UseIdx. 1507 /// The tie will cause the register allocator to ensure that the two 1508 /// operands are assigned the same physical register. 1509 /// 1510 /// Tied operands are managed automatically for explicit operands in the 1511 /// MCInstrDesc. This method is for exceptional cases like inline asm. 1512 void tieOperands(unsigned DefIdx, unsigned UseIdx); 1513 1514 /// Given the index of a tied register operand, find the 1515 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the 1516 /// index of the tied operand which must exist. 1517 unsigned findTiedOperandIdx(unsigned OpIdx) const; 1518 1519 /// Given the index of a register def operand, 1520 /// check if the register def is tied to a source operand, due to either 1521 /// two-address elimination or inline assembly constraints. Returns the 1522 /// first tied use operand index by reference if UseOpIdx is not null. 1523 bool isRegTiedToUseOperand(unsigned DefOpIdx, 1524 unsigned *UseOpIdx = nullptr) const { 1525 const MachineOperand &MO = getOperand(DefOpIdx); 1526 if (!MO.isReg() || !MO.isDef() || !MO.isTied()) 1527 return false; 1528 if (UseOpIdx) 1529 *UseOpIdx = findTiedOperandIdx(DefOpIdx); 1530 return true; 1531 } 1532 1533 /// Return true if the use operand of the specified index is tied to a def 1534 /// operand. It also returns the def operand index by reference if DefOpIdx 1535 /// is not null. 1536 bool isRegTiedToDefOperand(unsigned UseOpIdx, 1537 unsigned *DefOpIdx = nullptr) const { 1538 const MachineOperand &MO = getOperand(UseOpIdx); 1539 if (!MO.isReg() || !MO.isUse() || !MO.isTied()) 1540 return false; 1541 if (DefOpIdx) 1542 *DefOpIdx = findTiedOperandIdx(UseOpIdx); 1543 return true; 1544 } 1545 1546 /// Clears kill flags on all operands. 1547 void clearKillInfo(); 1548 1549 /// Replace all occurrences of FromReg with ToReg:SubIdx, 1550 /// properly composing subreg indices where necessary. 1551 void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, 1552 const TargetRegisterInfo &RegInfo); 1553 1554 /// We have determined MI kills a register. Look for the 1555 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true, 1556 /// add a implicit operand if it's not found. Returns true if the operand 1557 /// exists / is added. 1558 bool addRegisterKilled(Register IncomingReg, 1559 const TargetRegisterInfo *RegInfo, 1560 bool AddIfNotFound = false); 1561 1562 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes 1563 /// all aliasing registers. 1564 void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo); 1565 1566 /// We have determined MI defined a register without a use. 1567 /// Look for the operand that defines it and mark it as IsDead. If 1568 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns 1569 /// true if the operand exists / is added. 1570 bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, 1571 bool AddIfNotFound = false); 1572 1573 /// Clear all dead flags on operands defining register @p Reg. 1574 void clearRegisterDeads(Register Reg); 1575 1576 /// Mark all subregister defs of register @p Reg with the undef flag. 1577 /// This function is used when we determined to have a subregister def in an 1578 /// otherwise undefined super register. 1579 void setRegisterDefReadUndef(Register Reg, bool IsUndef = true); 1580 1581 /// We have determined MI defines a register. Make sure there is an operand 1582 /// defining Reg. 1583 void addRegisterDefined(Register Reg, 1584 const TargetRegisterInfo *RegInfo = nullptr); 1585 1586 /// Mark every physreg used by this instruction as 1587 /// dead except those in the UsedRegs list. 1588 /// 1589 /// On instructions with register mask operands, also add implicit-def 1590 /// operands for all registers in UsedRegs. 1591 void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs, 1592 const TargetRegisterInfo &TRI); 1593 1594 /// Return true if it is safe to move this instruction. If 1595 /// SawStore is set to true, it means that there is a store (or call) between 1596 /// the instruction's location and its intended destination. 1597 bool isSafeToMove(AAResults *AA, bool &SawStore) const; 1598 1599 /// Returns true if this instruction's memory access aliases the memory 1600 /// access of Other. 1601 // 1602 /// Assumes any physical registers used to compute addresses 1603 /// have the same value for both instructions. Returns false if neither 1604 /// instruction writes to memory. 1605 /// 1606 /// @param AA Optional alias analysis, used to compare memory operands. 1607 /// @param Other MachineInstr to check aliasing against. 1608 /// @param UseTBAA Whether to pass TBAA information to alias analysis. 1609 bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const; 1610 1611 /// Return true if this instruction may have an ordered 1612 /// or volatile memory reference, or if the information describing the memory 1613 /// reference is not available. Return false if it is known to have no 1614 /// ordered or volatile memory references. 1615 bool hasOrderedMemoryRef() const; 1616 1617 /// Return true if this load instruction never traps and points to a memory 1618 /// location whose value doesn't change during the execution of this function. 1619 /// 1620 /// Examples include loading a value from the constant pool or from the 1621 /// argument area of a function (if it does not change). If the instruction 1622 /// does multiple loads, this returns true only if all of the loads are 1623 /// dereferenceable and invariant. 1624 bool isDereferenceableInvariantLoad(AAResults *AA) const; 1625 1626 /// If the specified instruction is a PHI that always merges together the 1627 /// same virtual register, return the register, otherwise return 0. 1628 unsigned isConstantValuePHI() const; 1629 1630 /// Return true if this instruction has side effects that are not modeled 1631 /// by mayLoad / mayStore, etc. 1632 /// For all instructions, the property is encoded in MCInstrDesc::Flags 1633 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is 1634 /// INLINEASM instruction, in which case the side effect property is encoded 1635 /// in one of its operands (see InlineAsm::Extra_HasSideEffect). 1636 /// 1637 bool hasUnmodeledSideEffects() const; 1638 1639 /// Returns true if it is illegal to fold a load across this instruction. 1640 bool isLoadFoldBarrier() const; 1641 1642 /// Return true if all the defs of this instruction are dead. 1643 bool allDefsAreDead() const; 1644 1645 /// Return a valid size if the instruction is a spill instruction. 1646 Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const; 1647 1648 /// Return a valid size if the instruction is a folded spill instruction. 1649 Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const; 1650 1651 /// Return a valid size if the instruction is a restore instruction. 1652 Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const; 1653 1654 /// Return a valid size if the instruction is a folded restore instruction. 1655 Optional<unsigned> 1656 getFoldedRestoreSize(const TargetInstrInfo *TII) const; 1657 1658 /// Copy implicit register operands from specified 1659 /// instruction to this instruction. 1660 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI); 1661 1662 /// Debugging support 1663 /// @{ 1664 /// Determine the generic type to be printed (if needed) on uses and defs. 1665 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1666 const MachineRegisterInfo &MRI) const; 1667 1668 /// Return true when an instruction has tied register that can't be determined 1669 /// by the instruction's descriptor. This is useful for MIR printing, to 1670 /// determine whether we need to print the ties or not. 1671 bool hasComplexRegisterTies() const; 1672 1673 /// Print this MI to \p OS. 1674 /// Don't print information that can be inferred from other instructions if 1675 /// \p IsStandalone is false. It is usually true when only a fragment of the 1676 /// function is printed. 1677 /// Only print the defs and the opcode if \p SkipOpers is true. 1678 /// Otherwise, also print operands if \p SkipDebugLoc is true. 1679 /// Otherwise, also print the debug loc, with a terminating newline. 1680 /// \p TII is used to print the opcode name. If it's not present, but the 1681 /// MI is in a function, the opcode will be printed using the function's TII. 1682 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false, 1683 bool SkipDebugLoc = false, bool AddNewLine = true, 1684 const TargetInstrInfo *TII = nullptr) const; 1685 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true, 1686 bool SkipOpers = false, bool SkipDebugLoc = false, 1687 bool AddNewLine = true, 1688 const TargetInstrInfo *TII = nullptr) const; 1689 void dump() const; 1690 /// Print on dbgs() the current instruction and the instructions defining its 1691 /// operands and so on until we reach \p MaxDepth. 1692 void dumpr(const MachineRegisterInfo &MRI, 1693 unsigned MaxDepth = UINT_MAX) const; 1694 /// @} 1695 1696 //===--------------------------------------------------------------------===// 1697 // Accessors used to build up machine instructions. 1698 1699 /// Add the specified operand to the instruction. If it is an implicit 1700 /// operand, it is added to the end of the operand list. If it is an 1701 /// explicit operand it is added at the end of the explicit operand list 1702 /// (before the first implicit operand). 1703 /// 1704 /// MF must be the machine function that was used to allocate this 1705 /// instruction. 1706 /// 1707 /// MachineInstrBuilder provides a more convenient interface for creating 1708 /// instructions and adding operands. 1709 void addOperand(MachineFunction &MF, const MachineOperand &Op); 1710 1711 /// Add an operand without providing an MF reference. This only works for 1712 /// instructions that are inserted in a basic block. 1713 /// 1714 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be 1715 /// preferred. 1716 void addOperand(const MachineOperand &Op); 1717 1718 /// Replace the instruction descriptor (thus opcode) of 1719 /// the current instruction with a new one. 1720 void setDesc(const MCInstrDesc &TID) { MCID = &TID; } 1721 1722 /// Replace current source information with new such. 1723 /// Avoid using this, the constructor argument is preferable. 1724 void setDebugLoc(DebugLoc DL) { 1725 DbgLoc = std::move(DL); 1726 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor"); 1727 } 1728 1729 /// Erase an operand from an instruction, leaving it with one 1730 /// fewer operand than it started with. 1731 void removeOperand(unsigned OpNo); 1732 1733 /// Clear this MachineInstr's memory reference descriptor list. This resets 1734 /// the memrefs to their most conservative state. This should be used only 1735 /// as a last resort since it greatly pessimizes our knowledge of the memory 1736 /// access performed by the instruction. 1737 void dropMemRefs(MachineFunction &MF); 1738 1739 /// Assign this MachineInstr's memory reference descriptor list. 1740 /// 1741 /// Unlike other methods, this *will* allocate them into a new array 1742 /// associated with the provided `MachineFunction`. 1743 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs); 1744 1745 /// Add a MachineMemOperand to the machine instruction. 1746 /// This function should be used only occasionally. The setMemRefs function 1747 /// is the primary method for setting up a MachineInstr's MemRefs list. 1748 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO); 1749 1750 /// Clone another MachineInstr's memory reference descriptor list and replace 1751 /// ours with it. 1752 /// 1753 /// Note that `*this` may be the incoming MI! 1754 /// 1755 /// Prefer this API whenever possible as it can avoid allocations in common 1756 /// cases. 1757 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI); 1758 1759 /// Clone the merge of multiple MachineInstrs' memory reference descriptors 1760 /// list and replace ours with it. 1761 /// 1762 /// Note that `*this` may be one of the incoming MIs! 1763 /// 1764 /// Prefer this API whenever possible as it can avoid allocations in common 1765 /// cases. 1766 void cloneMergedMemRefs(MachineFunction &MF, 1767 ArrayRef<const MachineInstr *> MIs); 1768 1769 /// Set a symbol that will be emitted just prior to the instruction itself. 1770 /// 1771 /// Setting this to a null pointer will remove any such symbol. 1772 /// 1773 /// FIXME: This is not fully implemented yet. 1774 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol); 1775 1776 /// Set a symbol that will be emitted just after the instruction itself. 1777 /// 1778 /// Setting this to a null pointer will remove any such symbol. 1779 /// 1780 /// FIXME: This is not fully implemented yet. 1781 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol); 1782 1783 /// Clone another MachineInstr's pre- and post- instruction symbols and 1784 /// replace ours with it. 1785 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI); 1786 1787 /// Set a marker on instructions that denotes where we should create and emit 1788 /// heap alloc site labels. This waits until after instruction selection and 1789 /// optimizations to create the label, so it should still work if the 1790 /// instruction is removed or duplicated. 1791 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD); 1792 1793 /// Return the MIFlags which represent both MachineInstrs. This 1794 /// should be used when merging two MachineInstrs into one. This routine does 1795 /// not modify the MIFlags of this MachineInstr. 1796 uint16_t mergeFlagsWith(const MachineInstr& Other) const; 1797 1798 static uint16_t copyFlagsFromInstruction(const Instruction &I); 1799 1800 /// Copy all flags to MachineInst MIFlags 1801 void copyIRFlags(const Instruction &I); 1802 1803 /// Break any tie involving OpIdx. 1804 void untieRegOperand(unsigned OpIdx) { 1805 MachineOperand &MO = getOperand(OpIdx); 1806 if (MO.isReg() && MO.isTied()) { 1807 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0; 1808 MO.TiedTo = 0; 1809 } 1810 } 1811 1812 /// Add all implicit def and use operands to this instruction. 1813 void addImplicitDefUseOperands(MachineFunction &MF); 1814 1815 /// Scan instructions immediately following MI and collect any matching 1816 /// DBG_VALUEs. 1817 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues); 1818 1819 /// Find all DBG_VALUEs that point to the register def in this instruction 1820 /// and point them to \p Reg instead. 1821 void changeDebugValuesDefReg(Register Reg); 1822 1823 /// Returns the Intrinsic::ID for this instruction. 1824 /// \pre Must have an intrinsic ID operand. 1825 unsigned getIntrinsicID() const { 1826 return getOperand(getNumExplicitDefs()).getIntrinsicID(); 1827 } 1828 1829 /// Sets all register debug operands in this debug value instruction to be 1830 /// undef. 1831 void setDebugValueUndef() { 1832 assert(isDebugValue() && "Must be a debug value instruction."); 1833 for (MachineOperand &MO : debug_operands()) { 1834 if (MO.isReg()) { 1835 MO.setReg(0); 1836 MO.setSubReg(0); 1837 } 1838 } 1839 } 1840 1841 private: 1842 /// If this instruction is embedded into a MachineFunction, return the 1843 /// MachineRegisterInfo object for the current function, otherwise 1844 /// return null. 1845 MachineRegisterInfo *getRegInfo(); 1846 1847 /// Unlink all of the register operands in this instruction from their 1848 /// respective use lists. This requires that the operands already be on their 1849 /// use lists. 1850 void removeRegOperandsFromUseLists(MachineRegisterInfo&); 1851 1852 /// Add all of the register operands in this instruction from their 1853 /// respective use lists. This requires that the operands not be on their 1854 /// use lists yet. 1855 void addRegOperandsToUseLists(MachineRegisterInfo&); 1856 1857 /// Slow path for hasProperty when we're dealing with a bundle. 1858 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const; 1859 1860 /// Implements the logic of getRegClassConstraintEffectForVReg for the 1861 /// this MI and the given operand index \p OpIdx. 1862 /// If the related operand does not constrained Reg, this returns CurRC. 1863 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl( 1864 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC, 1865 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const; 1866 1867 /// Stores extra instruction information inline or allocates as ExtraInfo 1868 /// based on the number of pointers. 1869 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs, 1870 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol, 1871 MDNode *HeapAllocMarker); 1872 }; 1873 1874 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the 1875 /// instruction rather than by pointer value. 1876 /// The hashing and equality testing functions ignore definitions so this is 1877 /// useful for CSE, etc. 1878 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> { 1879 static inline MachineInstr *getEmptyKey() { 1880 return nullptr; 1881 } 1882 1883 static inline MachineInstr *getTombstoneKey() { 1884 return reinterpret_cast<MachineInstr*>(-1); 1885 } 1886 1887 static unsigned getHashValue(const MachineInstr* const &MI); 1888 1889 static bool isEqual(const MachineInstr* const &LHS, 1890 const MachineInstr* const &RHS) { 1891 if (RHS == getEmptyKey() || RHS == getTombstoneKey() || 1892 LHS == getEmptyKey() || LHS == getTombstoneKey()) 1893 return LHS == RHS; 1894 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs); 1895 } 1896 }; 1897 1898 //===----------------------------------------------------------------------===// 1899 // Debugging Support 1900 1901 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) { 1902 MI.print(OS); 1903 return OS; 1904 } 1905 1906 } // end namespace llvm 1907 1908 #endif // LLVM_CODEGEN_MACHINEINSTR_H 1909