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