1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===// 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 // Methods common to all machine instructions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/MachineInstr.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/Hashing.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallBitVector.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/MemoryLocation.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineInstrBundle.h" 27 #include "llvm/CodeGen/MachineMemOperand.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/MachineOperand.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/PseudoSourceValue.h" 32 #include "llvm/CodeGen/StackMaps.h" 33 #include "llvm/CodeGen/TargetInstrInfo.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/CodeGen/TargetSubtargetInfo.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DebugLoc.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/InlineAsm.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/IR/Metadata.h" 43 #include "llvm/IR/Module.h" 44 #include "llvm/IR/ModuleSlotTracker.h" 45 #include "llvm/IR/Operator.h" 46 #include "llvm/MC/MCInstrDesc.h" 47 #include "llvm/MC/MCRegisterInfo.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/Compiler.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/FormattedStream.h" 53 #include "llvm/Support/LowLevelTypeImpl.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include "llvm/Target/TargetMachine.h" 56 #include <algorithm> 57 #include <cassert> 58 #include <cstdint> 59 #include <cstring> 60 #include <utility> 61 62 using namespace llvm; 63 64 static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) { 65 if (const MachineBasicBlock *MBB = MI.getParent()) 66 if (const MachineFunction *MF = MBB->getParent()) 67 return MF; 68 return nullptr; 69 } 70 71 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from 72 // it. 73 static void tryToGetTargetInfo(const MachineInstr &MI, 74 const TargetRegisterInfo *&TRI, 75 const MachineRegisterInfo *&MRI, 76 const TargetIntrinsicInfo *&IntrinsicInfo, 77 const TargetInstrInfo *&TII) { 78 79 if (const MachineFunction *MF = getMFIfAvailable(MI)) { 80 TRI = MF->getSubtarget().getRegisterInfo(); 81 MRI = &MF->getRegInfo(); 82 IntrinsicInfo = MF->getTarget().getIntrinsicInfo(); 83 TII = MF->getSubtarget().getInstrInfo(); 84 } 85 } 86 87 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) { 88 if (MCID->ImplicitDefs) 89 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; 90 ++ImpDefs) 91 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true)); 92 if (MCID->ImplicitUses) 93 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses; 94 ++ImpUses) 95 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true)); 96 } 97 98 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the 99 /// implicit operands. It reserves space for the number of operands specified by 100 /// the MCInstrDesc. 101 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &TID, 102 DebugLoc DL, bool NoImp) 103 : MCID(&TID), DbgLoc(std::move(DL)), DebugInstrNum(0) { 104 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor"); 105 106 // Reserve space for the expected number of operands. 107 if (unsigned NumOps = MCID->getNumOperands() + 108 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) { 109 CapOperands = OperandCapacity::get(NumOps); 110 Operands = MF.allocateOperandArray(CapOperands); 111 } 112 113 if (!NoImp) 114 addImplicitDefUseOperands(MF); 115 } 116 117 /// MachineInstr ctor - Copies MachineInstr arg exactly. 118 /// Does not copy the number from debug instruction numbering, to preserve 119 /// uniqueness. 120 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI) 121 : MCID(&MI.getDesc()), Info(MI.Info), DbgLoc(MI.getDebugLoc()), 122 DebugInstrNum(0) { 123 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor"); 124 125 CapOperands = OperandCapacity::get(MI.getNumOperands()); 126 Operands = MF.allocateOperandArray(CapOperands); 127 128 // Copy operands. 129 for (const MachineOperand &MO : MI.operands()) 130 addOperand(MF, MO); 131 132 // Copy all the sensible flags. 133 setFlags(MI.Flags); 134 } 135 136 void MachineInstr::moveBefore(MachineInstr *MovePos) { 137 MovePos->getParent()->splice(MovePos, getParent(), getIterator()); 138 } 139 140 /// getRegInfo - If this instruction is embedded into a MachineFunction, 141 /// return the MachineRegisterInfo object for the current function, otherwise 142 /// return null. 143 MachineRegisterInfo *MachineInstr::getRegInfo() { 144 if (MachineBasicBlock *MBB = getParent()) 145 return &MBB->getParent()->getRegInfo(); 146 return nullptr; 147 } 148 149 void MachineInstr::removeRegOperandsFromUseLists(MachineRegisterInfo &MRI) { 150 for (MachineOperand &MO : operands()) 151 if (MO.isReg()) 152 MRI.removeRegOperandFromUseList(&MO); 153 } 154 155 void MachineInstr::addRegOperandsToUseLists(MachineRegisterInfo &MRI) { 156 for (MachineOperand &MO : operands()) 157 if (MO.isReg()) 158 MRI.addRegOperandToUseList(&MO); 159 } 160 161 void MachineInstr::addOperand(const MachineOperand &Op) { 162 MachineBasicBlock *MBB = getParent(); 163 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs"); 164 MachineFunction *MF = MBB->getParent(); 165 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs"); 166 addOperand(*MF, Op); 167 } 168 169 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping 170 /// ranges. If MRI is non-null also update use-def chains. 171 static void moveOperands(MachineOperand *Dst, MachineOperand *Src, 172 unsigned NumOps, MachineRegisterInfo *MRI) { 173 if (MRI) 174 return MRI->moveOperands(Dst, Src, NumOps); 175 // MachineOperand is a trivially copyable type so we can just use memmove. 176 assert(Dst && Src && "Unknown operands"); 177 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand)); 178 } 179 180 /// addOperand - Add the specified operand to the instruction. If it is an 181 /// implicit operand, it is added to the end of the operand list. If it is 182 /// an explicit operand it is added at the end of the explicit operand list 183 /// (before the first implicit operand). 184 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) { 185 assert(MCID && "Cannot add operands before providing an instr descriptor"); 186 187 // Check if we're adding one of our existing operands. 188 if (&Op >= Operands && &Op < Operands + NumOperands) { 189 // This is unusual: MI->addOperand(MI->getOperand(i)). 190 // If adding Op requires reallocating or moving existing operands around, 191 // the Op reference could go stale. Support it by copying Op. 192 MachineOperand CopyOp(Op); 193 return addOperand(MF, CopyOp); 194 } 195 196 // Find the insert location for the new operand. Implicit registers go at 197 // the end, everything else goes before the implicit regs. 198 // 199 // FIXME: Allow mixed explicit and implicit operands on inline asm. 200 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as 201 // implicit-defs, but they must not be moved around. See the FIXME in 202 // InstrEmitter.cpp. 203 unsigned OpNo = getNumOperands(); 204 bool isImpReg = Op.isReg() && Op.isImplicit(); 205 if (!isImpReg && !isInlineAsm()) { 206 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) { 207 --OpNo; 208 assert(!Operands[OpNo].isTied() && "Cannot move tied operands"); 209 } 210 } 211 212 // OpNo now points as the desired insertion point. Unless this is a variadic 213 // instruction, only implicit regs are allowed beyond MCID->getNumOperands(). 214 // RegMask operands go between the explicit and implicit operands. 215 assert((MCID->isVariadic() || OpNo < MCID->getNumOperands() || 216 Op.isValidExcessOperand()) && 217 "Trying to add an operand to a machine instr that is already done!"); 218 219 MachineRegisterInfo *MRI = getRegInfo(); 220 221 // Determine if the Operands array needs to be reallocated. 222 // Save the old capacity and operand array. 223 OperandCapacity OldCap = CapOperands; 224 MachineOperand *OldOperands = Operands; 225 if (!OldOperands || OldCap.getSize() == getNumOperands()) { 226 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1); 227 Operands = MF.allocateOperandArray(CapOperands); 228 // Move the operands before the insertion point. 229 if (OpNo) 230 moveOperands(Operands, OldOperands, OpNo, MRI); 231 } 232 233 // Move the operands following the insertion point. 234 if (OpNo != NumOperands) 235 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo, 236 MRI); 237 ++NumOperands; 238 239 // Deallocate the old operand array. 240 if (OldOperands != Operands && OldOperands) 241 MF.deallocateOperandArray(OldCap, OldOperands); 242 243 // Copy Op into place. It still needs to be inserted into the MRI use lists. 244 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op); 245 NewMO->ParentMI = this; 246 247 // When adding a register operand, tell MRI about it. 248 if (NewMO->isReg()) { 249 // Ensure isOnRegUseList() returns false, regardless of Op's status. 250 NewMO->Contents.Reg.Prev = nullptr; 251 // Ignore existing ties. This is not a property that can be copied. 252 NewMO->TiedTo = 0; 253 // Add the new operand to MRI, but only for instructions in an MBB. 254 if (MRI) 255 MRI->addRegOperandToUseList(NewMO); 256 // The MCID operand information isn't accurate until we start adding 257 // explicit operands. The implicit operands are added first, then the 258 // explicits are inserted before them. 259 if (!isImpReg) { 260 // Tie uses to defs as indicated in MCInstrDesc. 261 if (NewMO->isUse()) { 262 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO); 263 if (DefIdx != -1) 264 tieOperands(DefIdx, OpNo); 265 } 266 // If the register operand is flagged as early, mark the operand as such. 267 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1) 268 NewMO->setIsEarlyClobber(true); 269 } 270 // Ensure debug instructions set debug flag on register uses. 271 if (NewMO->isUse() && isDebugInstr()) 272 NewMO->setIsDebug(); 273 } 274 } 275 276 void MachineInstr::removeOperand(unsigned OpNo) { 277 assert(OpNo < getNumOperands() && "Invalid operand number"); 278 untieRegOperand(OpNo); 279 280 #ifndef NDEBUG 281 // Moving tied operands would break the ties. 282 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i) 283 if (Operands[i].isReg()) 284 assert(!Operands[i].isTied() && "Cannot move tied operands"); 285 #endif 286 287 MachineRegisterInfo *MRI = getRegInfo(); 288 if (MRI && Operands[OpNo].isReg()) 289 MRI->removeRegOperandFromUseList(Operands + OpNo); 290 291 // Don't call the MachineOperand destructor. A lot of this code depends on 292 // MachineOperand having a trivial destructor anyway, and adding a call here 293 // wouldn't make it 'destructor-correct'. 294 295 if (unsigned N = NumOperands - 1 - OpNo) 296 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI); 297 --NumOperands; 298 } 299 300 void MachineInstr::setExtraInfo(MachineFunction &MF, 301 ArrayRef<MachineMemOperand *> MMOs, 302 MCSymbol *PreInstrSymbol, 303 MCSymbol *PostInstrSymbol, 304 MDNode *HeapAllocMarker) { 305 bool HasPreInstrSymbol = PreInstrSymbol != nullptr; 306 bool HasPostInstrSymbol = PostInstrSymbol != nullptr; 307 bool HasHeapAllocMarker = HeapAllocMarker != nullptr; 308 int NumPointers = 309 MMOs.size() + HasPreInstrSymbol + HasPostInstrSymbol + HasHeapAllocMarker; 310 311 // Drop all extra info if there is none. 312 if (NumPointers <= 0) { 313 Info.clear(); 314 return; 315 } 316 317 // If more than one pointer, then store out of line. Store heap alloc markers 318 // out of line because PointerSumType cannot hold more than 4 tag types with 319 // 32-bit pointers. 320 // FIXME: Maybe we should make the symbols in the extra info mutable? 321 else if (NumPointers > 1 || HasHeapAllocMarker) { 322 Info.set<EIIK_OutOfLine>(MF.createMIExtraInfo( 323 MMOs, PreInstrSymbol, PostInstrSymbol, HeapAllocMarker)); 324 return; 325 } 326 327 // Otherwise store the single pointer inline. 328 if (HasPreInstrSymbol) 329 Info.set<EIIK_PreInstrSymbol>(PreInstrSymbol); 330 else if (HasPostInstrSymbol) 331 Info.set<EIIK_PostInstrSymbol>(PostInstrSymbol); 332 else 333 Info.set<EIIK_MMO>(MMOs[0]); 334 } 335 336 void MachineInstr::dropMemRefs(MachineFunction &MF) { 337 if (memoperands_empty()) 338 return; 339 340 setExtraInfo(MF, {}, getPreInstrSymbol(), getPostInstrSymbol(), 341 getHeapAllocMarker()); 342 } 343 344 void MachineInstr::setMemRefs(MachineFunction &MF, 345 ArrayRef<MachineMemOperand *> MMOs) { 346 if (MMOs.empty()) { 347 dropMemRefs(MF); 348 return; 349 } 350 351 setExtraInfo(MF, MMOs, getPreInstrSymbol(), getPostInstrSymbol(), 352 getHeapAllocMarker()); 353 } 354 355 void MachineInstr::addMemOperand(MachineFunction &MF, 356 MachineMemOperand *MO) { 357 SmallVector<MachineMemOperand *, 2> MMOs; 358 MMOs.append(memoperands_begin(), memoperands_end()); 359 MMOs.push_back(MO); 360 setMemRefs(MF, MMOs); 361 } 362 363 void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) { 364 if (this == &MI) 365 // Nothing to do for a self-clone! 366 return; 367 368 assert(&MF == MI.getMF() && 369 "Invalid machine functions when cloning memory refrences!"); 370 // See if we can just steal the extra info already allocated for the 371 // instruction. We can do this whenever the pre- and post-instruction symbols 372 // are the same (including null). 373 if (getPreInstrSymbol() == MI.getPreInstrSymbol() && 374 getPostInstrSymbol() == MI.getPostInstrSymbol() && 375 getHeapAllocMarker() == MI.getHeapAllocMarker()) { 376 Info = MI.Info; 377 return; 378 } 379 380 // Otherwise, fall back on a copy-based clone. 381 setMemRefs(MF, MI.memoperands()); 382 } 383 384 /// Check to see if the MMOs pointed to by the two MemRefs arrays are 385 /// identical. 386 static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS, 387 ArrayRef<MachineMemOperand *> RHS) { 388 if (LHS.size() != RHS.size()) 389 return false; 390 391 auto LHSPointees = make_pointee_range(LHS); 392 auto RHSPointees = make_pointee_range(RHS); 393 return std::equal(LHSPointees.begin(), LHSPointees.end(), 394 RHSPointees.begin()); 395 } 396 397 void MachineInstr::cloneMergedMemRefs(MachineFunction &MF, 398 ArrayRef<const MachineInstr *> MIs) { 399 // Try handling easy numbers of MIs with simpler mechanisms. 400 if (MIs.empty()) { 401 dropMemRefs(MF); 402 return; 403 } 404 if (MIs.size() == 1) { 405 cloneMemRefs(MF, *MIs[0]); 406 return; 407 } 408 // Because an empty memoperands list provides *no* information and must be 409 // handled conservatively (assuming the instruction can do anything), the only 410 // way to merge with it is to drop all other memoperands. 411 if (MIs[0]->memoperands_empty()) { 412 dropMemRefs(MF); 413 return; 414 } 415 416 // Handle the general case. 417 SmallVector<MachineMemOperand *, 2> MergedMMOs; 418 // Start with the first instruction. 419 assert(&MF == MIs[0]->getMF() && 420 "Invalid machine functions when cloning memory references!"); 421 MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end()); 422 // Now walk all the other instructions and accumulate any different MMOs. 423 for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) { 424 assert(&MF == MI.getMF() && 425 "Invalid machine functions when cloning memory references!"); 426 427 // Skip MIs with identical operands to the first. This is a somewhat 428 // arbitrary hack but will catch common cases without being quadratic. 429 // TODO: We could fully implement merge semantics here if needed. 430 if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands())) 431 continue; 432 433 // Because an empty memoperands list provides *no* information and must be 434 // handled conservatively (assuming the instruction can do anything), the 435 // only way to merge with it is to drop all other memoperands. 436 if (MI.memoperands_empty()) { 437 dropMemRefs(MF); 438 return; 439 } 440 441 // Otherwise accumulate these into our temporary buffer of the merged state. 442 MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end()); 443 } 444 445 setMemRefs(MF, MergedMMOs); 446 } 447 448 void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) { 449 // Do nothing if old and new symbols are the same. 450 if (Symbol == getPreInstrSymbol()) 451 return; 452 453 // If there was only one symbol and we're removing it, just clear info. 454 if (!Symbol && Info.is<EIIK_PreInstrSymbol>()) { 455 Info.clear(); 456 return; 457 } 458 459 setExtraInfo(MF, memoperands(), Symbol, getPostInstrSymbol(), 460 getHeapAllocMarker()); 461 } 462 463 void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) { 464 // Do nothing if old and new symbols are the same. 465 if (Symbol == getPostInstrSymbol()) 466 return; 467 468 // If there was only one symbol and we're removing it, just clear info. 469 if (!Symbol && Info.is<EIIK_PostInstrSymbol>()) { 470 Info.clear(); 471 return; 472 } 473 474 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), Symbol, 475 getHeapAllocMarker()); 476 } 477 478 void MachineInstr::setHeapAllocMarker(MachineFunction &MF, MDNode *Marker) { 479 // Do nothing if old and new symbols are the same. 480 if (Marker == getHeapAllocMarker()) 481 return; 482 483 setExtraInfo(MF, memoperands(), getPreInstrSymbol(), getPostInstrSymbol(), 484 Marker); 485 } 486 487 void MachineInstr::cloneInstrSymbols(MachineFunction &MF, 488 const MachineInstr &MI) { 489 if (this == &MI) 490 // Nothing to do for a self-clone! 491 return; 492 493 assert(&MF == MI.getMF() && 494 "Invalid machine functions when cloning instruction symbols!"); 495 496 setPreInstrSymbol(MF, MI.getPreInstrSymbol()); 497 setPostInstrSymbol(MF, MI.getPostInstrSymbol()); 498 setHeapAllocMarker(MF, MI.getHeapAllocMarker()); 499 } 500 501 uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const { 502 // For now, the just return the union of the flags. If the flags get more 503 // complicated over time, we might need more logic here. 504 return getFlags() | Other.getFlags(); 505 } 506 507 uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) { 508 uint16_t MIFlags = 0; 509 // Copy the wrapping flags. 510 if (const OverflowingBinaryOperator *OB = 511 dyn_cast<OverflowingBinaryOperator>(&I)) { 512 if (OB->hasNoSignedWrap()) 513 MIFlags |= MachineInstr::MIFlag::NoSWrap; 514 if (OB->hasNoUnsignedWrap()) 515 MIFlags |= MachineInstr::MIFlag::NoUWrap; 516 } 517 518 // Copy the exact flag. 519 if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I)) 520 if (PE->isExact()) 521 MIFlags |= MachineInstr::MIFlag::IsExact; 522 523 // Copy the fast-math flags. 524 if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) { 525 const FastMathFlags Flags = FP->getFastMathFlags(); 526 if (Flags.noNaNs()) 527 MIFlags |= MachineInstr::MIFlag::FmNoNans; 528 if (Flags.noInfs()) 529 MIFlags |= MachineInstr::MIFlag::FmNoInfs; 530 if (Flags.noSignedZeros()) 531 MIFlags |= MachineInstr::MIFlag::FmNsz; 532 if (Flags.allowReciprocal()) 533 MIFlags |= MachineInstr::MIFlag::FmArcp; 534 if (Flags.allowContract()) 535 MIFlags |= MachineInstr::MIFlag::FmContract; 536 if (Flags.approxFunc()) 537 MIFlags |= MachineInstr::MIFlag::FmAfn; 538 if (Flags.allowReassoc()) 539 MIFlags |= MachineInstr::MIFlag::FmReassoc; 540 } 541 542 return MIFlags; 543 } 544 545 void MachineInstr::copyIRFlags(const Instruction &I) { 546 Flags = copyFlagsFromInstruction(I); 547 } 548 549 bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const { 550 assert(!isBundledWithPred() && "Must be called on bundle header"); 551 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) { 552 if (MII->getDesc().getFlags() & Mask) { 553 if (Type == AnyInBundle) 554 return true; 555 } else { 556 if (Type == AllInBundle && !MII->isBundle()) 557 return false; 558 } 559 // This was the last instruction in the bundle. 560 if (!MII->isBundledWithSucc()) 561 return Type == AllInBundle; 562 } 563 } 564 565 bool MachineInstr::isIdenticalTo(const MachineInstr &Other, 566 MICheckType Check) const { 567 // If opcodes or number of operands are not the same then the two 568 // instructions are obviously not identical. 569 if (Other.getOpcode() != getOpcode() || 570 Other.getNumOperands() != getNumOperands()) 571 return false; 572 573 if (isBundle()) { 574 // We have passed the test above that both instructions have the same 575 // opcode, so we know that both instructions are bundles here. Let's compare 576 // MIs inside the bundle. 577 assert(Other.isBundle() && "Expected that both instructions are bundles."); 578 MachineBasicBlock::const_instr_iterator I1 = getIterator(); 579 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator(); 580 // Loop until we analysed the last intruction inside at least one of the 581 // bundles. 582 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) { 583 ++I1; 584 ++I2; 585 if (!I1->isIdenticalTo(*I2, Check)) 586 return false; 587 } 588 // If we've reached the end of just one of the two bundles, but not both, 589 // the instructions are not identical. 590 if (I1->isBundledWithSucc() || I2->isBundledWithSucc()) 591 return false; 592 } 593 594 // Check operands to make sure they match. 595 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 596 const MachineOperand &MO = getOperand(i); 597 const MachineOperand &OMO = Other.getOperand(i); 598 if (!MO.isReg()) { 599 if (!MO.isIdenticalTo(OMO)) 600 return false; 601 continue; 602 } 603 604 // Clients may or may not want to ignore defs when testing for equality. 605 // For example, machine CSE pass only cares about finding common 606 // subexpressions, so it's safe to ignore virtual register defs. 607 if (MO.isDef()) { 608 if (Check == IgnoreDefs) 609 continue; 610 else if (Check == IgnoreVRegDefs) { 611 if (!Register::isVirtualRegister(MO.getReg()) || 612 !Register::isVirtualRegister(OMO.getReg())) 613 if (!MO.isIdenticalTo(OMO)) 614 return false; 615 } else { 616 if (!MO.isIdenticalTo(OMO)) 617 return false; 618 if (Check == CheckKillDead && MO.isDead() != OMO.isDead()) 619 return false; 620 } 621 } else { 622 if (!MO.isIdenticalTo(OMO)) 623 return false; 624 if (Check == CheckKillDead && MO.isKill() != OMO.isKill()) 625 return false; 626 } 627 } 628 // If DebugLoc does not match then two debug instructions are not identical. 629 if (isDebugInstr()) 630 if (getDebugLoc() && Other.getDebugLoc() && 631 getDebugLoc() != Other.getDebugLoc()) 632 return false; 633 return true; 634 } 635 636 const MachineFunction *MachineInstr::getMF() const { 637 return getParent()->getParent(); 638 } 639 640 MachineInstr *MachineInstr::removeFromParent() { 641 assert(getParent() && "Not embedded in a basic block!"); 642 return getParent()->remove(this); 643 } 644 645 MachineInstr *MachineInstr::removeFromBundle() { 646 assert(getParent() && "Not embedded in a basic block!"); 647 return getParent()->remove_instr(this); 648 } 649 650 void MachineInstr::eraseFromParent() { 651 assert(getParent() && "Not embedded in a basic block!"); 652 getParent()->erase(this); 653 } 654 655 void MachineInstr::eraseFromBundle() { 656 assert(getParent() && "Not embedded in a basic block!"); 657 getParent()->erase_instr(this); 658 } 659 660 bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const { 661 if (!isCall(Type)) 662 return false; 663 switch (getOpcode()) { 664 case TargetOpcode::PATCHPOINT: 665 case TargetOpcode::STACKMAP: 666 case TargetOpcode::STATEPOINT: 667 case TargetOpcode::FENTRY_CALL: 668 return false; 669 } 670 return true; 671 } 672 673 bool MachineInstr::shouldUpdateCallSiteInfo() const { 674 if (isBundle()) 675 return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle); 676 return isCandidateForCallSiteEntry(); 677 } 678 679 unsigned MachineInstr::getNumExplicitOperands() const { 680 unsigned NumOperands = MCID->getNumOperands(); 681 if (!MCID->isVariadic()) 682 return NumOperands; 683 684 for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) { 685 const MachineOperand &MO = getOperand(I); 686 // The operands must always be in the following order: 687 // - explicit reg defs, 688 // - other explicit operands (reg uses, immediates, etc.), 689 // - implicit reg defs 690 // - implicit reg uses 691 if (MO.isReg() && MO.isImplicit()) 692 break; 693 ++NumOperands; 694 } 695 return NumOperands; 696 } 697 698 unsigned MachineInstr::getNumExplicitDefs() const { 699 unsigned NumDefs = MCID->getNumDefs(); 700 if (!MCID->isVariadic()) 701 return NumDefs; 702 703 for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) { 704 const MachineOperand &MO = getOperand(I); 705 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 706 break; 707 ++NumDefs; 708 } 709 return NumDefs; 710 } 711 712 void MachineInstr::bundleWithPred() { 713 assert(!isBundledWithPred() && "MI is already bundled with its predecessor"); 714 setFlag(BundledPred); 715 MachineBasicBlock::instr_iterator Pred = getIterator(); 716 --Pred; 717 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 718 Pred->setFlag(BundledSucc); 719 } 720 721 void MachineInstr::bundleWithSucc() { 722 assert(!isBundledWithSucc() && "MI is already bundled with its successor"); 723 setFlag(BundledSucc); 724 MachineBasicBlock::instr_iterator Succ = getIterator(); 725 ++Succ; 726 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags"); 727 Succ->setFlag(BundledPred); 728 } 729 730 void MachineInstr::unbundleFromPred() { 731 assert(isBundledWithPred() && "MI isn't bundled with its predecessor"); 732 clearFlag(BundledPred); 733 MachineBasicBlock::instr_iterator Pred = getIterator(); 734 --Pred; 735 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 736 Pred->clearFlag(BundledSucc); 737 } 738 739 void MachineInstr::unbundleFromSucc() { 740 assert(isBundledWithSucc() && "MI isn't bundled with its successor"); 741 clearFlag(BundledSucc); 742 MachineBasicBlock::instr_iterator Succ = getIterator(); 743 ++Succ; 744 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags"); 745 Succ->clearFlag(BundledPred); 746 } 747 748 bool MachineInstr::isStackAligningInlineAsm() const { 749 if (isInlineAsm()) { 750 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 751 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 752 return true; 753 } 754 return false; 755 } 756 757 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const { 758 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"); 759 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 760 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0); 761 } 762 763 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx, 764 unsigned *GroupNo) const { 765 assert(isInlineAsm() && "Expected an inline asm instruction"); 766 assert(OpIdx < getNumOperands() && "OpIdx out of range"); 767 768 // Ignore queries about the initial operands. 769 if (OpIdx < InlineAsm::MIOp_FirstOperand) 770 return -1; 771 772 unsigned Group = 0; 773 unsigned NumOps; 774 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 775 i += NumOps) { 776 const MachineOperand &FlagMO = getOperand(i); 777 // If we reach the implicit register operands, stop looking. 778 if (!FlagMO.isImm()) 779 return -1; 780 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 781 if (i + NumOps > OpIdx) { 782 if (GroupNo) 783 *GroupNo = Group; 784 return i; 785 } 786 ++Group; 787 } 788 return -1; 789 } 790 791 const DILabel *MachineInstr::getDebugLabel() const { 792 assert(isDebugLabel() && "not a DBG_LABEL"); 793 return cast<DILabel>(getOperand(0).getMetadata()); 794 } 795 796 const MachineOperand &MachineInstr::getDebugVariableOp() const { 797 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*"); 798 unsigned VariableOp = isDebugValueList() ? 0 : 2; 799 return getOperand(VariableOp); 800 } 801 802 MachineOperand &MachineInstr::getDebugVariableOp() { 803 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*"); 804 unsigned VariableOp = isDebugValueList() ? 0 : 2; 805 return getOperand(VariableOp); 806 } 807 808 const DILocalVariable *MachineInstr::getDebugVariable() const { 809 return cast<DILocalVariable>(getDebugVariableOp().getMetadata()); 810 } 811 812 const MachineOperand &MachineInstr::getDebugExpressionOp() const { 813 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*"); 814 unsigned ExpressionOp = isDebugValueList() ? 1 : 3; 815 return getOperand(ExpressionOp); 816 } 817 818 MachineOperand &MachineInstr::getDebugExpressionOp() { 819 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE*"); 820 unsigned ExpressionOp = isDebugValueList() ? 1 : 3; 821 return getOperand(ExpressionOp); 822 } 823 824 const DIExpression *MachineInstr::getDebugExpression() const { 825 return cast<DIExpression>(getDebugExpressionOp().getMetadata()); 826 } 827 828 bool MachineInstr::isDebugEntryValue() const { 829 return isDebugValue() && getDebugExpression()->isEntryValue(); 830 } 831 832 const TargetRegisterClass* 833 MachineInstr::getRegClassConstraint(unsigned OpIdx, 834 const TargetInstrInfo *TII, 835 const TargetRegisterInfo *TRI) const { 836 assert(getParent() && "Can't have an MBB reference here!"); 837 assert(getMF() && "Can't have an MF reference here!"); 838 const MachineFunction &MF = *getMF(); 839 840 // Most opcodes have fixed constraints in their MCInstrDesc. 841 if (!isInlineAsm()) 842 return TII->getRegClass(getDesc(), OpIdx, TRI, MF); 843 844 if (!getOperand(OpIdx).isReg()) 845 return nullptr; 846 847 // For tied uses on inline asm, get the constraint from the def. 848 unsigned DefIdx; 849 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx)) 850 OpIdx = DefIdx; 851 852 // Inline asm stores register class constraints in the flag word. 853 int FlagIdx = findInlineAsmFlagIdx(OpIdx); 854 if (FlagIdx < 0) 855 return nullptr; 856 857 unsigned Flag = getOperand(FlagIdx).getImm(); 858 unsigned RCID; 859 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse || 860 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef || 861 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) && 862 InlineAsm::hasRegClassConstraint(Flag, RCID)) 863 return TRI->getRegClass(RCID); 864 865 // Assume that all registers in a memory operand are pointers. 866 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem) 867 return TRI->getPointerRegClass(MF); 868 869 return nullptr; 870 } 871 872 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg( 873 Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, 874 const TargetRegisterInfo *TRI, bool ExploreBundle) const { 875 // Check every operands inside the bundle if we have 876 // been asked to. 877 if (ExploreBundle) 878 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC; 879 ++OpndIt) 880 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl( 881 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI); 882 else 883 // Otherwise, just check the current operands. 884 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i) 885 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI); 886 return CurRC; 887 } 888 889 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl( 890 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC, 891 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 892 assert(CurRC && "Invalid initial register class"); 893 // Check if Reg is constrained by some of its use/def from MI. 894 const MachineOperand &MO = getOperand(OpIdx); 895 if (!MO.isReg() || MO.getReg() != Reg) 896 return CurRC; 897 // If yes, accumulate the constraints through the operand. 898 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI); 899 } 900 901 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect( 902 unsigned OpIdx, const TargetRegisterClass *CurRC, 903 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 904 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI); 905 const MachineOperand &MO = getOperand(OpIdx); 906 assert(MO.isReg() && 907 "Cannot get register constraints for non-register operand"); 908 assert(CurRC && "Invalid initial register class"); 909 if (unsigned SubIdx = MO.getSubReg()) { 910 if (OpRC) 911 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx); 912 else 913 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx); 914 } else if (OpRC) 915 CurRC = TRI->getCommonSubClass(CurRC, OpRC); 916 return CurRC; 917 } 918 919 /// Return the number of instructions inside the MI bundle, not counting the 920 /// header instruction. 921 unsigned MachineInstr::getBundleSize() const { 922 MachineBasicBlock::const_instr_iterator I = getIterator(); 923 unsigned Size = 0; 924 while (I->isBundledWithSucc()) { 925 ++Size; 926 ++I; 927 } 928 return Size; 929 } 930 931 /// Returns true if the MachineInstr has an implicit-use operand of exactly 932 /// the given register (not considering sub/super-registers). 933 bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const { 934 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 935 const MachineOperand &MO = getOperand(i); 936 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg) 937 return true; 938 } 939 return false; 940 } 941 942 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of 943 /// the specific register or -1 if it is not found. It further tightens 944 /// the search criteria to a use that kills the register if isKill is true. 945 int MachineInstr::findRegisterUseOperandIdx( 946 Register Reg, bool isKill, const TargetRegisterInfo *TRI) const { 947 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 948 const MachineOperand &MO = getOperand(i); 949 if (!MO.isReg() || !MO.isUse()) 950 continue; 951 Register MOReg = MO.getReg(); 952 if (!MOReg) 953 continue; 954 if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg))) 955 if (!isKill || MO.isKill()) 956 return i; 957 } 958 return -1; 959 } 960 961 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes) 962 /// indicating if this instruction reads or writes Reg. This also considers 963 /// partial defines. 964 std::pair<bool,bool> 965 MachineInstr::readsWritesVirtualRegister(Register Reg, 966 SmallVectorImpl<unsigned> *Ops) const { 967 bool PartDef = false; // Partial redefine. 968 bool FullDef = false; // Full define. 969 bool Use = false; 970 971 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 972 const MachineOperand &MO = getOperand(i); 973 if (!MO.isReg() || MO.getReg() != Reg) 974 continue; 975 if (Ops) 976 Ops->push_back(i); 977 if (MO.isUse()) 978 Use |= !MO.isUndef(); 979 else if (MO.getSubReg() && !MO.isUndef()) 980 // A partial def undef doesn't count as reading the register. 981 PartDef = true; 982 else 983 FullDef = true; 984 } 985 // A partial redefine uses Reg unless there is also a full define. 986 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef); 987 } 988 989 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of 990 /// the specified register or -1 if it is not found. If isDead is true, defs 991 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it 992 /// also checks if there is a def of a super-register. 993 int 994 MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap, 995 const TargetRegisterInfo *TRI) const { 996 bool isPhys = Register::isPhysicalRegister(Reg); 997 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 998 const MachineOperand &MO = getOperand(i); 999 // Accept regmask operands when Overlap is set. 1000 // Ignore them when looking for a specific def operand (Overlap == false). 1001 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg)) 1002 return i; 1003 if (!MO.isReg() || !MO.isDef()) 1004 continue; 1005 Register MOReg = MO.getReg(); 1006 bool Found = (MOReg == Reg); 1007 if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) { 1008 if (Overlap) 1009 Found = TRI->regsOverlap(MOReg, Reg); 1010 else 1011 Found = TRI->isSubRegister(MOReg, Reg); 1012 } 1013 if (Found && (!isDead || MO.isDead())) 1014 return i; 1015 } 1016 return -1; 1017 } 1018 1019 /// findFirstPredOperandIdx() - Find the index of the first operand in the 1020 /// operand list that is used to represent the predicate. It returns -1 if 1021 /// none is found. 1022 int MachineInstr::findFirstPredOperandIdx() const { 1023 // Don't call MCID.findFirstPredOperandIdx() because this variant 1024 // is sometimes called on an instruction that's not yet complete, and 1025 // so the number of operands is less than the MCID indicates. In 1026 // particular, the PTX target does this. 1027 const MCInstrDesc &MCID = getDesc(); 1028 if (MCID.isPredicable()) { 1029 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1030 if (MCID.OpInfo[i].isPredicate()) 1031 return i; 1032 } 1033 1034 return -1; 1035 } 1036 1037 // MachineOperand::TiedTo is 4 bits wide. 1038 const unsigned TiedMax = 15; 1039 1040 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other. 1041 /// 1042 /// Use and def operands can be tied together, indicated by a non-zero TiedTo 1043 /// field. TiedTo can have these values: 1044 /// 1045 /// 0: Operand is not tied to anything. 1046 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1). 1047 /// TiedMax: Tied to an operand >= TiedMax-1. 1048 /// 1049 /// The tied def must be one of the first TiedMax operands on a normal 1050 /// instruction. INLINEASM instructions allow more tied defs. 1051 /// 1052 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) { 1053 MachineOperand &DefMO = getOperand(DefIdx); 1054 MachineOperand &UseMO = getOperand(UseIdx); 1055 assert(DefMO.isDef() && "DefIdx must be a def operand"); 1056 assert(UseMO.isUse() && "UseIdx must be a use operand"); 1057 assert(!DefMO.isTied() && "Def is already tied to another use"); 1058 assert(!UseMO.isTied() && "Use is already tied to another def"); 1059 1060 if (DefIdx < TiedMax) 1061 UseMO.TiedTo = DefIdx + 1; 1062 else { 1063 // Inline asm can use the group descriptors to find tied operands, 1064 // statepoint tied operands are trivial to match (1-1 reg def with reg use), 1065 // but on normal instruction, the tied def must be within the first TiedMax 1066 // operands. 1067 assert((isInlineAsm() || getOpcode() == TargetOpcode::STATEPOINT) && 1068 "DefIdx out of range"); 1069 UseMO.TiedTo = TiedMax; 1070 } 1071 1072 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx(). 1073 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax); 1074 } 1075 1076 /// Given the index of a tied register operand, find the operand it is tied to. 1077 /// Defs are tied to uses and vice versa. Returns the index of the tied operand 1078 /// which must exist. 1079 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const { 1080 const MachineOperand &MO = getOperand(OpIdx); 1081 assert(MO.isTied() && "Operand isn't tied"); 1082 1083 // Normally TiedTo is in range. 1084 if (MO.TiedTo < TiedMax) 1085 return MO.TiedTo - 1; 1086 1087 // Uses on normal instructions can be out of range. 1088 if (!isInlineAsm() && getOpcode() != TargetOpcode::STATEPOINT) { 1089 // Normal tied defs must be in the 0..TiedMax-1 range. 1090 if (MO.isUse()) 1091 return TiedMax - 1; 1092 // MO is a def. Search for the tied use. 1093 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) { 1094 const MachineOperand &UseMO = getOperand(i); 1095 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1) 1096 return i; 1097 } 1098 llvm_unreachable("Can't find tied use"); 1099 } 1100 1101 if (getOpcode() == TargetOpcode::STATEPOINT) { 1102 // In STATEPOINT defs correspond 1-1 to GC pointer operands passed 1103 // on registers. 1104 StatepointOpers SO(this); 1105 unsigned CurUseIdx = SO.getFirstGCPtrIdx(); 1106 assert(CurUseIdx != -1U && "only gc pointer statepoint operands can be tied"); 1107 unsigned NumDefs = getNumDefs(); 1108 for (unsigned CurDefIdx = 0; CurDefIdx < NumDefs; ++CurDefIdx) { 1109 while (!getOperand(CurUseIdx).isReg()) 1110 CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx); 1111 if (OpIdx == CurDefIdx) 1112 return CurUseIdx; 1113 if (OpIdx == CurUseIdx) 1114 return CurDefIdx; 1115 CurUseIdx = StackMaps::getNextMetaArgIdx(this, CurUseIdx); 1116 } 1117 llvm_unreachable("Can't find tied use"); 1118 } 1119 1120 // Now deal with inline asm by parsing the operand group descriptor flags. 1121 // Find the beginning of each operand group. 1122 SmallVector<unsigned, 8> GroupIdx; 1123 unsigned OpIdxGroup = ~0u; 1124 unsigned NumOps; 1125 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 1126 i += NumOps) { 1127 const MachineOperand &FlagMO = getOperand(i); 1128 assert(FlagMO.isImm() && "Invalid tied operand on inline asm"); 1129 unsigned CurGroup = GroupIdx.size(); 1130 GroupIdx.push_back(i); 1131 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 1132 // OpIdx belongs to this operand group. 1133 if (OpIdx > i && OpIdx < i + NumOps) 1134 OpIdxGroup = CurGroup; 1135 unsigned TiedGroup; 1136 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup)) 1137 continue; 1138 // Operands in this group are tied to operands in TiedGroup which must be 1139 // earlier. Find the number of operands between the two groups. 1140 unsigned Delta = i - GroupIdx[TiedGroup]; 1141 1142 // OpIdx is a use tied to TiedGroup. 1143 if (OpIdxGroup == CurGroup) 1144 return OpIdx - Delta; 1145 1146 // OpIdx is a def tied to this use group. 1147 if (OpIdxGroup == TiedGroup) 1148 return OpIdx + Delta; 1149 } 1150 llvm_unreachable("Invalid tied operand on inline asm"); 1151 } 1152 1153 /// clearKillInfo - Clears kill flags on all operands. 1154 /// 1155 void MachineInstr::clearKillInfo() { 1156 for (MachineOperand &MO : operands()) { 1157 if (MO.isReg() && MO.isUse()) 1158 MO.setIsKill(false); 1159 } 1160 } 1161 1162 void MachineInstr::substituteRegister(Register FromReg, Register ToReg, 1163 unsigned SubIdx, 1164 const TargetRegisterInfo &RegInfo) { 1165 if (Register::isPhysicalRegister(ToReg)) { 1166 if (SubIdx) 1167 ToReg = RegInfo.getSubReg(ToReg, SubIdx); 1168 for (MachineOperand &MO : operands()) { 1169 if (!MO.isReg() || MO.getReg() != FromReg) 1170 continue; 1171 MO.substPhysReg(ToReg, RegInfo); 1172 } 1173 } else { 1174 for (MachineOperand &MO : operands()) { 1175 if (!MO.isReg() || MO.getReg() != FromReg) 1176 continue; 1177 MO.substVirtReg(ToReg, SubIdx, RegInfo); 1178 } 1179 } 1180 } 1181 1182 /// isSafeToMove - Return true if it is safe to move this instruction. If 1183 /// SawStore is set to true, it means that there is a store (or call) between 1184 /// the instruction's location and its intended destination. 1185 bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const { 1186 // Ignore stuff that we obviously can't move. 1187 // 1188 // Treat volatile loads as stores. This is not strictly necessary for 1189 // volatiles, but it is required for atomic loads. It is not allowed to move 1190 // a load across an atomic load with Ordering > Monotonic. 1191 if (mayStore() || isCall() || isPHI() || 1192 (mayLoad() && hasOrderedMemoryRef())) { 1193 SawStore = true; 1194 return false; 1195 } 1196 1197 if (isPosition() || isDebugInstr() || isTerminator() || 1198 mayRaiseFPException() || hasUnmodeledSideEffects()) 1199 return false; 1200 1201 // See if this instruction does a load. If so, we have to guarantee that the 1202 // loaded value doesn't change between the load and the its intended 1203 // destination. The check for isInvariantLoad gives the target the chance to 1204 // classify the load as always returning a constant, e.g. a constant pool 1205 // load. 1206 if (mayLoad() && !isDereferenceableInvariantLoad()) 1207 // Otherwise, this is a real load. If there is a store between the load and 1208 // end of block, we can't move it. 1209 return !SawStore; 1210 1211 return true; 1212 } 1213 1214 static bool MemOperandsHaveAlias(const MachineFrameInfo &MFI, AAResults *AA, 1215 bool UseTBAA, const MachineMemOperand *MMOa, 1216 const MachineMemOperand *MMOb) { 1217 // The following interface to AA is fashioned after DAGCombiner::isAlias and 1218 // operates with MachineMemOperand offset with some important assumptions: 1219 // - LLVM fundamentally assumes flat address spaces. 1220 // - MachineOperand offset can *only* result from legalization and cannot 1221 // affect queries other than the trivial case of overlap checking. 1222 // - These offsets never wrap and never step outside of allocated objects. 1223 // - There should never be any negative offsets here. 1224 // 1225 // FIXME: Modify API to hide this math from "user" 1226 // Even before we go to AA we can reason locally about some memory objects. It 1227 // can save compile time, and possibly catch some corner cases not currently 1228 // covered. 1229 1230 int64_t OffsetA = MMOa->getOffset(); 1231 int64_t OffsetB = MMOb->getOffset(); 1232 int64_t MinOffset = std::min(OffsetA, OffsetB); 1233 1234 uint64_t WidthA = MMOa->getSize(); 1235 uint64_t WidthB = MMOb->getSize(); 1236 bool KnownWidthA = WidthA != MemoryLocation::UnknownSize; 1237 bool KnownWidthB = WidthB != MemoryLocation::UnknownSize; 1238 1239 const Value *ValA = MMOa->getValue(); 1240 const Value *ValB = MMOb->getValue(); 1241 bool SameVal = (ValA && ValB && (ValA == ValB)); 1242 if (!SameVal) { 1243 const PseudoSourceValue *PSVa = MMOa->getPseudoValue(); 1244 const PseudoSourceValue *PSVb = MMOb->getPseudoValue(); 1245 if (PSVa && ValB && !PSVa->mayAlias(&MFI)) 1246 return false; 1247 if (PSVb && ValA && !PSVb->mayAlias(&MFI)) 1248 return false; 1249 if (PSVa && PSVb && (PSVa == PSVb)) 1250 SameVal = true; 1251 } 1252 1253 if (SameVal) { 1254 if (!KnownWidthA || !KnownWidthB) 1255 return true; 1256 int64_t MaxOffset = std::max(OffsetA, OffsetB); 1257 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB; 1258 return (MinOffset + LowWidth > MaxOffset); 1259 } 1260 1261 if (!AA) 1262 return true; 1263 1264 if (!ValA || !ValB) 1265 return true; 1266 1267 assert((OffsetA >= 0) && "Negative MachineMemOperand offset"); 1268 assert((OffsetB >= 0) && "Negative MachineMemOperand offset"); 1269 1270 int64_t OverlapA = 1271 KnownWidthA ? WidthA + OffsetA - MinOffset : MemoryLocation::UnknownSize; 1272 int64_t OverlapB = 1273 KnownWidthB ? WidthB + OffsetB - MinOffset : MemoryLocation::UnknownSize; 1274 1275 return !AA->isNoAlias( 1276 MemoryLocation(ValA, OverlapA, UseTBAA ? MMOa->getAAInfo() : AAMDNodes()), 1277 MemoryLocation(ValB, OverlapB, 1278 UseTBAA ? MMOb->getAAInfo() : AAMDNodes())); 1279 } 1280 1281 bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other, 1282 bool UseTBAA) const { 1283 const MachineFunction *MF = getMF(); 1284 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1285 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1286 1287 // Exclude call instruction which may alter the memory but can not be handled 1288 // by this function. 1289 if (isCall() || Other.isCall()) 1290 return true; 1291 1292 // If neither instruction stores to memory, they can't alias in any 1293 // meaningful way, even if they read from the same address. 1294 if (!mayStore() && !Other.mayStore()) 1295 return false; 1296 1297 // Both instructions must be memory operations to be able to alias. 1298 if (!mayLoadOrStore() || !Other.mayLoadOrStore()) 1299 return false; 1300 1301 // Let the target decide if memory accesses cannot possibly overlap. 1302 if (TII->areMemAccessesTriviallyDisjoint(*this, Other)) 1303 return false; 1304 1305 // Memory operations without memory operands may access anything. Be 1306 // conservative and assume `MayAlias`. 1307 if (memoperands_empty() || Other.memoperands_empty()) 1308 return true; 1309 1310 // Skip if there are too many memory operands. 1311 auto NumChecks = getNumMemOperands() * Other.getNumMemOperands(); 1312 if (NumChecks > TII->getMemOperandAACheckLimit()) 1313 return true; 1314 1315 // Check each pair of memory operands from both instructions, which can't 1316 // alias only if all pairs won't alias. 1317 for (auto *MMOa : memoperands()) 1318 for (auto *MMOb : Other.memoperands()) 1319 if (MemOperandsHaveAlias(MFI, AA, UseTBAA, MMOa, MMOb)) 1320 return true; 1321 1322 return false; 1323 } 1324 1325 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered 1326 /// or volatile memory reference, or if the information describing the memory 1327 /// reference is not available. Return false if it is known to have no ordered 1328 /// memory references. 1329 bool MachineInstr::hasOrderedMemoryRef() const { 1330 // An instruction known never to access memory won't have a volatile access. 1331 if (!mayStore() && 1332 !mayLoad() && 1333 !isCall() && 1334 !hasUnmodeledSideEffects()) 1335 return false; 1336 1337 // Otherwise, if the instruction has no memory reference information, 1338 // conservatively assume it wasn't preserved. 1339 if (memoperands_empty()) 1340 return true; 1341 1342 // Check if any of our memory operands are ordered. 1343 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) { 1344 return !MMO->isUnordered(); 1345 }); 1346 } 1347 1348 /// isDereferenceableInvariantLoad - Return true if this instruction will never 1349 /// trap and is loading from a location whose value is invariant across a run of 1350 /// this function. 1351 bool MachineInstr::isDereferenceableInvariantLoad() const { 1352 // If the instruction doesn't load at all, it isn't an invariant load. 1353 if (!mayLoad()) 1354 return false; 1355 1356 // If the instruction has lost its memoperands, conservatively assume that 1357 // it may not be an invariant load. 1358 if (memoperands_empty()) 1359 return false; 1360 1361 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo(); 1362 1363 for (MachineMemOperand *MMO : memoperands()) { 1364 if (!MMO->isUnordered()) 1365 // If the memory operand has ordering side effects, we can't move the 1366 // instruction. Such an instruction is technically an invariant load, 1367 // but the caller code would need updated to expect that. 1368 return false; 1369 if (MMO->isStore()) return false; 1370 if (MMO->isInvariant() && MMO->isDereferenceable()) 1371 continue; 1372 1373 // A load from a constant PseudoSourceValue is invariant. 1374 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) { 1375 if (PSV->isConstant(&MFI)) 1376 continue; 1377 } 1378 1379 // Otherwise assume conservatively. 1380 return false; 1381 } 1382 1383 // Everything checks out. 1384 return true; 1385 } 1386 1387 /// isConstantValuePHI - If the specified instruction is a PHI that always 1388 /// merges together the same virtual register, return the register, otherwise 1389 /// return 0. 1390 unsigned MachineInstr::isConstantValuePHI() const { 1391 if (!isPHI()) 1392 return 0; 1393 assert(getNumOperands() >= 3 && 1394 "It's illegal to have a PHI without source operands"); 1395 1396 Register Reg = getOperand(1).getReg(); 1397 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2) 1398 if (getOperand(i).getReg() != Reg) 1399 return 0; 1400 return Reg; 1401 } 1402 1403 bool MachineInstr::hasUnmodeledSideEffects() const { 1404 if (hasProperty(MCID::UnmodeledSideEffects)) 1405 return true; 1406 if (isInlineAsm()) { 1407 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1408 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1409 return true; 1410 } 1411 1412 return false; 1413 } 1414 1415 bool MachineInstr::isLoadFoldBarrier() const { 1416 return mayStore() || isCall() || 1417 (hasUnmodeledSideEffects() && !isPseudoProbe()); 1418 } 1419 1420 /// allDefsAreDead - Return true if all the defs of this instruction are dead. 1421 /// 1422 bool MachineInstr::allDefsAreDead() const { 1423 for (const MachineOperand &MO : operands()) { 1424 if (!MO.isReg() || MO.isUse()) 1425 continue; 1426 if (!MO.isDead()) 1427 return false; 1428 } 1429 return true; 1430 } 1431 1432 /// copyImplicitOps - Copy implicit register operands from specified 1433 /// instruction to this instruction. 1434 void MachineInstr::copyImplicitOps(MachineFunction &MF, 1435 const MachineInstr &MI) { 1436 for (const MachineOperand &MO : 1437 llvm::drop_begin(MI.operands(), MI.getDesc().getNumOperands())) 1438 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask()) 1439 addOperand(MF, MO); 1440 } 1441 1442 bool MachineInstr::hasComplexRegisterTies() const { 1443 const MCInstrDesc &MCID = getDesc(); 1444 if (MCID.Opcode == TargetOpcode::STATEPOINT) 1445 return true; 1446 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 1447 const auto &Operand = getOperand(I); 1448 if (!Operand.isReg() || Operand.isDef()) 1449 // Ignore the defined registers as MCID marks only the uses as tied. 1450 continue; 1451 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 1452 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1; 1453 if (ExpectedTiedIdx != TiedIdx) 1454 return true; 1455 } 1456 return false; 1457 } 1458 1459 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1460 const MachineRegisterInfo &MRI) const { 1461 const MachineOperand &Op = getOperand(OpIdx); 1462 if (!Op.isReg()) 1463 return LLT{}; 1464 1465 if (isVariadic() || OpIdx >= getNumExplicitOperands()) 1466 return MRI.getType(Op.getReg()); 1467 1468 auto &OpInfo = getDesc().OpInfo[OpIdx]; 1469 if (!OpInfo.isGenericType()) 1470 return MRI.getType(Op.getReg()); 1471 1472 if (PrintedTypes[OpInfo.getGenericTypeIndex()]) 1473 return LLT{}; 1474 1475 LLT TypeToPrint = MRI.getType(Op.getReg()); 1476 // Don't mark the type index printed if it wasn't actually printed: maybe 1477 // another operand with the same type index has an actual type attached: 1478 if (TypeToPrint.isValid()) 1479 PrintedTypes.set(OpInfo.getGenericTypeIndex()); 1480 return TypeToPrint; 1481 } 1482 1483 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1484 LLVM_DUMP_METHOD void MachineInstr::dump() const { 1485 dbgs() << " "; 1486 print(dbgs()); 1487 } 1488 1489 LLVM_DUMP_METHOD void MachineInstr::dumprImpl( 1490 const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth, 1491 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const { 1492 if (Depth >= MaxDepth) 1493 return; 1494 if (!AlreadySeenInstrs.insert(this).second) 1495 return; 1496 // PadToColumn always inserts at least one space. 1497 // Don't mess up the alignment if we don't want any space. 1498 if (Depth) 1499 fdbgs().PadToColumn(Depth * 2); 1500 print(fdbgs()); 1501 for (const MachineOperand &MO : operands()) { 1502 if (!MO.isReg() || MO.isDef()) 1503 continue; 1504 Register Reg = MO.getReg(); 1505 if (Reg.isPhysical()) 1506 continue; 1507 const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg); 1508 if (NewMI == nullptr) 1509 continue; 1510 NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs); 1511 } 1512 } 1513 1514 LLVM_DUMP_METHOD void MachineInstr::dumpr(const MachineRegisterInfo &MRI, 1515 unsigned MaxDepth) const { 1516 SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs; 1517 dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs); 1518 } 1519 #endif 1520 1521 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers, 1522 bool SkipDebugLoc, bool AddNewLine, 1523 const TargetInstrInfo *TII) const { 1524 const Module *M = nullptr; 1525 const Function *F = nullptr; 1526 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1527 F = &MF->getFunction(); 1528 M = F->getParent(); 1529 if (!TII) 1530 TII = MF->getSubtarget().getInstrInfo(); 1531 } 1532 1533 ModuleSlotTracker MST(M); 1534 if (F) 1535 MST.incorporateFunction(*F); 1536 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII); 1537 } 1538 1539 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST, 1540 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc, 1541 bool AddNewLine, const TargetInstrInfo *TII) const { 1542 // We can be a bit tidier if we know the MachineFunction. 1543 const TargetRegisterInfo *TRI = nullptr; 1544 const MachineRegisterInfo *MRI = nullptr; 1545 const TargetIntrinsicInfo *IntrinsicInfo = nullptr; 1546 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII); 1547 1548 if (isCFIInstruction()) 1549 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 1550 1551 SmallBitVector PrintedTypes(8); 1552 bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies(); 1553 auto getTiedOperandIdx = [&](unsigned OpIdx) { 1554 if (!ShouldPrintRegisterTies) 1555 return 0U; 1556 const MachineOperand &MO = getOperand(OpIdx); 1557 if (MO.isReg() && MO.isTied() && !MO.isDef()) 1558 return findTiedOperandIdx(OpIdx); 1559 return 0U; 1560 }; 1561 unsigned StartOp = 0; 1562 unsigned e = getNumOperands(); 1563 1564 // Print explicitly defined operands on the left of an assignment syntax. 1565 while (StartOp < e) { 1566 const MachineOperand &MO = getOperand(StartOp); 1567 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 1568 break; 1569 1570 if (StartOp != 0) 1571 OS << ", "; 1572 1573 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{}; 1574 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp); 1575 MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone, 1576 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1577 ++StartOp; 1578 } 1579 1580 if (StartOp != 0) 1581 OS << " = "; 1582 1583 if (getFlag(MachineInstr::FrameSetup)) 1584 OS << "frame-setup "; 1585 if (getFlag(MachineInstr::FrameDestroy)) 1586 OS << "frame-destroy "; 1587 if (getFlag(MachineInstr::FmNoNans)) 1588 OS << "nnan "; 1589 if (getFlag(MachineInstr::FmNoInfs)) 1590 OS << "ninf "; 1591 if (getFlag(MachineInstr::FmNsz)) 1592 OS << "nsz "; 1593 if (getFlag(MachineInstr::FmArcp)) 1594 OS << "arcp "; 1595 if (getFlag(MachineInstr::FmContract)) 1596 OS << "contract "; 1597 if (getFlag(MachineInstr::FmAfn)) 1598 OS << "afn "; 1599 if (getFlag(MachineInstr::FmReassoc)) 1600 OS << "reassoc "; 1601 if (getFlag(MachineInstr::NoUWrap)) 1602 OS << "nuw "; 1603 if (getFlag(MachineInstr::NoSWrap)) 1604 OS << "nsw "; 1605 if (getFlag(MachineInstr::IsExact)) 1606 OS << "exact "; 1607 if (getFlag(MachineInstr::NoFPExcept)) 1608 OS << "nofpexcept "; 1609 if (getFlag(MachineInstr::NoMerge)) 1610 OS << "nomerge "; 1611 1612 // Print the opcode name. 1613 if (TII) 1614 OS << TII->getName(getOpcode()); 1615 else 1616 OS << "UNKNOWN"; 1617 1618 if (SkipOpers) 1619 return; 1620 1621 // Print the rest of the operands. 1622 bool FirstOp = true; 1623 unsigned AsmDescOp = ~0u; 1624 unsigned AsmOpCount = 0; 1625 1626 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) { 1627 // Print asm string. 1628 OS << " "; 1629 const unsigned OpIdx = InlineAsm::MIOp_AsmString; 1630 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{}; 1631 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx); 1632 getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone, 1633 ShouldPrintRegisterTies, TiedOperandIdx, TRI, 1634 IntrinsicInfo); 1635 1636 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack 1637 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1638 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1639 OS << " [sideeffect]"; 1640 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1641 OS << " [mayload]"; 1642 if (ExtraInfo & InlineAsm::Extra_MayStore) 1643 OS << " [maystore]"; 1644 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 1645 OS << " [isconvergent]"; 1646 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1647 OS << " [alignstack]"; 1648 if (getInlineAsmDialect() == InlineAsm::AD_ATT) 1649 OS << " [attdialect]"; 1650 if (getInlineAsmDialect() == InlineAsm::AD_Intel) 1651 OS << " [inteldialect]"; 1652 1653 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand; 1654 FirstOp = false; 1655 } 1656 1657 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { 1658 const MachineOperand &MO = getOperand(i); 1659 1660 if (FirstOp) FirstOp = false; else OS << ","; 1661 OS << " "; 1662 1663 if (isDebugValue() && MO.isMetadata()) { 1664 // Pretty print DBG_VALUE* instructions. 1665 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata()); 1666 if (DIV && !DIV->getName().empty()) 1667 OS << "!\"" << DIV->getName() << '\"'; 1668 else { 1669 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1670 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1671 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1672 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1673 } 1674 } else if (isDebugLabel() && MO.isMetadata()) { 1675 // Pretty print DBG_LABEL instructions. 1676 auto *DIL = dyn_cast<DILabel>(MO.getMetadata()); 1677 if (DIL && !DIL->getName().empty()) 1678 OS << "\"" << DIL->getName() << '\"'; 1679 else { 1680 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1681 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1682 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1683 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1684 } 1685 } else if (i == AsmDescOp && MO.isImm()) { 1686 // Pretty print the inline asm operand descriptor. 1687 OS << '$' << AsmOpCount++; 1688 unsigned Flag = MO.getImm(); 1689 OS << ":["; 1690 OS << InlineAsm::getKindName(InlineAsm::getKind(Flag)); 1691 1692 unsigned RCID = 0; 1693 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) && 1694 InlineAsm::hasRegClassConstraint(Flag, RCID)) { 1695 if (TRI) { 1696 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID)); 1697 } else 1698 OS << ":RC" << RCID; 1699 } 1700 1701 if (InlineAsm::isMemKind(Flag)) { 1702 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag); 1703 OS << ":" << InlineAsm::getMemConstraintName(MCID); 1704 } 1705 1706 unsigned TiedTo = 0; 1707 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo)) 1708 OS << " tiedto:$" << TiedTo; 1709 1710 OS << ']'; 1711 1712 // Compute the index of the next operand descriptor. 1713 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag); 1714 } else { 1715 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1716 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1717 if (MO.isImm() && isOperandSubregIdx(i)) 1718 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI); 1719 else 1720 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1721 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1722 } 1723 } 1724 1725 // Print any optional symbols attached to this instruction as-if they were 1726 // operands. 1727 if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) { 1728 if (!FirstOp) { 1729 FirstOp = false; 1730 OS << ','; 1731 } 1732 OS << " pre-instr-symbol "; 1733 MachineOperand::printSymbol(OS, *PreInstrSymbol); 1734 } 1735 if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) { 1736 if (!FirstOp) { 1737 FirstOp = false; 1738 OS << ','; 1739 } 1740 OS << " post-instr-symbol "; 1741 MachineOperand::printSymbol(OS, *PostInstrSymbol); 1742 } 1743 if (MDNode *HeapAllocMarker = getHeapAllocMarker()) { 1744 if (!FirstOp) { 1745 FirstOp = false; 1746 OS << ','; 1747 } 1748 OS << " heap-alloc-marker "; 1749 HeapAllocMarker->printAsOperand(OS, MST); 1750 } 1751 1752 if (DebugInstrNum) { 1753 if (!FirstOp) 1754 OS << ","; 1755 OS << " debug-instr-number " << DebugInstrNum; 1756 } 1757 1758 if (!SkipDebugLoc) { 1759 if (const DebugLoc &DL = getDebugLoc()) { 1760 if (!FirstOp) 1761 OS << ','; 1762 OS << " debug-location "; 1763 DL->printAsOperand(OS, MST); 1764 } 1765 } 1766 1767 if (!memoperands_empty()) { 1768 SmallVector<StringRef, 0> SSNs; 1769 const LLVMContext *Context = nullptr; 1770 std::unique_ptr<LLVMContext> CtxPtr; 1771 const MachineFrameInfo *MFI = nullptr; 1772 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1773 MFI = &MF->getFrameInfo(); 1774 Context = &MF->getFunction().getContext(); 1775 } else { 1776 CtxPtr = std::make_unique<LLVMContext>(); 1777 Context = CtxPtr.get(); 1778 } 1779 1780 OS << " :: "; 1781 bool NeedComma = false; 1782 for (const MachineMemOperand *Op : memoperands()) { 1783 if (NeedComma) 1784 OS << ", "; 1785 Op->print(OS, MST, SSNs, *Context, MFI, TII); 1786 NeedComma = true; 1787 } 1788 } 1789 1790 if (SkipDebugLoc) 1791 return; 1792 1793 bool HaveSemi = false; 1794 1795 // Print debug location information. 1796 if (const DebugLoc &DL = getDebugLoc()) { 1797 if (!HaveSemi) { 1798 OS << ';'; 1799 HaveSemi = true; 1800 } 1801 OS << ' '; 1802 DL.print(OS); 1803 } 1804 1805 // Print extra comments for DEBUG_VALUE. 1806 if (isDebugValue() && getDebugVariableOp().isMetadata()) { 1807 if (!HaveSemi) { 1808 OS << ";"; 1809 HaveSemi = true; 1810 } 1811 auto *DV = getDebugVariable(); 1812 OS << " line no:" << DV->getLine(); 1813 if (isIndirectDebugValue()) 1814 OS << " indirect"; 1815 } 1816 // TODO: DBG_LABEL 1817 1818 if (AddNewLine) 1819 OS << '\n'; 1820 } 1821 1822 bool MachineInstr::addRegisterKilled(Register IncomingReg, 1823 const TargetRegisterInfo *RegInfo, 1824 bool AddIfNotFound) { 1825 bool isPhysReg = Register::isPhysicalRegister(IncomingReg); 1826 bool hasAliases = isPhysReg && 1827 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid(); 1828 bool Found = false; 1829 SmallVector<unsigned,4> DeadOps; 1830 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1831 MachineOperand &MO = getOperand(i); 1832 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) 1833 continue; 1834 1835 // DEBUG_VALUE nodes do not contribute to code generation and should 1836 // always be ignored. Failure to do so may result in trying to modify 1837 // KILL flags on DEBUG_VALUE nodes. 1838 if (MO.isDebug()) 1839 continue; 1840 1841 Register Reg = MO.getReg(); 1842 if (!Reg) 1843 continue; 1844 1845 if (Reg == IncomingReg) { 1846 if (!Found) { 1847 if (MO.isKill()) 1848 // The register is already marked kill. 1849 return true; 1850 if (isPhysReg && isRegTiedToDefOperand(i)) 1851 // Two-address uses of physregs must not be marked kill. 1852 return true; 1853 MO.setIsKill(); 1854 Found = true; 1855 } 1856 } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) { 1857 // A super-register kill already exists. 1858 if (RegInfo->isSuperRegister(IncomingReg, Reg)) 1859 return true; 1860 if (RegInfo->isSubRegister(IncomingReg, Reg)) 1861 DeadOps.push_back(i); 1862 } 1863 } 1864 1865 // Trim unneeded kill operands. 1866 while (!DeadOps.empty()) { 1867 unsigned OpIdx = DeadOps.back(); 1868 if (getOperand(OpIdx).isImplicit() && 1869 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1870 removeOperand(OpIdx); 1871 else 1872 getOperand(OpIdx).setIsKill(false); 1873 DeadOps.pop_back(); 1874 } 1875 1876 // If not found, this means an alias of one of the operands is killed. Add a 1877 // new implicit operand if required. 1878 if (!Found && AddIfNotFound) { 1879 addOperand(MachineOperand::CreateReg(IncomingReg, 1880 false /*IsDef*/, 1881 true /*IsImp*/, 1882 true /*IsKill*/)); 1883 return true; 1884 } 1885 return Found; 1886 } 1887 1888 void MachineInstr::clearRegisterKills(Register Reg, 1889 const TargetRegisterInfo *RegInfo) { 1890 if (!Register::isPhysicalRegister(Reg)) 1891 RegInfo = nullptr; 1892 for (MachineOperand &MO : operands()) { 1893 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 1894 continue; 1895 Register OpReg = MO.getReg(); 1896 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg) 1897 MO.setIsKill(false); 1898 } 1899 } 1900 1901 bool MachineInstr::addRegisterDead(Register Reg, 1902 const TargetRegisterInfo *RegInfo, 1903 bool AddIfNotFound) { 1904 bool isPhysReg = Register::isPhysicalRegister(Reg); 1905 bool hasAliases = isPhysReg && 1906 MCRegAliasIterator(Reg, RegInfo, false).isValid(); 1907 bool Found = false; 1908 SmallVector<unsigned,4> DeadOps; 1909 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1910 MachineOperand &MO = getOperand(i); 1911 if (!MO.isReg() || !MO.isDef()) 1912 continue; 1913 Register MOReg = MO.getReg(); 1914 if (!MOReg) 1915 continue; 1916 1917 if (MOReg == Reg) { 1918 MO.setIsDead(); 1919 Found = true; 1920 } else if (hasAliases && MO.isDead() && 1921 Register::isPhysicalRegister(MOReg)) { 1922 // There exists a super-register that's marked dead. 1923 if (RegInfo->isSuperRegister(Reg, MOReg)) 1924 return true; 1925 if (RegInfo->isSubRegister(Reg, MOReg)) 1926 DeadOps.push_back(i); 1927 } 1928 } 1929 1930 // Trim unneeded dead operands. 1931 while (!DeadOps.empty()) { 1932 unsigned OpIdx = DeadOps.back(); 1933 if (getOperand(OpIdx).isImplicit() && 1934 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1935 removeOperand(OpIdx); 1936 else 1937 getOperand(OpIdx).setIsDead(false); 1938 DeadOps.pop_back(); 1939 } 1940 1941 // If not found, this means an alias of one of the operands is dead. Add a 1942 // new implicit operand if required. 1943 if (Found || !AddIfNotFound) 1944 return Found; 1945 1946 addOperand(MachineOperand::CreateReg(Reg, 1947 true /*IsDef*/, 1948 true /*IsImp*/, 1949 false /*IsKill*/, 1950 true /*IsDead*/)); 1951 return true; 1952 } 1953 1954 void MachineInstr::clearRegisterDeads(Register Reg) { 1955 for (MachineOperand &MO : operands()) { 1956 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg) 1957 continue; 1958 MO.setIsDead(false); 1959 } 1960 } 1961 1962 void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) { 1963 for (MachineOperand &MO : operands()) { 1964 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0) 1965 continue; 1966 MO.setIsUndef(IsUndef); 1967 } 1968 } 1969 1970 void MachineInstr::addRegisterDefined(Register Reg, 1971 const TargetRegisterInfo *RegInfo) { 1972 if (Register::isPhysicalRegister(Reg)) { 1973 MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo); 1974 if (MO) 1975 return; 1976 } else { 1977 for (const MachineOperand &MO : operands()) { 1978 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() && 1979 MO.getSubReg() == 0) 1980 return; 1981 } 1982 } 1983 addOperand(MachineOperand::CreateReg(Reg, 1984 true /*IsDef*/, 1985 true /*IsImp*/)); 1986 } 1987 1988 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs, 1989 const TargetRegisterInfo &TRI) { 1990 bool HasRegMask = false; 1991 for (MachineOperand &MO : operands()) { 1992 if (MO.isRegMask()) { 1993 HasRegMask = true; 1994 continue; 1995 } 1996 if (!MO.isReg() || !MO.isDef()) continue; 1997 Register Reg = MO.getReg(); 1998 if (!Reg.isPhysical()) 1999 continue; 2000 // If there are no uses, including partial uses, the def is dead. 2001 if (llvm::none_of(UsedRegs, 2002 [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); })) 2003 MO.setIsDead(); 2004 } 2005 2006 // This is a call with a register mask operand. 2007 // Mask clobbers are always dead, so add defs for the non-dead defines. 2008 if (HasRegMask) 2009 for (const Register &UsedReg : UsedRegs) 2010 addRegisterDefined(UsedReg, &TRI); 2011 } 2012 2013 unsigned 2014 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) { 2015 // Build up a buffer of hash code components. 2016 SmallVector<size_t, 16> HashComponents; 2017 HashComponents.reserve(MI->getNumOperands() + 1); 2018 HashComponents.push_back(MI->getOpcode()); 2019 for (const MachineOperand &MO : MI->operands()) { 2020 if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg())) 2021 continue; // Skip virtual register defs. 2022 2023 HashComponents.push_back(hash_value(MO)); 2024 } 2025 return hash_combine_range(HashComponents.begin(), HashComponents.end()); 2026 } 2027 2028 void MachineInstr::emitError(StringRef Msg) const { 2029 // Find the source location cookie. 2030 uint64_t LocCookie = 0; 2031 const MDNode *LocMD = nullptr; 2032 for (unsigned i = getNumOperands(); i != 0; --i) { 2033 if (getOperand(i-1).isMetadata() && 2034 (LocMD = getOperand(i-1).getMetadata()) && 2035 LocMD->getNumOperands() != 0) { 2036 if (const ConstantInt *CI = 2037 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) { 2038 LocCookie = CI->getZExtValue(); 2039 break; 2040 } 2041 } 2042 } 2043 2044 if (const MachineBasicBlock *MBB = getParent()) 2045 if (const MachineFunction *MF = MBB->getParent()) 2046 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg); 2047 report_fatal_error(Msg); 2048 } 2049 2050 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2051 const MCInstrDesc &MCID, bool IsIndirect, 2052 Register Reg, const MDNode *Variable, 2053 const MDNode *Expr) { 2054 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2055 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2056 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2057 "Expected inlined-at fields to agree"); 2058 auto MIB = BuildMI(MF, DL, MCID).addReg(Reg); 2059 if (IsIndirect) 2060 MIB.addImm(0U); 2061 else 2062 MIB.addReg(0U); 2063 return MIB.addMetadata(Variable).addMetadata(Expr); 2064 } 2065 2066 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2067 const MCInstrDesc &MCID, bool IsIndirect, 2068 const MachineOperand &MO, 2069 const MDNode *Variable, const MDNode *Expr) { 2070 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2071 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2072 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2073 "Expected inlined-at fields to agree"); 2074 if (MO.isReg()) 2075 return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr); 2076 2077 auto MIB = BuildMI(MF, DL, MCID).add(MO); 2078 if (IsIndirect) 2079 MIB.addImm(0U); 2080 else 2081 MIB.addReg(0U); 2082 return MIB.addMetadata(Variable).addMetadata(Expr); 2083 } 2084 2085 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2086 const MCInstrDesc &MCID, bool IsIndirect, 2087 ArrayRef<MachineOperand> MOs, 2088 const MDNode *Variable, const MDNode *Expr) { 2089 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2090 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2091 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2092 "Expected inlined-at fields to agree"); 2093 if (MCID.Opcode == TargetOpcode::DBG_VALUE) 2094 return BuildMI(MF, DL, MCID, IsIndirect, MOs[0], Variable, Expr); 2095 2096 auto MIB = BuildMI(MF, DL, MCID); 2097 MIB.addMetadata(Variable).addMetadata(Expr); 2098 for (const MachineOperand &MO : MOs) 2099 if (MO.isReg()) 2100 MIB.addReg(MO.getReg()); 2101 else 2102 MIB.add(MO); 2103 return MIB; 2104 } 2105 2106 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2107 MachineBasicBlock::iterator I, 2108 const DebugLoc &DL, const MCInstrDesc &MCID, 2109 bool IsIndirect, Register Reg, 2110 const MDNode *Variable, const MDNode *Expr) { 2111 MachineFunction &MF = *BB.getParent(); 2112 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr); 2113 BB.insert(I, MI); 2114 return MachineInstrBuilder(MF, MI); 2115 } 2116 2117 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2118 MachineBasicBlock::iterator I, 2119 const DebugLoc &DL, const MCInstrDesc &MCID, 2120 bool IsIndirect, MachineOperand &MO, 2121 const MDNode *Variable, const MDNode *Expr) { 2122 MachineFunction &MF = *BB.getParent(); 2123 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr); 2124 BB.insert(I, MI); 2125 return MachineInstrBuilder(MF, *MI); 2126 } 2127 2128 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2129 MachineBasicBlock::iterator I, 2130 const DebugLoc &DL, const MCInstrDesc &MCID, 2131 bool IsIndirect, ArrayRef<MachineOperand> MOs, 2132 const MDNode *Variable, const MDNode *Expr) { 2133 MachineFunction &MF = *BB.getParent(); 2134 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MOs, Variable, Expr); 2135 BB.insert(I, MI); 2136 return MachineInstrBuilder(MF, *MI); 2137 } 2138 2139 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot. 2140 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE. 2141 static const DIExpression * 2142 computeExprForSpill(const MachineInstr &MI, 2143 SmallVectorImpl<const MachineOperand *> &SpilledOperands) { 2144 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && 2145 "Expected inlined-at fields to agree"); 2146 2147 const DIExpression *Expr = MI.getDebugExpression(); 2148 if (MI.isIndirectDebugValue()) { 2149 assert(MI.getDebugOffset().getImm() == 0 && 2150 "DBG_VALUE with nonzero offset"); 2151 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 2152 } else if (MI.isDebugValueList()) { 2153 // We will replace the spilled register with a frame index, so 2154 // immediately deref all references to the spilled register. 2155 std::array<uint64_t, 1> Ops{{dwarf::DW_OP_deref}}; 2156 for (const MachineOperand *Op : SpilledOperands) { 2157 unsigned OpIdx = MI.getDebugOperandIndex(Op); 2158 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx); 2159 } 2160 } 2161 return Expr; 2162 } 2163 static const DIExpression *computeExprForSpill(const MachineInstr &MI, 2164 Register SpillReg) { 2165 assert(MI.hasDebugOperandForReg(SpillReg) && "Spill Reg is not used in MI."); 2166 SmallVector<const MachineOperand *> SpillOperands; 2167 for (const MachineOperand &Op : MI.getDebugOperandsForReg(SpillReg)) 2168 SpillOperands.push_back(&Op); 2169 return computeExprForSpill(MI, SpillOperands); 2170 } 2171 2172 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB, 2173 MachineBasicBlock::iterator I, 2174 const MachineInstr &Orig, 2175 int FrameIndex, Register SpillReg) { 2176 const DIExpression *Expr = computeExprForSpill(Orig, SpillReg); 2177 MachineInstrBuilder NewMI = 2178 BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc()); 2179 // Non-Variadic Operands: Location, Offset, Variable, Expression 2180 // Variadic Operands: Variable, Expression, Locations... 2181 if (Orig.isNonListDebugValue()) 2182 NewMI.addFrameIndex(FrameIndex).addImm(0U); 2183 NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr); 2184 if (Orig.isDebugValueList()) { 2185 for (const MachineOperand &Op : Orig.debug_operands()) 2186 if (Op.isReg() && Op.getReg() == SpillReg) 2187 NewMI.addFrameIndex(FrameIndex); 2188 else 2189 NewMI.add(MachineOperand(Op)); 2190 } 2191 return NewMI; 2192 } 2193 MachineInstr *llvm::buildDbgValueForSpill( 2194 MachineBasicBlock &BB, MachineBasicBlock::iterator I, 2195 const MachineInstr &Orig, int FrameIndex, 2196 SmallVectorImpl<const MachineOperand *> &SpilledOperands) { 2197 const DIExpression *Expr = computeExprForSpill(Orig, SpilledOperands); 2198 MachineInstrBuilder NewMI = 2199 BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc()); 2200 // Non-Variadic Operands: Location, Offset, Variable, Expression 2201 // Variadic Operands: Variable, Expression, Locations... 2202 if (Orig.isNonListDebugValue()) 2203 NewMI.addFrameIndex(FrameIndex).addImm(0U); 2204 NewMI.addMetadata(Orig.getDebugVariable()).addMetadata(Expr); 2205 if (Orig.isDebugValueList()) { 2206 for (const MachineOperand &Op : Orig.debug_operands()) 2207 if (is_contained(SpilledOperands, &Op)) 2208 NewMI.addFrameIndex(FrameIndex); 2209 else 2210 NewMI.add(MachineOperand(Op)); 2211 } 2212 return NewMI; 2213 } 2214 2215 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, 2216 Register Reg) { 2217 const DIExpression *Expr = computeExprForSpill(Orig, Reg); 2218 if (Orig.isNonListDebugValue()) 2219 Orig.getDebugOffset().ChangeToImmediate(0U); 2220 for (MachineOperand &Op : Orig.getDebugOperandsForReg(Reg)) 2221 Op.ChangeToFrameIndex(FrameIndex); 2222 Orig.getDebugExpressionOp().setMetadata(Expr); 2223 } 2224 2225 void MachineInstr::collectDebugValues( 2226 SmallVectorImpl<MachineInstr *> &DbgValues) { 2227 MachineInstr &MI = *this; 2228 if (!MI.getOperand(0).isReg()) 2229 return; 2230 2231 MachineBasicBlock::iterator DI = MI; ++DI; 2232 for (MachineBasicBlock::iterator DE = MI.getParent()->end(); 2233 DI != DE; ++DI) { 2234 if (!DI->isDebugValue()) 2235 return; 2236 if (DI->hasDebugOperandForReg(MI.getOperand(0).getReg())) 2237 DbgValues.push_back(&*DI); 2238 } 2239 } 2240 2241 void MachineInstr::changeDebugValuesDefReg(Register Reg) { 2242 // Collect matching debug values. 2243 SmallVector<MachineInstr *, 2> DbgValues; 2244 2245 if (!getOperand(0).isReg()) 2246 return; 2247 2248 Register DefReg = getOperand(0).getReg(); 2249 auto *MRI = getRegInfo(); 2250 for (auto &MO : MRI->use_operands(DefReg)) { 2251 auto *DI = MO.getParent(); 2252 if (!DI->isDebugValue()) 2253 continue; 2254 if (DI->hasDebugOperandForReg(DefReg)) { 2255 DbgValues.push_back(DI); 2256 } 2257 } 2258 2259 // Propagate Reg to debug value instructions. 2260 for (auto *DBI : DbgValues) 2261 for (MachineOperand &Op : DBI->getDebugOperandsForReg(DefReg)) 2262 Op.setReg(Reg); 2263 } 2264 2265 using MMOList = SmallVector<const MachineMemOperand *, 2>; 2266 2267 static unsigned getSpillSlotSize(const MMOList &Accesses, 2268 const MachineFrameInfo &MFI) { 2269 unsigned Size = 0; 2270 for (const auto *A : Accesses) 2271 if (MFI.isSpillSlotObjectIndex( 2272 cast<FixedStackPseudoSourceValue>(A->getPseudoValue()) 2273 ->getFrameIndex())) 2274 Size += A->getSize(); 2275 return Size; 2276 } 2277 2278 Optional<unsigned> 2279 MachineInstr::getSpillSize(const TargetInstrInfo *TII) const { 2280 int FI; 2281 if (TII->isStoreToStackSlotPostFE(*this, FI)) { 2282 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2283 if (MFI.isSpillSlotObjectIndex(FI)) 2284 return (*memoperands_begin())->getSize(); 2285 } 2286 return None; 2287 } 2288 2289 Optional<unsigned> 2290 MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const { 2291 MMOList Accesses; 2292 if (TII->hasStoreToStackSlot(*this, Accesses)) 2293 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2294 return None; 2295 } 2296 2297 Optional<unsigned> 2298 MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const { 2299 int FI; 2300 if (TII->isLoadFromStackSlotPostFE(*this, FI)) { 2301 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2302 if (MFI.isSpillSlotObjectIndex(FI)) 2303 return (*memoperands_begin())->getSize(); 2304 } 2305 return None; 2306 } 2307 2308 Optional<unsigned> 2309 MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const { 2310 MMOList Accesses; 2311 if (TII->hasLoadFromStackSlot(*this, Accesses)) 2312 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2313 return None; 2314 } 2315 2316 unsigned MachineInstr::getDebugInstrNum() { 2317 if (DebugInstrNum == 0) 2318 DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum(); 2319 return DebugInstrNum; 2320 } 2321 2322 unsigned MachineInstr::getDebugInstrNum(MachineFunction &MF) { 2323 if (DebugInstrNum == 0) 2324 DebugInstrNum = MF.getNewDebugInstrNum(); 2325 return DebugInstrNum; 2326 } 2327