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/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
49 void MachineOperand::setReg(unsigned Reg) {
50 if (getReg() == Reg) return; // No change.
52 // Otherwise, we have to change the register. If this operand is embedded
53 // into a machine function, we need to update the old and new register's
55 if (MachineInstr *MI = getParent())
56 if (MachineBasicBlock *MBB = MI->getParent())
57 if (MachineFunction *MF = MBB->getParent()) {
58 MachineRegisterInfo &MRI = MF->getRegInfo();
59 MRI.removeRegOperandFromUseList(this);
60 SmallContents.RegNo = Reg;
61 MRI.addRegOperandToUseList(this);
65 // Otherwise, just change the register, no problem. :)
66 SmallContents.RegNo = Reg;
69 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
70 const TargetRegisterInfo &TRI) {
71 assert(TargetRegisterInfo::isVirtualRegister(Reg));
72 if (SubIdx && getSubReg())
73 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
79 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
80 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
82 Reg = TRI.getSubReg(Reg, getSubReg());
83 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
84 // That won't happen in legal code.
90 /// Change a def to a use, or a use to a def.
91 void MachineOperand::setIsDef(bool Val) {
92 assert(isReg() && "Wrong MachineOperand accessor");
93 assert((!Val || !isDebug()) && "Marking a debug operation as def");
96 // MRI may keep uses and defs in different list positions.
97 if (MachineInstr *MI = getParent())
98 if (MachineBasicBlock *MBB = MI->getParent())
99 if (MachineFunction *MF = MBB->getParent()) {
100 MachineRegisterInfo &MRI = MF->getRegInfo();
101 MRI.removeRegOperandFromUseList(this);
103 MRI.addRegOperandToUseList(this);
109 // If this operand is currently a register operand, and if this is in a
110 // function, deregister the operand from the register's use/def list.
111 void MachineOperand::removeRegFromUses() {
112 if (!isReg() || !isOnRegUseList())
115 if (MachineInstr *MI = getParent()) {
116 if (MachineBasicBlock *MBB = MI->getParent()) {
117 if (MachineFunction *MF = MBB->getParent())
118 MF->getRegInfo().removeRegOperandFromUseList(this);
123 /// ChangeToImmediate - Replace this operand with a new immediate operand of
124 /// the specified value. If an operand is known to be an immediate already,
125 /// the setImm method should be used.
126 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
127 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
131 OpKind = MO_Immediate;
132 Contents.ImmVal = ImmVal;
135 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
136 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
140 OpKind = MO_FPImmediate;
141 Contents.CFP = FPImm;
144 /// ChangeToRegister - Replace this operand with a new register operand of
145 /// the specified value. If an operand is known to be an register already,
146 /// the setReg method should be used.
147 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
148 bool isKill, bool isDead, bool isUndef,
150 MachineRegisterInfo *RegInfo = nullptr;
151 if (MachineInstr *MI = getParent())
152 if (MachineBasicBlock *MBB = MI->getParent())
153 if (MachineFunction *MF = MBB->getParent())
154 RegInfo = &MF->getRegInfo();
155 // If this operand is already a register operand, remove it from the
156 // register's use/def lists.
157 bool WasReg = isReg();
158 if (RegInfo && WasReg)
159 RegInfo->removeRegOperandFromUseList(this);
161 // Change this to a register and set the reg#.
162 OpKind = MO_Register;
163 SmallContents.RegNo = Reg;
164 SubReg_TargetFlags = 0;
170 IsInternalRead = false;
171 IsEarlyClobber = false;
173 // Ensure isOnRegUseList() returns false.
174 Contents.Reg.Prev = nullptr;
175 // Preserve the tie when the operand was already a register.
179 // If this operand is embedded in a function, add the operand to the
180 // register's use/def list.
182 RegInfo->addRegOperandToUseList(this);
185 /// isIdenticalTo - Return true if this operand is identical to the specified
186 /// operand. Note that this should stay in sync with the hash_value overload
188 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
189 if (getType() != Other.getType() ||
190 getTargetFlags() != Other.getTargetFlags())
194 case MachineOperand::MO_Register:
195 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
196 getSubReg() == Other.getSubReg();
197 case MachineOperand::MO_Immediate:
198 return getImm() == Other.getImm();
199 case MachineOperand::MO_CImmediate:
200 return getCImm() == Other.getCImm();
201 case MachineOperand::MO_FPImmediate:
202 return getFPImm() == Other.getFPImm();
203 case MachineOperand::MO_MachineBasicBlock:
204 return getMBB() == Other.getMBB();
205 case MachineOperand::MO_FrameIndex:
206 return getIndex() == Other.getIndex();
207 case MachineOperand::MO_ConstantPoolIndex:
208 case MachineOperand::MO_TargetIndex:
209 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
210 case MachineOperand::MO_JumpTableIndex:
211 return getIndex() == Other.getIndex();
212 case MachineOperand::MO_GlobalAddress:
213 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
214 case MachineOperand::MO_ExternalSymbol:
215 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
216 getOffset() == Other.getOffset();
217 case MachineOperand::MO_BlockAddress:
218 return getBlockAddress() == Other.getBlockAddress() &&
219 getOffset() == Other.getOffset();
220 case MachineOperand::MO_RegisterMask:
221 case MachineOperand::MO_RegisterLiveOut:
222 return getRegMask() == Other.getRegMask();
223 case MachineOperand::MO_MCSymbol:
224 return getMCSymbol() == Other.getMCSymbol();
225 case MachineOperand::MO_CFIIndex:
226 return getCFIIndex() == Other.getCFIIndex();
227 case MachineOperand::MO_Metadata:
228 return getMetadata() == Other.getMetadata();
230 llvm_unreachable("Invalid machine operand type");
233 // Note: this must stay exactly in sync with isIdenticalTo above.
234 hash_code llvm::hash_value(const MachineOperand &MO) {
235 switch (MO.getType()) {
236 case MachineOperand::MO_Register:
237 // Register operands don't have target flags.
238 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
239 case MachineOperand::MO_Immediate:
240 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
241 case MachineOperand::MO_CImmediate:
242 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
243 case MachineOperand::MO_FPImmediate:
244 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
245 case MachineOperand::MO_MachineBasicBlock:
246 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
247 case MachineOperand::MO_FrameIndex:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
249 case MachineOperand::MO_ConstantPoolIndex:
250 case MachineOperand::MO_TargetIndex:
251 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
253 case MachineOperand::MO_JumpTableIndex:
254 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
255 case MachineOperand::MO_ExternalSymbol:
256 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
258 case MachineOperand::MO_GlobalAddress:
259 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
261 case MachineOperand::MO_BlockAddress:
262 return hash_combine(MO.getType(), MO.getTargetFlags(),
263 MO.getBlockAddress(), MO.getOffset());
264 case MachineOperand::MO_RegisterMask:
265 case MachineOperand::MO_RegisterLiveOut:
266 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
267 case MachineOperand::MO_Metadata:
268 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
269 case MachineOperand::MO_MCSymbol:
270 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
271 case MachineOperand::MO_CFIIndex:
272 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
274 llvm_unreachable("Invalid machine operand type");
277 /// print - Print the specified machine operand.
279 void MachineOperand::print(raw_ostream &OS,
280 const TargetRegisterInfo *TRI) const {
282 case MachineOperand::MO_Register:
283 OS << PrintReg(getReg(), TRI, getSubReg());
285 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
286 isInternalRead() || isEarlyClobber() || isTied()) {
288 bool NeedComma = false;
290 if (NeedComma) OS << ',';
291 if (isEarlyClobber())
292 OS << "earlyclobber,";
297 // <def,read-undef> only makes sense when getSubReg() is set.
298 // Don't clutter the output otherwise.
299 if (isUndef() && getSubReg())
301 } else if (isImplicit()) {
307 if (NeedComma) OS << ',';
312 if (NeedComma) OS << ',';
316 if (isUndef() && isUse()) {
317 if (NeedComma) OS << ',';
321 if (isInternalRead()) {
322 if (NeedComma) OS << ',';
327 if (NeedComma) OS << ',';
330 OS << unsigned(TiedTo - 1);
335 case MachineOperand::MO_Immediate:
338 case MachineOperand::MO_CImmediate:
339 getCImm()->getValue().print(OS, false);
341 case MachineOperand::MO_FPImmediate:
342 if (getFPImm()->getType()->isFloatTy())
343 OS << getFPImm()->getValueAPF().convertToFloat();
345 OS << getFPImm()->getValueAPF().convertToDouble();
347 case MachineOperand::MO_MachineBasicBlock:
348 OS << "<BB#" << getMBB()->getNumber() << ">";
350 case MachineOperand::MO_FrameIndex:
351 OS << "<fi#" << getIndex() << '>';
353 case MachineOperand::MO_ConstantPoolIndex:
354 OS << "<cp#" << getIndex();
355 if (getOffset()) OS << "+" << getOffset();
358 case MachineOperand::MO_TargetIndex:
359 OS << "<ti#" << getIndex();
360 if (getOffset()) OS << "+" << getOffset();
363 case MachineOperand::MO_JumpTableIndex:
364 OS << "<jt#" << getIndex() << '>';
366 case MachineOperand::MO_GlobalAddress:
368 getGlobal()->printAsOperand(OS, /*PrintType=*/false);
369 if (getOffset()) OS << "+" << getOffset();
372 case MachineOperand::MO_ExternalSymbol:
373 OS << "<es:" << getSymbolName();
374 if (getOffset()) OS << "+" << getOffset();
377 case MachineOperand::MO_BlockAddress:
379 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false);
380 if (getOffset()) OS << "+" << getOffset();
383 case MachineOperand::MO_RegisterMask:
386 case MachineOperand::MO_RegisterLiveOut:
387 OS << "<regliveout>";
389 case MachineOperand::MO_Metadata:
391 getMetadata()->printAsOperand(OS);
394 case MachineOperand::MO_MCSymbol:
395 OS << "<MCSym=" << *getMCSymbol() << '>';
397 case MachineOperand::MO_CFIIndex:
398 OS << "<call frame instruction>";
402 if (unsigned TF = getTargetFlags())
403 OS << "[TF=" << TF << ']';
406 //===----------------------------------------------------------------------===//
407 // MachineMemOperand Implementation
408 //===----------------------------------------------------------------------===//
410 /// getAddrSpace - Return the LLVM IR address space number that this pointer
412 unsigned MachinePointerInfo::getAddrSpace() const {
413 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
414 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
417 /// getConstantPool - Return a MachinePointerInfo record that refers to the
419 MachinePointerInfo MachinePointerInfo::getConstantPool() {
420 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
423 /// getFixedStack - Return a MachinePointerInfo record that refers to the
424 /// the specified FrameIndex.
425 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
426 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
429 MachinePointerInfo MachinePointerInfo::getJumpTable() {
430 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
433 MachinePointerInfo MachinePointerInfo::getGOT() {
434 return MachinePointerInfo(PseudoSourceValue::getGOT());
437 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
438 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
441 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
442 uint64_t s, unsigned int a,
443 const AAMDNodes &AAInfo,
444 const MDNode *Ranges)
445 : PtrInfo(ptrinfo), Size(s),
446 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
447 AAInfo(AAInfo), Ranges(Ranges) {
448 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
449 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
450 "invalid pointer value");
451 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
452 assert((isLoad() || isStore()) && "Not a load/store!");
455 /// Profile - Gather unique data for the object.
457 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
458 ID.AddInteger(getOffset());
460 ID.AddPointer(getOpaqueValue());
461 ID.AddInteger(Flags);
464 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
465 // The Value and Offset may differ due to CSE. But the flags and size
466 // should be the same.
467 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
468 assert(MMO->getSize() == getSize() && "Size mismatch!");
470 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
471 // Update the alignment value.
472 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
473 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
474 // Also update the base and offset, because the new alignment may
475 // not be applicable with the old ones.
476 PtrInfo = MMO->PtrInfo;
480 /// getAlignment - Return the minimum known alignment in bytes of the
481 /// actual memory reference.
482 uint64_t MachineMemOperand::getAlignment() const {
483 return MinAlign(getBaseAlignment(), getOffset());
486 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
487 assert((MMO.isLoad() || MMO.isStore()) &&
488 "SV has to be a load, store or both.");
490 if (MMO.isVolatile())
499 // Print the address information.
501 if (const Value *V = MMO.getValue())
502 V->printAsOperand(OS, /*PrintType=*/false);
503 else if (const PseudoSourceValue *PSV = MMO.getPseudoValue())
504 PSV->printCustom(OS);
508 unsigned AS = MMO.getAddrSpace();
510 OS << "(addrspace=" << AS << ')';
512 // If the alignment of the memory reference itself differs from the alignment
513 // of the base pointer, print the base alignment explicitly, next to the base
515 if (MMO.getBaseAlignment() != MMO.getAlignment())
516 OS << "(align=" << MMO.getBaseAlignment() << ")";
518 if (MMO.getOffset() != 0)
519 OS << "+" << MMO.getOffset();
522 // Print the alignment of the reference.
523 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
524 MMO.getBaseAlignment() != MMO.getSize())
525 OS << "(align=" << MMO.getAlignment() << ")";
528 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
530 if (TBAAInfo->getNumOperands() > 0)
531 TBAAInfo->getOperand(0)->printAsOperand(OS);
537 // Print AA scope info.
538 if (const MDNode *ScopeInfo = MMO.getAAInfo().Scope) {
539 OS << "(alias.scope=";
540 if (ScopeInfo->getNumOperands() > 0)
541 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
542 ScopeInfo->getOperand(i)->printAsOperand(OS);
551 // Print AA noalias scope info.
552 if (const MDNode *NoAliasInfo = MMO.getAAInfo().NoAlias) {
554 if (NoAliasInfo->getNumOperands() > 0)
555 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
556 NoAliasInfo->getOperand(i)->printAsOperand(OS);
565 // Print nontemporal info.
566 if (MMO.isNonTemporal())
567 OS << "(nontemporal)";
572 //===----------------------------------------------------------------------===//
573 // MachineInstr Implementation
574 //===----------------------------------------------------------------------===//
576 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
577 if (MCID->ImplicitDefs)
578 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
579 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
580 if (MCID->ImplicitUses)
581 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
582 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
585 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
586 /// implicit operands. It reserves space for the number of operands specified by
588 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
589 DebugLoc dl, bool NoImp)
590 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
591 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
592 debugLoc(std::move(dl)) {
593 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
595 // Reserve space for the expected number of operands.
596 if (unsigned NumOps = MCID->getNumOperands() +
597 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
598 CapOperands = OperandCapacity::get(NumOps);
599 Operands = MF.allocateOperandArray(CapOperands);
603 addImplicitDefUseOperands(MF);
606 /// MachineInstr ctor - Copies MachineInstr arg exactly
608 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
609 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
610 Flags(0), AsmPrinterFlags(0),
611 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
612 debugLoc(MI.getDebugLoc()) {
613 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
615 CapOperands = OperandCapacity::get(MI.getNumOperands());
616 Operands = MF.allocateOperandArray(CapOperands);
619 for (const MachineOperand &MO : MI.operands())
622 // Copy all the sensible flags.
626 /// getRegInfo - If this instruction is embedded into a MachineFunction,
627 /// return the MachineRegisterInfo object for the current function, otherwise
629 MachineRegisterInfo *MachineInstr::getRegInfo() {
630 if (MachineBasicBlock *MBB = getParent())
631 return &MBB->getParent()->getRegInfo();
635 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
636 /// this instruction from their respective use lists. This requires that the
637 /// operands already be on their use lists.
638 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
639 for (MachineOperand &MO : operands())
641 MRI.removeRegOperandFromUseList(&MO);
644 /// AddRegOperandsToUseLists - Add all of the register operands in
645 /// this instruction from their respective use lists. This requires that the
646 /// operands not be on their use lists yet.
647 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
648 for (MachineOperand &MO : operands())
650 MRI.addRegOperandToUseList(&MO);
653 void MachineInstr::addOperand(const MachineOperand &Op) {
654 MachineBasicBlock *MBB = getParent();
655 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
656 MachineFunction *MF = MBB->getParent();
657 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
661 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
662 /// ranges. If MRI is non-null also update use-def chains.
663 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
664 unsigned NumOps, MachineRegisterInfo *MRI) {
666 return MRI->moveOperands(Dst, Src, NumOps);
668 // MachineOperand is a trivially copyable type so we can just use memmove.
669 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
672 /// addOperand - Add the specified operand to the instruction. If it is an
673 /// implicit operand, it is added to the end of the operand list. If it is
674 /// an explicit operand it is added at the end of the explicit operand list
675 /// (before the first implicit operand).
676 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
677 assert(MCID && "Cannot add operands before providing an instr descriptor");
679 // Check if we're adding one of our existing operands.
680 if (&Op >= Operands && &Op < Operands + NumOperands) {
681 // This is unusual: MI->addOperand(MI->getOperand(i)).
682 // If adding Op requires reallocating or moving existing operands around,
683 // the Op reference could go stale. Support it by copying Op.
684 MachineOperand CopyOp(Op);
685 return addOperand(MF, CopyOp);
688 // Find the insert location for the new operand. Implicit registers go at
689 // the end, everything else goes before the implicit regs.
691 // FIXME: Allow mixed explicit and implicit operands on inline asm.
692 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
693 // implicit-defs, but they must not be moved around. See the FIXME in
695 unsigned OpNo = getNumOperands();
696 bool isImpReg = Op.isReg() && Op.isImplicit();
697 if (!isImpReg && !isInlineAsm()) {
698 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
700 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
705 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
706 // OpNo now points as the desired insertion point. Unless this is a variadic
707 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
708 // RegMask operands go between the explicit and implicit operands.
709 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
710 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
711 "Trying to add an operand to a machine instr that is already done!");
714 MachineRegisterInfo *MRI = getRegInfo();
716 // Determine if the Operands array needs to be reallocated.
717 // Save the old capacity and operand array.
718 OperandCapacity OldCap = CapOperands;
719 MachineOperand *OldOperands = Operands;
720 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
721 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
722 Operands = MF.allocateOperandArray(CapOperands);
723 // Move the operands before the insertion point.
725 moveOperands(Operands, OldOperands, OpNo, MRI);
728 // Move the operands following the insertion point.
729 if (OpNo != NumOperands)
730 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
734 // Deallocate the old operand array.
735 if (OldOperands != Operands && OldOperands)
736 MF.deallocateOperandArray(OldCap, OldOperands);
738 // Copy Op into place. It still needs to be inserted into the MRI use lists.
739 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
740 NewMO->ParentMI = this;
742 // When adding a register operand, tell MRI about it.
743 if (NewMO->isReg()) {
744 // Ensure isOnRegUseList() returns false, regardless of Op's status.
745 NewMO->Contents.Reg.Prev = nullptr;
746 // Ignore existing ties. This is not a property that can be copied.
748 // Add the new operand to MRI, but only for instructions in an MBB.
750 MRI->addRegOperandToUseList(NewMO);
751 // The MCID operand information isn't accurate until we start adding
752 // explicit operands. The implicit operands are added first, then the
753 // explicits are inserted before them.
755 // Tie uses to defs as indicated in MCInstrDesc.
756 if (NewMO->isUse()) {
757 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
759 tieOperands(DefIdx, OpNo);
761 // If the register operand is flagged as early, mark the operand as such.
762 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
763 NewMO->setIsEarlyClobber(true);
768 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
769 /// fewer operand than it started with.
771 void MachineInstr::RemoveOperand(unsigned OpNo) {
772 assert(OpNo < getNumOperands() && "Invalid operand number");
773 untieRegOperand(OpNo);
776 // Moving tied operands would break the ties.
777 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
778 if (Operands[i].isReg())
779 assert(!Operands[i].isTied() && "Cannot move tied operands");
782 MachineRegisterInfo *MRI = getRegInfo();
783 if (MRI && Operands[OpNo].isReg())
784 MRI->removeRegOperandFromUseList(Operands + OpNo);
786 // Don't call the MachineOperand destructor. A lot of this code depends on
787 // MachineOperand having a trivial destructor anyway, and adding a call here
788 // wouldn't make it 'destructor-correct'.
790 if (unsigned N = NumOperands - 1 - OpNo)
791 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
795 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
796 /// This function should be used only occasionally. The setMemRefs function
797 /// is the primary method for setting up a MachineInstr's MemRefs list.
798 void MachineInstr::addMemOperand(MachineFunction &MF,
799 MachineMemOperand *MO) {
800 mmo_iterator OldMemRefs = MemRefs;
801 unsigned OldNumMemRefs = NumMemRefs;
803 unsigned NewNum = NumMemRefs + 1;
804 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
806 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
807 NewMemRefs[NewNum - 1] = MO;
808 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
811 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
812 assert(!isBundledWithPred() && "Must be called on bundle header");
813 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
814 if (MII->getDesc().getFlags() & Mask) {
815 if (Type == AnyInBundle)
818 if (Type == AllInBundle && !MII->isBundle())
821 // This was the last instruction in the bundle.
822 if (!MII->isBundledWithSucc())
823 return Type == AllInBundle;
827 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
828 MICheckType Check) const {
829 // If opcodes or number of operands are not the same then the two
830 // instructions are obviously not identical.
831 if (Other->getOpcode() != getOpcode() ||
832 Other->getNumOperands() != getNumOperands())
836 // Both instructions are bundles, compare MIs inside the bundle.
837 MachineBasicBlock::const_instr_iterator I1 = *this;
838 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
839 MachineBasicBlock::const_instr_iterator I2 = *Other;
840 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
841 while (++I1 != E1 && I1->isInsideBundle()) {
843 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
848 // Check operands to make sure they match.
849 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
850 const MachineOperand &MO = getOperand(i);
851 const MachineOperand &OMO = Other->getOperand(i);
853 if (!MO.isIdenticalTo(OMO))
858 // Clients may or may not want to ignore defs when testing for equality.
859 // For example, machine CSE pass only cares about finding common
860 // subexpressions, so it's safe to ignore virtual register defs.
862 if (Check == IgnoreDefs)
864 else if (Check == IgnoreVRegDefs) {
865 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
866 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
867 if (MO.getReg() != OMO.getReg())
870 if (!MO.isIdenticalTo(OMO))
872 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
876 if (!MO.isIdenticalTo(OMO))
878 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
882 // If DebugLoc does not match then two dbg.values are not identical.
884 if (getDebugLoc() && Other->getDebugLoc() &&
885 getDebugLoc() != Other->getDebugLoc())
890 MachineInstr *MachineInstr::removeFromParent() {
891 assert(getParent() && "Not embedded in a basic block!");
892 return getParent()->remove(this);
895 MachineInstr *MachineInstr::removeFromBundle() {
896 assert(getParent() && "Not embedded in a basic block!");
897 return getParent()->remove_instr(this);
900 void MachineInstr::eraseFromParent() {
901 assert(getParent() && "Not embedded in a basic block!");
902 getParent()->erase(this);
905 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
906 assert(getParent() && "Not embedded in a basic block!");
907 MachineBasicBlock *MBB = getParent();
908 MachineFunction *MF = MBB->getParent();
909 assert(MF && "Not embedded in a function!");
911 MachineInstr *MI = (MachineInstr *)this;
912 MachineRegisterInfo &MRI = MF->getRegInfo();
914 for (const MachineOperand &MO : MI->operands()) {
915 if (!MO.isReg() || !MO.isDef())
917 unsigned Reg = MO.getReg();
918 if (!TargetRegisterInfo::isVirtualRegister(Reg))
920 MRI.markUsesInDebugValueAsUndef(Reg);
922 MI->eraseFromParent();
925 void MachineInstr::eraseFromBundle() {
926 assert(getParent() && "Not embedded in a basic block!");
927 getParent()->erase_instr(this);
930 /// getNumExplicitOperands - Returns the number of non-implicit operands.
932 unsigned MachineInstr::getNumExplicitOperands() const {
933 unsigned NumOperands = MCID->getNumOperands();
934 if (!MCID->isVariadic())
937 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
938 const MachineOperand &MO = getOperand(i);
939 if (!MO.isReg() || !MO.isImplicit())
945 void MachineInstr::bundleWithPred() {
946 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
947 setFlag(BundledPred);
948 MachineBasicBlock::instr_iterator Pred = this;
950 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
951 Pred->setFlag(BundledSucc);
954 void MachineInstr::bundleWithSucc() {
955 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
956 setFlag(BundledSucc);
957 MachineBasicBlock::instr_iterator Succ = this;
959 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
960 Succ->setFlag(BundledPred);
963 void MachineInstr::unbundleFromPred() {
964 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
965 clearFlag(BundledPred);
966 MachineBasicBlock::instr_iterator Pred = this;
968 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
969 Pred->clearFlag(BundledSucc);
972 void MachineInstr::unbundleFromSucc() {
973 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
974 clearFlag(BundledSucc);
975 MachineBasicBlock::instr_iterator Succ = this;
977 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
978 Succ->clearFlag(BundledPred);
981 bool MachineInstr::isStackAligningInlineAsm() const {
983 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
984 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
990 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
991 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
992 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
993 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
996 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
997 unsigned *GroupNo) const {
998 assert(isInlineAsm() && "Expected an inline asm instruction");
999 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1001 // Ignore queries about the initial operands.
1002 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1007 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1009 const MachineOperand &FlagMO = getOperand(i);
1010 // If we reach the implicit register operands, stop looking.
1011 if (!FlagMO.isImm())
1013 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1014 if (i + NumOps > OpIdx) {
1024 const TargetRegisterClass*
1025 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1026 const TargetInstrInfo *TII,
1027 const TargetRegisterInfo *TRI) const {
1028 assert(getParent() && "Can't have an MBB reference here!");
1029 assert(getParent()->getParent() && "Can't have an MF reference here!");
1030 const MachineFunction &MF = *getParent()->getParent();
1032 // Most opcodes have fixed constraints in their MCInstrDesc.
1034 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1036 if (!getOperand(OpIdx).isReg())
1039 // For tied uses on inline asm, get the constraint from the def.
1041 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1044 // Inline asm stores register class constraints in the flag word.
1045 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1049 unsigned Flag = getOperand(FlagIdx).getImm();
1051 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1052 return TRI->getRegClass(RCID);
1054 // Assume that all registers in a memory operand are pointers.
1055 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1056 return TRI->getPointerRegClass(MF);
1061 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1062 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1063 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1064 // Check every operands inside the bundle if we have
1067 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1069 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1070 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1072 // Otherwise, just check the current operands.
1073 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1074 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1079 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1080 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1081 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1082 assert(CurRC && "Invalid initial register class");
1083 // Check if Reg is constrained by some of its use/def from MI.
1084 const MachineOperand &MO = getOperand(OpIdx);
1085 if (!MO.isReg() || MO.getReg() != Reg)
1087 // If yes, accumulate the constraints through the operand.
1088 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1091 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1092 unsigned OpIdx, const TargetRegisterClass *CurRC,
1093 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1094 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1095 const MachineOperand &MO = getOperand(OpIdx);
1096 assert(MO.isReg() &&
1097 "Cannot get register constraints for non-register operand");
1098 assert(CurRC && "Invalid initial register class");
1099 if (unsigned SubIdx = MO.getSubReg()) {
1101 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1103 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1105 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1109 /// Return the number of instructions inside the MI bundle, not counting the
1110 /// header instruction.
1111 unsigned MachineInstr::getBundleSize() const {
1112 MachineBasicBlock::const_instr_iterator I = this;
1114 while (I->isBundledWithSucc())
1119 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1120 /// the specific register or -1 if it is not found. It further tightens
1121 /// the search criteria to a use that kills the register if isKill is true.
1122 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1123 const TargetRegisterInfo *TRI) const {
1124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1125 const MachineOperand &MO = getOperand(i);
1126 if (!MO.isReg() || !MO.isUse())
1128 unsigned MOReg = MO.getReg();
1133 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1134 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1135 TRI->isSubRegister(MOReg, Reg)))
1136 if (!isKill || MO.isKill())
1142 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1143 /// indicating if this instruction reads or writes Reg. This also considers
1144 /// partial defines.
1145 std::pair<bool,bool>
1146 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1147 SmallVectorImpl<unsigned> *Ops) const {
1148 bool PartDef = false; // Partial redefine.
1149 bool FullDef = false; // Full define.
1152 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1153 const MachineOperand &MO = getOperand(i);
1154 if (!MO.isReg() || MO.getReg() != Reg)
1159 Use |= !MO.isUndef();
1160 else if (MO.getSubReg() && !MO.isUndef())
1161 // A partial <def,undef> doesn't count as reading the register.
1166 // A partial redefine uses Reg unless there is also a full define.
1167 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1170 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1171 /// the specified register or -1 if it is not found. If isDead is true, defs
1172 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1173 /// also checks if there is a def of a super-register.
1175 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1176 const TargetRegisterInfo *TRI) const {
1177 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1178 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1179 const MachineOperand &MO = getOperand(i);
1180 // Accept regmask operands when Overlap is set.
1181 // Ignore them when looking for a specific def operand (Overlap == false).
1182 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1184 if (!MO.isReg() || !MO.isDef())
1186 unsigned MOReg = MO.getReg();
1187 bool Found = (MOReg == Reg);
1188 if (!Found && TRI && isPhys &&
1189 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1191 Found = TRI->regsOverlap(MOReg, Reg);
1193 Found = TRI->isSubRegister(MOReg, Reg);
1195 if (Found && (!isDead || MO.isDead()))
1201 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1202 /// operand list that is used to represent the predicate. It returns -1 if
1204 int MachineInstr::findFirstPredOperandIdx() const {
1205 // Don't call MCID.findFirstPredOperandIdx() because this variant
1206 // is sometimes called on an instruction that's not yet complete, and
1207 // so the number of operands is less than the MCID indicates. In
1208 // particular, the PTX target does this.
1209 const MCInstrDesc &MCID = getDesc();
1210 if (MCID.isPredicable()) {
1211 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1212 if (MCID.OpInfo[i].isPredicate())
1219 // MachineOperand::TiedTo is 4 bits wide.
1220 const unsigned TiedMax = 15;
1222 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1224 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1225 /// field. TiedTo can have these values:
1227 /// 0: Operand is not tied to anything.
1228 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1229 /// TiedMax: Tied to an operand >= TiedMax-1.
1231 /// The tied def must be one of the first TiedMax operands on a normal
1232 /// instruction. INLINEASM instructions allow more tied defs.
1234 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1235 MachineOperand &DefMO = getOperand(DefIdx);
1236 MachineOperand &UseMO = getOperand(UseIdx);
1237 assert(DefMO.isDef() && "DefIdx must be a def operand");
1238 assert(UseMO.isUse() && "UseIdx must be a use operand");
1239 assert(!DefMO.isTied() && "Def is already tied to another use");
1240 assert(!UseMO.isTied() && "Use is already tied to another def");
1242 if (DefIdx < TiedMax)
1243 UseMO.TiedTo = DefIdx + 1;
1245 // Inline asm can use the group descriptors to find tied operands, but on
1246 // normal instruction, the tied def must be within the first TiedMax
1248 assert(isInlineAsm() && "DefIdx out of range");
1249 UseMO.TiedTo = TiedMax;
1252 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1253 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1256 /// Given the index of a tied register operand, find the operand it is tied to.
1257 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1258 /// which must exist.
1259 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1260 const MachineOperand &MO = getOperand(OpIdx);
1261 assert(MO.isTied() && "Operand isn't tied");
1263 // Normally TiedTo is in range.
1264 if (MO.TiedTo < TiedMax)
1265 return MO.TiedTo - 1;
1267 // Uses on normal instructions can be out of range.
1268 if (!isInlineAsm()) {
1269 // Normal tied defs must be in the 0..TiedMax-1 range.
1272 // MO is a def. Search for the tied use.
1273 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1274 const MachineOperand &UseMO = getOperand(i);
1275 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1278 llvm_unreachable("Can't find tied use");
1281 // Now deal with inline asm by parsing the operand group descriptor flags.
1282 // Find the beginning of each operand group.
1283 SmallVector<unsigned, 8> GroupIdx;
1284 unsigned OpIdxGroup = ~0u;
1286 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1288 const MachineOperand &FlagMO = getOperand(i);
1289 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1290 unsigned CurGroup = GroupIdx.size();
1291 GroupIdx.push_back(i);
1292 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1293 // OpIdx belongs to this operand group.
1294 if (OpIdx > i && OpIdx < i + NumOps)
1295 OpIdxGroup = CurGroup;
1297 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1299 // Operands in this group are tied to operands in TiedGroup which must be
1300 // earlier. Find the number of operands between the two groups.
1301 unsigned Delta = i - GroupIdx[TiedGroup];
1303 // OpIdx is a use tied to TiedGroup.
1304 if (OpIdxGroup == CurGroup)
1305 return OpIdx - Delta;
1307 // OpIdx is a def tied to this use group.
1308 if (OpIdxGroup == TiedGroup)
1309 return OpIdx + Delta;
1311 llvm_unreachable("Invalid tied operand on inline asm");
1314 /// clearKillInfo - Clears kill flags on all operands.
1316 void MachineInstr::clearKillInfo() {
1317 for (MachineOperand &MO : operands()) {
1318 if (MO.isReg() && MO.isUse())
1319 MO.setIsKill(false);
1323 void MachineInstr::substituteRegister(unsigned FromReg,
1326 const TargetRegisterInfo &RegInfo) {
1327 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1329 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1330 for (MachineOperand &MO : operands()) {
1331 if (!MO.isReg() || MO.getReg() != FromReg)
1333 MO.substPhysReg(ToReg, RegInfo);
1336 for (MachineOperand &MO : operands()) {
1337 if (!MO.isReg() || MO.getReg() != FromReg)
1339 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1344 /// isSafeToMove - Return true if it is safe to move this instruction. If
1345 /// SawStore is set to true, it means that there is a store (or call) between
1346 /// the instruction's location and its intended destination.
1347 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1349 bool &SawStore) const {
1350 // Ignore stuff that we obviously can't move.
1352 // Treat volatile loads as stores. This is not strictly necessary for
1353 // volatiles, but it is required for atomic loads. It is not allowed to move
1354 // a load across an atomic load with Ordering > Monotonic.
1355 if (mayStore() || isCall() ||
1356 (mayLoad() && hasOrderedMemoryRef())) {
1361 if (isPosition() || isDebugValue() || isTerminator() ||
1362 hasUnmodeledSideEffects())
1365 // See if this instruction does a load. If so, we have to guarantee that the
1366 // loaded value doesn't change between the load and the its intended
1367 // destination. The check for isInvariantLoad gives the targe the chance to
1368 // classify the load as always returning a constant, e.g. a constant pool
1370 if (mayLoad() && !isInvariantLoad(AA))
1371 // Otherwise, this is a real load. If there is a store between the load and
1372 // end of block, we can't move it.
1378 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1379 /// or volatile memory reference, or if the information describing the memory
1380 /// reference is not available. Return false if it is known to have no ordered
1381 /// memory references.
1382 bool MachineInstr::hasOrderedMemoryRef() const {
1383 // An instruction known never to access memory won't have a volatile access.
1387 !hasUnmodeledSideEffects())
1390 // Otherwise, if the instruction has no memory reference information,
1391 // conservatively assume it wasn't preserved.
1392 if (memoperands_empty())
1395 // Check the memory reference information for ordered references.
1396 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1397 if (!(*I)->isUnordered())
1403 /// isInvariantLoad - Return true if this instruction is loading from a
1404 /// location whose value is invariant across the function. For example,
1405 /// loading a value from the constant pool or from the argument area
1406 /// of a function if it does not change. This should only return true of
1407 /// *all* loads the instruction does are invariant (if it does multiple loads).
1408 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1409 // If the instruction doesn't load at all, it isn't an invariant load.
1413 // If the instruction has lost its memoperands, conservatively assume that
1414 // it may not be an invariant load.
1415 if (memoperands_empty())
1418 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1420 for (mmo_iterator I = memoperands_begin(),
1421 E = memoperands_end(); I != E; ++I) {
1422 if ((*I)->isVolatile()) return false;
1423 if ((*I)->isStore()) return false;
1424 if ((*I)->isInvariant()) return true;
1427 // A load from a constant PseudoSourceValue is invariant.
1428 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1429 if (PSV->isConstant(MFI))
1432 if (const Value *V = (*I)->getValue()) {
1433 // If we have an AliasAnalysis, ask it whether the memory is constant.
1434 if (AA && AA->pointsToConstantMemory(
1435 AliasAnalysis::Location(V, (*I)->getSize(),
1436 (*I)->getAAInfo())))
1440 // Otherwise assume conservatively.
1444 // Everything checks out.
1448 /// isConstantValuePHI - If the specified instruction is a PHI that always
1449 /// merges together the same virtual register, return the register, otherwise
1451 unsigned MachineInstr::isConstantValuePHI() const {
1454 assert(getNumOperands() >= 3 &&
1455 "It's illegal to have a PHI without source operands");
1457 unsigned Reg = getOperand(1).getReg();
1458 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1459 if (getOperand(i).getReg() != Reg)
1464 bool MachineInstr::hasUnmodeledSideEffects() const {
1465 if (hasProperty(MCID::UnmodeledSideEffects))
1467 if (isInlineAsm()) {
1468 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1469 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1476 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1478 bool MachineInstr::allDefsAreDead() const {
1479 for (const MachineOperand &MO : operands()) {
1480 if (!MO.isReg() || MO.isUse())
1488 /// copyImplicitOps - Copy implicit register operands from specified
1489 /// instruction to this instruction.
1490 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1491 const MachineInstr *MI) {
1492 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1494 const MachineOperand &MO = MI->getOperand(i);
1495 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1500 void MachineInstr::dump() const {
1501 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1502 dbgs() << " " << *this;
1506 void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const {
1507 // We can be a bit tidier if we know the MachineFunction.
1508 const MachineFunction *MF = nullptr;
1509 const TargetRegisterInfo *TRI = nullptr;
1510 const MachineRegisterInfo *MRI = nullptr;
1511 const TargetInstrInfo *TII = nullptr;
1512 if (const MachineBasicBlock *MBB = getParent()) {
1513 MF = MBB->getParent();
1515 MRI = &MF->getRegInfo();
1516 TRI = MF->getSubtarget().getRegisterInfo();
1517 TII = MF->getSubtarget().getInstrInfo();
1521 // Save a list of virtual registers.
1522 SmallVector<unsigned, 8> VirtRegs;
1524 // Print explicitly defined operands on the left of an assignment syntax.
1525 unsigned StartOp = 0, e = getNumOperands();
1526 for (; StartOp < e && getOperand(StartOp).isReg() &&
1527 getOperand(StartOp).isDef() &&
1528 !getOperand(StartOp).isImplicit();
1530 if (StartOp != 0) OS << ", ";
1531 getOperand(StartOp).print(OS, TRI);
1532 unsigned Reg = getOperand(StartOp).getReg();
1533 if (TargetRegisterInfo::isVirtualRegister(Reg))
1534 VirtRegs.push_back(Reg);
1540 // Print the opcode name.
1542 OS << TII->getName(getOpcode());
1549 // Print the rest of the operands.
1550 bool OmittedAnyCallClobbers = false;
1551 bool FirstOp = true;
1552 unsigned AsmDescOp = ~0u;
1553 unsigned AsmOpCount = 0;
1555 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1556 // Print asm string.
1558 getOperand(InlineAsm::MIOp_AsmString).print(OS, TRI);
1560 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1561 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1562 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1563 OS << " [sideeffect]";
1564 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1566 if (ExtraInfo & InlineAsm::Extra_MayStore)
1567 OS << " [maystore]";
1568 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1569 OS << " [alignstack]";
1570 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1571 OS << " [attdialect]";
1572 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1573 OS << " [inteldialect]";
1575 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1580 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1581 const MachineOperand &MO = getOperand(i);
1583 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1584 VirtRegs.push_back(MO.getReg());
1586 // Omit call-clobbered registers which aren't used anywhere. This makes
1587 // call instructions much less noisy on targets where calls clobber lots
1588 // of registers. Don't rely on MO.isDead() because we may be called before
1589 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1590 if (MRI && isCall() &&
1591 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1592 unsigned Reg = MO.getReg();
1593 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1594 if (MRI->use_empty(Reg)) {
1595 bool HasAliasLive = false;
1596 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1597 unsigned AliasReg = *AI;
1598 if (!MRI->use_empty(AliasReg)) {
1599 HasAliasLive = true;
1603 if (!HasAliasLive) {
1604 OmittedAnyCallClobbers = true;
1611 if (FirstOp) FirstOp = false; else OS << ",";
1613 if (i < getDesc().NumOperands) {
1614 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1615 if (MCOI.isPredicate())
1617 if (MCOI.isOptionalDef())
1620 if (isDebugValue() && MO.isMetadata()) {
1621 // Pretty print DBG_VALUE instructions.
1622 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1623 if (DIV && !DIV->getName().empty())
1624 OS << "!\"" << DIV->getName() << '\"';
1627 } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1628 OS << TRI->getSubRegIndexName(MO.getImm());
1629 } else if (i == AsmDescOp && MO.isImm()) {
1630 // Pretty print the inline asm operand descriptor.
1631 OS << '$' << AsmOpCount++;
1632 unsigned Flag = MO.getImm();
1633 switch (InlineAsm::getKind(Flag)) {
1634 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1635 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1636 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1637 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1638 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1639 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1640 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1644 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1646 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1648 OS << ":RC" << RCID;
1651 unsigned TiedTo = 0;
1652 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1653 OS << " tiedto:$" << TiedTo;
1657 // Compute the index of the next operand descriptor.
1658 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1663 // Briefly indicate whether any call clobbers were omitted.
1664 if (OmittedAnyCallClobbers) {
1665 if (!FirstOp) OS << ",";
1669 bool HaveSemi = false;
1670 const unsigned PrintableFlags = FrameSetup;
1671 if (Flags & PrintableFlags) {
1672 if (!HaveSemi) OS << ";"; HaveSemi = true;
1675 if (Flags & FrameSetup)
1679 if (!memoperands_empty()) {
1680 if (!HaveSemi) OS << ";"; HaveSemi = true;
1683 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1686 if (std::next(i) != e)
1691 // Print the regclass of any virtual registers encountered.
1692 if (MRI && !VirtRegs.empty()) {
1693 if (!HaveSemi) OS << ";"; HaveSemi = true;
1694 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1695 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1696 OS << " " << TRI->getRegClassName(RC)
1697 << ':' << PrintReg(VirtRegs[i]);
1698 for (unsigned j = i+1; j != VirtRegs.size();) {
1699 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1703 if (VirtRegs[i] != VirtRegs[j])
1704 OS << "," << PrintReg(VirtRegs[j]);
1705 VirtRegs.erase(VirtRegs.begin()+j);
1710 // Print debug location information.
1711 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
1712 if (!HaveSemi) OS << ";";
1713 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
1714 OS << " line no:" << DV->getLine();
1715 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
1716 DebugLoc InlinedAtDL(InlinedAt);
1717 if (InlinedAtDL && MF) {
1718 OS << " inlined @[ ";
1719 InlinedAtDL.print(OS);
1723 if (isIndirectDebugValue())
1725 } else if (debugLoc && MF) {
1726 if (!HaveSemi) OS << ";";
1734 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1735 const TargetRegisterInfo *RegInfo,
1736 bool AddIfNotFound) {
1737 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1738 bool hasAliases = isPhysReg &&
1739 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1741 SmallVector<unsigned,4> DeadOps;
1742 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1743 MachineOperand &MO = getOperand(i);
1744 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1746 unsigned Reg = MO.getReg();
1750 if (Reg == IncomingReg) {
1753 // The register is already marked kill.
1755 if (isPhysReg && isRegTiedToDefOperand(i))
1756 // Two-address uses of physregs must not be marked kill.
1761 } else if (hasAliases && MO.isKill() &&
1762 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1763 // A super-register kill already exists.
1764 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1766 if (RegInfo->isSubRegister(IncomingReg, Reg))
1767 DeadOps.push_back(i);
1771 // Trim unneeded kill operands.
1772 while (!DeadOps.empty()) {
1773 unsigned OpIdx = DeadOps.back();
1774 if (getOperand(OpIdx).isImplicit())
1775 RemoveOperand(OpIdx);
1777 getOperand(OpIdx).setIsKill(false);
1781 // If not found, this means an alias of one of the operands is killed. Add a
1782 // new implicit operand if required.
1783 if (!Found && AddIfNotFound) {
1784 addOperand(MachineOperand::CreateReg(IncomingReg,
1793 void MachineInstr::clearRegisterKills(unsigned Reg,
1794 const TargetRegisterInfo *RegInfo) {
1795 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1797 for (MachineOperand &MO : operands()) {
1798 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1800 unsigned OpReg = MO.getReg();
1801 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1802 MO.setIsKill(false);
1806 bool MachineInstr::addRegisterDead(unsigned Reg,
1807 const TargetRegisterInfo *RegInfo,
1808 bool AddIfNotFound) {
1809 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1810 bool hasAliases = isPhysReg &&
1811 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1813 SmallVector<unsigned,4> DeadOps;
1814 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1815 MachineOperand &MO = getOperand(i);
1816 if (!MO.isReg() || !MO.isDef())
1818 unsigned MOReg = MO.getReg();
1825 } else if (hasAliases && MO.isDead() &&
1826 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1827 // There exists a super-register that's marked dead.
1828 if (RegInfo->isSuperRegister(Reg, MOReg))
1830 if (RegInfo->isSubRegister(Reg, MOReg))
1831 DeadOps.push_back(i);
1835 // Trim unneeded dead operands.
1836 while (!DeadOps.empty()) {
1837 unsigned OpIdx = DeadOps.back();
1838 if (getOperand(OpIdx).isImplicit())
1839 RemoveOperand(OpIdx);
1841 getOperand(OpIdx).setIsDead(false);
1845 // If not found, this means an alias of one of the operands is dead. Add a
1846 // new implicit operand if required.
1847 if (Found || !AddIfNotFound)
1850 addOperand(MachineOperand::CreateReg(Reg,
1858 void MachineInstr::clearRegisterDeads(unsigned Reg) {
1859 for (MachineOperand &MO : operands()) {
1860 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
1862 MO.setIsDead(false);
1866 void MachineInstr::addRegisterDefReadUndef(unsigned Reg) {
1867 for (MachineOperand &MO : operands()) {
1868 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
1874 void MachineInstr::addRegisterDefined(unsigned Reg,
1875 const TargetRegisterInfo *RegInfo) {
1876 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1877 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1881 for (const MachineOperand &MO : operands()) {
1882 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1883 MO.getSubReg() == 0)
1887 addOperand(MachineOperand::CreateReg(Reg,
1892 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1893 const TargetRegisterInfo &TRI) {
1894 bool HasRegMask = false;
1895 for (MachineOperand &MO : operands()) {
1896 if (MO.isRegMask()) {
1900 if (!MO.isReg() || !MO.isDef()) continue;
1901 unsigned Reg = MO.getReg();
1902 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1903 // If there are no uses, including partial uses, the def is dead.
1904 if (std::none_of(UsedRegs.begin(), UsedRegs.end(),
1905 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
1909 // This is a call with a register mask operand.
1910 // Mask clobbers are always dead, so add defs for the non-dead defines.
1912 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1914 addRegisterDefined(*I, &TRI);
1918 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1919 // Build up a buffer of hash code components.
1920 SmallVector<size_t, 8> HashComponents;
1921 HashComponents.reserve(MI->getNumOperands() + 1);
1922 HashComponents.push_back(MI->getOpcode());
1923 for (const MachineOperand &MO : MI->operands()) {
1924 if (MO.isReg() && MO.isDef() &&
1925 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1926 continue; // Skip virtual register defs.
1928 HashComponents.push_back(hash_value(MO));
1930 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1933 void MachineInstr::emitError(StringRef Msg) const {
1934 // Find the source location cookie.
1935 unsigned LocCookie = 0;
1936 const MDNode *LocMD = nullptr;
1937 for (unsigned i = getNumOperands(); i != 0; --i) {
1938 if (getOperand(i-1).isMetadata() &&
1939 (LocMD = getOperand(i-1).getMetadata()) &&
1940 LocMD->getNumOperands() != 0) {
1941 if (const ConstantInt *CI =
1942 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
1943 LocCookie = CI->getZExtValue();
1949 if (const MachineBasicBlock *MBB = getParent())
1950 if (const MachineFunction *MF = MBB->getParent())
1951 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1952 report_fatal_error(Msg);