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