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