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/TargetInstrInfo.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/Config/llvm-config.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DebugInfoMetadata.h" 43 #include "llvm/IR/DebugLoc.h" 44 #include "llvm/IR/DerivedTypes.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InlineAsm.h" 47 #include "llvm/IR/InstrTypes.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/Metadata.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/ModuleSlotTracker.h" 53 #include "llvm/IR/Operator.h" 54 #include "llvm/IR/Type.h" 55 #include "llvm/IR/Value.h" 56 #include "llvm/MC/MCInstrDesc.h" 57 #include "llvm/MC/MCRegisterInfo.h" 58 #include "llvm/MC/MCSymbol.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/FormattedStream.h" 65 #include "llvm/Support/LowLevelTypeImpl.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetIntrinsicInfo.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstddef> 73 #include <cstdint> 74 #include <cstring> 75 #include <iterator> 76 #include <utility> 77 78 using namespace llvm; 79 80 static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) { 81 if (const MachineBasicBlock *MBB = MI.getParent()) 82 if (const MachineFunction *MF = MBB->getParent()) 83 return MF; 84 return nullptr; 85 } 86 87 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from 88 // it. 89 static void tryToGetTargetInfo(const MachineInstr &MI, 90 const TargetRegisterInfo *&TRI, 91 const MachineRegisterInfo *&MRI, 92 const TargetIntrinsicInfo *&IntrinsicInfo, 93 const TargetInstrInfo *&TII) { 94 95 if (const MachineFunction *MF = getMFIfAvailable(MI)) { 96 TRI = MF->getSubtarget().getRegisterInfo(); 97 MRI = &MF->getRegInfo(); 98 IntrinsicInfo = MF->getTarget().getIntrinsicInfo(); 99 TII = MF->getSubtarget().getInstrInfo(); 100 } 101 } 102 103 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) { 104 if (MCID->ImplicitDefs) 105 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; 106 ++ImpDefs) 107 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true)); 108 if (MCID->ImplicitUses) 109 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses; 110 ++ImpUses) 111 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true)); 112 } 113 114 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the 115 /// implicit operands. It reserves space for the number of operands specified by 116 /// the MCInstrDesc. 117 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid, 118 DebugLoc dl, bool NoImp) 119 : MCID(&tid), debugLoc(std::move(dl)), DebugInstrNum(0) { 120 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 121 122 // Reserve space for the expected number of operands. 123 if (unsigned NumOps = MCID->getNumOperands() + 124 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) { 125 CapOperands = OperandCapacity::get(NumOps); 126 Operands = MF.allocateOperandArray(CapOperands); 127 } 128 129 if (!NoImp) 130 addImplicitDefUseOperands(MF); 131 } 132 133 /// MachineInstr ctor - Copies MachineInstr arg exactly. 134 /// Does not copy the number from debug instruction numbering, to preserve 135 /// uniqueness. 136 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI) 137 : MCID(&MI.getDesc()), Info(MI.Info), debugLoc(MI.getDebugLoc()), 138 DebugInstrNum(0) { 139 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 140 141 CapOperands = OperandCapacity::get(MI.getNumOperands()); 142 Operands = MF.allocateOperandArray(CapOperands); 143 144 // Copy operands. 145 for (const MachineOperand &MO : MI.operands()) 146 addOperand(MF, MO); 147 148 // Copy all the sensible flags. 149 setFlags(MI.Flags); 150 } 151 152 void MachineInstr::moveBefore(MachineInstr *MovePos) { 153 MovePos->getParent()->splice(MovePos, getParent(), getIterator()); 154 } 155 156 /// getRegInfo - If this instruction is embedded into a MachineFunction, 157 /// return the MachineRegisterInfo object for the current function, otherwise 158 /// return null. 159 MachineRegisterInfo *MachineInstr::getRegInfo() { 160 if (MachineBasicBlock *MBB = getParent()) 161 return &MBB->getParent()->getRegInfo(); 162 return nullptr; 163 } 164 165 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in 166 /// this instruction from their respective use lists. This requires that the 167 /// operands already be on their use lists. 168 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) { 169 for (MachineOperand &MO : operands()) 170 if (MO.isReg()) 171 MRI.removeRegOperandFromUseList(&MO); 172 } 173 174 /// AddRegOperandsToUseLists - Add all of the register operands in 175 /// this instruction from their respective use lists. This requires that the 176 /// operands not be on their use lists yet. 177 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) { 178 for (MachineOperand &MO : operands()) 179 if (MO.isReg()) 180 MRI.addRegOperandToUseList(&MO); 181 } 182 183 void MachineInstr::addOperand(const MachineOperand &Op) { 184 MachineBasicBlock *MBB = getParent(); 185 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs"); 186 MachineFunction *MF = MBB->getParent(); 187 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs"); 188 addOperand(*MF, Op); 189 } 190 191 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping 192 /// ranges. If MRI is non-null also update use-def chains. 193 static void moveOperands(MachineOperand *Dst, MachineOperand *Src, 194 unsigned NumOps, MachineRegisterInfo *MRI) { 195 if (MRI) 196 return MRI->moveOperands(Dst, Src, NumOps); 197 // MachineOperand is a trivially copyable type so we can just use memmove. 198 assert(Dst && Src && "Unknown operands"); 199 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand)); 200 } 201 202 /// addOperand - Add the specified operand to the instruction. If it is an 203 /// implicit operand, it is added to the end of the operand list. If it is 204 /// an explicit operand it is added at the end of the explicit operand list 205 /// (before the first implicit operand). 206 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) { 207 assert(MCID && "Cannot add operands before providing an instr descriptor"); 208 209 // Check if we're adding one of our existing operands. 210 if (&Op >= Operands && &Op < Operands + NumOperands) { 211 // This is unusual: MI->addOperand(MI->getOperand(i)). 212 // If adding Op requires reallocating or moving existing operands around, 213 // the Op reference could go stale. Support it by copying Op. 214 MachineOperand CopyOp(Op); 215 return addOperand(MF, CopyOp); 216 } 217 218 // Find the insert location for the new operand. Implicit registers go at 219 // the end, everything else goes before the implicit regs. 220 // 221 // FIXME: Allow mixed explicit and implicit operands on inline asm. 222 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as 223 // implicit-defs, but they must not be moved around. See the FIXME in 224 // InstrEmitter.cpp. 225 unsigned OpNo = getNumOperands(); 226 bool isImpReg = Op.isReg() && Op.isImplicit(); 227 if (!isImpReg && !isInlineAsm()) { 228 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) { 229 --OpNo; 230 assert(!Operands[OpNo].isTied() && "Cannot move tied operands"); 231 } 232 } 233 234 #ifndef NDEBUG 235 bool isDebugOp = Op.getType() == MachineOperand::MO_Metadata || 236 Op.getType() == MachineOperand::MO_MCSymbol; 237 // OpNo now points as the desired insertion point. Unless this is a variadic 238 // instruction, only implicit regs are allowed beyond MCID->getNumOperands(). 239 // RegMask operands go between the explicit and implicit operands. 240 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() || 241 OpNo < MCID->getNumOperands() || isDebugOp) && 242 "Trying to add an operand to a machine instr that is already done!"); 243 #endif 244 245 MachineRegisterInfo *MRI = getRegInfo(); 246 247 // Determine if the Operands array needs to be reallocated. 248 // Save the old capacity and operand array. 249 OperandCapacity OldCap = CapOperands; 250 MachineOperand *OldOperands = Operands; 251 if (!OldOperands || OldCap.getSize() == getNumOperands()) { 252 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1); 253 Operands = MF.allocateOperandArray(CapOperands); 254 // Move the operands before the insertion point. 255 if (OpNo) 256 moveOperands(Operands, OldOperands, OpNo, MRI); 257 } 258 259 // Move the operands following the insertion point. 260 if (OpNo != NumOperands) 261 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo, 262 MRI); 263 ++NumOperands; 264 265 // Deallocate the old operand array. 266 if (OldOperands != Operands && OldOperands) 267 MF.deallocateOperandArray(OldCap, OldOperands); 268 269 // Copy Op into place. It still needs to be inserted into the MRI use lists. 270 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op); 271 NewMO->ParentMI = this; 272 273 // When adding a register operand, tell MRI about it. 274 if (NewMO->isReg()) { 275 // Ensure isOnRegUseList() returns false, regardless of Op's status. 276 NewMO->Contents.Reg.Prev = nullptr; 277 // Ignore existing ties. This is not a property that can be copied. 278 NewMO->TiedTo = 0; 279 // Add the new operand to MRI, but only for instructions in an MBB. 280 if (MRI) 281 MRI->addRegOperandToUseList(NewMO); 282 // The MCID operand information isn't accurate until we start adding 283 // explicit operands. The implicit operands are added first, then the 284 // explicits are inserted before them. 285 if (!isImpReg) { 286 // Tie uses to defs as indicated in MCInstrDesc. 287 if (NewMO->isUse()) { 288 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO); 289 if (DefIdx != -1) 290 tieOperands(DefIdx, OpNo); 291 } 292 // If the register operand is flagged as early, mark the operand as such. 293 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1) 294 NewMO->setIsEarlyClobber(true); 295 } 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::eraseFromParentAndMarkDBGValuesForRemoval() { 682 assert(getParent() && "Not embedded in a basic block!"); 683 MachineBasicBlock *MBB = getParent(); 684 MachineFunction *MF = MBB->getParent(); 685 assert(MF && "Not embedded in a function!"); 686 687 MachineInstr *MI = (MachineInstr *)this; 688 MachineRegisterInfo &MRI = MF->getRegInfo(); 689 690 for (const MachineOperand &MO : MI->operands()) { 691 if (!MO.isReg() || !MO.isDef()) 692 continue; 693 Register Reg = MO.getReg(); 694 if (!Reg.isVirtual()) 695 continue; 696 MRI.markUsesInDebugValueAsUndef(Reg); 697 } 698 MI->eraseFromParent(); 699 } 700 701 void MachineInstr::eraseFromBundle() { 702 assert(getParent() && "Not embedded in a basic block!"); 703 getParent()->erase_instr(this); 704 } 705 706 bool MachineInstr::isCandidateForCallSiteEntry(QueryType Type) const { 707 if (!isCall(Type)) 708 return false; 709 switch (getOpcode()) { 710 case TargetOpcode::PATCHABLE_EVENT_CALL: 711 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL: 712 case TargetOpcode::PATCHPOINT: 713 case TargetOpcode::STACKMAP: 714 case TargetOpcode::STATEPOINT: 715 return false; 716 } 717 return true; 718 } 719 720 bool MachineInstr::shouldUpdateCallSiteInfo() const { 721 if (isBundle()) 722 return isCandidateForCallSiteEntry(MachineInstr::AnyInBundle); 723 return isCandidateForCallSiteEntry(); 724 } 725 726 unsigned MachineInstr::getNumExplicitOperands() const { 727 unsigned NumOperands = MCID->getNumOperands(); 728 if (!MCID->isVariadic()) 729 return NumOperands; 730 731 for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) { 732 const MachineOperand &MO = getOperand(I); 733 // The operands must always be in the following order: 734 // - explicit reg defs, 735 // - other explicit operands (reg uses, immediates, etc.), 736 // - implicit reg defs 737 // - implicit reg uses 738 if (MO.isReg() && MO.isImplicit()) 739 break; 740 ++NumOperands; 741 } 742 return NumOperands; 743 } 744 745 unsigned MachineInstr::getNumExplicitDefs() const { 746 unsigned NumDefs = MCID->getNumDefs(); 747 if (!MCID->isVariadic()) 748 return NumDefs; 749 750 for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) { 751 const MachineOperand &MO = getOperand(I); 752 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 753 break; 754 ++NumDefs; 755 } 756 return NumDefs; 757 } 758 759 void MachineInstr::bundleWithPred() { 760 assert(!isBundledWithPred() && "MI is already bundled with its predecessor"); 761 setFlag(BundledPred); 762 MachineBasicBlock::instr_iterator Pred = getIterator(); 763 --Pred; 764 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 765 Pred->setFlag(BundledSucc); 766 } 767 768 void MachineInstr::bundleWithSucc() { 769 assert(!isBundledWithSucc() && "MI is already bundled with its successor"); 770 setFlag(BundledSucc); 771 MachineBasicBlock::instr_iterator Succ = getIterator(); 772 ++Succ; 773 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags"); 774 Succ->setFlag(BundledPred); 775 } 776 777 void MachineInstr::unbundleFromPred() { 778 assert(isBundledWithPred() && "MI isn't bundled with its predecessor"); 779 clearFlag(BundledPred); 780 MachineBasicBlock::instr_iterator Pred = getIterator(); 781 --Pred; 782 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 783 Pred->clearFlag(BundledSucc); 784 } 785 786 void MachineInstr::unbundleFromSucc() { 787 assert(isBundledWithSucc() && "MI isn't bundled with its successor"); 788 clearFlag(BundledSucc); 789 MachineBasicBlock::instr_iterator Succ = getIterator(); 790 ++Succ; 791 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags"); 792 Succ->clearFlag(BundledPred); 793 } 794 795 bool MachineInstr::isStackAligningInlineAsm() const { 796 if (isInlineAsm()) { 797 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 798 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 799 return true; 800 } 801 return false; 802 } 803 804 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const { 805 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"); 806 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 807 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0); 808 } 809 810 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx, 811 unsigned *GroupNo) const { 812 assert(isInlineAsm() && "Expected an inline asm instruction"); 813 assert(OpIdx < getNumOperands() && "OpIdx out of range"); 814 815 // Ignore queries about the initial operands. 816 if (OpIdx < InlineAsm::MIOp_FirstOperand) 817 return -1; 818 819 unsigned Group = 0; 820 unsigned NumOps; 821 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 822 i += NumOps) { 823 const MachineOperand &FlagMO = getOperand(i); 824 // If we reach the implicit register operands, stop looking. 825 if (!FlagMO.isImm()) 826 return -1; 827 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 828 if (i + NumOps > OpIdx) { 829 if (GroupNo) 830 *GroupNo = Group; 831 return i; 832 } 833 ++Group; 834 } 835 return -1; 836 } 837 838 const DILabel *MachineInstr::getDebugLabel() const { 839 assert(isDebugLabel() && "not a DBG_LABEL"); 840 return cast<DILabel>(getOperand(0).getMetadata()); 841 } 842 843 const MachineOperand &MachineInstr::getDebugVariableOp() const { 844 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE"); 845 return getOperand(2); 846 } 847 848 MachineOperand &MachineInstr::getDebugVariableOp() { 849 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE"); 850 return getOperand(2); 851 } 852 853 const DILocalVariable *MachineInstr::getDebugVariable() const { 854 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE"); 855 return cast<DILocalVariable>(getOperand(2).getMetadata()); 856 } 857 858 MachineOperand &MachineInstr::getDebugExpressionOp() { 859 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE"); 860 return getOperand(3); 861 } 862 863 const DIExpression *MachineInstr::getDebugExpression() const { 864 assert((isDebugValue() || isDebugRef()) && "not a DBG_VALUE"); 865 return cast<DIExpression>(getOperand(3).getMetadata()); 866 } 867 868 bool MachineInstr::isDebugEntryValue() const { 869 return isDebugValue() && getDebugExpression()->isEntryValue(); 870 } 871 872 const TargetRegisterClass* 873 MachineInstr::getRegClassConstraint(unsigned OpIdx, 874 const TargetInstrInfo *TII, 875 const TargetRegisterInfo *TRI) const { 876 assert(getParent() && "Can't have an MBB reference here!"); 877 assert(getMF() && "Can't have an MF reference here!"); 878 const MachineFunction &MF = *getMF(); 879 880 // Most opcodes have fixed constraints in their MCInstrDesc. 881 if (!isInlineAsm()) 882 return TII->getRegClass(getDesc(), OpIdx, TRI, MF); 883 884 if (!getOperand(OpIdx).isReg()) 885 return nullptr; 886 887 // For tied uses on inline asm, get the constraint from the def. 888 unsigned DefIdx; 889 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx)) 890 OpIdx = DefIdx; 891 892 // Inline asm stores register class constraints in the flag word. 893 int FlagIdx = findInlineAsmFlagIdx(OpIdx); 894 if (FlagIdx < 0) 895 return nullptr; 896 897 unsigned Flag = getOperand(FlagIdx).getImm(); 898 unsigned RCID; 899 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse || 900 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef || 901 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) && 902 InlineAsm::hasRegClassConstraint(Flag, RCID)) 903 return TRI->getRegClass(RCID); 904 905 // Assume that all registers in a memory operand are pointers. 906 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem) 907 return TRI->getPointerRegClass(MF); 908 909 return nullptr; 910 } 911 912 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg( 913 Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, 914 const TargetRegisterInfo *TRI, bool ExploreBundle) const { 915 // Check every operands inside the bundle if we have 916 // been asked to. 917 if (ExploreBundle) 918 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC; 919 ++OpndIt) 920 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl( 921 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI); 922 else 923 // Otherwise, just check the current operands. 924 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i) 925 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI); 926 return CurRC; 927 } 928 929 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl( 930 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC, 931 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 932 assert(CurRC && "Invalid initial register class"); 933 // Check if Reg is constrained by some of its use/def from MI. 934 const MachineOperand &MO = getOperand(OpIdx); 935 if (!MO.isReg() || MO.getReg() != Reg) 936 return CurRC; 937 // If yes, accumulate the constraints through the operand. 938 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI); 939 } 940 941 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect( 942 unsigned OpIdx, const TargetRegisterClass *CurRC, 943 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 944 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI); 945 const MachineOperand &MO = getOperand(OpIdx); 946 assert(MO.isReg() && 947 "Cannot get register constraints for non-register operand"); 948 assert(CurRC && "Invalid initial register class"); 949 if (unsigned SubIdx = MO.getSubReg()) { 950 if (OpRC) 951 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx); 952 else 953 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx); 954 } else if (OpRC) 955 CurRC = TRI->getCommonSubClass(CurRC, OpRC); 956 return CurRC; 957 } 958 959 /// Return the number of instructions inside the MI bundle, not counting the 960 /// header instruction. 961 unsigned MachineInstr::getBundleSize() const { 962 MachineBasicBlock::const_instr_iterator I = getIterator(); 963 unsigned Size = 0; 964 while (I->isBundledWithSucc()) { 965 ++Size; 966 ++I; 967 } 968 return Size; 969 } 970 971 /// Returns true if the MachineInstr has an implicit-use operand of exactly 972 /// the given register (not considering sub/super-registers). 973 bool MachineInstr::hasRegisterImplicitUseOperand(Register Reg) const { 974 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 975 const MachineOperand &MO = getOperand(i); 976 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg) 977 return true; 978 } 979 return false; 980 } 981 982 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of 983 /// the specific register or -1 if it is not found. It further tightens 984 /// the search criteria to a use that kills the register if isKill is true. 985 int MachineInstr::findRegisterUseOperandIdx( 986 Register Reg, bool isKill, const TargetRegisterInfo *TRI) const { 987 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 988 const MachineOperand &MO = getOperand(i); 989 if (!MO.isReg() || !MO.isUse()) 990 continue; 991 Register MOReg = MO.getReg(); 992 if (!MOReg) 993 continue; 994 if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg))) 995 if (!isKill || MO.isKill()) 996 return i; 997 } 998 return -1; 999 } 1000 1001 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes) 1002 /// indicating if this instruction reads or writes Reg. This also considers 1003 /// partial defines. 1004 std::pair<bool,bool> 1005 MachineInstr::readsWritesVirtualRegister(Register Reg, 1006 SmallVectorImpl<unsigned> *Ops) const { 1007 bool PartDef = false; // Partial redefine. 1008 bool FullDef = false; // Full define. 1009 bool Use = false; 1010 1011 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1012 const MachineOperand &MO = getOperand(i); 1013 if (!MO.isReg() || MO.getReg() != Reg) 1014 continue; 1015 if (Ops) 1016 Ops->push_back(i); 1017 if (MO.isUse()) 1018 Use |= !MO.isUndef(); 1019 else if (MO.getSubReg() && !MO.isUndef()) 1020 // A partial def undef doesn't count as reading the register. 1021 PartDef = true; 1022 else 1023 FullDef = true; 1024 } 1025 // A partial redefine uses Reg unless there is also a full define. 1026 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef); 1027 } 1028 1029 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of 1030 /// the specified register or -1 if it is not found. If isDead is true, defs 1031 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it 1032 /// also checks if there is a def of a super-register. 1033 int 1034 MachineInstr::findRegisterDefOperandIdx(Register Reg, bool isDead, bool Overlap, 1035 const TargetRegisterInfo *TRI) const { 1036 bool isPhys = Register::isPhysicalRegister(Reg); 1037 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1038 const MachineOperand &MO = getOperand(i); 1039 // Accept regmask operands when Overlap is set. 1040 // Ignore them when looking for a specific def operand (Overlap == false). 1041 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg)) 1042 return i; 1043 if (!MO.isReg() || !MO.isDef()) 1044 continue; 1045 Register MOReg = MO.getReg(); 1046 bool Found = (MOReg == Reg); 1047 if (!Found && TRI && isPhys && Register::isPhysicalRegister(MOReg)) { 1048 if (Overlap) 1049 Found = TRI->regsOverlap(MOReg, Reg); 1050 else 1051 Found = TRI->isSubRegister(MOReg, Reg); 1052 } 1053 if (Found && (!isDead || MO.isDead())) 1054 return i; 1055 } 1056 return -1; 1057 } 1058 1059 /// findFirstPredOperandIdx() - Find the index of the first operand in the 1060 /// operand list that is used to represent the predicate. It returns -1 if 1061 /// none is found. 1062 int MachineInstr::findFirstPredOperandIdx() const { 1063 // Don't call MCID.findFirstPredOperandIdx() because this variant 1064 // is sometimes called on an instruction that's not yet complete, and 1065 // so the number of operands is less than the MCID indicates. In 1066 // particular, the PTX target does this. 1067 const MCInstrDesc &MCID = getDesc(); 1068 if (MCID.isPredicable()) { 1069 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1070 if (MCID.OpInfo[i].isPredicate()) 1071 return i; 1072 } 1073 1074 return -1; 1075 } 1076 1077 // MachineOperand::TiedTo is 4 bits wide. 1078 const unsigned TiedMax = 15; 1079 1080 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other. 1081 /// 1082 /// Use and def operands can be tied together, indicated by a non-zero TiedTo 1083 /// field. TiedTo can have these values: 1084 /// 1085 /// 0: Operand is not tied to anything. 1086 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1). 1087 /// TiedMax: Tied to an operand >= TiedMax-1. 1088 /// 1089 /// The tied def must be one of the first TiedMax operands on a normal 1090 /// instruction. INLINEASM instructions allow more tied defs. 1091 /// 1092 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) { 1093 MachineOperand &DefMO = getOperand(DefIdx); 1094 MachineOperand &UseMO = getOperand(UseIdx); 1095 assert(DefMO.isDef() && "DefIdx must be a def operand"); 1096 assert(UseMO.isUse() && "UseIdx must be a use operand"); 1097 assert(!DefMO.isTied() && "Def is already tied to another use"); 1098 assert(!UseMO.isTied() && "Use is already tied to another def"); 1099 1100 if (DefIdx < TiedMax) 1101 UseMO.TiedTo = DefIdx + 1; 1102 else { 1103 // Inline asm can use the group descriptors to find tied operands, but on 1104 // normal instruction, the tied def must be within the first TiedMax 1105 // operands. 1106 assert(isInlineAsm() && "DefIdx out of range"); 1107 UseMO.TiedTo = TiedMax; 1108 } 1109 1110 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx(). 1111 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax); 1112 } 1113 1114 /// Given the index of a tied register operand, find the operand it is tied to. 1115 /// Defs are tied to uses and vice versa. Returns the index of the tied operand 1116 /// which must exist. 1117 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const { 1118 const MachineOperand &MO = getOperand(OpIdx); 1119 assert(MO.isTied() && "Operand isn't tied"); 1120 1121 // Normally TiedTo is in range. 1122 if (MO.TiedTo < TiedMax) 1123 return MO.TiedTo - 1; 1124 1125 // Uses on normal instructions can be out of range. 1126 if (!isInlineAsm()) { 1127 // Normal tied defs must be in the 0..TiedMax-1 range. 1128 if (MO.isUse()) 1129 return TiedMax - 1; 1130 // MO is a def. Search for the tied use. 1131 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) { 1132 const MachineOperand &UseMO = getOperand(i); 1133 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1) 1134 return i; 1135 } 1136 llvm_unreachable("Can't find tied use"); 1137 } 1138 1139 // Now deal with inline asm by parsing the operand group descriptor flags. 1140 // Find the beginning of each operand group. 1141 SmallVector<unsigned, 8> GroupIdx; 1142 unsigned OpIdxGroup = ~0u; 1143 unsigned NumOps; 1144 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 1145 i += NumOps) { 1146 const MachineOperand &FlagMO = getOperand(i); 1147 assert(FlagMO.isImm() && "Invalid tied operand on inline asm"); 1148 unsigned CurGroup = GroupIdx.size(); 1149 GroupIdx.push_back(i); 1150 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 1151 // OpIdx belongs to this operand group. 1152 if (OpIdx > i && OpIdx < i + NumOps) 1153 OpIdxGroup = CurGroup; 1154 unsigned TiedGroup; 1155 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup)) 1156 continue; 1157 // Operands in this group are tied to operands in TiedGroup which must be 1158 // earlier. Find the number of operands between the two groups. 1159 unsigned Delta = i - GroupIdx[TiedGroup]; 1160 1161 // OpIdx is a use tied to TiedGroup. 1162 if (OpIdxGroup == CurGroup) 1163 return OpIdx - Delta; 1164 1165 // OpIdx is a def tied to this use group. 1166 if (OpIdxGroup == TiedGroup) 1167 return OpIdx + Delta; 1168 } 1169 llvm_unreachable("Invalid tied operand on inline asm"); 1170 } 1171 1172 /// clearKillInfo - Clears kill flags on all operands. 1173 /// 1174 void MachineInstr::clearKillInfo() { 1175 for (MachineOperand &MO : operands()) { 1176 if (MO.isReg() && MO.isUse()) 1177 MO.setIsKill(false); 1178 } 1179 } 1180 1181 void MachineInstr::substituteRegister(Register FromReg, Register ToReg, 1182 unsigned SubIdx, 1183 const TargetRegisterInfo &RegInfo) { 1184 if (Register::isPhysicalRegister(ToReg)) { 1185 if (SubIdx) 1186 ToReg = RegInfo.getSubReg(ToReg, SubIdx); 1187 for (MachineOperand &MO : operands()) { 1188 if (!MO.isReg() || MO.getReg() != FromReg) 1189 continue; 1190 MO.substPhysReg(ToReg, RegInfo); 1191 } 1192 } else { 1193 for (MachineOperand &MO : operands()) { 1194 if (!MO.isReg() || MO.getReg() != FromReg) 1195 continue; 1196 MO.substVirtReg(ToReg, SubIdx, RegInfo); 1197 } 1198 } 1199 } 1200 1201 /// isSafeToMove - Return true if it is safe to move this instruction. If 1202 /// SawStore is set to true, it means that there is a store (or call) between 1203 /// the instruction's location and its intended destination. 1204 bool MachineInstr::isSafeToMove(AAResults *AA, bool &SawStore) const { 1205 // Ignore stuff that we obviously can't move. 1206 // 1207 // Treat volatile loads as stores. This is not strictly necessary for 1208 // volatiles, but it is required for atomic loads. It is not allowed to move 1209 // a load across an atomic load with Ordering > Monotonic. 1210 if (mayStore() || isCall() || isPHI() || 1211 (mayLoad() && hasOrderedMemoryRef())) { 1212 SawStore = true; 1213 return false; 1214 } 1215 1216 if (isPosition() || isDebugInstr() || isTerminator() || 1217 mayRaiseFPException() || hasUnmodeledSideEffects()) 1218 return false; 1219 1220 // See if this instruction does a load. If so, we have to guarantee that the 1221 // loaded value doesn't change between the load and the its intended 1222 // destination. The check for isInvariantLoad gives the target the chance to 1223 // classify the load as always returning a constant, e.g. a constant pool 1224 // load. 1225 if (mayLoad() && !isDereferenceableInvariantLoad(AA)) 1226 // Otherwise, this is a real load. If there is a store between the load and 1227 // end of block, we can't move it. 1228 return !SawStore; 1229 1230 return true; 1231 } 1232 1233 bool MachineInstr::mayAlias(AAResults *AA, const MachineInstr &Other, 1234 bool UseTBAA) const { 1235 const MachineFunction *MF = getMF(); 1236 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1237 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1238 1239 // Execulde call instruction which may alter the memory but can not be handled 1240 // by this function. 1241 if (isCall() || Other.isCall()) 1242 return true; 1243 1244 // If neither instruction stores to memory, they can't alias in any 1245 // meaningful way, even if they read from the same address. 1246 if (!mayStore() && !Other.mayStore()) 1247 return false; 1248 1249 // Both instructions must be memory operations to be able to alias. 1250 if (!mayLoadOrStore() || !Other.mayLoadOrStore()) 1251 return false; 1252 1253 // Let the target decide if memory accesses cannot possibly overlap. 1254 if (TII->areMemAccessesTriviallyDisjoint(*this, Other)) 1255 return false; 1256 1257 // FIXME: Need to handle multiple memory operands to support all targets. 1258 if (!hasOneMemOperand() || !Other.hasOneMemOperand()) 1259 return true; 1260 1261 MachineMemOperand *MMOa = *memoperands_begin(); 1262 MachineMemOperand *MMOb = *Other.memoperands_begin(); 1263 1264 // The following interface to AA is fashioned after DAGCombiner::isAlias 1265 // and operates with MachineMemOperand offset with some important 1266 // assumptions: 1267 // - LLVM fundamentally assumes flat address spaces. 1268 // - MachineOperand offset can *only* result from legalization and 1269 // cannot affect queries other than the trivial case of overlap 1270 // checking. 1271 // - These offsets never wrap and never step outside 1272 // of allocated objects. 1273 // - There should never be any negative offsets here. 1274 // 1275 // FIXME: Modify API to hide this math from "user" 1276 // Even before we go to AA we can reason locally about some 1277 // memory objects. It can save compile time, and possibly catch some 1278 // corner cases not currently covered. 1279 1280 int64_t OffsetA = MMOa->getOffset(); 1281 int64_t OffsetB = MMOb->getOffset(); 1282 int64_t MinOffset = std::min(OffsetA, OffsetB); 1283 1284 uint64_t WidthA = MMOa->getSize(); 1285 uint64_t WidthB = MMOb->getSize(); 1286 bool KnownWidthA = WidthA != MemoryLocation::UnknownSize; 1287 bool KnownWidthB = WidthB != MemoryLocation::UnknownSize; 1288 1289 const Value *ValA = MMOa->getValue(); 1290 const Value *ValB = MMOb->getValue(); 1291 bool SameVal = (ValA && ValB && (ValA == ValB)); 1292 if (!SameVal) { 1293 const PseudoSourceValue *PSVa = MMOa->getPseudoValue(); 1294 const PseudoSourceValue *PSVb = MMOb->getPseudoValue(); 1295 if (PSVa && ValB && !PSVa->mayAlias(&MFI)) 1296 return false; 1297 if (PSVb && ValA && !PSVb->mayAlias(&MFI)) 1298 return false; 1299 if (PSVa && PSVb && (PSVa == PSVb)) 1300 SameVal = true; 1301 } 1302 1303 if (SameVal) { 1304 if (!KnownWidthA || !KnownWidthB) 1305 return true; 1306 int64_t MaxOffset = std::max(OffsetA, OffsetB); 1307 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB; 1308 return (MinOffset + LowWidth > MaxOffset); 1309 } 1310 1311 if (!AA) 1312 return true; 1313 1314 if (!ValA || !ValB) 1315 return true; 1316 1317 assert((OffsetA >= 0) && "Negative MachineMemOperand offset"); 1318 assert((OffsetB >= 0) && "Negative MachineMemOperand offset"); 1319 1320 int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset 1321 : MemoryLocation::UnknownSize; 1322 int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset 1323 : MemoryLocation::UnknownSize; 1324 1325 AliasResult AAResult = AA->alias( 1326 MemoryLocation(ValA, OverlapA, 1327 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()), 1328 MemoryLocation(ValB, OverlapB, 1329 UseTBAA ? MMOb->getAAInfo() : AAMDNodes())); 1330 1331 return (AAResult != NoAlias); 1332 } 1333 1334 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered 1335 /// or volatile memory reference, or if the information describing the memory 1336 /// reference is not available. Return false if it is known to have no ordered 1337 /// memory references. 1338 bool MachineInstr::hasOrderedMemoryRef() const { 1339 // An instruction known never to access memory won't have a volatile access. 1340 if (!mayStore() && 1341 !mayLoad() && 1342 !isCall() && 1343 !hasUnmodeledSideEffects()) 1344 return false; 1345 1346 // Otherwise, if the instruction has no memory reference information, 1347 // conservatively assume it wasn't preserved. 1348 if (memoperands_empty()) 1349 return true; 1350 1351 // Check if any of our memory operands are ordered. 1352 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) { 1353 return !MMO->isUnordered(); 1354 }); 1355 } 1356 1357 /// isDereferenceableInvariantLoad - Return true if this instruction will never 1358 /// trap and is loading from a location whose value is invariant across a run of 1359 /// this function. 1360 bool MachineInstr::isDereferenceableInvariantLoad(AAResults *AA) const { 1361 // If the instruction doesn't load at all, it isn't an invariant load. 1362 if (!mayLoad()) 1363 return false; 1364 1365 // If the instruction has lost its memoperands, conservatively assume that 1366 // it may not be an invariant load. 1367 if (memoperands_empty()) 1368 return false; 1369 1370 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo(); 1371 1372 for (MachineMemOperand *MMO : memoperands()) { 1373 if (!MMO->isUnordered()) 1374 // If the memory operand has ordering side effects, we can't move the 1375 // instruction. Such an instruction is technically an invariant load, 1376 // but the caller code would need updated to expect that. 1377 return false; 1378 if (MMO->isStore()) return false; 1379 if (MMO->isInvariant() && MMO->isDereferenceable()) 1380 continue; 1381 1382 // A load from a constant PseudoSourceValue is invariant. 1383 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) 1384 if (PSV->isConstant(&MFI)) 1385 continue; 1386 1387 if (const Value *V = MMO->getValue()) { 1388 // If we have an AliasAnalysis, ask it whether the memory is constant. 1389 if (AA && 1390 AA->pointsToConstantMemory( 1391 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo()))) 1392 continue; 1393 } 1394 1395 // Otherwise assume conservatively. 1396 return false; 1397 } 1398 1399 // Everything checks out. 1400 return true; 1401 } 1402 1403 /// isConstantValuePHI - If the specified instruction is a PHI that always 1404 /// merges together the same virtual register, return the register, otherwise 1405 /// return 0. 1406 unsigned MachineInstr::isConstantValuePHI() const { 1407 if (!isPHI()) 1408 return 0; 1409 assert(getNumOperands() >= 3 && 1410 "It's illegal to have a PHI without source operands"); 1411 1412 Register Reg = getOperand(1).getReg(); 1413 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2) 1414 if (getOperand(i).getReg() != Reg) 1415 return 0; 1416 return Reg; 1417 } 1418 1419 bool MachineInstr::hasUnmodeledSideEffects() const { 1420 if (hasProperty(MCID::UnmodeledSideEffects)) 1421 return true; 1422 if (isInlineAsm()) { 1423 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1424 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1425 return true; 1426 } 1427 1428 return false; 1429 } 1430 1431 bool MachineInstr::isLoadFoldBarrier() const { 1432 return mayStore() || isCall() || hasUnmodeledSideEffects(); 1433 } 1434 1435 /// allDefsAreDead - Return true if all the defs of this instruction are dead. 1436 /// 1437 bool MachineInstr::allDefsAreDead() const { 1438 for (const MachineOperand &MO : operands()) { 1439 if (!MO.isReg() || MO.isUse()) 1440 continue; 1441 if (!MO.isDead()) 1442 return false; 1443 } 1444 return true; 1445 } 1446 1447 /// copyImplicitOps - Copy implicit register operands from specified 1448 /// instruction to this instruction. 1449 void MachineInstr::copyImplicitOps(MachineFunction &MF, 1450 const MachineInstr &MI) { 1451 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands(); 1452 i != e; ++i) { 1453 const MachineOperand &MO = MI.getOperand(i); 1454 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask()) 1455 addOperand(MF, MO); 1456 } 1457 } 1458 1459 bool MachineInstr::hasComplexRegisterTies() const { 1460 const MCInstrDesc &MCID = getDesc(); 1461 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 1462 const auto &Operand = getOperand(I); 1463 if (!Operand.isReg() || Operand.isDef()) 1464 // Ignore the defined registers as MCID marks only the uses as tied. 1465 continue; 1466 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 1467 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1; 1468 if (ExpectedTiedIdx != TiedIdx) 1469 return true; 1470 } 1471 return false; 1472 } 1473 1474 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1475 const MachineRegisterInfo &MRI) const { 1476 const MachineOperand &Op = getOperand(OpIdx); 1477 if (!Op.isReg()) 1478 return LLT{}; 1479 1480 if (isVariadic() || OpIdx >= getNumExplicitOperands()) 1481 return MRI.getType(Op.getReg()); 1482 1483 auto &OpInfo = getDesc().OpInfo[OpIdx]; 1484 if (!OpInfo.isGenericType()) 1485 return MRI.getType(Op.getReg()); 1486 1487 if (PrintedTypes[OpInfo.getGenericTypeIndex()]) 1488 return LLT{}; 1489 1490 LLT TypeToPrint = MRI.getType(Op.getReg()); 1491 // Don't mark the type index printed if it wasn't actually printed: maybe 1492 // another operand with the same type index has an actual type attached: 1493 if (TypeToPrint.isValid()) 1494 PrintedTypes.set(OpInfo.getGenericTypeIndex()); 1495 return TypeToPrint; 1496 } 1497 1498 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1499 LLVM_DUMP_METHOD void MachineInstr::dump() const { 1500 dbgs() << " "; 1501 print(dbgs()); 1502 } 1503 1504 LLVM_DUMP_METHOD void MachineInstr::dumprImpl( 1505 const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth, 1506 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const { 1507 if (Depth >= MaxDepth) 1508 return; 1509 if (!AlreadySeenInstrs.insert(this).second) 1510 return; 1511 // PadToColumn always inserts at least one space. 1512 // Don't mess up the alignment if we don't want any space. 1513 if (Depth) 1514 fdbgs().PadToColumn(Depth * 2); 1515 print(fdbgs()); 1516 for (const MachineOperand &MO : operands()) { 1517 if (!MO.isReg() || MO.isDef()) 1518 continue; 1519 Register Reg = MO.getReg(); 1520 if (Reg.isPhysical()) 1521 continue; 1522 const MachineInstr *NewMI = MRI.getUniqueVRegDef(Reg); 1523 if (NewMI == nullptr) 1524 continue; 1525 NewMI->dumprImpl(MRI, Depth + 1, MaxDepth, AlreadySeenInstrs); 1526 } 1527 } 1528 1529 LLVM_DUMP_METHOD void MachineInstr::dumpr(const MachineRegisterInfo &MRI, 1530 unsigned MaxDepth) const { 1531 SmallPtrSet<const MachineInstr *, 16> AlreadySeenInstrs; 1532 dumprImpl(MRI, 0, MaxDepth, AlreadySeenInstrs); 1533 } 1534 #endif 1535 1536 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers, 1537 bool SkipDebugLoc, bool AddNewLine, 1538 const TargetInstrInfo *TII) const { 1539 const Module *M = nullptr; 1540 const Function *F = nullptr; 1541 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1542 F = &MF->getFunction(); 1543 M = F->getParent(); 1544 if (!TII) 1545 TII = MF->getSubtarget().getInstrInfo(); 1546 } 1547 1548 ModuleSlotTracker MST(M); 1549 if (F) 1550 MST.incorporateFunction(*F); 1551 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, AddNewLine, TII); 1552 } 1553 1554 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST, 1555 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc, 1556 bool AddNewLine, const TargetInstrInfo *TII) const { 1557 // We can be a bit tidier if we know the MachineFunction. 1558 const TargetRegisterInfo *TRI = nullptr; 1559 const MachineRegisterInfo *MRI = nullptr; 1560 const TargetIntrinsicInfo *IntrinsicInfo = nullptr; 1561 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII); 1562 1563 if (isCFIInstruction()) 1564 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 1565 1566 SmallBitVector PrintedTypes(8); 1567 bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies(); 1568 auto getTiedOperandIdx = [&](unsigned OpIdx) { 1569 if (!ShouldPrintRegisterTies) 1570 return 0U; 1571 const MachineOperand &MO = getOperand(OpIdx); 1572 if (MO.isReg() && MO.isTied() && !MO.isDef()) 1573 return findTiedOperandIdx(OpIdx); 1574 return 0U; 1575 }; 1576 unsigned StartOp = 0; 1577 unsigned e = getNumOperands(); 1578 1579 // Print explicitly defined operands on the left of an assignment syntax. 1580 while (StartOp < e) { 1581 const MachineOperand &MO = getOperand(StartOp); 1582 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 1583 break; 1584 1585 if (StartOp != 0) 1586 OS << ", "; 1587 1588 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{}; 1589 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp); 1590 MO.print(OS, MST, TypeToPrint, StartOp, /*PrintDef=*/false, IsStandalone, 1591 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1592 ++StartOp; 1593 } 1594 1595 if (StartOp != 0) 1596 OS << " = "; 1597 1598 if (getFlag(MachineInstr::FrameSetup)) 1599 OS << "frame-setup "; 1600 if (getFlag(MachineInstr::FrameDestroy)) 1601 OS << "frame-destroy "; 1602 if (getFlag(MachineInstr::FmNoNans)) 1603 OS << "nnan "; 1604 if (getFlag(MachineInstr::FmNoInfs)) 1605 OS << "ninf "; 1606 if (getFlag(MachineInstr::FmNsz)) 1607 OS << "nsz "; 1608 if (getFlag(MachineInstr::FmArcp)) 1609 OS << "arcp "; 1610 if (getFlag(MachineInstr::FmContract)) 1611 OS << "contract "; 1612 if (getFlag(MachineInstr::FmAfn)) 1613 OS << "afn "; 1614 if (getFlag(MachineInstr::FmReassoc)) 1615 OS << "reassoc "; 1616 if (getFlag(MachineInstr::NoUWrap)) 1617 OS << "nuw "; 1618 if (getFlag(MachineInstr::NoSWrap)) 1619 OS << "nsw "; 1620 if (getFlag(MachineInstr::IsExact)) 1621 OS << "exact "; 1622 if (getFlag(MachineInstr::NoFPExcept)) 1623 OS << "nofpexcept "; 1624 if (getFlag(MachineInstr::NoMerge)) 1625 OS << "nomerge "; 1626 1627 // Print the opcode name. 1628 if (TII) 1629 OS << TII->getName(getOpcode()); 1630 else 1631 OS << "UNKNOWN"; 1632 1633 if (SkipOpers) 1634 return; 1635 1636 // Print the rest of the operands. 1637 bool FirstOp = true; 1638 unsigned AsmDescOp = ~0u; 1639 unsigned AsmOpCount = 0; 1640 1641 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) { 1642 // Print asm string. 1643 OS << " "; 1644 const unsigned OpIdx = InlineAsm::MIOp_AsmString; 1645 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{}; 1646 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx); 1647 getOperand(OpIdx).print(OS, MST, TypeToPrint, OpIdx, /*PrintDef=*/true, IsStandalone, 1648 ShouldPrintRegisterTies, TiedOperandIdx, TRI, 1649 IntrinsicInfo); 1650 1651 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack 1652 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1653 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1654 OS << " [sideeffect]"; 1655 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1656 OS << " [mayload]"; 1657 if (ExtraInfo & InlineAsm::Extra_MayStore) 1658 OS << " [maystore]"; 1659 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 1660 OS << " [isconvergent]"; 1661 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1662 OS << " [alignstack]"; 1663 if (getInlineAsmDialect() == InlineAsm::AD_ATT) 1664 OS << " [attdialect]"; 1665 if (getInlineAsmDialect() == InlineAsm::AD_Intel) 1666 OS << " [inteldialect]"; 1667 1668 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand; 1669 FirstOp = false; 1670 } 1671 1672 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { 1673 const MachineOperand &MO = getOperand(i); 1674 1675 if (FirstOp) FirstOp = false; else OS << ","; 1676 OS << " "; 1677 1678 if (isDebugValue() && MO.isMetadata()) { 1679 // Pretty print DBG_VALUE instructions. 1680 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata()); 1681 if (DIV && !DIV->getName().empty()) 1682 OS << "!\"" << DIV->getName() << '\"'; 1683 else { 1684 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1685 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1686 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1687 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1688 } 1689 } else if (isDebugLabel() && MO.isMetadata()) { 1690 // Pretty print DBG_LABEL instructions. 1691 auto *DIL = dyn_cast<DILabel>(MO.getMetadata()); 1692 if (DIL && !DIL->getName().empty()) 1693 OS << "\"" << DIL->getName() << '\"'; 1694 else { 1695 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1696 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1697 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1698 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1699 } 1700 } else if (i == AsmDescOp && MO.isImm()) { 1701 // Pretty print the inline asm operand descriptor. 1702 OS << '$' << AsmOpCount++; 1703 unsigned Flag = MO.getImm(); 1704 OS << ":["; 1705 OS << InlineAsm::getKindName(InlineAsm::getKind(Flag)); 1706 1707 unsigned RCID = 0; 1708 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) && 1709 InlineAsm::hasRegClassConstraint(Flag, RCID)) { 1710 if (TRI) { 1711 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID)); 1712 } else 1713 OS << ":RC" << RCID; 1714 } 1715 1716 if (InlineAsm::isMemKind(Flag)) { 1717 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag); 1718 OS << ":" << InlineAsm::getMemConstraintName(MCID); 1719 } 1720 1721 unsigned TiedTo = 0; 1722 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo)) 1723 OS << " tiedto:$" << TiedTo; 1724 1725 OS << ']'; 1726 1727 // Compute the index of the next operand descriptor. 1728 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag); 1729 } else { 1730 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1731 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1732 if (MO.isImm() && isOperandSubregIdx(i)) 1733 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI); 1734 else 1735 MO.print(OS, MST, TypeToPrint, i, /*PrintDef=*/true, IsStandalone, 1736 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1737 } 1738 } 1739 1740 // Print any optional symbols attached to this instruction as-if they were 1741 // operands. 1742 if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) { 1743 if (!FirstOp) { 1744 FirstOp = false; 1745 OS << ','; 1746 } 1747 OS << " pre-instr-symbol "; 1748 MachineOperand::printSymbol(OS, *PreInstrSymbol); 1749 } 1750 if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) { 1751 if (!FirstOp) { 1752 FirstOp = false; 1753 OS << ','; 1754 } 1755 OS << " post-instr-symbol "; 1756 MachineOperand::printSymbol(OS, *PostInstrSymbol); 1757 } 1758 if (MDNode *HeapAllocMarker = getHeapAllocMarker()) { 1759 if (!FirstOp) { 1760 FirstOp = false; 1761 OS << ','; 1762 } 1763 OS << " heap-alloc-marker "; 1764 HeapAllocMarker->printAsOperand(OS, MST); 1765 } 1766 1767 if (DebugInstrNum) { 1768 if (!FirstOp) 1769 OS << ","; 1770 OS << " debug-instr-number " << DebugInstrNum; 1771 } 1772 1773 if (!SkipDebugLoc) { 1774 if (const DebugLoc &DL = getDebugLoc()) { 1775 if (!FirstOp) 1776 OS << ','; 1777 OS << " debug-location "; 1778 DL->printAsOperand(OS, MST); 1779 } 1780 } 1781 1782 if (!memoperands_empty()) { 1783 SmallVector<StringRef, 0> SSNs; 1784 const LLVMContext *Context = nullptr; 1785 std::unique_ptr<LLVMContext> CtxPtr; 1786 const MachineFrameInfo *MFI = nullptr; 1787 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1788 MFI = &MF->getFrameInfo(); 1789 Context = &MF->getFunction().getContext(); 1790 } else { 1791 CtxPtr = std::make_unique<LLVMContext>(); 1792 Context = CtxPtr.get(); 1793 } 1794 1795 OS << " :: "; 1796 bool NeedComma = false; 1797 for (const MachineMemOperand *Op : memoperands()) { 1798 if (NeedComma) 1799 OS << ", "; 1800 Op->print(OS, MST, SSNs, *Context, MFI, TII); 1801 NeedComma = true; 1802 } 1803 } 1804 1805 if (SkipDebugLoc) 1806 return; 1807 1808 bool HaveSemi = false; 1809 1810 // Print debug location information. 1811 if (const DebugLoc &DL = getDebugLoc()) { 1812 if (!HaveSemi) { 1813 OS << ';'; 1814 HaveSemi = true; 1815 } 1816 OS << ' '; 1817 DL.print(OS); 1818 } 1819 1820 // Print extra comments for DEBUG_VALUE. 1821 if (isDebugValue() && getDebugVariableOp().isMetadata()) { 1822 if (!HaveSemi) { 1823 OS << ";"; 1824 HaveSemi = true; 1825 } 1826 auto *DV = getDebugVariable(); 1827 OS << " line no:" << DV->getLine(); 1828 if (isIndirectDebugValue()) 1829 OS << " indirect"; 1830 } 1831 // TODO: DBG_LABEL 1832 1833 if (AddNewLine) 1834 OS << '\n'; 1835 } 1836 1837 bool MachineInstr::addRegisterKilled(Register IncomingReg, 1838 const TargetRegisterInfo *RegInfo, 1839 bool AddIfNotFound) { 1840 bool isPhysReg = Register::isPhysicalRegister(IncomingReg); 1841 bool hasAliases = isPhysReg && 1842 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid(); 1843 bool Found = false; 1844 SmallVector<unsigned,4> DeadOps; 1845 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1846 MachineOperand &MO = getOperand(i); 1847 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) 1848 continue; 1849 1850 // DEBUG_VALUE nodes do not contribute to code generation and should 1851 // always be ignored. Failure to do so may result in trying to modify 1852 // KILL flags on DEBUG_VALUE nodes. 1853 if (MO.isDebug()) 1854 continue; 1855 1856 Register Reg = MO.getReg(); 1857 if (!Reg) 1858 continue; 1859 1860 if (Reg == IncomingReg) { 1861 if (!Found) { 1862 if (MO.isKill()) 1863 // The register is already marked kill. 1864 return true; 1865 if (isPhysReg && isRegTiedToDefOperand(i)) 1866 // Two-address uses of physregs must not be marked kill. 1867 return true; 1868 MO.setIsKill(); 1869 Found = true; 1870 } 1871 } else if (hasAliases && MO.isKill() && Register::isPhysicalRegister(Reg)) { 1872 // A super-register kill already exists. 1873 if (RegInfo->isSuperRegister(IncomingReg, Reg)) 1874 return true; 1875 if (RegInfo->isSubRegister(IncomingReg, Reg)) 1876 DeadOps.push_back(i); 1877 } 1878 } 1879 1880 // Trim unneeded kill operands. 1881 while (!DeadOps.empty()) { 1882 unsigned OpIdx = DeadOps.back(); 1883 if (getOperand(OpIdx).isImplicit() && 1884 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1885 RemoveOperand(OpIdx); 1886 else 1887 getOperand(OpIdx).setIsKill(false); 1888 DeadOps.pop_back(); 1889 } 1890 1891 // If not found, this means an alias of one of the operands is killed. Add a 1892 // new implicit operand if required. 1893 if (!Found && AddIfNotFound) { 1894 addOperand(MachineOperand::CreateReg(IncomingReg, 1895 false /*IsDef*/, 1896 true /*IsImp*/, 1897 true /*IsKill*/)); 1898 return true; 1899 } 1900 return Found; 1901 } 1902 1903 void MachineInstr::clearRegisterKills(Register Reg, 1904 const TargetRegisterInfo *RegInfo) { 1905 if (!Register::isPhysicalRegister(Reg)) 1906 RegInfo = nullptr; 1907 for (MachineOperand &MO : operands()) { 1908 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 1909 continue; 1910 Register OpReg = MO.getReg(); 1911 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg) 1912 MO.setIsKill(false); 1913 } 1914 } 1915 1916 bool MachineInstr::addRegisterDead(Register Reg, 1917 const TargetRegisterInfo *RegInfo, 1918 bool AddIfNotFound) { 1919 bool isPhysReg = Register::isPhysicalRegister(Reg); 1920 bool hasAliases = isPhysReg && 1921 MCRegAliasIterator(Reg, RegInfo, false).isValid(); 1922 bool Found = false; 1923 SmallVector<unsigned,4> DeadOps; 1924 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1925 MachineOperand &MO = getOperand(i); 1926 if (!MO.isReg() || !MO.isDef()) 1927 continue; 1928 Register MOReg = MO.getReg(); 1929 if (!MOReg) 1930 continue; 1931 1932 if (MOReg == Reg) { 1933 MO.setIsDead(); 1934 Found = true; 1935 } else if (hasAliases && MO.isDead() && 1936 Register::isPhysicalRegister(MOReg)) { 1937 // There exists a super-register that's marked dead. 1938 if (RegInfo->isSuperRegister(Reg, MOReg)) 1939 return true; 1940 if (RegInfo->isSubRegister(Reg, MOReg)) 1941 DeadOps.push_back(i); 1942 } 1943 } 1944 1945 // Trim unneeded dead operands. 1946 while (!DeadOps.empty()) { 1947 unsigned OpIdx = DeadOps.back(); 1948 if (getOperand(OpIdx).isImplicit() && 1949 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1950 RemoveOperand(OpIdx); 1951 else 1952 getOperand(OpIdx).setIsDead(false); 1953 DeadOps.pop_back(); 1954 } 1955 1956 // If not found, this means an alias of one of the operands is dead. Add a 1957 // new implicit operand if required. 1958 if (Found || !AddIfNotFound) 1959 return Found; 1960 1961 addOperand(MachineOperand::CreateReg(Reg, 1962 true /*IsDef*/, 1963 true /*IsImp*/, 1964 false /*IsKill*/, 1965 true /*IsDead*/)); 1966 return true; 1967 } 1968 1969 void MachineInstr::clearRegisterDeads(Register Reg) { 1970 for (MachineOperand &MO : operands()) { 1971 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg) 1972 continue; 1973 MO.setIsDead(false); 1974 } 1975 } 1976 1977 void MachineInstr::setRegisterDefReadUndef(Register Reg, bool IsUndef) { 1978 for (MachineOperand &MO : operands()) { 1979 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0) 1980 continue; 1981 MO.setIsUndef(IsUndef); 1982 } 1983 } 1984 1985 void MachineInstr::addRegisterDefined(Register Reg, 1986 const TargetRegisterInfo *RegInfo) { 1987 if (Register::isPhysicalRegister(Reg)) { 1988 MachineOperand *MO = findRegisterDefOperand(Reg, false, false, RegInfo); 1989 if (MO) 1990 return; 1991 } else { 1992 for (const MachineOperand &MO : operands()) { 1993 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() && 1994 MO.getSubReg() == 0) 1995 return; 1996 } 1997 } 1998 addOperand(MachineOperand::CreateReg(Reg, 1999 true /*IsDef*/, 2000 true /*IsImp*/)); 2001 } 2002 2003 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs, 2004 const TargetRegisterInfo &TRI) { 2005 bool HasRegMask = false; 2006 for (MachineOperand &MO : operands()) { 2007 if (MO.isRegMask()) { 2008 HasRegMask = true; 2009 continue; 2010 } 2011 if (!MO.isReg() || !MO.isDef()) continue; 2012 Register Reg = MO.getReg(); 2013 if (!Reg.isPhysical()) 2014 continue; 2015 // If there are no uses, including partial uses, the def is dead. 2016 if (llvm::none_of(UsedRegs, 2017 [&](MCRegister Use) { return TRI.regsOverlap(Use, Reg); })) 2018 MO.setIsDead(); 2019 } 2020 2021 // This is a call with a register mask operand. 2022 // Mask clobbers are always dead, so add defs for the non-dead defines. 2023 if (HasRegMask) 2024 for (ArrayRef<Register>::iterator I = UsedRegs.begin(), E = UsedRegs.end(); 2025 I != E; ++I) 2026 addRegisterDefined(*I, &TRI); 2027 } 2028 2029 unsigned 2030 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) { 2031 // Build up a buffer of hash code components. 2032 SmallVector<size_t, 16> HashComponents; 2033 HashComponents.reserve(MI->getNumOperands() + 1); 2034 HashComponents.push_back(MI->getOpcode()); 2035 for (const MachineOperand &MO : MI->operands()) { 2036 if (MO.isReg() && MO.isDef() && Register::isVirtualRegister(MO.getReg())) 2037 continue; // Skip virtual register defs. 2038 2039 HashComponents.push_back(hash_value(MO)); 2040 } 2041 return hash_combine_range(HashComponents.begin(), HashComponents.end()); 2042 } 2043 2044 void MachineInstr::emitError(StringRef Msg) const { 2045 // Find the source location cookie. 2046 unsigned LocCookie = 0; 2047 const MDNode *LocMD = nullptr; 2048 for (unsigned i = getNumOperands(); i != 0; --i) { 2049 if (getOperand(i-1).isMetadata() && 2050 (LocMD = getOperand(i-1).getMetadata()) && 2051 LocMD->getNumOperands() != 0) { 2052 if (const ConstantInt *CI = 2053 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) { 2054 LocCookie = CI->getZExtValue(); 2055 break; 2056 } 2057 } 2058 } 2059 2060 if (const MachineBasicBlock *MBB = getParent()) 2061 if (const MachineFunction *MF = MBB->getParent()) 2062 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg); 2063 report_fatal_error(Msg); 2064 } 2065 2066 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2067 const MCInstrDesc &MCID, bool IsIndirect, 2068 Register Reg, const MDNode *Variable, 2069 const MDNode *Expr) { 2070 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2071 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2072 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2073 "Expected inlined-at fields to agree"); 2074 auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug); 2075 if (IsIndirect) 2076 MIB.addImm(0U); 2077 else 2078 MIB.addReg(0U, RegState::Debug); 2079 return MIB.addMetadata(Variable).addMetadata(Expr); 2080 } 2081 2082 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2083 const MCInstrDesc &MCID, bool IsIndirect, 2084 MachineOperand &MO, const MDNode *Variable, 2085 const MDNode *Expr) { 2086 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2087 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2088 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2089 "Expected inlined-at fields to agree"); 2090 if (MO.isReg()) 2091 return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr); 2092 2093 auto MIB = BuildMI(MF, DL, MCID).add(MO); 2094 if (IsIndirect) 2095 MIB.addImm(0U); 2096 else 2097 MIB.addReg(0U, RegState::Debug); 2098 return MIB.addMetadata(Variable).addMetadata(Expr); 2099 } 2100 2101 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2102 MachineBasicBlock::iterator I, 2103 const DebugLoc &DL, const MCInstrDesc &MCID, 2104 bool IsIndirect, Register Reg, 2105 const MDNode *Variable, const MDNode *Expr) { 2106 MachineFunction &MF = *BB.getParent(); 2107 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr); 2108 BB.insert(I, MI); 2109 return MachineInstrBuilder(MF, MI); 2110 } 2111 2112 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2113 MachineBasicBlock::iterator I, 2114 const DebugLoc &DL, const MCInstrDesc &MCID, 2115 bool IsIndirect, MachineOperand &MO, 2116 const MDNode *Variable, const MDNode *Expr) { 2117 MachineFunction &MF = *BB.getParent(); 2118 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr); 2119 BB.insert(I, MI); 2120 return MachineInstrBuilder(MF, *MI); 2121 } 2122 2123 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot. 2124 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE. 2125 static const DIExpression *computeExprForSpill(const MachineInstr &MI) { 2126 assert(MI.getOperand(0).isReg() && "can't spill non-register"); 2127 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && 2128 "Expected inlined-at fields to agree"); 2129 2130 const DIExpression *Expr = MI.getDebugExpression(); 2131 if (MI.isIndirectDebugValue()) { 2132 assert(MI.getDebugOffset().getImm() == 0 && 2133 "DBG_VALUE with nonzero offset"); 2134 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 2135 } 2136 return Expr; 2137 } 2138 2139 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB, 2140 MachineBasicBlock::iterator I, 2141 const MachineInstr &Orig, 2142 int FrameIndex) { 2143 const DIExpression *Expr = computeExprForSpill(Orig); 2144 return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc()) 2145 .addFrameIndex(FrameIndex) 2146 .addImm(0U) 2147 .addMetadata(Orig.getDebugVariable()) 2148 .addMetadata(Expr); 2149 } 2150 2151 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) { 2152 const DIExpression *Expr = computeExprForSpill(Orig); 2153 Orig.getDebugOperand(0).ChangeToFrameIndex(FrameIndex); 2154 Orig.getDebugOffset().ChangeToImmediate(0U); 2155 Orig.getDebugExpressionOp().setMetadata(Expr); 2156 } 2157 2158 void MachineInstr::collectDebugValues( 2159 SmallVectorImpl<MachineInstr *> &DbgValues) { 2160 MachineInstr &MI = *this; 2161 if (!MI.getOperand(0).isReg()) 2162 return; 2163 2164 MachineBasicBlock::iterator DI = MI; ++DI; 2165 for (MachineBasicBlock::iterator DE = MI.getParent()->end(); 2166 DI != DE; ++DI) { 2167 if (!DI->isDebugValue()) 2168 return; 2169 if (DI->getDebugOperandForReg(MI.getOperand(0).getReg())) 2170 DbgValues.push_back(&*DI); 2171 } 2172 } 2173 2174 void MachineInstr::changeDebugValuesDefReg(Register Reg) { 2175 // Collect matching debug values. 2176 SmallVector<MachineInstr *, 2> DbgValues; 2177 2178 if (!getOperand(0).isReg()) 2179 return; 2180 2181 Register DefReg = getOperand(0).getReg(); 2182 auto *MRI = getRegInfo(); 2183 for (auto &MO : MRI->use_operands(DefReg)) { 2184 auto *DI = MO.getParent(); 2185 if (!DI->isDebugValue()) 2186 continue; 2187 if (DI->getDebugOperandForReg(DefReg)) { 2188 DbgValues.push_back(DI); 2189 } 2190 } 2191 2192 // Propagate Reg to debug value instructions. 2193 for (auto *DBI : DbgValues) 2194 DBI->getDebugOperandForReg(DefReg)->setReg(Reg); 2195 } 2196 2197 using MMOList = SmallVector<const MachineMemOperand *, 2>; 2198 2199 static unsigned getSpillSlotSize(const MMOList &Accesses, 2200 const MachineFrameInfo &MFI) { 2201 unsigned Size = 0; 2202 for (auto A : Accesses) 2203 if (MFI.isSpillSlotObjectIndex( 2204 cast<FixedStackPseudoSourceValue>(A->getPseudoValue()) 2205 ->getFrameIndex())) 2206 Size += A->getSize(); 2207 return Size; 2208 } 2209 2210 Optional<unsigned> 2211 MachineInstr::getSpillSize(const TargetInstrInfo *TII) const { 2212 int FI; 2213 if (TII->isStoreToStackSlotPostFE(*this, FI)) { 2214 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2215 if (MFI.isSpillSlotObjectIndex(FI)) 2216 return (*memoperands_begin())->getSize(); 2217 } 2218 return None; 2219 } 2220 2221 Optional<unsigned> 2222 MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const { 2223 MMOList Accesses; 2224 if (TII->hasStoreToStackSlot(*this, Accesses)) 2225 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2226 return None; 2227 } 2228 2229 Optional<unsigned> 2230 MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const { 2231 int FI; 2232 if (TII->isLoadFromStackSlotPostFE(*this, FI)) { 2233 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2234 if (MFI.isSpillSlotObjectIndex(FI)) 2235 return (*memoperands_begin())->getSize(); 2236 } 2237 return None; 2238 } 2239 2240 Optional<unsigned> 2241 MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const { 2242 MMOList Accesses; 2243 if (TII->hasLoadFromStackSlot(*this, Accesses)) 2244 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2245 return None; 2246 } 2247 2248 unsigned MachineInstr::getDebugInstrNum() { 2249 if (DebugInstrNum == 0) 2250 DebugInstrNum = getParent()->getParent()->getNewDebugInstrNum(); 2251 return DebugInstrNum; 2252 } 2253