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