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