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(
582 BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
585 /// getConstantPool - Return a MachinePointerInfo record that refers to the
587 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
588 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
591 /// getFixedStack - Return a MachinePointerInfo record that refers to the
592 /// the specified FrameIndex.
593 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
594 int FI, int64_t Offset) {
595 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
598 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
599 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
602 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
603 return MachinePointerInfo(MF.getPSVManager().getGOT());
606 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
608 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
611 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
612 uint64_t s, unsigned int a,
613 const AAMDNodes &AAInfo,
614 const MDNode *Ranges,
616 AtomicOrdering Ordering,
617 AtomicOrdering FailureOrdering)
618 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
619 AAInfo(AAInfo), Ranges(Ranges) {
620 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
621 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
622 "invalid pointer value");
623 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
624 assert((isLoad() || isStore()) && "Not a load/store!");
626 AtomicInfo.SSID = static_cast<unsigned>(SSID);
627 assert(getSyncScopeID() == SSID && "Value truncated");
628 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
629 assert(getOrdering() == Ordering && "Value truncated");
630 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
631 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
634 /// Profile - Gather unique data for the object.
636 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
637 ID.AddInteger(getOffset());
639 ID.AddPointer(getOpaqueValue());
640 ID.AddInteger(getFlags());
641 ID.AddInteger(getBaseAlignment());
644 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
645 // The Value and Offset may differ due to CSE. But the flags and size
646 // should be the same.
647 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
648 assert(MMO->getSize() == getSize() && "Size mismatch!");
650 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
651 // Update the alignment value.
652 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
653 // Also update the base and offset, because the new alignment may
654 // not be applicable with the old ones.
655 PtrInfo = MMO->PtrInfo;
659 /// getAlignment - Return the minimum known alignment in bytes of the
660 /// actual memory reference.
661 uint64_t MachineMemOperand::getAlignment() const {
662 return MinAlign(getBaseAlignment(), getOffset());
665 void MachineMemOperand::print(raw_ostream &OS) const {
666 ModuleSlotTracker DummyMST(nullptr);
669 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
670 assert((isLoad() || isStore()) &&
671 "SV has to be a load, store or both.");
682 // Print the address information.
684 if (const Value *V = getValue())
685 V->printAsOperand(OS, /*PrintType=*/false, MST);
686 else if (const PseudoSourceValue *PSV = getPseudoValue())
687 PSV->printCustom(OS);
691 unsigned AS = getAddrSpace();
693 OS << "(addrspace=" << AS << ')';
695 // If the alignment of the memory reference itself differs from the alignment
696 // of the base pointer, print the base alignment explicitly, next to the base
698 if (getBaseAlignment() != getAlignment())
699 OS << "(align=" << getBaseAlignment() << ")";
701 if (getOffset() != 0)
702 OS << "+" << getOffset();
705 // Print the alignment of the reference.
706 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
707 OS << "(align=" << getAlignment() << ")";
710 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
712 if (TBAAInfo->getNumOperands() > 0)
713 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
719 // Print AA scope info.
720 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
721 OS << "(alias.scope=";
722 if (ScopeInfo->getNumOperands() > 0)
723 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
724 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
733 // Print AA noalias scope info.
734 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
736 if (NoAliasInfo->getNumOperands() > 0)
737 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
738 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
748 OS << "(nontemporal)";
749 if (isDereferenceable())
750 OS << "(dereferenceable)";
753 if (getFlags() & MOTargetFlag1)
755 if (getFlags() & MOTargetFlag2)
757 if (getFlags() & MOTargetFlag3)
761 //===----------------------------------------------------------------------===//
762 // MachineInstr Implementation
763 //===----------------------------------------------------------------------===//
765 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
766 if (MCID->ImplicitDefs)
767 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
769 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
770 if (MCID->ImplicitUses)
771 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
773 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
776 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
777 /// implicit operands. It reserves space for the number of operands specified by
779 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
780 DebugLoc dl, bool NoImp)
781 : MCID(&tid), debugLoc(std::move(dl)) {
782 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
784 // Reserve space for the expected number of operands.
785 if (unsigned NumOps = MCID->getNumOperands() +
786 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
787 CapOperands = OperandCapacity::get(NumOps);
788 Operands = MF.allocateOperandArray(CapOperands);
792 addImplicitDefUseOperands(MF);
795 /// MachineInstr ctor - Copies MachineInstr arg exactly
797 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
798 : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
799 debugLoc(MI.getDebugLoc()) {
800 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
802 CapOperands = OperandCapacity::get(MI.getNumOperands());
803 Operands = MF.allocateOperandArray(CapOperands);
806 for (const MachineOperand &MO : MI.operands())
809 // Copy all the sensible flags.
813 /// getRegInfo - If this instruction is embedded into a MachineFunction,
814 /// return the MachineRegisterInfo object for the current function, otherwise
816 MachineRegisterInfo *MachineInstr::getRegInfo() {
817 if (MachineBasicBlock *MBB = getParent())
818 return &MBB->getParent()->getRegInfo();
822 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
823 /// this instruction from their respective use lists. This requires that the
824 /// operands already be on their use lists.
825 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
826 for (MachineOperand &MO : operands())
828 MRI.removeRegOperandFromUseList(&MO);
831 /// AddRegOperandsToUseLists - Add all of the register operands in
832 /// this instruction from their respective use lists. This requires that the
833 /// operands not be on their use lists yet.
834 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
835 for (MachineOperand &MO : operands())
837 MRI.addRegOperandToUseList(&MO);
840 void MachineInstr::addOperand(const MachineOperand &Op) {
841 MachineBasicBlock *MBB = getParent();
842 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
843 MachineFunction *MF = MBB->getParent();
844 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
848 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
849 /// ranges. If MRI is non-null also update use-def chains.
850 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
851 unsigned NumOps, MachineRegisterInfo *MRI) {
853 return MRI->moveOperands(Dst, Src, NumOps);
855 // MachineOperand is a trivially copyable type so we can just use memmove.
856 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
859 /// addOperand - Add the specified operand to the instruction. If it is an
860 /// implicit operand, it is added to the end of the operand list. If it is
861 /// an explicit operand it is added at the end of the explicit operand list
862 /// (before the first implicit operand).
863 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
864 assert(MCID && "Cannot add operands before providing an instr descriptor");
866 // Check if we're adding one of our existing operands.
867 if (&Op >= Operands && &Op < Operands + NumOperands) {
868 // This is unusual: MI->addOperand(MI->getOperand(i)).
869 // If adding Op requires reallocating or moving existing operands around,
870 // the Op reference could go stale. Support it by copying Op.
871 MachineOperand CopyOp(Op);
872 return addOperand(MF, CopyOp);
875 // Find the insert location for the new operand. Implicit registers go at
876 // the end, everything else goes before the implicit regs.
878 // FIXME: Allow mixed explicit and implicit operands on inline asm.
879 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
880 // implicit-defs, but they must not be moved around. See the FIXME in
882 unsigned OpNo = getNumOperands();
883 bool isImpReg = Op.isReg() && Op.isImplicit();
884 if (!isImpReg && !isInlineAsm()) {
885 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
887 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
892 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
893 // OpNo now points as the desired insertion point. Unless this is a variadic
894 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
895 // RegMask operands go between the explicit and implicit operands.
896 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
897 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
898 "Trying to add an operand to a machine instr that is already done!");
901 MachineRegisterInfo *MRI = getRegInfo();
903 // Determine if the Operands array needs to be reallocated.
904 // Save the old capacity and operand array.
905 OperandCapacity OldCap = CapOperands;
906 MachineOperand *OldOperands = Operands;
907 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
908 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
909 Operands = MF.allocateOperandArray(CapOperands);
910 // Move the operands before the insertion point.
912 moveOperands(Operands, OldOperands, OpNo, MRI);
915 // Move the operands following the insertion point.
916 if (OpNo != NumOperands)
917 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
921 // Deallocate the old operand array.
922 if (OldOperands != Operands && OldOperands)
923 MF.deallocateOperandArray(OldCap, OldOperands);
925 // Copy Op into place. It still needs to be inserted into the MRI use lists.
926 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
927 NewMO->ParentMI = this;
929 // When adding a register operand, tell MRI about it.
930 if (NewMO->isReg()) {
931 // Ensure isOnRegUseList() returns false, regardless of Op's status.
932 NewMO->Contents.Reg.Prev = nullptr;
933 // Ignore existing ties. This is not a property that can be copied.
935 // Add the new operand to MRI, but only for instructions in an MBB.
937 MRI->addRegOperandToUseList(NewMO);
938 // The MCID operand information isn't accurate until we start adding
939 // explicit operands. The implicit operands are added first, then the
940 // explicits are inserted before them.
942 // Tie uses to defs as indicated in MCInstrDesc.
943 if (NewMO->isUse()) {
944 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
946 tieOperands(DefIdx, OpNo);
948 // If the register operand is flagged as early, mark the operand as such.
949 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
950 NewMO->setIsEarlyClobber(true);
955 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
956 /// fewer operand than it started with.
958 void MachineInstr::RemoveOperand(unsigned OpNo) {
959 assert(OpNo < getNumOperands() && "Invalid operand number");
960 untieRegOperand(OpNo);
963 // Moving tied operands would break the ties.
964 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
965 if (Operands[i].isReg())
966 assert(!Operands[i].isTied() && "Cannot move tied operands");
969 MachineRegisterInfo *MRI = getRegInfo();
970 if (MRI && Operands[OpNo].isReg())
971 MRI->removeRegOperandFromUseList(Operands + OpNo);
973 // Don't call the MachineOperand destructor. A lot of this code depends on
974 // MachineOperand having a trivial destructor anyway, and adding a call here
975 // wouldn't make it 'destructor-correct'.
977 if (unsigned N = NumOperands - 1 - OpNo)
978 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
982 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
983 /// This function should be used only occasionally. The setMemRefs function
984 /// is the primary method for setting up a MachineInstr's MemRefs list.
985 void MachineInstr::addMemOperand(MachineFunction &MF,
986 MachineMemOperand *MO) {
987 mmo_iterator OldMemRefs = MemRefs;
988 unsigned OldNumMemRefs = NumMemRefs;
990 unsigned NewNum = NumMemRefs + 1;
991 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
993 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
994 NewMemRefs[NewNum - 1] = MO;
995 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
998 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
1000 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
1001 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
1002 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
1003 if ((E1 - I1) != (E2 - I2))
1005 for (; I1 != E1; ++I1, ++I2) {
1012 std::pair<MachineInstr::mmo_iterator, unsigned>
1013 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
1015 // If either of the incoming memrefs are empty, we must be conservative and
1016 // treat this as if we've exhausted our space for memrefs and dropped them.
1017 if (memoperands_empty() || Other.memoperands_empty())
1018 return std::make_pair(nullptr, 0);
1020 // If both instructions have identical memrefs, we don't need to merge them.
1021 // Since many instructions have a single memref, and we tend to merge things
1022 // like pairs of loads from the same location, this catches a large number of
1023 // cases in practice.
1024 if (hasIdenticalMMOs(*this, Other))
1025 return std::make_pair(MemRefs, NumMemRefs);
1027 // TODO: consider uniquing elements within the operand lists to reduce
1028 // space usage and fall back to conservative information less often.
1029 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
1031 // If we don't have enough room to store this many memrefs, be conservative
1032 // and drop them. Otherwise, we'd fail asserts when trying to add them to
1033 // the new instruction.
1034 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
1035 return std::make_pair(nullptr, 0);
1037 MachineFunction *MF = getParent()->getParent();
1038 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
1039 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
1041 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
1043 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
1046 return std::make_pair(MemBegin, CombinedNumMemRefs);
1049 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
1050 assert(!isBundledWithPred() && "Must be called on bundle header");
1051 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1052 if (MII->getDesc().getFlags() & Mask) {
1053 if (Type == AnyInBundle)
1056 if (Type == AllInBundle && !MII->isBundle())
1059 // This was the last instruction in the bundle.
1060 if (!MII->isBundledWithSucc())
1061 return Type == AllInBundle;
1065 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1066 MICheckType Check) const {
1067 // If opcodes or number of operands are not the same then the two
1068 // instructions are obviously not identical.
1069 if (Other.getOpcode() != getOpcode() ||
1070 Other.getNumOperands() != getNumOperands())
1074 // We have passed the test above that both instructions have the same
1075 // opcode, so we know that both instructions are bundles here. Let's compare
1076 // MIs inside the bundle.
1077 assert(Other.isBundle() && "Expected that both instructions are bundles.");
1078 MachineBasicBlock::const_instr_iterator I1 = getIterator();
1079 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1080 // Loop until we analysed the last intruction inside at least one of the
1082 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1085 if (!I1->isIdenticalTo(*I2, Check))
1088 // If we've reached the end of just one of the two bundles, but not both,
1089 // the instructions are not identical.
1090 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1094 // Check operands to make sure they match.
1095 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1096 const MachineOperand &MO = getOperand(i);
1097 const MachineOperand &OMO = Other.getOperand(i);
1099 if (!MO.isIdenticalTo(OMO))
1104 // Clients may or may not want to ignore defs when testing for equality.
1105 // For example, machine CSE pass only cares about finding common
1106 // subexpressions, so it's safe to ignore virtual register defs.
1108 if (Check == IgnoreDefs)
1110 else if (Check == IgnoreVRegDefs) {
1111 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1112 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1113 if (MO.getReg() != OMO.getReg())
1116 if (!MO.isIdenticalTo(OMO))
1118 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1122 if (!MO.isIdenticalTo(OMO))
1124 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1128 // If DebugLoc does not match then two dbg.values are not identical.
1130 if (getDebugLoc() && Other.getDebugLoc() &&
1131 getDebugLoc() != Other.getDebugLoc())
1136 MachineInstr *MachineInstr::removeFromParent() {
1137 assert(getParent() && "Not embedded in a basic block!");
1138 return getParent()->remove(this);
1141 MachineInstr *MachineInstr::removeFromBundle() {
1142 assert(getParent() && "Not embedded in a basic block!");
1143 return getParent()->remove_instr(this);
1146 void MachineInstr::eraseFromParent() {
1147 assert(getParent() && "Not embedded in a basic block!");
1148 getParent()->erase(this);
1151 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1152 assert(getParent() && "Not embedded in a basic block!");
1153 MachineBasicBlock *MBB = getParent();
1154 MachineFunction *MF = MBB->getParent();
1155 assert(MF && "Not embedded in a function!");
1157 MachineInstr *MI = (MachineInstr *)this;
1158 MachineRegisterInfo &MRI = MF->getRegInfo();
1160 for (const MachineOperand &MO : MI->operands()) {
1161 if (!MO.isReg() || !MO.isDef())
1163 unsigned Reg = MO.getReg();
1164 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1166 MRI.markUsesInDebugValueAsUndef(Reg);
1168 MI->eraseFromParent();
1171 void MachineInstr::eraseFromBundle() {
1172 assert(getParent() && "Not embedded in a basic block!");
1173 getParent()->erase_instr(this);
1176 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1178 unsigned MachineInstr::getNumExplicitOperands() const {
1179 unsigned NumOperands = MCID->getNumOperands();
1180 if (!MCID->isVariadic())
1183 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1184 const MachineOperand &MO = getOperand(i);
1185 if (!MO.isReg() || !MO.isImplicit())
1191 void MachineInstr::bundleWithPred() {
1192 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1193 setFlag(BundledPred);
1194 MachineBasicBlock::instr_iterator Pred = getIterator();
1196 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1197 Pred->setFlag(BundledSucc);
1200 void MachineInstr::bundleWithSucc() {
1201 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1202 setFlag(BundledSucc);
1203 MachineBasicBlock::instr_iterator Succ = getIterator();
1205 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1206 Succ->setFlag(BundledPred);
1209 void MachineInstr::unbundleFromPred() {
1210 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1211 clearFlag(BundledPred);
1212 MachineBasicBlock::instr_iterator Pred = getIterator();
1214 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1215 Pred->clearFlag(BundledSucc);
1218 void MachineInstr::unbundleFromSucc() {
1219 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1220 clearFlag(BundledSucc);
1221 MachineBasicBlock::instr_iterator Succ = getIterator();
1223 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1224 Succ->clearFlag(BundledPred);
1227 bool MachineInstr::isStackAligningInlineAsm() const {
1228 if (isInlineAsm()) {
1229 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1230 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1236 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1237 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1238 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1239 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1242 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1243 unsigned *GroupNo) const {
1244 assert(isInlineAsm() && "Expected an inline asm instruction");
1245 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1247 // Ignore queries about the initial operands.
1248 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1253 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1255 const MachineOperand &FlagMO = getOperand(i);
1256 // If we reach the implicit register operands, stop looking.
1257 if (!FlagMO.isImm())
1259 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1260 if (i + NumOps > OpIdx) {
1270 const DILocalVariable *MachineInstr::getDebugVariable() const {
1271 assert(isDebugValue() && "not a DBG_VALUE");
1272 return cast<DILocalVariable>(getOperand(2).getMetadata());
1275 const DIExpression *MachineInstr::getDebugExpression() const {
1276 assert(isDebugValue() && "not a DBG_VALUE");
1277 return cast<DIExpression>(getOperand(3).getMetadata());
1280 const TargetRegisterClass*
1281 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1282 const TargetInstrInfo *TII,
1283 const TargetRegisterInfo *TRI) const {
1284 assert(getParent() && "Can't have an MBB reference here!");
1285 assert(getParent()->getParent() && "Can't have an MF reference here!");
1286 const MachineFunction &MF = *getParent()->getParent();
1288 // Most opcodes have fixed constraints in their MCInstrDesc.
1290 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1292 if (!getOperand(OpIdx).isReg())
1295 // For tied uses on inline asm, get the constraint from the def.
1297 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1300 // Inline asm stores register class constraints in the flag word.
1301 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1305 unsigned Flag = getOperand(FlagIdx).getImm();
1307 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1308 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1309 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1310 InlineAsm::hasRegClassConstraint(Flag, RCID))
1311 return TRI->getRegClass(RCID);
1313 // Assume that all registers in a memory operand are pointers.
1314 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1315 return TRI->getPointerRegClass(MF);
1320 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1321 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1322 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1323 // Check every operands inside the bundle if we have
1326 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1328 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1329 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1331 // Otherwise, just check the current operands.
1332 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1333 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1337 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1338 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1339 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1340 assert(CurRC && "Invalid initial register class");
1341 // Check if Reg is constrained by some of its use/def from MI.
1342 const MachineOperand &MO = getOperand(OpIdx);
1343 if (!MO.isReg() || MO.getReg() != Reg)
1345 // If yes, accumulate the constraints through the operand.
1346 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1349 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1350 unsigned OpIdx, const TargetRegisterClass *CurRC,
1351 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1352 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1353 const MachineOperand &MO = getOperand(OpIdx);
1354 assert(MO.isReg() &&
1355 "Cannot get register constraints for non-register operand");
1356 assert(CurRC && "Invalid initial register class");
1357 if (unsigned SubIdx = MO.getSubReg()) {
1359 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1361 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1363 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1367 /// Return the number of instructions inside the MI bundle, not counting the
1368 /// header instruction.
1369 unsigned MachineInstr::getBundleSize() const {
1370 MachineBasicBlock::const_instr_iterator I = getIterator();
1372 while (I->isBundledWithSucc()) {
1379 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1380 /// the given register (not considering sub/super-registers).
1381 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1383 const MachineOperand &MO = getOperand(i);
1384 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1390 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1391 /// the specific register or -1 if it is not found. It further tightens
1392 /// the search criteria to a use that kills the register if isKill is true.
1393 int MachineInstr::findRegisterUseOperandIdx(
1394 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1395 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1396 const MachineOperand &MO = getOperand(i);
1397 if (!MO.isReg() || !MO.isUse())
1399 unsigned MOReg = MO.getReg();
1402 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1403 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1404 TRI->isSubRegister(MOReg, Reg)))
1405 if (!isKill || MO.isKill())
1411 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1412 /// indicating if this instruction reads or writes Reg. This also considers
1413 /// partial defines.
1414 std::pair<bool,bool>
1415 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1416 SmallVectorImpl<unsigned> *Ops) const {
1417 bool PartDef = false; // Partial redefine.
1418 bool FullDef = false; // Full define.
1421 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1422 const MachineOperand &MO = getOperand(i);
1423 if (!MO.isReg() || MO.getReg() != Reg)
1428 Use |= !MO.isUndef();
1429 else if (MO.getSubReg() && !MO.isUndef())
1430 // A partial <def,undef> doesn't count as reading the register.
1435 // A partial redefine uses Reg unless there is also a full define.
1436 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1439 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1440 /// the specified register or -1 if it is not found. If isDead is true, defs
1441 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1442 /// also checks if there is a def of a super-register.
1444 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1445 const TargetRegisterInfo *TRI) const {
1446 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1447 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1448 const MachineOperand &MO = getOperand(i);
1449 // Accept regmask operands when Overlap is set.
1450 // Ignore them when looking for a specific def operand (Overlap == false).
1451 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1453 if (!MO.isReg() || !MO.isDef())
1455 unsigned MOReg = MO.getReg();
1456 bool Found = (MOReg == Reg);
1457 if (!Found && TRI && isPhys &&
1458 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1460 Found = TRI->regsOverlap(MOReg, Reg);
1462 Found = TRI->isSubRegister(MOReg, Reg);
1464 if (Found && (!isDead || MO.isDead()))
1470 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1471 /// operand list that is used to represent the predicate. It returns -1 if
1473 int MachineInstr::findFirstPredOperandIdx() const {
1474 // Don't call MCID.findFirstPredOperandIdx() because this variant
1475 // is sometimes called on an instruction that's not yet complete, and
1476 // so the number of operands is less than the MCID indicates. In
1477 // particular, the PTX target does this.
1478 const MCInstrDesc &MCID = getDesc();
1479 if (MCID.isPredicable()) {
1480 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1481 if (MCID.OpInfo[i].isPredicate())
1488 // MachineOperand::TiedTo is 4 bits wide.
1489 const unsigned TiedMax = 15;
1491 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1493 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1494 /// field. TiedTo can have these values:
1496 /// 0: Operand is not tied to anything.
1497 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1498 /// TiedMax: Tied to an operand >= TiedMax-1.
1500 /// The tied def must be one of the first TiedMax operands on a normal
1501 /// instruction. INLINEASM instructions allow more tied defs.
1503 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1504 MachineOperand &DefMO = getOperand(DefIdx);
1505 MachineOperand &UseMO = getOperand(UseIdx);
1506 assert(DefMO.isDef() && "DefIdx must be a def operand");
1507 assert(UseMO.isUse() && "UseIdx must be a use operand");
1508 assert(!DefMO.isTied() && "Def is already tied to another use");
1509 assert(!UseMO.isTied() && "Use is already tied to another def");
1511 if (DefIdx < TiedMax)
1512 UseMO.TiedTo = DefIdx + 1;
1514 // Inline asm can use the group descriptors to find tied operands, but on
1515 // normal instruction, the tied def must be within the first TiedMax
1517 assert(isInlineAsm() && "DefIdx out of range");
1518 UseMO.TiedTo = TiedMax;
1521 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1522 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1525 /// Given the index of a tied register operand, find the operand it is tied to.
1526 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1527 /// which must exist.
1528 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1529 const MachineOperand &MO = getOperand(OpIdx);
1530 assert(MO.isTied() && "Operand isn't tied");
1532 // Normally TiedTo is in range.
1533 if (MO.TiedTo < TiedMax)
1534 return MO.TiedTo - 1;
1536 // Uses on normal instructions can be out of range.
1537 if (!isInlineAsm()) {
1538 // Normal tied defs must be in the 0..TiedMax-1 range.
1541 // MO is a def. Search for the tied use.
1542 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1543 const MachineOperand &UseMO = getOperand(i);
1544 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1547 llvm_unreachable("Can't find tied use");
1550 // Now deal with inline asm by parsing the operand group descriptor flags.
1551 // Find the beginning of each operand group.
1552 SmallVector<unsigned, 8> GroupIdx;
1553 unsigned OpIdxGroup = ~0u;
1555 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1557 const MachineOperand &FlagMO = getOperand(i);
1558 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1559 unsigned CurGroup = GroupIdx.size();
1560 GroupIdx.push_back(i);
1561 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1562 // OpIdx belongs to this operand group.
1563 if (OpIdx > i && OpIdx < i + NumOps)
1564 OpIdxGroup = CurGroup;
1566 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1568 // Operands in this group are tied to operands in TiedGroup which must be
1569 // earlier. Find the number of operands between the two groups.
1570 unsigned Delta = i - GroupIdx[TiedGroup];
1572 // OpIdx is a use tied to TiedGroup.
1573 if (OpIdxGroup == CurGroup)
1574 return OpIdx - Delta;
1576 // OpIdx is a def tied to this use group.
1577 if (OpIdxGroup == TiedGroup)
1578 return OpIdx + Delta;
1580 llvm_unreachable("Invalid tied operand on inline asm");
1583 /// clearKillInfo - Clears kill flags on all operands.
1585 void MachineInstr::clearKillInfo() {
1586 for (MachineOperand &MO : operands()) {
1587 if (MO.isReg() && MO.isUse())
1588 MO.setIsKill(false);
1592 void MachineInstr::substituteRegister(unsigned FromReg,
1595 const TargetRegisterInfo &RegInfo) {
1596 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1598 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1599 for (MachineOperand &MO : operands()) {
1600 if (!MO.isReg() || MO.getReg() != FromReg)
1602 MO.substPhysReg(ToReg, RegInfo);
1605 for (MachineOperand &MO : operands()) {
1606 if (!MO.isReg() || MO.getReg() != FromReg)
1608 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1613 /// isSafeToMove - Return true if it is safe to move this instruction. If
1614 /// SawStore is set to true, it means that there is a store (or call) between
1615 /// the instruction's location and its intended destination.
1616 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1617 // Ignore stuff that we obviously can't move.
1619 // Treat volatile loads as stores. This is not strictly necessary for
1620 // volatiles, but it is required for atomic loads. It is not allowed to move
1621 // a load across an atomic load with Ordering > Monotonic.
1622 if (mayStore() || isCall() ||
1623 (mayLoad() && hasOrderedMemoryRef())) {
1628 if (isPosition() || isDebugValue() || isTerminator() ||
1629 hasUnmodeledSideEffects())
1632 // See if this instruction does a load. If so, we have to guarantee that the
1633 // loaded value doesn't change between the load and the its intended
1634 // destination. The check for isInvariantLoad gives the targe the chance to
1635 // classify the load as always returning a constant, e.g. a constant pool
1637 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1638 // Otherwise, this is a real load. If there is a store between the load and
1639 // end of block, we can't move it.
1645 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1647 const MachineFunction *MF = getParent()->getParent();
1648 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1650 // If neither instruction stores to memory, they can't alias in any
1651 // meaningful way, even if they read from the same address.
1652 if (!mayStore() && !Other.mayStore())
1655 // Let the target decide if memory accesses cannot possibly overlap.
1656 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1662 // FIXME: Need to handle multiple memory operands to support all targets.
1663 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1666 MachineMemOperand *MMOa = *memoperands_begin();
1667 MachineMemOperand *MMOb = *Other.memoperands_begin();
1669 if (!MMOa->getValue() || !MMOb->getValue())
1672 // The following interface to AA is fashioned after DAGCombiner::isAlias
1673 // and operates with MachineMemOperand offset with some important
1675 // - LLVM fundamentally assumes flat address spaces.
1676 // - MachineOperand offset can *only* result from legalization and
1677 // cannot affect queries other than the trivial case of overlap
1679 // - These offsets never wrap and never step outside
1680 // of allocated objects.
1681 // - There should never be any negative offsets here.
1683 // FIXME: Modify API to hide this math from "user"
1684 // FIXME: Even before we go to AA we can reason locally about some
1685 // memory objects. It can save compile time, and possibly catch some
1686 // corner cases not currently covered.
1688 assert((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
1689 assert((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
1691 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
1692 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
1693 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
1695 AliasResult AAResult =
1696 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
1697 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1698 MemoryLocation(MMOb->getValue(), Overlapb,
1699 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1701 return (AAResult != NoAlias);
1704 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1705 /// or volatile memory reference, or if the information describing the memory
1706 /// reference is not available. Return false if it is known to have no ordered
1707 /// memory references.
1708 bool MachineInstr::hasOrderedMemoryRef() const {
1709 // An instruction known never to access memory won't have a volatile access.
1713 !hasUnmodeledSideEffects())
1716 // Otherwise, if the instruction has no memory reference information,
1717 // conservatively assume it wasn't preserved.
1718 if (memoperands_empty())
1721 // Check if any of our memory operands are ordered.
1722 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
1723 return !MMO->isUnordered();
1727 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1728 /// trap and is loading from a location whose value is invariant across a run of
1730 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1731 // If the instruction doesn't load at all, it isn't an invariant load.
1735 // If the instruction has lost its memoperands, conservatively assume that
1736 // it may not be an invariant load.
1737 if (memoperands_empty())
1740 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1742 for (MachineMemOperand *MMO : memoperands()) {
1743 if (MMO->isVolatile()) return false;
1744 if (MMO->isStore()) return false;
1745 if (MMO->isInvariant() && MMO->isDereferenceable())
1748 // A load from a constant PseudoSourceValue is invariant.
1749 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1750 if (PSV->isConstant(&MFI))
1753 if (const Value *V = MMO->getValue()) {
1754 // If we have an AliasAnalysis, ask it whether the memory is constant.
1756 AA->pointsToConstantMemory(
1757 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1761 // Otherwise assume conservatively.
1765 // Everything checks out.
1769 /// isConstantValuePHI - If the specified instruction is a PHI that always
1770 /// merges together the same virtual register, return the register, otherwise
1772 unsigned MachineInstr::isConstantValuePHI() const {
1775 assert(getNumOperands() >= 3 &&
1776 "It's illegal to have a PHI without source operands");
1778 unsigned Reg = getOperand(1).getReg();
1779 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1780 if (getOperand(i).getReg() != Reg)
1785 bool MachineInstr::hasUnmodeledSideEffects() const {
1786 if (hasProperty(MCID::UnmodeledSideEffects))
1788 if (isInlineAsm()) {
1789 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1790 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1797 bool MachineInstr::isLoadFoldBarrier() const {
1798 return mayStore() || isCall() || hasUnmodeledSideEffects();
1801 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1803 bool MachineInstr::allDefsAreDead() const {
1804 for (const MachineOperand &MO : operands()) {
1805 if (!MO.isReg() || MO.isUse())
1813 /// copyImplicitOps - Copy implicit register operands from specified
1814 /// instruction to this instruction.
1815 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1816 const MachineInstr &MI) {
1817 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1819 const MachineOperand &MO = MI.getOperand(i);
1820 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1825 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1826 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1832 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1833 const TargetInstrInfo *TII) const {
1834 const Module *M = nullptr;
1835 if (const MachineBasicBlock *MBB = getParent())
1836 if (const MachineFunction *MF = MBB->getParent())
1837 M = MF->getFunction()->getParent();
1839 ModuleSlotTracker MST(M);
1840 print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1843 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1844 bool SkipOpers, bool SkipDebugLoc,
1845 const TargetInstrInfo *TII) const {
1846 // We can be a bit tidier if we know the MachineFunction.
1847 const MachineFunction *MF = nullptr;
1848 const TargetRegisterInfo *TRI = nullptr;
1849 const MachineRegisterInfo *MRI = nullptr;
1850 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1852 if (const MachineBasicBlock *MBB = getParent()) {
1853 MF = MBB->getParent();
1855 MRI = &MF->getRegInfo();
1856 TRI = MF->getSubtarget().getRegisterInfo();
1858 TII = MF->getSubtarget().getInstrInfo();
1859 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1863 // Save a list of virtual registers.
1864 SmallVector<unsigned, 8> VirtRegs;
1866 // Print explicitly defined operands on the left of an assignment syntax.
1867 unsigned StartOp = 0, e = getNumOperands();
1868 for (; StartOp < e && getOperand(StartOp).isReg() &&
1869 getOperand(StartOp).isDef() &&
1870 !getOperand(StartOp).isImplicit();
1872 if (StartOp != 0) OS << ", ";
1873 getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1874 unsigned Reg = getOperand(StartOp).getReg();
1875 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1876 VirtRegs.push_back(Reg);
1877 LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1879 OS << '(' << Ty << ')';
1886 // Print the opcode name.
1888 OS << TII->getName(getOpcode());
1895 // Print the rest of the operands.
1896 bool FirstOp = true;
1897 unsigned AsmDescOp = ~0u;
1898 unsigned AsmOpCount = 0;
1900 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1901 // Print asm string.
1903 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1905 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1906 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1907 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1908 OS << " [sideeffect]";
1909 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1911 if (ExtraInfo & InlineAsm::Extra_MayStore)
1912 OS << " [maystore]";
1913 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1914 OS << " [isconvergent]";
1915 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1916 OS << " [alignstack]";
1917 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1918 OS << " [attdialect]";
1919 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1920 OS << " [inteldialect]";
1922 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1926 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1927 const MachineOperand &MO = getOperand(i);
1929 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1930 VirtRegs.push_back(MO.getReg());
1932 if (FirstOp) FirstOp = false; else OS << ",";
1934 if (i < getDesc().NumOperands) {
1935 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1936 if (MCOI.isPredicate())
1938 if (MCOI.isOptionalDef())
1941 if (isDebugValue() && MO.isMetadata()) {
1942 // Pretty print DBG_VALUE instructions.
1943 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1944 if (DIV && !DIV->getName().empty())
1945 OS << "!\"" << DIV->getName() << '\"';
1947 MO.print(OS, MST, TRI);
1948 } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1949 (isSubregToReg() && i == 3)) && MO.isImm()) {
1950 OS << TRI->getSubRegIndexName(MO.getImm());
1951 } else if (i == AsmDescOp && MO.isImm()) {
1952 // Pretty print the inline asm operand descriptor.
1953 OS << '$' << AsmOpCount++;
1954 unsigned Flag = MO.getImm();
1955 switch (InlineAsm::getKind(Flag)) {
1956 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1957 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1958 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1959 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1960 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1961 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1962 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1966 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1967 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1969 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1971 OS << ":RC" << RCID;
1974 if (InlineAsm::isMemKind(Flag)) {
1975 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1977 case InlineAsm::Constraint_es: OS << ":es"; break;
1978 case InlineAsm::Constraint_i: OS << ":i"; break;
1979 case InlineAsm::Constraint_m: OS << ":m"; break;
1980 case InlineAsm::Constraint_o: OS << ":o"; break;
1981 case InlineAsm::Constraint_v: OS << ":v"; break;
1982 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1983 case InlineAsm::Constraint_R: OS << ":R"; break;
1984 case InlineAsm::Constraint_S: OS << ":S"; break;
1985 case InlineAsm::Constraint_T: OS << ":T"; break;
1986 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1987 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1988 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1989 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1990 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1991 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1992 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1993 case InlineAsm::Constraint_X: OS << ":X"; break;
1994 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1995 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1996 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1997 default: OS << ":?"; break;
2001 unsigned TiedTo = 0;
2002 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
2003 OS << " tiedto:$" << TiedTo;
2007 // Compute the index of the next operand descriptor.
2008 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
2010 MO.print(OS, MST, TRI);
2013 bool HaveSemi = false;
2014 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2015 if (Flags & PrintableFlags) {
2022 if (Flags & FrameSetup)
2025 if (Flags & FrameDestroy)
2026 OS << "FrameDestroy";
2029 if (!memoperands_empty()) {
2036 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2038 (*i)->print(OS, MST);
2039 if (std::next(i) != e)
2044 // Print the regclass of any virtual registers encountered.
2045 if (MRI && !VirtRegs.empty()) {
2050 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2051 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2054 // Generic virtual registers do not have register classes.
2055 if (RC.is<const RegisterBank *>())
2056 OS << " " << RC.get<const RegisterBank *>()->getName();
2059 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2060 OS << ':' << PrintReg(VirtRegs[i]);
2061 for (unsigned j = i+1; j != VirtRegs.size();) {
2062 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2066 if (VirtRegs[i] != VirtRegs[j])
2067 OS << "," << PrintReg(VirtRegs[j]);
2068 VirtRegs.erase(VirtRegs.begin()+j);
2073 // Print debug location information.
2074 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2077 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2078 OS << " line no:" << DV->getLine();
2079 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2080 DebugLoc InlinedAtDL(InlinedAt);
2081 if (InlinedAtDL && MF) {
2082 OS << " inlined @[ ";
2083 InlinedAtDL.print(OS);
2087 if (isIndirectDebugValue())
2089 } else if (SkipDebugLoc) {
2091 } else if (debugLoc && MF) {
2101 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2102 const TargetRegisterInfo *RegInfo,
2103 bool AddIfNotFound) {
2104 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2105 bool hasAliases = isPhysReg &&
2106 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2108 SmallVector<unsigned,4> DeadOps;
2109 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2110 MachineOperand &MO = getOperand(i);
2111 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2114 // DEBUG_VALUE nodes do not contribute to code generation and should
2115 // always be ignored. Failure to do so may result in trying to modify
2116 // KILL flags on DEBUG_VALUE nodes.
2120 unsigned Reg = MO.getReg();
2124 if (Reg == IncomingReg) {
2127 // The register is already marked kill.
2129 if (isPhysReg && isRegTiedToDefOperand(i))
2130 // Two-address uses of physregs must not be marked kill.
2135 } else if (hasAliases && MO.isKill() &&
2136 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2137 // A super-register kill already exists.
2138 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2140 if (RegInfo->isSubRegister(IncomingReg, Reg))
2141 DeadOps.push_back(i);
2145 // Trim unneeded kill operands.
2146 while (!DeadOps.empty()) {
2147 unsigned OpIdx = DeadOps.back();
2148 if (getOperand(OpIdx).isImplicit())
2149 RemoveOperand(OpIdx);
2151 getOperand(OpIdx).setIsKill(false);
2155 // If not found, this means an alias of one of the operands is killed. Add a
2156 // new implicit operand if required.
2157 if (!Found && AddIfNotFound) {
2158 addOperand(MachineOperand::CreateReg(IncomingReg,
2167 void MachineInstr::clearRegisterKills(unsigned Reg,
2168 const TargetRegisterInfo *RegInfo) {
2169 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2171 for (MachineOperand &MO : operands()) {
2172 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2174 unsigned OpReg = MO.getReg();
2175 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2176 MO.setIsKill(false);
2180 bool MachineInstr::addRegisterDead(unsigned Reg,
2181 const TargetRegisterInfo *RegInfo,
2182 bool AddIfNotFound) {
2183 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2184 bool hasAliases = isPhysReg &&
2185 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2187 SmallVector<unsigned,4> DeadOps;
2188 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2189 MachineOperand &MO = getOperand(i);
2190 if (!MO.isReg() || !MO.isDef())
2192 unsigned MOReg = MO.getReg();
2199 } else if (hasAliases && MO.isDead() &&
2200 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2201 // There exists a super-register that's marked dead.
2202 if (RegInfo->isSuperRegister(Reg, MOReg))
2204 if (RegInfo->isSubRegister(Reg, MOReg))
2205 DeadOps.push_back(i);
2209 // Trim unneeded dead operands.
2210 while (!DeadOps.empty()) {
2211 unsigned OpIdx = DeadOps.back();
2212 if (getOperand(OpIdx).isImplicit())
2213 RemoveOperand(OpIdx);
2215 getOperand(OpIdx).setIsDead(false);
2219 // If not found, this means an alias of one of the operands is dead. Add a
2220 // new implicit operand if required.
2221 if (Found || !AddIfNotFound)
2224 addOperand(MachineOperand::CreateReg(Reg,
2232 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2233 for (MachineOperand &MO : operands()) {
2234 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2236 MO.setIsDead(false);
2240 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2241 for (MachineOperand &MO : operands()) {
2242 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2244 MO.setIsUndef(IsUndef);
2248 void MachineInstr::addRegisterDefined(unsigned Reg,
2249 const TargetRegisterInfo *RegInfo) {
2250 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2251 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2255 for (const MachineOperand &MO : operands()) {
2256 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2257 MO.getSubReg() == 0)
2261 addOperand(MachineOperand::CreateReg(Reg,
2266 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2267 const TargetRegisterInfo &TRI) {
2268 bool HasRegMask = false;
2269 for (MachineOperand &MO : operands()) {
2270 if (MO.isRegMask()) {
2274 if (!MO.isReg() || !MO.isDef()) continue;
2275 unsigned Reg = MO.getReg();
2276 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2277 // If there are no uses, including partial uses, the def is dead.
2278 if (llvm::none_of(UsedRegs,
2279 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2283 // This is a call with a register mask operand.
2284 // Mask clobbers are always dead, so add defs for the non-dead defines.
2286 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2288 addRegisterDefined(*I, &TRI);
2292 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2293 // Build up a buffer of hash code components.
2294 SmallVector<size_t, 8> HashComponents;
2295 HashComponents.reserve(MI->getNumOperands() + 1);
2296 HashComponents.push_back(MI->getOpcode());
2297 for (const MachineOperand &MO : MI->operands()) {
2298 if (MO.isReg() && MO.isDef() &&
2299 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2300 continue; // Skip virtual register defs.
2302 HashComponents.push_back(hash_value(MO));
2304 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2307 void MachineInstr::emitError(StringRef Msg) const {
2308 // Find the source location cookie.
2309 unsigned LocCookie = 0;
2310 const MDNode *LocMD = nullptr;
2311 for (unsigned i = getNumOperands(); i != 0; --i) {
2312 if (getOperand(i-1).isMetadata() &&
2313 (LocMD = getOperand(i-1).getMetadata()) &&
2314 LocMD->getNumOperands() != 0) {
2315 if (const ConstantInt *CI =
2316 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2317 LocCookie = CI->getZExtValue();
2323 if (const MachineBasicBlock *MBB = getParent())
2324 if (const MachineFunction *MF = MBB->getParent())
2325 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2326 report_fatal_error(Msg);
2329 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2330 const MCInstrDesc &MCID, bool IsIndirect,
2331 unsigned Reg, unsigned Offset,
2332 const MDNode *Variable, const MDNode *Expr) {
2333 assert(isa<DILocalVariable>(Variable) && "not a variable");
2334 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2335 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2336 "Expected inlined-at fields to agree");
2338 return BuildMI(MF, DL, MCID)
2339 .addReg(Reg, RegState::Debug)
2341 .addMetadata(Variable)
2344 assert(Offset == 0 && "A direct address cannot have an offset.");
2345 return BuildMI(MF, DL, MCID)
2346 .addReg(Reg, RegState::Debug)
2347 .addReg(0U, RegState::Debug)
2348 .addMetadata(Variable)
2353 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2354 MachineBasicBlock::iterator I,
2355 const DebugLoc &DL, const MCInstrDesc &MCID,
2356 bool IsIndirect, unsigned Reg,
2357 unsigned Offset, const MDNode *Variable,
2358 const MDNode *Expr) {
2359 assert(isa<DILocalVariable>(Variable) && "not a variable");
2360 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2361 MachineFunction &MF = *BB.getParent();
2363 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2365 return MachineInstrBuilder(MF, MI);
2368 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
2369 MachineBasicBlock::iterator I,
2370 const MachineInstr &Orig,
2372 const MDNode *Var = Orig.getDebugVariable();
2373 const auto *Expr = cast_or_null<DIExpression>(Orig.getDebugExpression());
2374 bool IsIndirect = Orig.isIndirectDebugValue();
2375 uint64_t Offset = IsIndirect ? Orig.getOperand(1).getImm() : 0;
2376 DebugLoc DL = Orig.getDebugLoc();
2377 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
2378 "Expected inlined-at fields to agree");
2379 // If the DBG_VALUE already was a memory location, add an extra
2380 // DW_OP_deref. Otherwise just turning this from a register into a
2381 // memory/indirect location is sufficient.
2383 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
2384 return BuildMI(BB, I, DL, Orig.getDesc())
2385 .addFrameIndex(FrameIndex)