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