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