1 //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Loads.h"
25 #include "llvm/Analysis/MemoryLocation.h"
26 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineInstrBundle.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/InstrTypes.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/ModuleSlotTracker.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Value.h"
50 #include "llvm/MC/MCInstrDesc.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/LowLevelTypeImpl.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetInstrInfo.h"
62 #include "llvm/Target/TargetIntrinsicInfo.h"
63 #include "llvm/Target/TargetMachine.h"
64 #include "llvm/Target/TargetRegisterInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
76 static cl::opt<bool> PrintWholeRegMask(
77 "print-whole-regmask",
78 cl::desc("Print the full contents of regmask operands in IR dumps"),
79 cl::init(true), cl::Hidden);
81 //===----------------------------------------------------------------------===//
82 // MachineOperand Implementation
83 //===----------------------------------------------------------------------===//
85 void MachineOperand::setReg(unsigned Reg) {
86 if (getReg() == Reg) return; // No change.
88 // Otherwise, we have to change the register. If this operand is embedded
89 // into a machine function, we need to update the old and new register's
91 if (MachineInstr *MI = getParent())
92 if (MachineBasicBlock *MBB = MI->getParent())
93 if (MachineFunction *MF = MBB->getParent()) {
94 MachineRegisterInfo &MRI = MF->getRegInfo();
95 MRI.removeRegOperandFromUseList(this);
96 SmallContents.RegNo = Reg;
97 MRI.addRegOperandToUseList(this);
101 // Otherwise, just change the register, no problem. :)
102 SmallContents.RegNo = Reg;
105 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
106 const TargetRegisterInfo &TRI) {
107 assert(TargetRegisterInfo::isVirtualRegister(Reg));
108 if (SubIdx && getSubReg())
109 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
115 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
116 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
118 Reg = TRI.getSubReg(Reg, getSubReg());
119 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
120 // That won't happen in legal code.
128 /// Change a def to a use, or a use to a def.
129 void MachineOperand::setIsDef(bool Val) {
130 assert(isReg() && "Wrong MachineOperand accessor");
131 assert((!Val || !isDebug()) && "Marking a debug operation as def");
134 // MRI may keep uses and defs in different list positions.
135 if (MachineInstr *MI = getParent())
136 if (MachineBasicBlock *MBB = MI->getParent())
137 if (MachineFunction *MF = MBB->getParent()) {
138 MachineRegisterInfo &MRI = MF->getRegInfo();
139 MRI.removeRegOperandFromUseList(this);
141 MRI.addRegOperandToUseList(this);
147 // If this operand is currently a register operand, and if this is in a
148 // function, deregister the operand from the register's use/def list.
149 void MachineOperand::removeRegFromUses() {
150 if (!isReg() || !isOnRegUseList())
153 if (MachineInstr *MI = getParent()) {
154 if (MachineBasicBlock *MBB = MI->getParent()) {
155 if (MachineFunction *MF = MBB->getParent())
156 MF->getRegInfo().removeRegOperandFromUseList(this);
161 /// ChangeToImmediate - Replace this operand with a new immediate operand of
162 /// the specified value. If an operand is known to be an immediate already,
163 /// the setImm method should be used.
164 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
165 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
169 OpKind = MO_Immediate;
170 Contents.ImmVal = ImmVal;
173 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
174 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
178 OpKind = MO_FPImmediate;
179 Contents.CFP = FPImm;
182 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
183 assert((!isReg() || !isTied()) &&
184 "Cannot change a tied operand into an external symbol");
188 OpKind = MO_ExternalSymbol;
189 Contents.OffsetedInfo.Val.SymbolName = SymName;
190 setOffset(0); // Offset is always 0.
191 setTargetFlags(TargetFlags);
194 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
195 assert((!isReg() || !isTied()) &&
196 "Cannot change a tied operand into an MCSymbol");
200 OpKind = MO_MCSymbol;
204 void MachineOperand::ChangeToFrameIndex(int Idx) {
205 assert((!isReg() || !isTied()) &&
206 "Cannot change a tied operand into a FrameIndex");
210 OpKind = MO_FrameIndex;
214 /// ChangeToRegister - Replace this operand with a new register operand of
215 /// the specified value. If an operand is known to be an register already,
216 /// the setReg method should be used.
217 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
218 bool isKill, bool isDead, bool isUndef,
220 MachineRegisterInfo *RegInfo = nullptr;
221 if (MachineInstr *MI = getParent())
222 if (MachineBasicBlock *MBB = MI->getParent())
223 if (MachineFunction *MF = MBB->getParent())
224 RegInfo = &MF->getRegInfo();
225 // If this operand is already a register operand, remove it from the
226 // register's use/def lists.
227 bool WasReg = isReg();
228 if (RegInfo && WasReg)
229 RegInfo->removeRegOperandFromUseList(this);
231 // Change this to a register and set the reg#.
232 OpKind = MO_Register;
233 SmallContents.RegNo = Reg;
234 SubReg_TargetFlags = 0;
240 IsInternalRead = false;
241 IsEarlyClobber = false;
243 // Ensure isOnRegUseList() returns false.
244 Contents.Reg.Prev = nullptr;
245 // Preserve the tie when the operand was already a register.
249 // If this operand is embedded in a function, add the operand to the
250 // register's use/def list.
252 RegInfo->addRegOperandToUseList(this);
255 /// isIdenticalTo - Return true if this operand is identical to the specified
256 /// operand. Note that this should stay in sync with the hash_value overload
258 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
259 if (getType() != Other.getType() ||
260 getTargetFlags() != Other.getTargetFlags())
264 case MachineOperand::MO_Register:
265 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
266 getSubReg() == Other.getSubReg();
267 case MachineOperand::MO_Immediate:
268 return getImm() == Other.getImm();
269 case MachineOperand::MO_CImmediate:
270 return getCImm() == Other.getCImm();
271 case MachineOperand::MO_FPImmediate:
272 return getFPImm() == Other.getFPImm();
273 case MachineOperand::MO_MachineBasicBlock:
274 return getMBB() == Other.getMBB();
275 case MachineOperand::MO_FrameIndex:
276 return getIndex() == Other.getIndex();
277 case MachineOperand::MO_ConstantPoolIndex:
278 case MachineOperand::MO_TargetIndex:
279 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
280 case MachineOperand::MO_JumpTableIndex:
281 return getIndex() == Other.getIndex();
282 case MachineOperand::MO_GlobalAddress:
283 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
284 case MachineOperand::MO_ExternalSymbol:
285 return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
286 getOffset() == Other.getOffset();
287 case MachineOperand::MO_BlockAddress:
288 return getBlockAddress() == Other.getBlockAddress() &&
289 getOffset() == Other.getOffset();
290 case MachineOperand::MO_RegisterMask:
291 case MachineOperand::MO_RegisterLiveOut: {
292 // Shallow compare of the two RegMasks
293 const uint32_t *RegMask = getRegMask();
294 const uint32_t *OtherRegMask = Other.getRegMask();
295 if (RegMask == OtherRegMask)
298 // Calculate the size of the RegMask
299 const MachineFunction *MF = getParent()->getParent()->getParent();
300 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
301 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
303 // Deep compare of the two RegMasks
304 return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
306 case MachineOperand::MO_MCSymbol:
307 return getMCSymbol() == Other.getMCSymbol();
308 case MachineOperand::MO_CFIIndex:
309 return getCFIIndex() == Other.getCFIIndex();
310 case MachineOperand::MO_Metadata:
311 return getMetadata() == Other.getMetadata();
312 case MachineOperand::MO_IntrinsicID:
313 return getIntrinsicID() == Other.getIntrinsicID();
314 case MachineOperand::MO_Predicate:
315 return getPredicate() == Other.getPredicate();
317 llvm_unreachable("Invalid machine operand type");
320 // Note: this must stay exactly in sync with isIdenticalTo above.
321 hash_code llvm::hash_value(const MachineOperand &MO) {
322 switch (MO.getType()) {
323 case MachineOperand::MO_Register:
324 // Register operands don't have target flags.
325 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
326 case MachineOperand::MO_Immediate:
327 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
328 case MachineOperand::MO_CImmediate:
329 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
330 case MachineOperand::MO_FPImmediate:
331 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
332 case MachineOperand::MO_MachineBasicBlock:
333 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
334 case MachineOperand::MO_FrameIndex:
335 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
336 case MachineOperand::MO_ConstantPoolIndex:
337 case MachineOperand::MO_TargetIndex:
338 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
340 case MachineOperand::MO_JumpTableIndex:
341 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
342 case MachineOperand::MO_ExternalSymbol:
343 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
345 case MachineOperand::MO_GlobalAddress:
346 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
348 case MachineOperand::MO_BlockAddress:
349 return hash_combine(MO.getType(), MO.getTargetFlags(),
350 MO.getBlockAddress(), MO.getOffset());
351 case MachineOperand::MO_RegisterMask:
352 case MachineOperand::MO_RegisterLiveOut:
353 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
354 case MachineOperand::MO_Metadata:
355 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
356 case MachineOperand::MO_MCSymbol:
357 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
358 case MachineOperand::MO_CFIIndex:
359 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
360 case MachineOperand::MO_IntrinsicID:
361 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
362 case MachineOperand::MO_Predicate:
363 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
365 llvm_unreachable("Invalid machine operand type");
368 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
369 const TargetIntrinsicInfo *IntrinsicInfo) const {
370 ModuleSlotTracker DummyMST(nullptr);
371 print(OS, DummyMST, TRI, IntrinsicInfo);
374 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
375 const TargetRegisterInfo *TRI,
376 const TargetIntrinsicInfo *IntrinsicInfo) const {
378 case MachineOperand::MO_Register:
379 OS << PrintReg(getReg(), TRI, getSubReg());
381 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
382 isInternalRead() || isEarlyClobber() || isTied()) {
384 bool NeedComma = false;
386 if (NeedComma) OS << ',';
387 if (isEarlyClobber())
388 OS << "earlyclobber,";
393 // <def,read-undef> only makes sense when getSubReg() is set.
394 // Don't clutter the output otherwise.
395 if (isUndef() && getSubReg())
397 } else if (isImplicit()) {
403 if (NeedComma) OS << ',';
408 if (NeedComma) OS << ',';
412 if (isUndef() && isUse()) {
413 if (NeedComma) OS << ',';
417 if (isInternalRead()) {
418 if (NeedComma) OS << ',';
423 if (NeedComma) OS << ',';
426 OS << unsigned(TiedTo - 1);
431 case MachineOperand::MO_Immediate:
434 case MachineOperand::MO_CImmediate:
435 getCImm()->getValue().print(OS, false);
437 case MachineOperand::MO_FPImmediate:
438 if (getFPImm()->getType()->isFloatTy()) {
439 OS << getFPImm()->getValueAPF().convertToFloat();
440 } else if (getFPImm()->getType()->isHalfTy()) {
441 APFloat APF = getFPImm()->getValueAPF();
443 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
444 OS << "half " << APF.convertToFloat();
445 } else if (getFPImm()->getType()->isFP128Ty()) {
446 APFloat APF = getFPImm()->getValueAPF();
448 getFPImm()->getValueAPF().toString(Str);
449 OS << "quad " << Str;
450 } else if (getFPImm()->getType()->isX86_FP80Ty()) {
451 APFloat APF = getFPImm()->getValueAPF();
452 OS << "x86_fp80 0xK";
453 APInt API = APF.bitcastToAPInt();
454 OS << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
456 OS << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
459 OS << getFPImm()->getValueAPF().convertToDouble();
462 case MachineOperand::MO_MachineBasicBlock:
463 OS << "<BB#" << getMBB()->getNumber() << ">";
465 case MachineOperand::MO_FrameIndex:
466 OS << "<fi#" << getIndex() << '>';
468 case MachineOperand::MO_ConstantPoolIndex:
469 OS << "<cp#" << getIndex();
470 if (getOffset()) OS << "+" << getOffset();
473 case MachineOperand::MO_TargetIndex:
474 OS << "<ti#" << getIndex();
475 if (getOffset()) OS << "+" << getOffset();
478 case MachineOperand::MO_JumpTableIndex:
479 OS << "<jt#" << getIndex() << '>';
481 case MachineOperand::MO_GlobalAddress:
483 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
484 if (getOffset()) OS << "+" << getOffset();
487 case MachineOperand::MO_ExternalSymbol:
488 OS << "<es:" << getSymbolName();
489 if (getOffset()) OS << "+" << getOffset();
492 case MachineOperand::MO_BlockAddress:
494 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
495 if (getOffset()) OS << "+" << getOffset();
498 case MachineOperand::MO_RegisterMask: {
499 unsigned NumRegsInMask = 0;
500 unsigned NumRegsEmitted = 0;
502 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
503 unsigned MaskWord = i / 32;
504 unsigned MaskBit = i % 32;
505 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
506 if (PrintWholeRegMask || NumRegsEmitted <= 10) {
507 OS << " " << PrintReg(i, TRI);
513 if (NumRegsEmitted != NumRegsInMask)
514 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
518 case MachineOperand::MO_RegisterLiveOut:
519 OS << "<regliveout>";
521 case MachineOperand::MO_Metadata:
523 getMetadata()->printAsOperand(OS, MST);
526 case MachineOperand::MO_MCSymbol:
527 OS << "<MCSym=" << *getMCSymbol() << '>';
529 case MachineOperand::MO_CFIIndex:
530 OS << "<call frame instruction>";
532 case MachineOperand::MO_IntrinsicID: {
533 Intrinsic::ID ID = getIntrinsicID();
534 if (ID < Intrinsic::num_intrinsics)
535 OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
536 else if (IntrinsicInfo)
537 OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
539 OS << "<intrinsic:" << ID << '>';
542 case MachineOperand::MO_Predicate: {
543 auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
544 OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
545 << CmpInst::getPredicateName(Pred) << '>';
549 if (unsigned TF = getTargetFlags())
550 OS << "[TF=" << TF << ']';
553 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
554 LLVM_DUMP_METHOD void MachineOperand::dump() const {
555 dbgs() << *this << '\n';
559 //===----------------------------------------------------------------------===//
560 // MachineMemOperand Implementation
561 //===----------------------------------------------------------------------===//
563 /// getAddrSpace - Return the LLVM IR address space number that this pointer
565 unsigned MachinePointerInfo::getAddrSpace() const {
566 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
567 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
570 /// isDereferenceable - Return true if V is always dereferenceable for
571 /// Offset + Size byte.
572 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
573 const DataLayout &DL) const {
574 if (!V.is<const Value*>())
577 const Value *BasePtr = V.get<const Value*>();
578 if (BasePtr == nullptr)
581 return isDereferenceableAndAlignedPointer(BasePtr, 1,
582 APInt(DL.getPointerSize(),
587 /// getConstantPool - Return a MachinePointerInfo record that refers to the
589 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
590 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
593 /// getFixedStack - Return a MachinePointerInfo record that refers to the
594 /// the specified FrameIndex.
595 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
596 int FI, int64_t Offset) {
597 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
600 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
601 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
604 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
605 return MachinePointerInfo(MF.getPSVManager().getGOT());
608 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
610 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
613 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
614 uint64_t s, unsigned int a,
615 const AAMDNodes &AAInfo,
616 const MDNode *Ranges,
618 AtomicOrdering Ordering,
619 AtomicOrdering FailureOrdering)
620 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
621 AAInfo(AAInfo), Ranges(Ranges) {
622 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
623 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
624 "invalid pointer value");
625 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
626 assert((isLoad() || isStore()) && "Not a load/store!");
628 AtomicInfo.SSID = static_cast<unsigned>(SSID);
629 assert(getSyncScopeID() == SSID && "Value truncated");
630 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
631 assert(getOrdering() == Ordering && "Value truncated");
632 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
633 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
636 /// Profile - Gather unique data for the object.
638 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
639 ID.AddInteger(getOffset());
641 ID.AddPointer(getOpaqueValue());
642 ID.AddInteger(getFlags());
643 ID.AddInteger(getBaseAlignment());
646 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
647 // The Value and Offset may differ due to CSE. But the flags and size
648 // should be the same.
649 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
650 assert(MMO->getSize() == getSize() && "Size mismatch!");
652 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
653 // Update the alignment value.
654 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
655 // Also update the base and offset, because the new alignment may
656 // not be applicable with the old ones.
657 PtrInfo = MMO->PtrInfo;
661 /// getAlignment - Return the minimum known alignment in bytes of the
662 /// actual memory reference.
663 uint64_t MachineMemOperand::getAlignment() const {
664 return MinAlign(getBaseAlignment(), getOffset());
667 void MachineMemOperand::print(raw_ostream &OS) const {
668 ModuleSlotTracker DummyMST(nullptr);
671 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
672 assert((isLoad() || isStore()) &&
673 "SV has to be a load, store or both.");
684 // Print the address information.
686 if (const Value *V = getValue())
687 V->printAsOperand(OS, /*PrintType=*/false, MST);
688 else if (const PseudoSourceValue *PSV = getPseudoValue())
689 PSV->printCustom(OS);
693 unsigned AS = getAddrSpace();
695 OS << "(addrspace=" << AS << ')';
697 // If the alignment of the memory reference itself differs from the alignment
698 // of the base pointer, print the base alignment explicitly, next to the base
700 if (getBaseAlignment() != getAlignment())
701 OS << "(align=" << getBaseAlignment() << ")";
703 if (getOffset() != 0)
704 OS << "+" << getOffset();
707 // Print the alignment of the reference.
708 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
709 OS << "(align=" << getAlignment() << ")";
712 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
714 if (TBAAInfo->getNumOperands() > 0)
715 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
721 // Print AA scope info.
722 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
723 OS << "(alias.scope=";
724 if (ScopeInfo->getNumOperands() > 0)
725 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
726 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
735 // Print AA noalias scope info.
736 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
738 if (NoAliasInfo->getNumOperands() > 0)
739 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
740 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
750 OS << "(nontemporal)";
751 if (isDereferenceable())
752 OS << "(dereferenceable)";
755 if (getFlags() & MOTargetFlag1)
757 if (getFlags() & MOTargetFlag2)
759 if (getFlags() & MOTargetFlag3)
763 //===----------------------------------------------------------------------===//
764 // MachineInstr Implementation
765 //===----------------------------------------------------------------------===//
767 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
768 if (MCID->ImplicitDefs)
769 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
771 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
772 if (MCID->ImplicitUses)
773 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
775 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
778 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
779 /// implicit operands. It reserves space for the number of operands specified by
781 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
782 DebugLoc dl, bool NoImp)
783 : MCID(&tid), debugLoc(std::move(dl)) {
784 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
786 // Reserve space for the expected number of operands.
787 if (unsigned NumOps = MCID->getNumOperands() +
788 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
789 CapOperands = OperandCapacity::get(NumOps);
790 Operands = MF.allocateOperandArray(CapOperands);
794 addImplicitDefUseOperands(MF);
797 /// MachineInstr ctor - Copies MachineInstr arg exactly
799 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
800 : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
801 debugLoc(MI.getDebugLoc()) {
802 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
804 CapOperands = OperandCapacity::get(MI.getNumOperands());
805 Operands = MF.allocateOperandArray(CapOperands);
808 for (const MachineOperand &MO : MI.operands())
811 // Copy all the sensible flags.
815 /// getRegInfo - If this instruction is embedded into a MachineFunction,
816 /// return the MachineRegisterInfo object for the current function, otherwise
818 MachineRegisterInfo *MachineInstr::getRegInfo() {
819 if (MachineBasicBlock *MBB = getParent())
820 return &MBB->getParent()->getRegInfo();
824 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
825 /// this instruction from their respective use lists. This requires that the
826 /// operands already be on their use lists.
827 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
828 for (MachineOperand &MO : operands())
830 MRI.removeRegOperandFromUseList(&MO);
833 /// AddRegOperandsToUseLists - Add all of the register operands in
834 /// this instruction from their respective use lists. This requires that the
835 /// operands not be on their use lists yet.
836 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
837 for (MachineOperand &MO : operands())
839 MRI.addRegOperandToUseList(&MO);
842 void MachineInstr::addOperand(const MachineOperand &Op) {
843 MachineBasicBlock *MBB = getParent();
844 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
845 MachineFunction *MF = MBB->getParent();
846 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
850 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
851 /// ranges. If MRI is non-null also update use-def chains.
852 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
853 unsigned NumOps, MachineRegisterInfo *MRI) {
855 return MRI->moveOperands(Dst, Src, NumOps);
857 // MachineOperand is a trivially copyable type so we can just use memmove.
858 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
861 /// addOperand - Add the specified operand to the instruction. If it is an
862 /// implicit operand, it is added to the end of the operand list. If it is
863 /// an explicit operand it is added at the end of the explicit operand list
864 /// (before the first implicit operand).
865 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
866 assert(MCID && "Cannot add operands before providing an instr descriptor");
868 // Check if we're adding one of our existing operands.
869 if (&Op >= Operands && &Op < Operands + NumOperands) {
870 // This is unusual: MI->addOperand(MI->getOperand(i)).
871 // If adding Op requires reallocating or moving existing operands around,
872 // the Op reference could go stale. Support it by copying Op.
873 MachineOperand CopyOp(Op);
874 return addOperand(MF, CopyOp);
877 // Find the insert location for the new operand. Implicit registers go at
878 // the end, everything else goes before the implicit regs.
880 // FIXME: Allow mixed explicit and implicit operands on inline asm.
881 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
882 // implicit-defs, but they must not be moved around. See the FIXME in
884 unsigned OpNo = getNumOperands();
885 bool isImpReg = Op.isReg() && Op.isImplicit();
886 if (!isImpReg && !isInlineAsm()) {
887 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
889 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
894 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
895 // OpNo now points as the desired insertion point. Unless this is a variadic
896 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
897 // RegMask operands go between the explicit and implicit operands.
898 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
899 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
900 "Trying to add an operand to a machine instr that is already done!");
903 MachineRegisterInfo *MRI = getRegInfo();
905 // Determine if the Operands array needs to be reallocated.
906 // Save the old capacity and operand array.
907 OperandCapacity OldCap = CapOperands;
908 MachineOperand *OldOperands = Operands;
909 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
910 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
911 Operands = MF.allocateOperandArray(CapOperands);
912 // Move the operands before the insertion point.
914 moveOperands(Operands, OldOperands, OpNo, MRI);
917 // Move the operands following the insertion point.
918 if (OpNo != NumOperands)
919 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
923 // Deallocate the old operand array.
924 if (OldOperands != Operands && OldOperands)
925 MF.deallocateOperandArray(OldCap, OldOperands);
927 // Copy Op into place. It still needs to be inserted into the MRI use lists.
928 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
929 NewMO->ParentMI = this;
931 // When adding a register operand, tell MRI about it.
932 if (NewMO->isReg()) {
933 // Ensure isOnRegUseList() returns false, regardless of Op's status.
934 NewMO->Contents.Reg.Prev = nullptr;
935 // Ignore existing ties. This is not a property that can be copied.
937 // Add the new operand to MRI, but only for instructions in an MBB.
939 MRI->addRegOperandToUseList(NewMO);
940 // The MCID operand information isn't accurate until we start adding
941 // explicit operands. The implicit operands are added first, then the
942 // explicits are inserted before them.
944 // Tie uses to defs as indicated in MCInstrDesc.
945 if (NewMO->isUse()) {
946 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
948 tieOperands(DefIdx, OpNo);
950 // If the register operand is flagged as early, mark the operand as such.
951 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
952 NewMO->setIsEarlyClobber(true);
957 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
958 /// fewer operand than it started with.
960 void MachineInstr::RemoveOperand(unsigned OpNo) {
961 assert(OpNo < getNumOperands() && "Invalid operand number");
962 untieRegOperand(OpNo);
965 // Moving tied operands would break the ties.
966 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
967 if (Operands[i].isReg())
968 assert(!Operands[i].isTied() && "Cannot move tied operands");
971 MachineRegisterInfo *MRI = getRegInfo();
972 if (MRI && Operands[OpNo].isReg())
973 MRI->removeRegOperandFromUseList(Operands + OpNo);
975 // Don't call the MachineOperand destructor. A lot of this code depends on
976 // MachineOperand having a trivial destructor anyway, and adding a call here
977 // wouldn't make it 'destructor-correct'.
979 if (unsigned N = NumOperands - 1 - OpNo)
980 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
984 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
985 /// This function should be used only occasionally. The setMemRefs function
986 /// is the primary method for setting up a MachineInstr's MemRefs list.
987 void MachineInstr::addMemOperand(MachineFunction &MF,
988 MachineMemOperand *MO) {
989 mmo_iterator OldMemRefs = MemRefs;
990 unsigned OldNumMemRefs = NumMemRefs;
992 unsigned NewNum = NumMemRefs + 1;
993 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
995 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
996 NewMemRefs[NewNum - 1] = MO;
997 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
1000 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
1002 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
1003 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
1004 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
1005 if ((E1 - I1) != (E2 - I2))
1007 for (; I1 != E1; ++I1, ++I2) {
1014 std::pair<MachineInstr::mmo_iterator, unsigned>
1015 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
1017 // If either of the incoming memrefs are empty, we must be conservative and
1018 // treat this as if we've exhausted our space for memrefs and dropped them.
1019 if (memoperands_empty() || Other.memoperands_empty())
1020 return std::make_pair(nullptr, 0);
1022 // If both instructions have identical memrefs, we don't need to merge them.
1023 // Since many instructions have a single memref, and we tend to merge things
1024 // like pairs of loads from the same location, this catches a large number of
1025 // cases in practice.
1026 if (hasIdenticalMMOs(*this, Other))
1027 return std::make_pair(MemRefs, NumMemRefs);
1029 // TODO: consider uniquing elements within the operand lists to reduce
1030 // space usage and fall back to conservative information less often.
1031 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
1033 // If we don't have enough room to store this many memrefs, be conservative
1034 // and drop them. Otherwise, we'd fail asserts when trying to add them to
1035 // the new instruction.
1036 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
1037 return std::make_pair(nullptr, 0);
1039 MachineFunction *MF = getParent()->getParent();
1040 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
1041 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
1043 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
1045 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
1048 return std::make_pair(MemBegin, CombinedNumMemRefs);
1051 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
1052 assert(!isBundledWithPred() && "Must be called on bundle header");
1053 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1054 if (MII->getDesc().getFlags() & Mask) {
1055 if (Type == AnyInBundle)
1058 if (Type == AllInBundle && !MII->isBundle())
1061 // This was the last instruction in the bundle.
1062 if (!MII->isBundledWithSucc())
1063 return Type == AllInBundle;
1067 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1068 MICheckType Check) const {
1069 // If opcodes or number of operands are not the same then the two
1070 // instructions are obviously not identical.
1071 if (Other.getOpcode() != getOpcode() ||
1072 Other.getNumOperands() != getNumOperands())
1076 // We have passed the test above that both instructions have the same
1077 // opcode, so we know that both instructions are bundles here. Let's compare
1078 // MIs inside the bundle.
1079 assert(Other.isBundle() && "Expected that both instructions are bundles.");
1080 MachineBasicBlock::const_instr_iterator I1 = getIterator();
1081 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1082 // Loop until we analysed the last intruction inside at least one of the
1084 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1087 if (!I1->isIdenticalTo(*I2, Check))
1090 // If we've reached the end of just one of the two bundles, but not both,
1091 // the instructions are not identical.
1092 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1096 // Check operands to make sure they match.
1097 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1098 const MachineOperand &MO = getOperand(i);
1099 const MachineOperand &OMO = Other.getOperand(i);
1101 if (!MO.isIdenticalTo(OMO))
1106 // Clients may or may not want to ignore defs when testing for equality.
1107 // For example, machine CSE pass only cares about finding common
1108 // subexpressions, so it's safe to ignore virtual register defs.
1110 if (Check == IgnoreDefs)
1112 else if (Check == IgnoreVRegDefs) {
1113 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1114 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1115 if (MO.getReg() != OMO.getReg())
1118 if (!MO.isIdenticalTo(OMO))
1120 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1124 if (!MO.isIdenticalTo(OMO))
1126 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1130 // If DebugLoc does not match then two dbg.values are not identical.
1132 if (getDebugLoc() && Other.getDebugLoc() &&
1133 getDebugLoc() != Other.getDebugLoc())
1138 MachineInstr *MachineInstr::removeFromParent() {
1139 assert(getParent() && "Not embedded in a basic block!");
1140 return getParent()->remove(this);
1143 MachineInstr *MachineInstr::removeFromBundle() {
1144 assert(getParent() && "Not embedded in a basic block!");
1145 return getParent()->remove_instr(this);
1148 void MachineInstr::eraseFromParent() {
1149 assert(getParent() && "Not embedded in a basic block!");
1150 getParent()->erase(this);
1153 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1154 assert(getParent() && "Not embedded in a basic block!");
1155 MachineBasicBlock *MBB = getParent();
1156 MachineFunction *MF = MBB->getParent();
1157 assert(MF && "Not embedded in a function!");
1159 MachineInstr *MI = (MachineInstr *)this;
1160 MachineRegisterInfo &MRI = MF->getRegInfo();
1162 for (const MachineOperand &MO : MI->operands()) {
1163 if (!MO.isReg() || !MO.isDef())
1165 unsigned Reg = MO.getReg();
1166 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1168 MRI.markUsesInDebugValueAsUndef(Reg);
1170 MI->eraseFromParent();
1173 void MachineInstr::eraseFromBundle() {
1174 assert(getParent() && "Not embedded in a basic block!");
1175 getParent()->erase_instr(this);
1178 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1180 unsigned MachineInstr::getNumExplicitOperands() const {
1181 unsigned NumOperands = MCID->getNumOperands();
1182 if (!MCID->isVariadic())
1185 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1186 const MachineOperand &MO = getOperand(i);
1187 if (!MO.isReg() || !MO.isImplicit())
1193 void MachineInstr::bundleWithPred() {
1194 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1195 setFlag(BundledPred);
1196 MachineBasicBlock::instr_iterator Pred = getIterator();
1198 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1199 Pred->setFlag(BundledSucc);
1202 void MachineInstr::bundleWithSucc() {
1203 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1204 setFlag(BundledSucc);
1205 MachineBasicBlock::instr_iterator Succ = getIterator();
1207 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1208 Succ->setFlag(BundledPred);
1211 void MachineInstr::unbundleFromPred() {
1212 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1213 clearFlag(BundledPred);
1214 MachineBasicBlock::instr_iterator Pred = getIterator();
1216 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1217 Pred->clearFlag(BundledSucc);
1220 void MachineInstr::unbundleFromSucc() {
1221 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1222 clearFlag(BundledSucc);
1223 MachineBasicBlock::instr_iterator Succ = getIterator();
1225 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1226 Succ->clearFlag(BundledPred);
1229 bool MachineInstr::isStackAligningInlineAsm() const {
1230 if (isInlineAsm()) {
1231 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1232 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1238 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1239 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1240 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1241 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1244 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1245 unsigned *GroupNo) const {
1246 assert(isInlineAsm() && "Expected an inline asm instruction");
1247 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1249 // Ignore queries about the initial operands.
1250 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1255 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1257 const MachineOperand &FlagMO = getOperand(i);
1258 // If we reach the implicit register operands, stop looking.
1259 if (!FlagMO.isImm())
1261 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1262 if (i + NumOps > OpIdx) {
1272 const DILocalVariable *MachineInstr::getDebugVariable() const {
1273 assert(isDebugValue() && "not a DBG_VALUE");
1274 return cast<DILocalVariable>(getOperand(2).getMetadata());
1277 const DIExpression *MachineInstr::getDebugExpression() const {
1278 assert(isDebugValue() && "not a DBG_VALUE");
1279 return cast<DIExpression>(getOperand(3).getMetadata());
1282 const TargetRegisterClass*
1283 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1284 const TargetInstrInfo *TII,
1285 const TargetRegisterInfo *TRI) const {
1286 assert(getParent() && "Can't have an MBB reference here!");
1287 assert(getParent()->getParent() && "Can't have an MF reference here!");
1288 const MachineFunction &MF = *getParent()->getParent();
1290 // Most opcodes have fixed constraints in their MCInstrDesc.
1292 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1294 if (!getOperand(OpIdx).isReg())
1297 // For tied uses on inline asm, get the constraint from the def.
1299 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1302 // Inline asm stores register class constraints in the flag word.
1303 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1307 unsigned Flag = getOperand(FlagIdx).getImm();
1309 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1310 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1311 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1312 InlineAsm::hasRegClassConstraint(Flag, RCID))
1313 return TRI->getRegClass(RCID);
1315 // Assume that all registers in a memory operand are pointers.
1316 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1317 return TRI->getPointerRegClass(MF);
1322 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1323 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1324 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1325 // Check every operands inside the bundle if we have
1328 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1330 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1331 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1333 // Otherwise, just check the current operands.
1334 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1335 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1339 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1340 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1341 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1342 assert(CurRC && "Invalid initial register class");
1343 // Check if Reg is constrained by some of its use/def from MI.
1344 const MachineOperand &MO = getOperand(OpIdx);
1345 if (!MO.isReg() || MO.getReg() != Reg)
1347 // If yes, accumulate the constraints through the operand.
1348 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1351 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1352 unsigned OpIdx, const TargetRegisterClass *CurRC,
1353 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1354 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1355 const MachineOperand &MO = getOperand(OpIdx);
1356 assert(MO.isReg() &&
1357 "Cannot get register constraints for non-register operand");
1358 assert(CurRC && "Invalid initial register class");
1359 if (unsigned SubIdx = MO.getSubReg()) {
1361 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1363 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1365 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1369 /// Return the number of instructions inside the MI bundle, not counting the
1370 /// header instruction.
1371 unsigned MachineInstr::getBundleSize() const {
1372 MachineBasicBlock::const_instr_iterator I = getIterator();
1374 while (I->isBundledWithSucc()) {
1381 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1382 /// the given register (not considering sub/super-registers).
1383 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1384 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1385 const MachineOperand &MO = getOperand(i);
1386 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1392 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1393 /// the specific register or -1 if it is not found. It further tightens
1394 /// the search criteria to a use that kills the register if isKill is true.
1395 int MachineInstr::findRegisterUseOperandIdx(
1396 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1397 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1398 const MachineOperand &MO = getOperand(i);
1399 if (!MO.isReg() || !MO.isUse())
1401 unsigned MOReg = MO.getReg();
1404 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1405 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1406 TRI->isSubRegister(MOReg, Reg)))
1407 if (!isKill || MO.isKill())
1413 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1414 /// indicating if this instruction reads or writes Reg. This also considers
1415 /// partial defines.
1416 std::pair<bool,bool>
1417 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1418 SmallVectorImpl<unsigned> *Ops) const {
1419 bool PartDef = false; // Partial redefine.
1420 bool FullDef = false; // Full define.
1423 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1424 const MachineOperand &MO = getOperand(i);
1425 if (!MO.isReg() || MO.getReg() != Reg)
1430 Use |= !MO.isUndef();
1431 else if (MO.getSubReg() && !MO.isUndef())
1432 // A partial <def,undef> doesn't count as reading the register.
1437 // A partial redefine uses Reg unless there is also a full define.
1438 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1441 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1442 /// the specified register or -1 if it is not found. If isDead is true, defs
1443 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1444 /// also checks if there is a def of a super-register.
1446 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1447 const TargetRegisterInfo *TRI) const {
1448 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1449 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1450 const MachineOperand &MO = getOperand(i);
1451 // Accept regmask operands when Overlap is set.
1452 // Ignore them when looking for a specific def operand (Overlap == false).
1453 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1455 if (!MO.isReg() || !MO.isDef())
1457 unsigned MOReg = MO.getReg();
1458 bool Found = (MOReg == Reg);
1459 if (!Found && TRI && isPhys &&
1460 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1462 Found = TRI->regsOverlap(MOReg, Reg);
1464 Found = TRI->isSubRegister(MOReg, Reg);
1466 if (Found && (!isDead || MO.isDead()))
1472 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1473 /// operand list that is used to represent the predicate. It returns -1 if
1475 int MachineInstr::findFirstPredOperandIdx() const {
1476 // Don't call MCID.findFirstPredOperandIdx() because this variant
1477 // is sometimes called on an instruction that's not yet complete, and
1478 // so the number of operands is less than the MCID indicates. In
1479 // particular, the PTX target does this.
1480 const MCInstrDesc &MCID = getDesc();
1481 if (MCID.isPredicable()) {
1482 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1483 if (MCID.OpInfo[i].isPredicate())
1490 // MachineOperand::TiedTo is 4 bits wide.
1491 const unsigned TiedMax = 15;
1493 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1495 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1496 /// field. TiedTo can have these values:
1498 /// 0: Operand is not tied to anything.
1499 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1500 /// TiedMax: Tied to an operand >= TiedMax-1.
1502 /// The tied def must be one of the first TiedMax operands on a normal
1503 /// instruction. INLINEASM instructions allow more tied defs.
1505 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1506 MachineOperand &DefMO = getOperand(DefIdx);
1507 MachineOperand &UseMO = getOperand(UseIdx);
1508 assert(DefMO.isDef() && "DefIdx must be a def operand");
1509 assert(UseMO.isUse() && "UseIdx must be a use operand");
1510 assert(!DefMO.isTied() && "Def is already tied to another use");
1511 assert(!UseMO.isTied() && "Use is already tied to another def");
1513 if (DefIdx < TiedMax)
1514 UseMO.TiedTo = DefIdx + 1;
1516 // Inline asm can use the group descriptors to find tied operands, but on
1517 // normal instruction, the tied def must be within the first TiedMax
1519 assert(isInlineAsm() && "DefIdx out of range");
1520 UseMO.TiedTo = TiedMax;
1523 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1524 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1527 /// Given the index of a tied register operand, find the operand it is tied to.
1528 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1529 /// which must exist.
1530 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1531 const MachineOperand &MO = getOperand(OpIdx);
1532 assert(MO.isTied() && "Operand isn't tied");
1534 // Normally TiedTo is in range.
1535 if (MO.TiedTo < TiedMax)
1536 return MO.TiedTo - 1;
1538 // Uses on normal instructions can be out of range.
1539 if (!isInlineAsm()) {
1540 // Normal tied defs must be in the 0..TiedMax-1 range.
1543 // MO is a def. Search for the tied use.
1544 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1545 const MachineOperand &UseMO = getOperand(i);
1546 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1549 llvm_unreachable("Can't find tied use");
1552 // Now deal with inline asm by parsing the operand group descriptor flags.
1553 // Find the beginning of each operand group.
1554 SmallVector<unsigned, 8> GroupIdx;
1555 unsigned OpIdxGroup = ~0u;
1557 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1559 const MachineOperand &FlagMO = getOperand(i);
1560 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1561 unsigned CurGroup = GroupIdx.size();
1562 GroupIdx.push_back(i);
1563 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1564 // OpIdx belongs to this operand group.
1565 if (OpIdx > i && OpIdx < i + NumOps)
1566 OpIdxGroup = CurGroup;
1568 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1570 // Operands in this group are tied to operands in TiedGroup which must be
1571 // earlier. Find the number of operands between the two groups.
1572 unsigned Delta = i - GroupIdx[TiedGroup];
1574 // OpIdx is a use tied to TiedGroup.
1575 if (OpIdxGroup == CurGroup)
1576 return OpIdx - Delta;
1578 // OpIdx is a def tied to this use group.
1579 if (OpIdxGroup == TiedGroup)
1580 return OpIdx + Delta;
1582 llvm_unreachable("Invalid tied operand on inline asm");
1585 /// clearKillInfo - Clears kill flags on all operands.
1587 void MachineInstr::clearKillInfo() {
1588 for (MachineOperand &MO : operands()) {
1589 if (MO.isReg() && MO.isUse())
1590 MO.setIsKill(false);
1594 void MachineInstr::substituteRegister(unsigned FromReg,
1597 const TargetRegisterInfo &RegInfo) {
1598 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1600 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1601 for (MachineOperand &MO : operands()) {
1602 if (!MO.isReg() || MO.getReg() != FromReg)
1604 MO.substPhysReg(ToReg, RegInfo);
1607 for (MachineOperand &MO : operands()) {
1608 if (!MO.isReg() || MO.getReg() != FromReg)
1610 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1615 /// isSafeToMove - Return true if it is safe to move this instruction. If
1616 /// SawStore is set to true, it means that there is a store (or call) between
1617 /// the instruction's location and its intended destination.
1618 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1619 // Ignore stuff that we obviously can't move.
1621 // Treat volatile loads as stores. This is not strictly necessary for
1622 // volatiles, but it is required for atomic loads. It is not allowed to move
1623 // a load across an atomic load with Ordering > Monotonic.
1624 if (mayStore() || isCall() ||
1625 (mayLoad() && hasOrderedMemoryRef())) {
1630 if (isPosition() || isDebugValue() || isTerminator() ||
1631 hasUnmodeledSideEffects())
1634 // See if this instruction does a load. If so, we have to guarantee that the
1635 // loaded value doesn't change between the load and the its intended
1636 // destination. The check for isInvariantLoad gives the targe the chance to
1637 // classify the load as always returning a constant, e.g. a constant pool
1639 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1640 // Otherwise, this is a real load. If there is a store between the load and
1641 // end of block, we can't move it.
1647 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1649 const MachineFunction *MF = getParent()->getParent();
1650 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1652 // If neither instruction stores to memory, they can't alias in any
1653 // meaningful way, even if they read from the same address.
1654 if (!mayStore() && !Other.mayStore())
1657 // Let the target decide if memory accesses cannot possibly overlap.
1658 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1664 // FIXME: Need to handle multiple memory operands to support all targets.
1665 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1668 MachineMemOperand *MMOa = *memoperands_begin();
1669 MachineMemOperand *MMOb = *Other.memoperands_begin();
1671 if (!MMOa->getValue() || !MMOb->getValue())
1674 // The following interface to AA is fashioned after DAGCombiner::isAlias
1675 // and operates with MachineMemOperand offset with some important
1677 // - LLVM fundamentally assumes flat address spaces.
1678 // - MachineOperand offset can *only* result from legalization and
1679 // cannot affect queries other than the trivial case of overlap
1681 // - These offsets never wrap and never step outside
1682 // of allocated objects.
1683 // - There should never be any negative offsets here.
1685 // FIXME: Modify API to hide this math from "user"
1686 // FIXME: Even before we go to AA we can reason locally about some
1687 // memory objects. It can save compile time, and possibly catch some
1688 // corner cases not currently covered.
1690 assert((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
1691 assert((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
1693 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
1694 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
1695 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
1697 AliasResult AAResult =
1698 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
1699 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1700 MemoryLocation(MMOb->getValue(), Overlapb,
1701 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1703 return (AAResult != NoAlias);
1706 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1707 /// or volatile memory reference, or if the information describing the memory
1708 /// reference is not available. Return false if it is known to have no ordered
1709 /// memory references.
1710 bool MachineInstr::hasOrderedMemoryRef() const {
1711 // An instruction known never to access memory won't have a volatile access.
1715 !hasUnmodeledSideEffects())
1718 // Otherwise, if the instruction has no memory reference information,
1719 // conservatively assume it wasn't preserved.
1720 if (memoperands_empty())
1723 // Check if any of our memory operands are ordered.
1724 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1725 return !MMO->isUnordered();
1729 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1730 /// trap and is loading from a location whose value is invariant across a run of
1732 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1733 // If the instruction doesn't load at all, it isn't an invariant load.
1737 // If the instruction has lost its memoperands, conservatively assume that
1738 // it may not be an invariant load.
1739 if (memoperands_empty())
1742 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1744 for (MachineMemOperand *MMO : memoperands()) {
1745 if (MMO->isVolatile()) return false;
1746 if (MMO->isStore()) return false;
1747 if (MMO->isInvariant() && MMO->isDereferenceable())
1750 // A load from a constant PseudoSourceValue is invariant.
1751 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1752 if (PSV->isConstant(&MFI))
1755 if (const Value *V = MMO->getValue()) {
1756 // If we have an AliasAnalysis, ask it whether the memory is constant.
1758 AA->pointsToConstantMemory(
1759 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1763 // Otherwise assume conservatively.
1767 // Everything checks out.
1771 /// isConstantValuePHI - If the specified instruction is a PHI that always
1772 /// merges together the same virtual register, return the register, otherwise
1774 unsigned MachineInstr::isConstantValuePHI() const {
1777 assert(getNumOperands() >= 3 &&
1778 "It's illegal to have a PHI without source operands");
1780 unsigned Reg = getOperand(1).getReg();
1781 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1782 if (getOperand(i).getReg() != Reg)
1787 bool MachineInstr::hasUnmodeledSideEffects() const {
1788 if (hasProperty(MCID::UnmodeledSideEffects))
1790 if (isInlineAsm()) {
1791 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1792 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1799 bool MachineInstr::isLoadFoldBarrier() const {
1800 return mayStore() || isCall() || hasUnmodeledSideEffects();
1803 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1805 bool MachineInstr::allDefsAreDead() const {
1806 for (const MachineOperand &MO : operands()) {
1807 if (!MO.isReg() || MO.isUse())
1815 /// copyImplicitOps - Copy implicit register operands from specified
1816 /// instruction to this instruction.
1817 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1818 const MachineInstr &MI) {
1819 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1821 const MachineOperand &MO = MI.getOperand(i);
1822 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1827 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1828 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1834 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1835 const TargetInstrInfo *TII) const {
1836 const Module *M = nullptr;
1837 if (const MachineBasicBlock *MBB = getParent())
1838 if (const MachineFunction *MF = MBB->getParent())
1839 M = MF->getFunction()->getParent();
1841 ModuleSlotTracker MST(M);
1842 print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1845 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1846 bool SkipOpers, bool SkipDebugLoc,
1847 const TargetInstrInfo *TII) const {
1848 // We can be a bit tidier if we know the MachineFunction.
1849 const MachineFunction *MF = nullptr;
1850 const TargetRegisterInfo *TRI = nullptr;
1851 const MachineRegisterInfo *MRI = nullptr;
1852 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1854 if (const MachineBasicBlock *MBB = getParent()) {
1855 MF = MBB->getParent();
1857 MRI = &MF->getRegInfo();
1858 TRI = MF->getSubtarget().getRegisterInfo();
1860 TII = MF->getSubtarget().getInstrInfo();
1861 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1865 // Save a list of virtual registers.
1866 SmallVector<unsigned, 8> VirtRegs;
1868 // Print explicitly defined operands on the left of an assignment syntax.
1869 unsigned StartOp = 0, e = getNumOperands();
1870 for (; StartOp < e && getOperand(StartOp).isReg() &&
1871 getOperand(StartOp).isDef() &&
1872 !getOperand(StartOp).isImplicit();
1874 if (StartOp != 0) OS << ", ";
1875 getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1876 unsigned Reg = getOperand(StartOp).getReg();
1877 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1878 VirtRegs.push_back(Reg);
1879 LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1881 OS << '(' << Ty << ')';
1888 // Print the opcode name.
1890 OS << TII->getName(getOpcode());
1897 // Print the rest of the operands.
1898 bool FirstOp = true;
1899 unsigned AsmDescOp = ~0u;
1900 unsigned AsmOpCount = 0;
1902 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1903 // Print asm string.
1905 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1907 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1908 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1909 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1910 OS << " [sideeffect]";
1911 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1913 if (ExtraInfo & InlineAsm::Extra_MayStore)
1914 OS << " [maystore]";
1915 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1916 OS << " [isconvergent]";
1917 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1918 OS << " [alignstack]";
1919 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1920 OS << " [attdialect]";
1921 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1922 OS << " [inteldialect]";
1924 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1928 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1929 const MachineOperand &MO = getOperand(i);
1931 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1932 VirtRegs.push_back(MO.getReg());
1934 if (FirstOp) FirstOp = false; else OS << ",";
1936 if (i < getDesc().NumOperands) {
1937 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1938 if (MCOI.isPredicate())
1940 if (MCOI.isOptionalDef())
1943 if (isDebugValue() && MO.isMetadata()) {
1944 // Pretty print DBG_VALUE instructions.
1945 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1946 if (DIV && !DIV->getName().empty())
1947 OS << "!\"" << DIV->getName() << '\"';
1949 MO.print(OS, MST, TRI);
1950 } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1951 (isSubregToReg() && i == 3)) && MO.isImm()) {
1952 OS << TRI->getSubRegIndexName(MO.getImm());
1953 } else if (i == AsmDescOp && MO.isImm()) {
1954 // Pretty print the inline asm operand descriptor.
1955 OS << '$' << AsmOpCount++;
1956 unsigned Flag = MO.getImm();
1957 switch (InlineAsm::getKind(Flag)) {
1958 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1959 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1960 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1961 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1962 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1963 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1964 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1968 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1969 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1971 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1973 OS << ":RC" << RCID;
1976 if (InlineAsm::isMemKind(Flag)) {
1977 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1979 case InlineAsm::Constraint_es: OS << ":es"; break;
1980 case InlineAsm::Constraint_i: OS << ":i"; break;
1981 case InlineAsm::Constraint_m: OS << ":m"; break;
1982 case InlineAsm::Constraint_o: OS << ":o"; break;
1983 case InlineAsm::Constraint_v: OS << ":v"; break;
1984 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1985 case InlineAsm::Constraint_R: OS << ":R"; break;
1986 case InlineAsm::Constraint_S: OS << ":S"; break;
1987 case InlineAsm::Constraint_T: OS << ":T"; break;
1988 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1989 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1990 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1991 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1992 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1993 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1994 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1995 case InlineAsm::Constraint_X: OS << ":X"; break;
1996 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1997 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1998 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1999 default: OS << ":?"; break;
2003 unsigned TiedTo = 0;
2004 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
2005 OS << " tiedto:$" << TiedTo;
2009 // Compute the index of the next operand descriptor.
2010 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
2012 MO.print(OS, MST, TRI);
2015 bool HaveSemi = false;
2016 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2017 if (Flags & PrintableFlags) {
2024 if (Flags & FrameSetup)
2027 if (Flags & FrameDestroy)
2028 OS << "FrameDestroy";
2031 if (!memoperands_empty()) {
2038 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2040 (*i)->print(OS, MST);
2041 if (std::next(i) != e)
2046 // Print the regclass of any virtual registers encountered.
2047 if (MRI && !VirtRegs.empty()) {
2052 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2053 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2056 // Generic virtual registers do not have register classes.
2057 if (RC.is<const RegisterBank *>())
2058 OS << " " << RC.get<const RegisterBank *>()->getName();
2061 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2062 OS << ':' << PrintReg(VirtRegs[i]);
2063 for (unsigned j = i+1; j != VirtRegs.size();) {
2064 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2068 if (VirtRegs[i] != VirtRegs[j])
2069 OS << "," << PrintReg(VirtRegs[j]);
2070 VirtRegs.erase(VirtRegs.begin()+j);
2075 // Print debug location information.
2076 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2079 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2080 OS << " line no:" << DV->getLine();
2081 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2082 DebugLoc InlinedAtDL(InlinedAt);
2083 if (InlinedAtDL && MF) {
2084 OS << " inlined @[ ";
2085 InlinedAtDL.print(OS);
2089 if (isIndirectDebugValue())
2091 } else if (SkipDebugLoc) {
2093 } else if (debugLoc && MF) {
2103 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2104 const TargetRegisterInfo *RegInfo,
2105 bool AddIfNotFound) {
2106 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2107 bool hasAliases = isPhysReg &&
2108 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2110 SmallVector<unsigned,4> DeadOps;
2111 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2112 MachineOperand &MO = getOperand(i);
2113 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2116 // DEBUG_VALUE nodes do not contribute to code generation and should
2117 // always be ignored. Failure to do so may result in trying to modify
2118 // KILL flags on DEBUG_VALUE nodes.
2122 unsigned Reg = MO.getReg();
2126 if (Reg == IncomingReg) {
2129 // The register is already marked kill.
2131 if (isPhysReg && isRegTiedToDefOperand(i))
2132 // Two-address uses of physregs must not be marked kill.
2137 } else if (hasAliases && MO.isKill() &&
2138 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2139 // A super-register kill already exists.
2140 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2142 if (RegInfo->isSubRegister(IncomingReg, Reg))
2143 DeadOps.push_back(i);
2147 // Trim unneeded kill operands.
2148 while (!DeadOps.empty()) {
2149 unsigned OpIdx = DeadOps.back();
2150 if (getOperand(OpIdx).isImplicit())
2151 RemoveOperand(OpIdx);
2153 getOperand(OpIdx).setIsKill(false);
2157 // If not found, this means an alias of one of the operands is killed. Add a
2158 // new implicit operand if required.
2159 if (!Found && AddIfNotFound) {
2160 addOperand(MachineOperand::CreateReg(IncomingReg,
2169 void MachineInstr::clearRegisterKills(unsigned Reg,
2170 const TargetRegisterInfo *RegInfo) {
2171 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2173 for (MachineOperand &MO : operands()) {
2174 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2176 unsigned OpReg = MO.getReg();
2177 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2178 MO.setIsKill(false);
2182 bool MachineInstr::addRegisterDead(unsigned Reg,
2183 const TargetRegisterInfo *RegInfo,
2184 bool AddIfNotFound) {
2185 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2186 bool hasAliases = isPhysReg &&
2187 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2189 SmallVector<unsigned,4> DeadOps;
2190 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2191 MachineOperand &MO = getOperand(i);
2192 if (!MO.isReg() || !MO.isDef())
2194 unsigned MOReg = MO.getReg();
2201 } else if (hasAliases && MO.isDead() &&
2202 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2203 // There exists a super-register that's marked dead.
2204 if (RegInfo->isSuperRegister(Reg, MOReg))
2206 if (RegInfo->isSubRegister(Reg, MOReg))
2207 DeadOps.push_back(i);
2211 // Trim unneeded dead operands.
2212 while (!DeadOps.empty()) {
2213 unsigned OpIdx = DeadOps.back();
2214 if (getOperand(OpIdx).isImplicit())
2215 RemoveOperand(OpIdx);
2217 getOperand(OpIdx).setIsDead(false);
2221 // If not found, this means an alias of one of the operands is dead. Add a
2222 // new implicit operand if required.
2223 if (Found || !AddIfNotFound)
2226 addOperand(MachineOperand::CreateReg(Reg,
2234 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2235 for (MachineOperand &MO : operands()) {
2236 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2238 MO.setIsDead(false);
2242 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2243 for (MachineOperand &MO : operands()) {
2244 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2246 MO.setIsUndef(IsUndef);
2250 void MachineInstr::addRegisterDefined(unsigned Reg,
2251 const TargetRegisterInfo *RegInfo) {
2252 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2253 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2257 for (const MachineOperand &MO : operands()) {
2258 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2259 MO.getSubReg() == 0)
2263 addOperand(MachineOperand::CreateReg(Reg,
2268 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2269 const TargetRegisterInfo &TRI) {
2270 bool HasRegMask = false;
2271 for (MachineOperand &MO : operands()) {
2272 if (MO.isRegMask()) {
2276 if (!MO.isReg() || !MO.isDef()) continue;
2277 unsigned Reg = MO.getReg();
2278 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2279 // If there are no uses, including partial uses, the def is dead.
2280 if (llvm::none_of(UsedRegs,
2281 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2285 // This is a call with a register mask operand.
2286 // Mask clobbers are always dead, so add defs for the non-dead defines.
2288 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2290 addRegisterDefined(*I, &TRI);
2294 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2295 // Build up a buffer of hash code components.
2296 SmallVector<size_t, 8> HashComponents;
2297 HashComponents.reserve(MI->getNumOperands() + 1);
2298 HashComponents.push_back(MI->getOpcode());
2299 for (const MachineOperand &MO : MI->operands()) {
2300 if (MO.isReg() && MO.isDef() &&
2301 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2302 continue; // Skip virtual register defs.
2304 HashComponents.push_back(hash_value(MO));
2306 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2309 void MachineInstr::emitError(StringRef Msg) const {
2310 // Find the source location cookie.
2311 unsigned LocCookie = 0;
2312 const MDNode *LocMD = nullptr;
2313 for (unsigned i = getNumOperands(); i != 0; --i) {
2314 if (getOperand(i-1).isMetadata() &&
2315 (LocMD = getOperand(i-1).getMetadata()) &&
2316 LocMD->getNumOperands() != 0) {
2317 if (const ConstantInt *CI =
2318 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2319 LocCookie = CI->getZExtValue();
2325 if (const MachineBasicBlock *MBB = getParent())
2326 if (const MachineFunction *MF = MBB->getParent())
2327 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2328 report_fatal_error(Msg);
2331 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2332 const MCInstrDesc &MCID, bool IsIndirect,
2333 unsigned Reg, unsigned Offset,
2334 const MDNode *Variable, const MDNode *Expr) {
2335 assert(isa<DILocalVariable>(Variable) && "not a variable");
2336 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2337 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2338 "Expected inlined-at fields to agree");
2340 return BuildMI(MF, DL, MCID)
2341 .addReg(Reg, RegState::Debug)
2343 .addMetadata(Variable)
2346 assert(Offset == 0 && "A direct address cannot have an offset.");
2347 return BuildMI(MF, DL, MCID)
2348 .addReg(Reg, RegState::Debug)
2349 .addReg(0U, RegState::Debug)
2350 .addMetadata(Variable)
2355 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2356 MachineBasicBlock::iterator I,
2357 const DebugLoc &DL, const MCInstrDesc &MCID,
2358 bool IsIndirect, unsigned Reg,
2359 unsigned Offset, const MDNode *Variable,
2360 const MDNode *Expr) {
2361 assert(isa<DILocalVariable>(Variable) && "not a variable");
2362 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2363 MachineFunction &MF = *BB.getParent();
2365 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2367 return MachineInstrBuilder(MF, MI);
2370 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2371 MachineBasicBlock::iterator I,
2372 const MachineInstr &Orig,
2374 const MDNode *Var = Orig.getDebugVariable();
2375 const auto *Expr = cast_or_null<DIExpression>(Orig.getDebugExpression());
2376 bool IsIndirect = Orig.isIndirectDebugValue();
2377 uint64_t Offset = IsIndirect ? Orig.getOperand(1).getImm() : 0;
2378 DebugLoc DL = Orig.getDebugLoc();
2379 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
2380 "Expected inlined-at fields to agree");
2381 // If the DBG_VALUE already was a memory location, add an extra
2382 // DW_OP_deref. Otherwise just turning this from a register into a
2383 // memory/indirect location is sufficient.
2385 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
2386 return BuildMI(BB, I, DL, Orig.getDesc())
2387 .addFrameIndex(FrameIndex)