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