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