1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Methods common to all machine instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineInstr.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/FoldingSet.h" 18 #include "llvm/ADT/Hashing.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/Loads.h" 26 #include "llvm/Analysis/MemoryLocation.h" 27 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstrBuilder.h" 31 #include "llvm/CodeGen/MachineInstrBundle.h" 32 #include "llvm/CodeGen/MachineMemOperand.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineOperand.h" 35 #include "llvm/CodeGen/MachineRegisterInfo.h" 36 #include "llvm/CodeGen/PseudoSourceValue.h" 37 #include "llvm/CodeGen/TargetInstrInfo.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/IR/Constants.h" 41 #include "llvm/IR/DebugInfoMetadata.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/Function.h" 45 #include "llvm/IR/InlineAsm.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/Metadata.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/IR/ModuleSlotTracker.h" 52 #include "llvm/IR/Type.h" 53 #include "llvm/IR/Value.h" 54 #include "llvm/MC/MCInstrDesc.h" 55 #include "llvm/MC/MCRegisterInfo.h" 56 #include "llvm/MC/MCSymbol.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Compiler.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/LowLevelTypeImpl.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetIntrinsicInfo.h" 66 #include "llvm/Target/TargetMachine.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstddef> 70 #include <cstdint> 71 #include <cstring> 72 #include <iterator> 73 #include <utility> 74 75 using namespace llvm; 76 77 static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) { 78 if (const MachineBasicBlock *MBB = MI.getParent()) 79 if (const MachineFunction *MF = MBB->getParent()) 80 return MF; 81 return nullptr; 82 } 83 84 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from 85 // it. 86 static void tryToGetTargetInfo(const MachineInstr &MI, 87 const TargetRegisterInfo *&TRI, 88 const MachineRegisterInfo *&MRI, 89 const TargetIntrinsicInfo *&IntrinsicInfo, 90 const TargetInstrInfo *&TII) { 91 92 if (const MachineFunction *MF = getMFIfAvailable(MI)) { 93 TRI = MF->getSubtarget().getRegisterInfo(); 94 MRI = &MF->getRegInfo(); 95 IntrinsicInfo = MF->getTarget().getIntrinsicInfo(); 96 TII = MF->getSubtarget().getInstrInfo(); 97 } 98 } 99 100 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) { 101 if (MCID->ImplicitDefs) 102 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; 103 ++ImpDefs) 104 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true)); 105 if (MCID->ImplicitUses) 106 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses; 107 ++ImpUses) 108 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true)); 109 } 110 111 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the 112 /// implicit operands. It reserves space for the number of operands specified by 113 /// the MCInstrDesc. 114 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid, 115 DebugLoc dl, bool NoImp) 116 : MCID(&tid), debugLoc(std::move(dl)) { 117 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 118 119 // Reserve space for the expected number of operands. 120 if (unsigned NumOps = MCID->getNumOperands() + 121 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) { 122 CapOperands = OperandCapacity::get(NumOps); 123 Operands = MF.allocateOperandArray(CapOperands); 124 } 125 126 if (!NoImp) 127 addImplicitDefUseOperands(MF); 128 } 129 130 /// MachineInstr ctor - Copies MachineInstr arg exactly 131 /// 132 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI) 133 : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs), 134 debugLoc(MI.getDebugLoc()) { 135 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 136 137 CapOperands = OperandCapacity::get(MI.getNumOperands()); 138 Operands = MF.allocateOperandArray(CapOperands); 139 140 // Copy operands. 141 for (const MachineOperand &MO : MI.operands()) 142 addOperand(MF, MO); 143 144 // Copy all the sensible flags. 145 setFlags(MI.Flags); 146 } 147 148 /// getRegInfo - If this instruction is embedded into a MachineFunction, 149 /// return the MachineRegisterInfo object for the current function, otherwise 150 /// return null. 151 MachineRegisterInfo *MachineInstr::getRegInfo() { 152 if (MachineBasicBlock *MBB = getParent()) 153 return &MBB->getParent()->getRegInfo(); 154 return nullptr; 155 } 156 157 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in 158 /// this instruction from their respective use lists. This requires that the 159 /// operands already be on their use lists. 160 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) { 161 for (MachineOperand &MO : operands()) 162 if (MO.isReg()) 163 MRI.removeRegOperandFromUseList(&MO); 164 } 165 166 /// AddRegOperandsToUseLists - Add all of the register operands in 167 /// this instruction from their respective use lists. This requires that the 168 /// operands not be on their use lists yet. 169 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) { 170 for (MachineOperand &MO : operands()) 171 if (MO.isReg()) 172 MRI.addRegOperandToUseList(&MO); 173 } 174 175 void MachineInstr::addOperand(const MachineOperand &Op) { 176 MachineBasicBlock *MBB = getParent(); 177 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs"); 178 MachineFunction *MF = MBB->getParent(); 179 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs"); 180 addOperand(*MF, Op); 181 } 182 183 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping 184 /// ranges. If MRI is non-null also update use-def chains. 185 static void moveOperands(MachineOperand *Dst, MachineOperand *Src, 186 unsigned NumOps, MachineRegisterInfo *MRI) { 187 if (MRI) 188 return MRI->moveOperands(Dst, Src, NumOps); 189 190 // MachineOperand is a trivially copyable type so we can just use memmove. 191 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand)); 192 } 193 194 /// addOperand - Add the specified operand to the instruction. If it is an 195 /// implicit operand, it is added to the end of the operand list. If it is 196 /// an explicit operand it is added at the end of the explicit operand list 197 /// (before the first implicit operand). 198 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) { 199 assert(MCID && "Cannot add operands before providing an instr descriptor"); 200 201 // Check if we're adding one of our existing operands. 202 if (&Op >= Operands && &Op < Operands + NumOperands) { 203 // This is unusual: MI->addOperand(MI->getOperand(i)). 204 // If adding Op requires reallocating or moving existing operands around, 205 // the Op reference could go stale. Support it by copying Op. 206 MachineOperand CopyOp(Op); 207 return addOperand(MF, CopyOp); 208 } 209 210 // Find the insert location for the new operand. Implicit registers go at 211 // the end, everything else goes before the implicit regs. 212 // 213 // FIXME: Allow mixed explicit and implicit operands on inline asm. 214 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as 215 // implicit-defs, but they must not be moved around. See the FIXME in 216 // InstrEmitter.cpp. 217 unsigned OpNo = getNumOperands(); 218 bool isImpReg = Op.isReg() && Op.isImplicit(); 219 if (!isImpReg && !isInlineAsm()) { 220 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) { 221 --OpNo; 222 assert(!Operands[OpNo].isTied() && "Cannot move tied operands"); 223 } 224 } 225 226 #ifndef NDEBUG 227 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata; 228 // OpNo now points as the desired insertion point. Unless this is a variadic 229 // instruction, only implicit regs are allowed beyond MCID->getNumOperands(). 230 // RegMask operands go between the explicit and implicit operands. 231 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() || 232 OpNo < MCID->getNumOperands() || isMetaDataOp) && 233 "Trying to add an operand to a machine instr that is already done!"); 234 #endif 235 236 MachineRegisterInfo *MRI = getRegInfo(); 237 238 // Determine if the Operands array needs to be reallocated. 239 // Save the old capacity and operand array. 240 OperandCapacity OldCap = CapOperands; 241 MachineOperand *OldOperands = Operands; 242 if (!OldOperands || OldCap.getSize() == getNumOperands()) { 243 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1); 244 Operands = MF.allocateOperandArray(CapOperands); 245 // Move the operands before the insertion point. 246 if (OpNo) 247 moveOperands(Operands, OldOperands, OpNo, MRI); 248 } 249 250 // Move the operands following the insertion point. 251 if (OpNo != NumOperands) 252 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo, 253 MRI); 254 ++NumOperands; 255 256 // Deallocate the old operand array. 257 if (OldOperands != Operands && OldOperands) 258 MF.deallocateOperandArray(OldCap, OldOperands); 259 260 // Copy Op into place. It still needs to be inserted into the MRI use lists. 261 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op); 262 NewMO->ParentMI = this; 263 264 // When adding a register operand, tell MRI about it. 265 if (NewMO->isReg()) { 266 // Ensure isOnRegUseList() returns false, regardless of Op's status. 267 NewMO->Contents.Reg.Prev = nullptr; 268 // Ignore existing ties. This is not a property that can be copied. 269 NewMO->TiedTo = 0; 270 // Add the new operand to MRI, but only for instructions in an MBB. 271 if (MRI) 272 MRI->addRegOperandToUseList(NewMO); 273 // The MCID operand information isn't accurate until we start adding 274 // explicit operands. The implicit operands are added first, then the 275 // explicits are inserted before them. 276 if (!isImpReg) { 277 // Tie uses to defs as indicated in MCInstrDesc. 278 if (NewMO->isUse()) { 279 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO); 280 if (DefIdx != -1) 281 tieOperands(DefIdx, OpNo); 282 } 283 // If the register operand is flagged as early, mark the operand as such. 284 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1) 285 NewMO->setIsEarlyClobber(true); 286 } 287 } 288 } 289 290 /// RemoveOperand - Erase an operand from an instruction, leaving it with one 291 /// fewer operand than it started with. 292 /// 293 void MachineInstr::RemoveOperand(unsigned OpNo) { 294 assert(OpNo < getNumOperands() && "Invalid operand number"); 295 untieRegOperand(OpNo); 296 297 #ifndef NDEBUG 298 // Moving tied operands would break the ties. 299 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i) 300 if (Operands[i].isReg()) 301 assert(!Operands[i].isTied() && "Cannot move tied operands"); 302 #endif 303 304 MachineRegisterInfo *MRI = getRegInfo(); 305 if (MRI && Operands[OpNo].isReg()) 306 MRI->removeRegOperandFromUseList(Operands + OpNo); 307 308 // Don't call the MachineOperand destructor. A lot of this code depends on 309 // MachineOperand having a trivial destructor anyway, and adding a call here 310 // wouldn't make it 'destructor-correct'. 311 312 if (unsigned N = NumOperands - 1 - OpNo) 313 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI); 314 --NumOperands; 315 } 316 317 /// addMemOperand - Add a MachineMemOperand to the machine instruction. 318 /// This function should be used only occasionally. The setMemRefs function 319 /// is the primary method for setting up a MachineInstr's MemRefs list. 320 void MachineInstr::addMemOperand(MachineFunction &MF, 321 MachineMemOperand *MO) { 322 mmo_iterator OldMemRefs = MemRefs; 323 unsigned OldNumMemRefs = NumMemRefs; 324 325 unsigned NewNum = NumMemRefs + 1; 326 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum); 327 328 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs); 329 NewMemRefs[NewNum - 1] = MO; 330 setMemRefs(NewMemRefs, NewMemRefs + NewNum); 331 } 332 333 /// Check to see if the MMOs pointed to by the two MemRefs arrays are 334 /// identical. 335 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) { 336 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end(); 337 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end(); 338 if ((E1 - I1) != (E2 - I2)) 339 return false; 340 for (; I1 != E1; ++I1, ++I2) { 341 if (**I1 != **I2) 342 return false; 343 } 344 return true; 345 } 346 347 std::pair<MachineInstr::mmo_iterator, unsigned> 348 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) { 349 350 // If either of the incoming memrefs are empty, we must be conservative and 351 // treat this as if we've exhausted our space for memrefs and dropped them. 352 if (memoperands_empty() || Other.memoperands_empty()) 353 return std::make_pair(nullptr, 0); 354 355 // If both instructions have identical memrefs, we don't need to merge them. 356 // Since many instructions have a single memref, and we tend to merge things 357 // like pairs of loads from the same location, this catches a large number of 358 // cases in practice. 359 if (hasIdenticalMMOs(*this, Other)) 360 return std::make_pair(MemRefs, NumMemRefs); 361 362 // TODO: consider uniquing elements within the operand lists to reduce 363 // space usage and fall back to conservative information less often. 364 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs; 365 366 // If we don't have enough room to store this many memrefs, be conservative 367 // and drop them. Otherwise, we'd fail asserts when trying to add them to 368 // the new instruction. 369 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs)) 370 return std::make_pair(nullptr, 0); 371 372 MachineFunction *MF = getMF(); 373 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs); 374 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(), 375 MemBegin); 376 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(), 377 MemEnd); 378 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs && 379 "missing memrefs"); 380 381 return std::make_pair(MemBegin, CombinedNumMemRefs); 382 } 383 384 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const { 385 assert(!isBundledWithPred() && "Must be called on bundle header"); 386 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) { 387 if (MII->getDesc().getFlags() & Mask) { 388 if (Type == AnyInBundle) 389 return true; 390 } else { 391 if (Type == AllInBundle && !MII->isBundle()) 392 return false; 393 } 394 // This was the last instruction in the bundle. 395 if (!MII->isBundledWithSucc()) 396 return Type == AllInBundle; 397 } 398 } 399 400 bool MachineInstr::isIdenticalTo(const MachineInstr &Other, 401 MICheckType Check) const { 402 // If opcodes or number of operands are not the same then the two 403 // instructions are obviously not identical. 404 if (Other.getOpcode() != getOpcode() || 405 Other.getNumOperands() != getNumOperands()) 406 return false; 407 408 if (isBundle()) { 409 // We have passed the test above that both instructions have the same 410 // opcode, so we know that both instructions are bundles here. Let's compare 411 // MIs inside the bundle. 412 assert(Other.isBundle() && "Expected that both instructions are bundles."); 413 MachineBasicBlock::const_instr_iterator I1 = getIterator(); 414 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator(); 415 // Loop until we analysed the last intruction inside at least one of the 416 // bundles. 417 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) { 418 ++I1; 419 ++I2; 420 if (!I1->isIdenticalTo(*I2, Check)) 421 return false; 422 } 423 // If we've reached the end of just one of the two bundles, but not both, 424 // the instructions are not identical. 425 if (I1->isBundledWithSucc() || I2->isBundledWithSucc()) 426 return false; 427 } 428 429 // Check operands to make sure they match. 430 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 431 const MachineOperand &MO = getOperand(i); 432 const MachineOperand &OMO = Other.getOperand(i); 433 if (!MO.isReg()) { 434 if (!MO.isIdenticalTo(OMO)) 435 return false; 436 continue; 437 } 438 439 // Clients may or may not want to ignore defs when testing for equality. 440 // For example, machine CSE pass only cares about finding common 441 // subexpressions, so it's safe to ignore virtual register defs. 442 if (MO.isDef()) { 443 if (Check == IgnoreDefs) 444 continue; 445 else if (Check == IgnoreVRegDefs) { 446 if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) || 447 !TargetRegisterInfo::isVirtualRegister(OMO.getReg())) 448 if (!MO.isIdenticalTo(OMO)) 449 return false; 450 } else { 451 if (!MO.isIdenticalTo(OMO)) 452 return false; 453 if (Check == CheckKillDead && MO.isDead() != OMO.isDead()) 454 return false; 455 } 456 } else { 457 if (!MO.isIdenticalTo(OMO)) 458 return false; 459 if (Check == CheckKillDead && MO.isKill() != OMO.isKill()) 460 return false; 461 } 462 } 463 // If DebugLoc does not match then two dbg.values are not identical. 464 if (isDebugValue()) 465 if (getDebugLoc() && Other.getDebugLoc() && 466 getDebugLoc() != Other.getDebugLoc()) 467 return false; 468 return true; 469 } 470 471 const MachineFunction *MachineInstr::getMF() const { 472 return getParent()->getParent(); 473 } 474 475 MachineInstr *MachineInstr::removeFromParent() { 476 assert(getParent() && "Not embedded in a basic block!"); 477 return getParent()->remove(this); 478 } 479 480 MachineInstr *MachineInstr::removeFromBundle() { 481 assert(getParent() && "Not embedded in a basic block!"); 482 return getParent()->remove_instr(this); 483 } 484 485 void MachineInstr::eraseFromParent() { 486 assert(getParent() && "Not embedded in a basic block!"); 487 getParent()->erase(this); 488 } 489 490 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() { 491 assert(getParent() && "Not embedded in a basic block!"); 492 MachineBasicBlock *MBB = getParent(); 493 MachineFunction *MF = MBB->getParent(); 494 assert(MF && "Not embedded in a function!"); 495 496 MachineInstr *MI = (MachineInstr *)this; 497 MachineRegisterInfo &MRI = MF->getRegInfo(); 498 499 for (const MachineOperand &MO : MI->operands()) { 500 if (!MO.isReg() || !MO.isDef()) 501 continue; 502 unsigned Reg = MO.getReg(); 503 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 504 continue; 505 MRI.markUsesInDebugValueAsUndef(Reg); 506 } 507 MI->eraseFromParent(); 508 } 509 510 void MachineInstr::eraseFromBundle() { 511 assert(getParent() && "Not embedded in a basic block!"); 512 getParent()->erase_instr(this); 513 } 514 515 /// getNumExplicitOperands - Returns the number of non-implicit operands. 516 /// 517 unsigned MachineInstr::getNumExplicitOperands() const { 518 unsigned NumOperands = MCID->getNumOperands(); 519 if (!MCID->isVariadic()) 520 return NumOperands; 521 522 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) { 523 const MachineOperand &MO = getOperand(i); 524 if (!MO.isReg() || !MO.isImplicit()) 525 NumOperands++; 526 } 527 return NumOperands; 528 } 529 530 void MachineInstr::bundleWithPred() { 531 assert(!isBundledWithPred() && "MI is already bundled with its predecessor"); 532 setFlag(BundledPred); 533 MachineBasicBlock::instr_iterator Pred = getIterator(); 534 --Pred; 535 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 536 Pred->setFlag(BundledSucc); 537 } 538 539 void MachineInstr::bundleWithSucc() { 540 assert(!isBundledWithSucc() && "MI is already bundled with its successor"); 541 setFlag(BundledSucc); 542 MachineBasicBlock::instr_iterator Succ = getIterator(); 543 ++Succ; 544 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags"); 545 Succ->setFlag(BundledPred); 546 } 547 548 void MachineInstr::unbundleFromPred() { 549 assert(isBundledWithPred() && "MI isn't bundled with its predecessor"); 550 clearFlag(BundledPred); 551 MachineBasicBlock::instr_iterator Pred = getIterator(); 552 --Pred; 553 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 554 Pred->clearFlag(BundledSucc); 555 } 556 557 void MachineInstr::unbundleFromSucc() { 558 assert(isBundledWithSucc() && "MI isn't bundled with its successor"); 559 clearFlag(BundledSucc); 560 MachineBasicBlock::instr_iterator Succ = getIterator(); 561 ++Succ; 562 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags"); 563 Succ->clearFlag(BundledPred); 564 } 565 566 bool MachineInstr::isStackAligningInlineAsm() const { 567 if (isInlineAsm()) { 568 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 569 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 570 return true; 571 } 572 return false; 573 } 574 575 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const { 576 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"); 577 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 578 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0); 579 } 580 581 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx, 582 unsigned *GroupNo) const { 583 assert(isInlineAsm() && "Expected an inline asm instruction"); 584 assert(OpIdx < getNumOperands() && "OpIdx out of range"); 585 586 // Ignore queries about the initial operands. 587 if (OpIdx < InlineAsm::MIOp_FirstOperand) 588 return -1; 589 590 unsigned Group = 0; 591 unsigned NumOps; 592 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 593 i += NumOps) { 594 const MachineOperand &FlagMO = getOperand(i); 595 // If we reach the implicit register operands, stop looking. 596 if (!FlagMO.isImm()) 597 return -1; 598 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 599 if (i + NumOps > OpIdx) { 600 if (GroupNo) 601 *GroupNo = Group; 602 return i; 603 } 604 ++Group; 605 } 606 return -1; 607 } 608 609 const DILocalVariable *MachineInstr::getDebugVariable() const { 610 assert(isDebugValue() && "not a DBG_VALUE"); 611 return cast<DILocalVariable>(getOperand(2).getMetadata()); 612 } 613 614 const DIExpression *MachineInstr::getDebugExpression() const { 615 assert(isDebugValue() && "not a DBG_VALUE"); 616 return cast<DIExpression>(getOperand(3).getMetadata()); 617 } 618 619 const TargetRegisterClass* 620 MachineInstr::getRegClassConstraint(unsigned OpIdx, 621 const TargetInstrInfo *TII, 622 const TargetRegisterInfo *TRI) const { 623 assert(getParent() && "Can't have an MBB reference here!"); 624 assert(getMF() && "Can't have an MF reference here!"); 625 const MachineFunction &MF = *getMF(); 626 627 // Most opcodes have fixed constraints in their MCInstrDesc. 628 if (!isInlineAsm()) 629 return TII->getRegClass(getDesc(), OpIdx, TRI, MF); 630 631 if (!getOperand(OpIdx).isReg()) 632 return nullptr; 633 634 // For tied uses on inline asm, get the constraint from the def. 635 unsigned DefIdx; 636 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx)) 637 OpIdx = DefIdx; 638 639 // Inline asm stores register class constraints in the flag word. 640 int FlagIdx = findInlineAsmFlagIdx(OpIdx); 641 if (FlagIdx < 0) 642 return nullptr; 643 644 unsigned Flag = getOperand(FlagIdx).getImm(); 645 unsigned RCID; 646 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse || 647 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef || 648 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) && 649 InlineAsm::hasRegClassConstraint(Flag, RCID)) 650 return TRI->getRegClass(RCID); 651 652 // Assume that all registers in a memory operand are pointers. 653 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem) 654 return TRI->getPointerRegClass(MF); 655 656 return nullptr; 657 } 658 659 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg( 660 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, 661 const TargetRegisterInfo *TRI, bool ExploreBundle) const { 662 // Check every operands inside the bundle if we have 663 // been asked to. 664 if (ExploreBundle) 665 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC; 666 ++OpndIt) 667 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl( 668 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI); 669 else 670 // Otherwise, just check the current operands. 671 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i) 672 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI); 673 return CurRC; 674 } 675 676 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl( 677 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC, 678 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 679 assert(CurRC && "Invalid initial register class"); 680 // Check if Reg is constrained by some of its use/def from MI. 681 const MachineOperand &MO = getOperand(OpIdx); 682 if (!MO.isReg() || MO.getReg() != Reg) 683 return CurRC; 684 // If yes, accumulate the constraints through the operand. 685 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI); 686 } 687 688 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect( 689 unsigned OpIdx, const TargetRegisterClass *CurRC, 690 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 691 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI); 692 const MachineOperand &MO = getOperand(OpIdx); 693 assert(MO.isReg() && 694 "Cannot get register constraints for non-register operand"); 695 assert(CurRC && "Invalid initial register class"); 696 if (unsigned SubIdx = MO.getSubReg()) { 697 if (OpRC) 698 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx); 699 else 700 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx); 701 } else if (OpRC) 702 CurRC = TRI->getCommonSubClass(CurRC, OpRC); 703 return CurRC; 704 } 705 706 /// Return the number of instructions inside the MI bundle, not counting the 707 /// header instruction. 708 unsigned MachineInstr::getBundleSize() const { 709 MachineBasicBlock::const_instr_iterator I = getIterator(); 710 unsigned Size = 0; 711 while (I->isBundledWithSucc()) { 712 ++Size; 713 ++I; 714 } 715 return Size; 716 } 717 718 /// Returns true if the MachineInstr has an implicit-use operand of exactly 719 /// the given register (not considering sub/super-registers). 720 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const { 721 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 722 const MachineOperand &MO = getOperand(i); 723 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg) 724 return true; 725 } 726 return false; 727 } 728 729 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of 730 /// the specific register or -1 if it is not found. It further tightens 731 /// the search criteria to a use that kills the register if isKill is true. 732 int MachineInstr::findRegisterUseOperandIdx( 733 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const { 734 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 735 const MachineOperand &MO = getOperand(i); 736 if (!MO.isReg() || !MO.isUse()) 737 continue; 738 unsigned MOReg = MO.getReg(); 739 if (!MOReg) 740 continue; 741 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) && 742 TargetRegisterInfo::isPhysicalRegister(Reg) && 743 TRI->isSubRegister(MOReg, Reg))) 744 if (!isKill || MO.isKill()) 745 return i; 746 } 747 return -1; 748 } 749 750 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes) 751 /// indicating if this instruction reads or writes Reg. This also considers 752 /// partial defines. 753 std::pair<bool,bool> 754 MachineInstr::readsWritesVirtualRegister(unsigned Reg, 755 SmallVectorImpl<unsigned> *Ops) const { 756 bool PartDef = false; // Partial redefine. 757 bool FullDef = false; // Full define. 758 bool Use = false; 759 760 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 761 const MachineOperand &MO = getOperand(i); 762 if (!MO.isReg() || MO.getReg() != Reg) 763 continue; 764 if (Ops) 765 Ops->push_back(i); 766 if (MO.isUse()) 767 Use |= !MO.isUndef(); 768 else if (MO.getSubReg() && !MO.isUndef()) 769 // A partial def undef doesn't count as reading the register. 770 PartDef = true; 771 else 772 FullDef = true; 773 } 774 // A partial redefine uses Reg unless there is also a full define. 775 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef); 776 } 777 778 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of 779 /// the specified register or -1 if it is not found. If isDead is true, defs 780 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it 781 /// also checks if there is a def of a super-register. 782 int 783 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap, 784 const TargetRegisterInfo *TRI) const { 785 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg); 786 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 787 const MachineOperand &MO = getOperand(i); 788 // Accept regmask operands when Overlap is set. 789 // Ignore them when looking for a specific def operand (Overlap == false). 790 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg)) 791 return i; 792 if (!MO.isReg() || !MO.isDef()) 793 continue; 794 unsigned MOReg = MO.getReg(); 795 bool Found = (MOReg == Reg); 796 if (!Found && TRI && isPhys && 797 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 798 if (Overlap) 799 Found = TRI->regsOverlap(MOReg, Reg); 800 else 801 Found = TRI->isSubRegister(MOReg, Reg); 802 } 803 if (Found && (!isDead || MO.isDead())) 804 return i; 805 } 806 return -1; 807 } 808 809 /// findFirstPredOperandIdx() - Find the index of the first operand in the 810 /// operand list that is used to represent the predicate. It returns -1 if 811 /// none is found. 812 int MachineInstr::findFirstPredOperandIdx() const { 813 // Don't call MCID.findFirstPredOperandIdx() because this variant 814 // is sometimes called on an instruction that's not yet complete, and 815 // so the number of operands is less than the MCID indicates. In 816 // particular, the PTX target does this. 817 const MCInstrDesc &MCID = getDesc(); 818 if (MCID.isPredicable()) { 819 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 820 if (MCID.OpInfo[i].isPredicate()) 821 return i; 822 } 823 824 return -1; 825 } 826 827 // MachineOperand::TiedTo is 4 bits wide. 828 const unsigned TiedMax = 15; 829 830 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other. 831 /// 832 /// Use and def operands can be tied together, indicated by a non-zero TiedTo 833 /// field. TiedTo can have these values: 834 /// 835 /// 0: Operand is not tied to anything. 836 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1). 837 /// TiedMax: Tied to an operand >= TiedMax-1. 838 /// 839 /// The tied def must be one of the first TiedMax operands on a normal 840 /// instruction. INLINEASM instructions allow more tied defs. 841 /// 842 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) { 843 MachineOperand &DefMO = getOperand(DefIdx); 844 MachineOperand &UseMO = getOperand(UseIdx); 845 assert(DefMO.isDef() && "DefIdx must be a def operand"); 846 assert(UseMO.isUse() && "UseIdx must be a use operand"); 847 assert(!DefMO.isTied() && "Def is already tied to another use"); 848 assert(!UseMO.isTied() && "Use is already tied to another def"); 849 850 if (DefIdx < TiedMax) 851 UseMO.TiedTo = DefIdx + 1; 852 else { 853 // Inline asm can use the group descriptors to find tied operands, but on 854 // normal instruction, the tied def must be within the first TiedMax 855 // operands. 856 assert(isInlineAsm() && "DefIdx out of range"); 857 UseMO.TiedTo = TiedMax; 858 } 859 860 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx(). 861 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax); 862 } 863 864 /// Given the index of a tied register operand, find the operand it is tied to. 865 /// Defs are tied to uses and vice versa. Returns the index of the tied operand 866 /// which must exist. 867 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const { 868 const MachineOperand &MO = getOperand(OpIdx); 869 assert(MO.isTied() && "Operand isn't tied"); 870 871 // Normally TiedTo is in range. 872 if (MO.TiedTo < TiedMax) 873 return MO.TiedTo - 1; 874 875 // Uses on normal instructions can be out of range. 876 if (!isInlineAsm()) { 877 // Normal tied defs must be in the 0..TiedMax-1 range. 878 if (MO.isUse()) 879 return TiedMax - 1; 880 // MO is a def. Search for the tied use. 881 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) { 882 const MachineOperand &UseMO = getOperand(i); 883 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1) 884 return i; 885 } 886 llvm_unreachable("Can't find tied use"); 887 } 888 889 // Now deal with inline asm by parsing the operand group descriptor flags. 890 // Find the beginning of each operand group. 891 SmallVector<unsigned, 8> GroupIdx; 892 unsigned OpIdxGroup = ~0u; 893 unsigned NumOps; 894 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 895 i += NumOps) { 896 const MachineOperand &FlagMO = getOperand(i); 897 assert(FlagMO.isImm() && "Invalid tied operand on inline asm"); 898 unsigned CurGroup = GroupIdx.size(); 899 GroupIdx.push_back(i); 900 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 901 // OpIdx belongs to this operand group. 902 if (OpIdx > i && OpIdx < i + NumOps) 903 OpIdxGroup = CurGroup; 904 unsigned TiedGroup; 905 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup)) 906 continue; 907 // Operands in this group are tied to operands in TiedGroup which must be 908 // earlier. Find the number of operands between the two groups. 909 unsigned Delta = i - GroupIdx[TiedGroup]; 910 911 // OpIdx is a use tied to TiedGroup. 912 if (OpIdxGroup == CurGroup) 913 return OpIdx - Delta; 914 915 // OpIdx is a def tied to this use group. 916 if (OpIdxGroup == TiedGroup) 917 return OpIdx + Delta; 918 } 919 llvm_unreachable("Invalid tied operand on inline asm"); 920 } 921 922 /// clearKillInfo - Clears kill flags on all operands. 923 /// 924 void MachineInstr::clearKillInfo() { 925 for (MachineOperand &MO : operands()) { 926 if (MO.isReg() && MO.isUse()) 927 MO.setIsKill(false); 928 } 929 } 930 931 void MachineInstr::substituteRegister(unsigned FromReg, 932 unsigned ToReg, 933 unsigned SubIdx, 934 const TargetRegisterInfo &RegInfo) { 935 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) { 936 if (SubIdx) 937 ToReg = RegInfo.getSubReg(ToReg, SubIdx); 938 for (MachineOperand &MO : operands()) { 939 if (!MO.isReg() || MO.getReg() != FromReg) 940 continue; 941 MO.substPhysReg(ToReg, RegInfo); 942 } 943 } else { 944 for (MachineOperand &MO : operands()) { 945 if (!MO.isReg() || MO.getReg() != FromReg) 946 continue; 947 MO.substVirtReg(ToReg, SubIdx, RegInfo); 948 } 949 } 950 } 951 952 /// isSafeToMove - Return true if it is safe to move this instruction. If 953 /// SawStore is set to true, it means that there is a store (or call) between 954 /// the instruction's location and its intended destination. 955 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const { 956 // Ignore stuff that we obviously can't move. 957 // 958 // Treat volatile loads as stores. This is not strictly necessary for 959 // volatiles, but it is required for atomic loads. It is not allowed to move 960 // a load across an atomic load with Ordering > Monotonic. 961 if (mayStore() || isCall() || isPHI() || 962 (mayLoad() && hasOrderedMemoryRef())) { 963 SawStore = true; 964 return false; 965 } 966 967 if (isPosition() || isDebugValue() || isTerminator() || 968 hasUnmodeledSideEffects()) 969 return false; 970 971 // See if this instruction does a load. If so, we have to guarantee that the 972 // loaded value doesn't change between the load and the its intended 973 // destination. The check for isInvariantLoad gives the targe the chance to 974 // classify the load as always returning a constant, e.g. a constant pool 975 // load. 976 if (mayLoad() && !isDereferenceableInvariantLoad(AA)) 977 // Otherwise, this is a real load. If there is a store between the load and 978 // end of block, we can't move it. 979 return !SawStore; 980 981 return true; 982 } 983 984 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other, 985 bool UseTBAA) { 986 const MachineFunction *MF = getMF(); 987 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 988 const MachineFrameInfo &MFI = MF->getFrameInfo(); 989 990 // If neither instruction stores to memory, they can't alias in any 991 // meaningful way, even if they read from the same address. 992 if (!mayStore() && !Other.mayStore()) 993 return false; 994 995 // Let the target decide if memory accesses cannot possibly overlap. 996 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA)) 997 return false; 998 999 // FIXME: Need to handle multiple memory operands to support all targets. 1000 if (!hasOneMemOperand() || !Other.hasOneMemOperand()) 1001 return true; 1002 1003 MachineMemOperand *MMOa = *memoperands_begin(); 1004 MachineMemOperand *MMOb = *Other.memoperands_begin(); 1005 1006 // The following interface to AA is fashioned after DAGCombiner::isAlias 1007 // and operates with MachineMemOperand offset with some important 1008 // assumptions: 1009 // - LLVM fundamentally assumes flat address spaces. 1010 // - MachineOperand offset can *only* result from legalization and 1011 // cannot affect queries other than the trivial case of overlap 1012 // checking. 1013 // - These offsets never wrap and never step outside 1014 // of allocated objects. 1015 // - There should never be any negative offsets here. 1016 // 1017 // FIXME: Modify API to hide this math from "user" 1018 // Even before we go to AA we can reason locally about some 1019 // memory objects. It can save compile time, and possibly catch some 1020 // corner cases not currently covered. 1021 1022 int64_t OffsetA = MMOa->getOffset(); 1023 int64_t OffsetB = MMOb->getOffset(); 1024 1025 int64_t MinOffset = std::min(OffsetA, OffsetB); 1026 int64_t WidthA = MMOa->getSize(); 1027 int64_t WidthB = MMOb->getSize(); 1028 const Value *ValA = MMOa->getValue(); 1029 const Value *ValB = MMOb->getValue(); 1030 bool SameVal = (ValA && ValB && (ValA == ValB)); 1031 if (!SameVal) { 1032 const PseudoSourceValue *PSVa = MMOa->getPseudoValue(); 1033 const PseudoSourceValue *PSVb = MMOb->getPseudoValue(); 1034 if (PSVa && ValB && !PSVa->mayAlias(&MFI)) 1035 return false; 1036 if (PSVb && ValA && !PSVb->mayAlias(&MFI)) 1037 return false; 1038 if (PSVa && PSVb && (PSVa == PSVb)) 1039 SameVal = true; 1040 } 1041 1042 if (SameVal) { 1043 int64_t MaxOffset = std::max(OffsetA, OffsetB); 1044 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB; 1045 return (MinOffset + LowWidth > MaxOffset); 1046 } 1047 1048 if (!AA) 1049 return true; 1050 1051 if (!ValA || !ValB) 1052 return true; 1053 1054 assert((OffsetA >= 0) && "Negative MachineMemOperand offset"); 1055 assert((OffsetB >= 0) && "Negative MachineMemOperand offset"); 1056 1057 int64_t Overlapa = WidthA + OffsetA - MinOffset; 1058 int64_t Overlapb = WidthB + OffsetB - MinOffset; 1059 1060 AliasResult AAResult = AA->alias( 1061 MemoryLocation(ValA, Overlapa, 1062 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()), 1063 MemoryLocation(ValB, Overlapb, 1064 UseTBAA ? MMOb->getAAInfo() : AAMDNodes())); 1065 1066 return (AAResult != NoAlias); 1067 } 1068 1069 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered 1070 /// or volatile memory reference, or if the information describing the memory 1071 /// reference is not available. Return false if it is known to have no ordered 1072 /// memory references. 1073 bool MachineInstr::hasOrderedMemoryRef() const { 1074 // An instruction known never to access memory won't have a volatile access. 1075 if (!mayStore() && 1076 !mayLoad() && 1077 !isCall() && 1078 !hasUnmodeledSideEffects()) 1079 return false; 1080 1081 // Otherwise, if the instruction has no memory reference information, 1082 // conservatively assume it wasn't preserved. 1083 if (memoperands_empty()) 1084 return true; 1085 1086 // Check if any of our memory operands are ordered. 1087 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) { 1088 return !MMO->isUnordered(); 1089 }); 1090 } 1091 1092 /// isDereferenceableInvariantLoad - Return true if this instruction will never 1093 /// trap and is loading from a location whose value is invariant across a run of 1094 /// this function. 1095 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const { 1096 // If the instruction doesn't load at all, it isn't an invariant load. 1097 if (!mayLoad()) 1098 return false; 1099 1100 // If the instruction has lost its memoperands, conservatively assume that 1101 // it may not be an invariant load. 1102 if (memoperands_empty()) 1103 return false; 1104 1105 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo(); 1106 1107 for (MachineMemOperand *MMO : memoperands()) { 1108 if (MMO->isVolatile()) return false; 1109 if (MMO->isStore()) return false; 1110 if (MMO->isInvariant() && MMO->isDereferenceable()) 1111 continue; 1112 1113 // A load from a constant PseudoSourceValue is invariant. 1114 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) 1115 if (PSV->isConstant(&MFI)) 1116 continue; 1117 1118 if (const Value *V = MMO->getValue()) { 1119 // If we have an AliasAnalysis, ask it whether the memory is constant. 1120 if (AA && 1121 AA->pointsToConstantMemory( 1122 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo()))) 1123 continue; 1124 } 1125 1126 // Otherwise assume conservatively. 1127 return false; 1128 } 1129 1130 // Everything checks out. 1131 return true; 1132 } 1133 1134 /// isConstantValuePHI - If the specified instruction is a PHI that always 1135 /// merges together the same virtual register, return the register, otherwise 1136 /// return 0. 1137 unsigned MachineInstr::isConstantValuePHI() const { 1138 if (!isPHI()) 1139 return 0; 1140 assert(getNumOperands() >= 3 && 1141 "It's illegal to have a PHI without source operands"); 1142 1143 unsigned Reg = getOperand(1).getReg(); 1144 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2) 1145 if (getOperand(i).getReg() != Reg) 1146 return 0; 1147 return Reg; 1148 } 1149 1150 bool MachineInstr::hasUnmodeledSideEffects() const { 1151 if (hasProperty(MCID::UnmodeledSideEffects)) 1152 return true; 1153 if (isInlineAsm()) { 1154 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1155 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1156 return true; 1157 } 1158 1159 return false; 1160 } 1161 1162 bool MachineInstr::isLoadFoldBarrier() const { 1163 return mayStore() || isCall() || hasUnmodeledSideEffects(); 1164 } 1165 1166 /// allDefsAreDead - Return true if all the defs of this instruction are dead. 1167 /// 1168 bool MachineInstr::allDefsAreDead() const { 1169 for (const MachineOperand &MO : operands()) { 1170 if (!MO.isReg() || MO.isUse()) 1171 continue; 1172 if (!MO.isDead()) 1173 return false; 1174 } 1175 return true; 1176 } 1177 1178 /// copyImplicitOps - Copy implicit register operands from specified 1179 /// instruction to this instruction. 1180 void MachineInstr::copyImplicitOps(MachineFunction &MF, 1181 const MachineInstr &MI) { 1182 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands(); 1183 i != e; ++i) { 1184 const MachineOperand &MO = MI.getOperand(i); 1185 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask()) 1186 addOperand(MF, MO); 1187 } 1188 } 1189 1190 bool MachineInstr::hasComplexRegisterTies() const { 1191 const MCInstrDesc &MCID = getDesc(); 1192 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 1193 const auto &Operand = getOperand(I); 1194 if (!Operand.isReg() || Operand.isDef()) 1195 // Ignore the defined registers as MCID marks only the uses as tied. 1196 continue; 1197 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 1198 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1; 1199 if (ExpectedTiedIdx != TiedIdx) 1200 return true; 1201 } 1202 return false; 1203 } 1204 1205 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1206 const MachineRegisterInfo &MRI) const { 1207 const MachineOperand &Op = getOperand(OpIdx); 1208 if (!Op.isReg()) 1209 return LLT{}; 1210 1211 if (isVariadic() || OpIdx >= getNumExplicitOperands()) 1212 return MRI.getType(Op.getReg()); 1213 1214 auto &OpInfo = getDesc().OpInfo[OpIdx]; 1215 if (!OpInfo.isGenericType()) 1216 return MRI.getType(Op.getReg()); 1217 1218 if (PrintedTypes[OpInfo.getGenericTypeIndex()]) 1219 return LLT{}; 1220 1221 PrintedTypes.set(OpInfo.getGenericTypeIndex()); 1222 return MRI.getType(Op.getReg()); 1223 } 1224 1225 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1226 LLVM_DUMP_METHOD void MachineInstr::dump() const { 1227 dbgs() << " "; 1228 print(dbgs()); 1229 } 1230 #endif 1231 1232 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers, 1233 bool SkipDebugLoc, const TargetInstrInfo *TII) const { 1234 const Module *M = nullptr; 1235 const Function *F = nullptr; 1236 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1237 F = &MF->getFunction(); 1238 M = F->getParent(); 1239 } 1240 1241 ModuleSlotTracker MST(M); 1242 if (F) 1243 MST.incorporateFunction(*F); 1244 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII); 1245 } 1246 1247 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST, 1248 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc, 1249 const TargetInstrInfo *TII) const { 1250 // We can be a bit tidier if we know the MachineFunction. 1251 const MachineFunction *MF = nullptr; 1252 const TargetRegisterInfo *TRI = nullptr; 1253 const MachineRegisterInfo *MRI = nullptr; 1254 const TargetIntrinsicInfo *IntrinsicInfo = nullptr; 1255 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII); 1256 1257 if (isCFIInstruction()) 1258 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 1259 1260 SmallBitVector PrintedTypes(8); 1261 bool ShouldPrintRegisterTies = hasComplexRegisterTies(); 1262 auto getTiedOperandIdx = [&](unsigned OpIdx) { 1263 if (!ShouldPrintRegisterTies) 1264 return 0U; 1265 const MachineOperand &MO = getOperand(OpIdx); 1266 if (MO.isReg() && MO.isTied() && !MO.isDef()) 1267 return findTiedOperandIdx(OpIdx); 1268 return 0U; 1269 }; 1270 unsigned StartOp = 0; 1271 unsigned e = getNumOperands(); 1272 1273 // Print explicitly defined operands on the left of an assignment syntax. 1274 while (StartOp < e) { 1275 const MachineOperand &MO = getOperand(StartOp); 1276 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 1277 break; 1278 1279 if (StartOp != 0) 1280 OS << ", "; 1281 1282 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{}; 1283 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp); 1284 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone, 1285 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1286 ++StartOp; 1287 } 1288 1289 if (StartOp != 0) 1290 OS << " = "; 1291 1292 if (getFlag(MachineInstr::FrameSetup)) 1293 OS << "frame-setup "; 1294 else if (getFlag(MachineInstr::FrameDestroy)) 1295 OS << "frame-destroy "; 1296 1297 // Print the opcode name. 1298 if (TII) 1299 OS << TII->getName(getOpcode()); 1300 else 1301 OS << "UNKNOWN"; 1302 1303 if (SkipOpers) 1304 return; 1305 1306 // Print the rest of the operands. 1307 bool FirstOp = true; 1308 unsigned AsmDescOp = ~0u; 1309 unsigned AsmOpCount = 0; 1310 1311 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) { 1312 // Print asm string. 1313 OS << " "; 1314 const unsigned OpIdx = InlineAsm::MIOp_AsmString; 1315 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{}; 1316 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx); 1317 getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1318 ShouldPrintRegisterTies, TiedOperandIdx, TRI, 1319 IntrinsicInfo); 1320 1321 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack 1322 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1323 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1324 OS << " [sideeffect]"; 1325 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1326 OS << " [mayload]"; 1327 if (ExtraInfo & InlineAsm::Extra_MayStore) 1328 OS << " [maystore]"; 1329 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 1330 OS << " [isconvergent]"; 1331 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1332 OS << " [alignstack]"; 1333 if (getInlineAsmDialect() == InlineAsm::AD_ATT) 1334 OS << " [attdialect]"; 1335 if (getInlineAsmDialect() == InlineAsm::AD_Intel) 1336 OS << " [inteldialect]"; 1337 1338 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand; 1339 FirstOp = false; 1340 } 1341 1342 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { 1343 const MachineOperand &MO = getOperand(i); 1344 1345 if (FirstOp) FirstOp = false; else OS << ","; 1346 OS << " "; 1347 1348 if (isDebugValue() && MO.isMetadata()) { 1349 // Pretty print DBG_VALUE instructions. 1350 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata()); 1351 if (DIV && !DIV->getName().empty()) 1352 OS << "!\"" << DIV->getName() << '\"'; 1353 else { 1354 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1355 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1356 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1357 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1358 } 1359 } else if (i == AsmDescOp && MO.isImm()) { 1360 // Pretty print the inline asm operand descriptor. 1361 OS << '$' << AsmOpCount++; 1362 unsigned Flag = MO.getImm(); 1363 switch (InlineAsm::getKind(Flag)) { 1364 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break; 1365 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break; 1366 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break; 1367 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break; 1368 case InlineAsm::Kind_Imm: OS << ":[imm"; break; 1369 case InlineAsm::Kind_Mem: OS << ":[mem"; break; 1370 default: OS << ":[??" << InlineAsm::getKind(Flag); break; 1371 } 1372 1373 unsigned RCID = 0; 1374 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) && 1375 InlineAsm::hasRegClassConstraint(Flag, RCID)) { 1376 if (TRI) { 1377 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID)); 1378 } else 1379 OS << ":RC" << RCID; 1380 } 1381 1382 if (InlineAsm::isMemKind(Flag)) { 1383 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag); 1384 switch (MCID) { 1385 case InlineAsm::Constraint_es: OS << ":es"; break; 1386 case InlineAsm::Constraint_i: OS << ":i"; break; 1387 case InlineAsm::Constraint_m: OS << ":m"; break; 1388 case InlineAsm::Constraint_o: OS << ":o"; break; 1389 case InlineAsm::Constraint_v: OS << ":v"; break; 1390 case InlineAsm::Constraint_Q: OS << ":Q"; break; 1391 case InlineAsm::Constraint_R: OS << ":R"; break; 1392 case InlineAsm::Constraint_S: OS << ":S"; break; 1393 case InlineAsm::Constraint_T: OS << ":T"; break; 1394 case InlineAsm::Constraint_Um: OS << ":Um"; break; 1395 case InlineAsm::Constraint_Un: OS << ":Un"; break; 1396 case InlineAsm::Constraint_Uq: OS << ":Uq"; break; 1397 case InlineAsm::Constraint_Us: OS << ":Us"; break; 1398 case InlineAsm::Constraint_Ut: OS << ":Ut"; break; 1399 case InlineAsm::Constraint_Uv: OS << ":Uv"; break; 1400 case InlineAsm::Constraint_Uy: OS << ":Uy"; break; 1401 case InlineAsm::Constraint_X: OS << ":X"; break; 1402 case InlineAsm::Constraint_Z: OS << ":Z"; break; 1403 case InlineAsm::Constraint_ZC: OS << ":ZC"; break; 1404 case InlineAsm::Constraint_Zy: OS << ":Zy"; break; 1405 default: OS << ":?"; break; 1406 } 1407 } 1408 1409 unsigned TiedTo = 0; 1410 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo)) 1411 OS << " tiedto:$" << TiedTo; 1412 1413 OS << ']'; 1414 1415 // Compute the index of the next operand descriptor. 1416 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag); 1417 } else { 1418 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1419 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1420 if (MO.isImm() && isOperandSubregIdx(i)) 1421 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI); 1422 else 1423 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1424 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1425 } 1426 } 1427 1428 bool HaveSemi = false; 1429 if (!memoperands_empty()) { 1430 if (!HaveSemi) { 1431 OS << ";"; 1432 HaveSemi = true; 1433 } 1434 1435 OS << " mem:"; 1436 for (mmo_iterator i = memoperands_begin(), e = memoperands_end(); 1437 i != e; ++i) { 1438 (*i)->print(OS, MST); 1439 if (std::next(i) != e) 1440 OS << " "; 1441 } 1442 } 1443 1444 // Print debug location information. 1445 if (isDebugValue() && getOperand(e - 2).isMetadata()) { 1446 if (!HaveSemi) 1447 OS << ";"; 1448 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata()); 1449 OS << " line no:" << DV->getLine(); 1450 if (auto *InlinedAt = debugLoc->getInlinedAt()) { 1451 DebugLoc InlinedAtDL(InlinedAt); 1452 if (InlinedAtDL && MF) { 1453 OS << " inlined @[ "; 1454 InlinedAtDL.print(OS); 1455 OS << " ]"; 1456 } 1457 } 1458 if (isIndirectDebugValue()) 1459 OS << " indirect"; 1460 } else if (SkipDebugLoc) { 1461 return; 1462 } else if (debugLoc && MF) { 1463 if (!HaveSemi) 1464 OS << ";"; 1465 OS << " dbg:"; 1466 debugLoc.print(OS); 1467 } 1468 1469 OS << '\n'; 1470 } 1471 1472 bool MachineInstr::addRegisterKilled(unsigned IncomingReg, 1473 const TargetRegisterInfo *RegInfo, 1474 bool AddIfNotFound) { 1475 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg); 1476 bool hasAliases = isPhysReg && 1477 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid(); 1478 bool Found = false; 1479 SmallVector<unsigned,4> DeadOps; 1480 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1481 MachineOperand &MO = getOperand(i); 1482 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) 1483 continue; 1484 1485 // DEBUG_VALUE nodes do not contribute to code generation and should 1486 // always be ignored. Failure to do so may result in trying to modify 1487 // KILL flags on DEBUG_VALUE nodes. 1488 if (MO.isDebug()) 1489 continue; 1490 1491 unsigned Reg = MO.getReg(); 1492 if (!Reg) 1493 continue; 1494 1495 if (Reg == IncomingReg) { 1496 if (!Found) { 1497 if (MO.isKill()) 1498 // The register is already marked kill. 1499 return true; 1500 if (isPhysReg && isRegTiedToDefOperand(i)) 1501 // Two-address uses of physregs must not be marked kill. 1502 return true; 1503 MO.setIsKill(); 1504 Found = true; 1505 } 1506 } else if (hasAliases && MO.isKill() && 1507 TargetRegisterInfo::isPhysicalRegister(Reg)) { 1508 // A super-register kill already exists. 1509 if (RegInfo->isSuperRegister(IncomingReg, Reg)) 1510 return true; 1511 if (RegInfo->isSubRegister(IncomingReg, Reg)) 1512 DeadOps.push_back(i); 1513 } 1514 } 1515 1516 // Trim unneeded kill operands. 1517 while (!DeadOps.empty()) { 1518 unsigned OpIdx = DeadOps.back(); 1519 if (getOperand(OpIdx).isImplicit()) 1520 RemoveOperand(OpIdx); 1521 else 1522 getOperand(OpIdx).setIsKill(false); 1523 DeadOps.pop_back(); 1524 } 1525 1526 // If not found, this means an alias of one of the operands is killed. Add a 1527 // new implicit operand if required. 1528 if (!Found && AddIfNotFound) { 1529 addOperand(MachineOperand::CreateReg(IncomingReg, 1530 false /*IsDef*/, 1531 true /*IsImp*/, 1532 true /*IsKill*/)); 1533 return true; 1534 } 1535 return Found; 1536 } 1537 1538 void MachineInstr::clearRegisterKills(unsigned Reg, 1539 const TargetRegisterInfo *RegInfo) { 1540 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) 1541 RegInfo = nullptr; 1542 for (MachineOperand &MO : operands()) { 1543 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 1544 continue; 1545 unsigned OpReg = MO.getReg(); 1546 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg) 1547 MO.setIsKill(false); 1548 } 1549 } 1550 1551 bool MachineInstr::addRegisterDead(unsigned Reg, 1552 const TargetRegisterInfo *RegInfo, 1553 bool AddIfNotFound) { 1554 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg); 1555 bool hasAliases = isPhysReg && 1556 MCRegAliasIterator(Reg, RegInfo, false).isValid(); 1557 bool Found = false; 1558 SmallVector<unsigned,4> DeadOps; 1559 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1560 MachineOperand &MO = getOperand(i); 1561 if (!MO.isReg() || !MO.isDef()) 1562 continue; 1563 unsigned MOReg = MO.getReg(); 1564 if (!MOReg) 1565 continue; 1566 1567 if (MOReg == Reg) { 1568 MO.setIsDead(); 1569 Found = true; 1570 } else if (hasAliases && MO.isDead() && 1571 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 1572 // There exists a super-register that's marked dead. 1573 if (RegInfo->isSuperRegister(Reg, MOReg)) 1574 return true; 1575 if (RegInfo->isSubRegister(Reg, MOReg)) 1576 DeadOps.push_back(i); 1577 } 1578 } 1579 1580 // Trim unneeded dead operands. 1581 while (!DeadOps.empty()) { 1582 unsigned OpIdx = DeadOps.back(); 1583 if (getOperand(OpIdx).isImplicit()) 1584 RemoveOperand(OpIdx); 1585 else 1586 getOperand(OpIdx).setIsDead(false); 1587 DeadOps.pop_back(); 1588 } 1589 1590 // If not found, this means an alias of one of the operands is dead. Add a 1591 // new implicit operand if required. 1592 if (Found || !AddIfNotFound) 1593 return Found; 1594 1595 addOperand(MachineOperand::CreateReg(Reg, 1596 true /*IsDef*/, 1597 true /*IsImp*/, 1598 false /*IsKill*/, 1599 true /*IsDead*/)); 1600 return true; 1601 } 1602 1603 void MachineInstr::clearRegisterDeads(unsigned Reg) { 1604 for (MachineOperand &MO : operands()) { 1605 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg) 1606 continue; 1607 MO.setIsDead(false); 1608 } 1609 } 1610 1611 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) { 1612 for (MachineOperand &MO : operands()) { 1613 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0) 1614 continue; 1615 MO.setIsUndef(IsUndef); 1616 } 1617 } 1618 1619 void MachineInstr::addRegisterDefined(unsigned Reg, 1620 const TargetRegisterInfo *RegInfo) { 1621 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1622 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo); 1623 if (MO) 1624 return; 1625 } else { 1626 for (const MachineOperand &MO : operands()) { 1627 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() && 1628 MO.getSubReg() == 0) 1629 return; 1630 } 1631 } 1632 addOperand(MachineOperand::CreateReg(Reg, 1633 true /*IsDef*/, 1634 true /*IsImp*/)); 1635 } 1636 1637 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs, 1638 const TargetRegisterInfo &TRI) { 1639 bool HasRegMask = false; 1640 for (MachineOperand &MO : operands()) { 1641 if (MO.isRegMask()) { 1642 HasRegMask = true; 1643 continue; 1644 } 1645 if (!MO.isReg() || !MO.isDef()) continue; 1646 unsigned Reg = MO.getReg(); 1647 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; 1648 // If there are no uses, including partial uses, the def is dead. 1649 if (llvm::none_of(UsedRegs, 1650 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); })) 1651 MO.setIsDead(); 1652 } 1653 1654 // This is a call with a register mask operand. 1655 // Mask clobbers are always dead, so add defs for the non-dead defines. 1656 if (HasRegMask) 1657 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end(); 1658 I != E; ++I) 1659 addRegisterDefined(*I, &TRI); 1660 } 1661 1662 unsigned 1663 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) { 1664 // Build up a buffer of hash code components. 1665 SmallVector<size_t, 8> HashComponents; 1666 HashComponents.reserve(MI->getNumOperands() + 1); 1667 HashComponents.push_back(MI->getOpcode()); 1668 for (const MachineOperand &MO : MI->operands()) { 1669 if (MO.isReg() && MO.isDef() && 1670 TargetRegisterInfo::isVirtualRegister(MO.getReg())) 1671 continue; // Skip virtual register defs. 1672 1673 HashComponents.push_back(hash_value(MO)); 1674 } 1675 return hash_combine_range(HashComponents.begin(), HashComponents.end()); 1676 } 1677 1678 void MachineInstr::emitError(StringRef Msg) const { 1679 // Find the source location cookie. 1680 unsigned LocCookie = 0; 1681 const MDNode *LocMD = nullptr; 1682 for (unsigned i = getNumOperands(); i != 0; --i) { 1683 if (getOperand(i-1).isMetadata() && 1684 (LocMD = getOperand(i-1).getMetadata()) && 1685 LocMD->getNumOperands() != 0) { 1686 if (const ConstantInt *CI = 1687 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) { 1688 LocCookie = CI->getZExtValue(); 1689 break; 1690 } 1691 } 1692 } 1693 1694 if (const MachineBasicBlock *MBB = getParent()) 1695 if (const MachineFunction *MF = MBB->getParent()) 1696 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg); 1697 report_fatal_error(Msg); 1698 } 1699 1700 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 1701 const MCInstrDesc &MCID, bool IsIndirect, 1702 unsigned Reg, const MDNode *Variable, 1703 const MDNode *Expr) { 1704 assert(isa<DILocalVariable>(Variable) && "not a variable"); 1705 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 1706 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 1707 "Expected inlined-at fields to agree"); 1708 if (IsIndirect) 1709 return BuildMI(MF, DL, MCID) 1710 .addReg(Reg, RegState::Debug) 1711 .addImm(0U) 1712 .addMetadata(Variable) 1713 .addMetadata(Expr); 1714 else 1715 return BuildMI(MF, DL, MCID) 1716 .addReg(Reg, RegState::Debug) 1717 .addReg(0U, RegState::Debug) 1718 .addMetadata(Variable) 1719 .addMetadata(Expr); 1720 } 1721 1722 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 1723 MachineBasicBlock::iterator I, 1724 const DebugLoc &DL, const MCInstrDesc &MCID, 1725 bool IsIndirect, unsigned Reg, 1726 const MDNode *Variable, const MDNode *Expr) { 1727 assert(isa<DILocalVariable>(Variable) && "not a variable"); 1728 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 1729 MachineFunction &MF = *BB.getParent(); 1730 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr); 1731 BB.insert(I, MI); 1732 return MachineInstrBuilder(MF, MI); 1733 } 1734 1735 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot. 1736 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE. 1737 static const DIExpression *computeExprForSpill(const MachineInstr &MI) { 1738 assert(MI.getOperand(0).isReg() && "can't spill non-register"); 1739 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && 1740 "Expected inlined-at fields to agree"); 1741 1742 const DIExpression *Expr = MI.getDebugExpression(); 1743 if (MI.isIndirectDebugValue()) { 1744 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); 1745 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref); 1746 } 1747 return Expr; 1748 } 1749 1750 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB, 1751 MachineBasicBlock::iterator I, 1752 const MachineInstr &Orig, 1753 int FrameIndex) { 1754 const DIExpression *Expr = computeExprForSpill(Orig); 1755 return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc()) 1756 .addFrameIndex(FrameIndex) 1757 .addImm(0U) 1758 .addMetadata(Orig.getDebugVariable()) 1759 .addMetadata(Expr); 1760 } 1761 1762 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) { 1763 const DIExpression *Expr = computeExprForSpill(Orig); 1764 Orig.getOperand(0).ChangeToFrameIndex(FrameIndex); 1765 Orig.getOperand(1).ChangeToImmediate(0U); 1766 Orig.getOperand(3).setMetadata(Expr); 1767 } 1768