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