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