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