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, const TargetMachine *TM) const {
280 // If the instruction is embedded into a basic block, we can find the
281 // target info for the instruction.
283 if (const MachineInstr *MI = getParent())
284 if (const MachineBasicBlock *MBB = MI->getParent())
285 if (const MachineFunction *MF = MBB->getParent())
286 TM = &MF->getTarget();
287 const TargetRegisterInfo *TRI =
288 TM ? TM->getSubtargetImpl()->getRegisterInfo() : nullptr;
291 case MachineOperand::MO_Register:
292 OS << PrintReg(getReg(), TRI, getSubReg());
294 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
295 isInternalRead() || isEarlyClobber() || isTied()) {
297 bool NeedComma = false;
299 if (NeedComma) OS << ',';
300 if (isEarlyClobber())
301 OS << "earlyclobber,";
306 // <def,read-undef> only makes sense when getSubReg() is set.
307 // Don't clutter the output otherwise.
308 if (isUndef() && getSubReg())
310 } else if (isImplicit()) {
316 if (NeedComma) OS << ',';
321 if (NeedComma) OS << ',';
325 if (isUndef() && isUse()) {
326 if (NeedComma) OS << ',';
330 if (isInternalRead()) {
331 if (NeedComma) OS << ',';
336 if (NeedComma) OS << ',';
339 OS << unsigned(TiedTo - 1);
344 case MachineOperand::MO_Immediate:
347 case MachineOperand::MO_CImmediate:
348 getCImm()->getValue().print(OS, false);
350 case MachineOperand::MO_FPImmediate:
351 if (getFPImm()->getType()->isFloatTy())
352 OS << getFPImm()->getValueAPF().convertToFloat();
354 OS << getFPImm()->getValueAPF().convertToDouble();
356 case MachineOperand::MO_MachineBasicBlock:
357 OS << "<BB#" << getMBB()->getNumber() << ">";
359 case MachineOperand::MO_FrameIndex:
360 OS << "<fi#" << getIndex() << '>';
362 case MachineOperand::MO_ConstantPoolIndex:
363 OS << "<cp#" << getIndex();
364 if (getOffset()) OS << "+" << getOffset();
367 case MachineOperand::MO_TargetIndex:
368 OS << "<ti#" << getIndex();
369 if (getOffset()) OS << "+" << getOffset();
372 case MachineOperand::MO_JumpTableIndex:
373 OS << "<jt#" << getIndex() << '>';
375 case MachineOperand::MO_GlobalAddress:
377 getGlobal()->printAsOperand(OS, /*PrintType=*/false);
378 if (getOffset()) OS << "+" << getOffset();
381 case MachineOperand::MO_ExternalSymbol:
382 OS << "<es:" << getSymbolName();
383 if (getOffset()) OS << "+" << getOffset();
386 case MachineOperand::MO_BlockAddress:
388 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false);
389 if (getOffset()) OS << "+" << getOffset();
392 case MachineOperand::MO_RegisterMask:
395 case MachineOperand::MO_RegisterLiveOut:
396 OS << "<regliveout>";
398 case MachineOperand::MO_Metadata:
400 getMetadata()->printAsOperand(OS);
403 case MachineOperand::MO_MCSymbol:
404 OS << "<MCSym=" << *getMCSymbol() << '>';
406 case MachineOperand::MO_CFIIndex:
407 OS << "<call frame instruction>";
411 if (unsigned TF = getTargetFlags())
412 OS << "[TF=" << TF << ']';
415 //===----------------------------------------------------------------------===//
416 // MachineMemOperand Implementation
417 //===----------------------------------------------------------------------===//
419 /// getAddrSpace - Return the LLVM IR address space number that this pointer
421 unsigned MachinePointerInfo::getAddrSpace() const {
422 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
423 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
426 /// getConstantPool - Return a MachinePointerInfo record that refers to the
428 MachinePointerInfo MachinePointerInfo::getConstantPool() {
429 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
432 /// getFixedStack - Return a MachinePointerInfo record that refers to the
433 /// the specified FrameIndex.
434 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
435 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
438 MachinePointerInfo MachinePointerInfo::getJumpTable() {
439 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
442 MachinePointerInfo MachinePointerInfo::getGOT() {
443 return MachinePointerInfo(PseudoSourceValue::getGOT());
446 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
447 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
450 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
451 uint64_t s, unsigned int a,
452 const AAMDNodes &AAInfo,
453 const MDNode *Ranges)
454 : PtrInfo(ptrinfo), Size(s),
455 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
456 AAInfo(AAInfo), Ranges(Ranges) {
457 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
458 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
459 "invalid pointer value");
460 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
461 assert((isLoad() || isStore()) && "Not a load/store!");
464 /// Profile - Gather unique data for the object.
466 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
467 ID.AddInteger(getOffset());
469 ID.AddPointer(getOpaqueValue());
470 ID.AddInteger(Flags);
473 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
474 // The Value and Offset may differ due to CSE. But the flags and size
475 // should be the same.
476 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
477 assert(MMO->getSize() == getSize() && "Size mismatch!");
479 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
480 // Update the alignment value.
481 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
482 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
483 // Also update the base and offset, because the new alignment may
484 // not be applicable with the old ones.
485 PtrInfo = MMO->PtrInfo;
489 /// getAlignment - Return the minimum known alignment in bytes of the
490 /// actual memory reference.
491 uint64_t MachineMemOperand::getAlignment() const {
492 return MinAlign(getBaseAlignment(), getOffset());
495 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
496 assert((MMO.isLoad() || MMO.isStore()) &&
497 "SV has to be a load, store or both.");
499 if (MMO.isVolatile())
508 // Print the address information.
510 if (const Value *V = MMO.getValue())
511 V->printAsOperand(OS, /*PrintType=*/false);
512 else if (const PseudoSourceValue *PSV = MMO.getPseudoValue())
513 PSV->printCustom(OS);
517 unsigned AS = MMO.getAddrSpace();
519 OS << "(addrspace=" << AS << ')';
521 // If the alignment of the memory reference itself differs from the alignment
522 // of the base pointer, print the base alignment explicitly, next to the base
524 if (MMO.getBaseAlignment() != MMO.getAlignment())
525 OS << "(align=" << MMO.getBaseAlignment() << ")";
527 if (MMO.getOffset() != 0)
528 OS << "+" << MMO.getOffset();
531 // Print the alignment of the reference.
532 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
533 MMO.getBaseAlignment() != MMO.getSize())
534 OS << "(align=" << MMO.getAlignment() << ")";
537 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
539 if (TBAAInfo->getNumOperands() > 0)
540 TBAAInfo->getOperand(0)->printAsOperand(OS);
546 // Print AA scope info.
547 if (const MDNode *ScopeInfo = MMO.getAAInfo().Scope) {
548 OS << "(alias.scope=";
549 if (ScopeInfo->getNumOperands() > 0)
550 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
551 ScopeInfo->getOperand(i)->printAsOperand(OS);
560 // Print AA noalias scope info.
561 if (const MDNode *NoAliasInfo = MMO.getAAInfo().NoAlias) {
563 if (NoAliasInfo->getNumOperands() > 0)
564 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
565 NoAliasInfo->getOperand(i)->printAsOperand(OS);
574 // Print nontemporal info.
575 if (MMO.isNonTemporal())
576 OS << "(nontemporal)";
581 //===----------------------------------------------------------------------===//
582 // MachineInstr Implementation
583 //===----------------------------------------------------------------------===//
585 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
586 if (MCID->ImplicitDefs)
587 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
588 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
589 if (MCID->ImplicitUses)
590 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
591 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
594 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
595 /// implicit operands. It reserves space for the number of operands specified by
597 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
598 DebugLoc dl, bool NoImp)
599 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
600 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
601 debugLoc(std::move(dl)) {
602 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
604 // Reserve space for the expected number of operands.
605 if (unsigned NumOps = MCID->getNumOperands() +
606 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
607 CapOperands = OperandCapacity::get(NumOps);
608 Operands = MF.allocateOperandArray(CapOperands);
612 addImplicitDefUseOperands(MF);
615 /// MachineInstr ctor - Copies MachineInstr arg exactly
617 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
618 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
619 Flags(0), AsmPrinterFlags(0),
620 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
621 debugLoc(MI.getDebugLoc()) {
622 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
624 CapOperands = OperandCapacity::get(MI.getNumOperands());
625 Operands = MF.allocateOperandArray(CapOperands);
628 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
629 addOperand(MF, MI.getOperand(i));
631 // Copy all the sensible flags.
635 /// getRegInfo - If this instruction is embedded into a MachineFunction,
636 /// return the MachineRegisterInfo object for the current function, otherwise
638 MachineRegisterInfo *MachineInstr::getRegInfo() {
639 if (MachineBasicBlock *MBB = getParent())
640 return &MBB->getParent()->getRegInfo();
644 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
645 /// this instruction from their respective use lists. This requires that the
646 /// operands already be on their use lists.
647 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
648 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
649 if (Operands[i].isReg())
650 MRI.removeRegOperandFromUseList(&Operands[i]);
653 /// AddRegOperandsToUseLists - Add all of the register operands in
654 /// this instruction from their respective use lists. This requires that the
655 /// operands not be on their use lists yet.
656 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
657 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
658 if (Operands[i].isReg())
659 MRI.addRegOperandToUseList(&Operands[i]);
662 void MachineInstr::addOperand(const MachineOperand &Op) {
663 MachineBasicBlock *MBB = getParent();
664 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
665 MachineFunction *MF = MBB->getParent();
666 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
670 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
671 /// ranges. If MRI is non-null also update use-def chains.
672 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
673 unsigned NumOps, MachineRegisterInfo *MRI) {
675 return MRI->moveOperands(Dst, Src, NumOps);
677 // MachineOperand is a trivially copyable type so we can just use memmove.
678 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
681 /// addOperand - Add the specified operand to the instruction. If it is an
682 /// implicit operand, it is added to the end of the operand list. If it is
683 /// an explicit operand it is added at the end of the explicit operand list
684 /// (before the first implicit operand).
685 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
686 assert(MCID && "Cannot add operands before providing an instr descriptor");
688 // Check if we're adding one of our existing operands.
689 if (&Op >= Operands && &Op < Operands + NumOperands) {
690 // This is unusual: MI->addOperand(MI->getOperand(i)).
691 // If adding Op requires reallocating or moving existing operands around,
692 // the Op reference could go stale. Support it by copying Op.
693 MachineOperand CopyOp(Op);
694 return addOperand(MF, CopyOp);
697 // Find the insert location for the new operand. Implicit registers go at
698 // the end, everything else goes before the implicit regs.
700 // FIXME: Allow mixed explicit and implicit operands on inline asm.
701 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
702 // implicit-defs, but they must not be moved around. See the FIXME in
704 unsigned OpNo = getNumOperands();
705 bool isImpReg = Op.isReg() && Op.isImplicit();
706 if (!isImpReg && !isInlineAsm()) {
707 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
709 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
714 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
715 // OpNo now points as the desired insertion point. Unless this is a variadic
716 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
717 // RegMask operands go between the explicit and implicit operands.
718 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
719 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
720 "Trying to add an operand to a machine instr that is already done!");
723 MachineRegisterInfo *MRI = getRegInfo();
725 // Determine if the Operands array needs to be reallocated.
726 // Save the old capacity and operand array.
727 OperandCapacity OldCap = CapOperands;
728 MachineOperand *OldOperands = Operands;
729 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
730 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
731 Operands = MF.allocateOperandArray(CapOperands);
732 // Move the operands before the insertion point.
734 moveOperands(Operands, OldOperands, OpNo, MRI);
737 // Move the operands following the insertion point.
738 if (OpNo != NumOperands)
739 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
743 // Deallocate the old operand array.
744 if (OldOperands != Operands && OldOperands)
745 MF.deallocateOperandArray(OldCap, OldOperands);
747 // Copy Op into place. It still needs to be inserted into the MRI use lists.
748 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
749 NewMO->ParentMI = this;
751 // When adding a register operand, tell MRI about it.
752 if (NewMO->isReg()) {
753 // Ensure isOnRegUseList() returns false, regardless of Op's status.
754 NewMO->Contents.Reg.Prev = nullptr;
755 // Ignore existing ties. This is not a property that can be copied.
757 // Add the new operand to MRI, but only for instructions in an MBB.
759 MRI->addRegOperandToUseList(NewMO);
760 // The MCID operand information isn't accurate until we start adding
761 // explicit operands. The implicit operands are added first, then the
762 // explicits are inserted before them.
764 // Tie uses to defs as indicated in MCInstrDesc.
765 if (NewMO->isUse()) {
766 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
768 tieOperands(DefIdx, OpNo);
770 // If the register operand is flagged as early, mark the operand as such.
771 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
772 NewMO->setIsEarlyClobber(true);
777 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
778 /// fewer operand than it started with.
780 void MachineInstr::RemoveOperand(unsigned OpNo) {
781 assert(OpNo < getNumOperands() && "Invalid operand number");
782 untieRegOperand(OpNo);
785 // Moving tied operands would break the ties.
786 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
787 if (Operands[i].isReg())
788 assert(!Operands[i].isTied() && "Cannot move tied operands");
791 MachineRegisterInfo *MRI = getRegInfo();
792 if (MRI && Operands[OpNo].isReg())
793 MRI->removeRegOperandFromUseList(Operands + OpNo);
795 // Don't call the MachineOperand destructor. A lot of this code depends on
796 // MachineOperand having a trivial destructor anyway, and adding a call here
797 // wouldn't make it 'destructor-correct'.
799 if (unsigned N = NumOperands - 1 - OpNo)
800 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
804 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
805 /// This function should be used only occasionally. The setMemRefs function
806 /// is the primary method for setting up a MachineInstr's MemRefs list.
807 void MachineInstr::addMemOperand(MachineFunction &MF,
808 MachineMemOperand *MO) {
809 mmo_iterator OldMemRefs = MemRefs;
810 unsigned OldNumMemRefs = NumMemRefs;
812 unsigned NewNum = NumMemRefs + 1;
813 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
815 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
816 NewMemRefs[NewNum - 1] = MO;
817 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
820 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
821 assert(!isBundledWithPred() && "Must be called on bundle header");
822 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
823 if (MII->getDesc().getFlags() & Mask) {
824 if (Type == AnyInBundle)
827 if (Type == AllInBundle && !MII->isBundle())
830 // This was the last instruction in the bundle.
831 if (!MII->isBundledWithSucc())
832 return Type == AllInBundle;
836 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
837 MICheckType Check) const {
838 // If opcodes or number of operands are not the same then the two
839 // instructions are obviously not identical.
840 if (Other->getOpcode() != getOpcode() ||
841 Other->getNumOperands() != getNumOperands())
845 // Both instructions are bundles, compare MIs inside the bundle.
846 MachineBasicBlock::const_instr_iterator I1 = *this;
847 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
848 MachineBasicBlock::const_instr_iterator I2 = *Other;
849 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
850 while (++I1 != E1 && I1->isInsideBundle()) {
852 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
857 // Check operands to make sure they match.
858 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
859 const MachineOperand &MO = getOperand(i);
860 const MachineOperand &OMO = Other->getOperand(i);
862 if (!MO.isIdenticalTo(OMO))
867 // Clients may or may not want to ignore defs when testing for equality.
868 // For example, machine CSE pass only cares about finding common
869 // subexpressions, so it's safe to ignore virtual register defs.
871 if (Check == IgnoreDefs)
873 else if (Check == IgnoreVRegDefs) {
874 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
875 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
876 if (MO.getReg() != OMO.getReg())
879 if (!MO.isIdenticalTo(OMO))
881 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
885 if (!MO.isIdenticalTo(OMO))
887 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
891 // If DebugLoc does not match then two dbg.values are not identical.
893 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
894 && getDebugLoc() != Other->getDebugLoc())
899 MachineInstr *MachineInstr::removeFromParent() {
900 assert(getParent() && "Not embedded in a basic block!");
901 return getParent()->remove(this);
904 MachineInstr *MachineInstr::removeFromBundle() {
905 assert(getParent() && "Not embedded in a basic block!");
906 return getParent()->remove_instr(this);
909 void MachineInstr::eraseFromParent() {
910 assert(getParent() && "Not embedded in a basic block!");
911 getParent()->erase(this);
914 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
915 assert(getParent() && "Not embedded in a basic block!");
916 MachineBasicBlock *MBB = getParent();
917 MachineFunction *MF = MBB->getParent();
918 assert(MF && "Not embedded in a function!");
920 MachineInstr *MI = (MachineInstr *)this;
921 MachineRegisterInfo &MRI = MF->getRegInfo();
923 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
924 const MachineOperand &MO = MI->getOperand(i);
925 if (!MO.isReg() || !MO.isDef())
927 unsigned Reg = MO.getReg();
928 if (!TargetRegisterInfo::isVirtualRegister(Reg))
930 MRI.markUsesInDebugValueAsUndef(Reg);
932 MI->eraseFromParent();
935 void MachineInstr::eraseFromBundle() {
936 assert(getParent() && "Not embedded in a basic block!");
937 getParent()->erase_instr(this);
940 /// getNumExplicitOperands - Returns the number of non-implicit operands.
942 unsigned MachineInstr::getNumExplicitOperands() const {
943 unsigned NumOperands = MCID->getNumOperands();
944 if (!MCID->isVariadic())
947 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
948 const MachineOperand &MO = getOperand(i);
949 if (!MO.isReg() || !MO.isImplicit())
955 void MachineInstr::bundleWithPred() {
956 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
957 setFlag(BundledPred);
958 MachineBasicBlock::instr_iterator Pred = this;
960 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
961 Pred->setFlag(BundledSucc);
964 void MachineInstr::bundleWithSucc() {
965 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
966 setFlag(BundledSucc);
967 MachineBasicBlock::instr_iterator Succ = this;
969 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
970 Succ->setFlag(BundledPred);
973 void MachineInstr::unbundleFromPred() {
974 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
975 clearFlag(BundledPred);
976 MachineBasicBlock::instr_iterator Pred = this;
978 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
979 Pred->clearFlag(BundledSucc);
982 void MachineInstr::unbundleFromSucc() {
983 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
984 clearFlag(BundledSucc);
985 MachineBasicBlock::instr_iterator Succ = this;
987 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
988 Succ->clearFlag(BundledPred);
991 bool MachineInstr::isStackAligningInlineAsm() const {
993 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
994 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1000 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1001 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1002 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1003 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1006 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1007 unsigned *GroupNo) const {
1008 assert(isInlineAsm() && "Expected an inline asm instruction");
1009 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1011 // Ignore queries about the initial operands.
1012 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1017 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1019 const MachineOperand &FlagMO = getOperand(i);
1020 // If we reach the implicit register operands, stop looking.
1021 if (!FlagMO.isImm())
1023 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1024 if (i + NumOps > OpIdx) {
1034 const TargetRegisterClass*
1035 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1036 const TargetInstrInfo *TII,
1037 const TargetRegisterInfo *TRI) const {
1038 assert(getParent() && "Can't have an MBB reference here!");
1039 assert(getParent()->getParent() && "Can't have an MF reference here!");
1040 const MachineFunction &MF = *getParent()->getParent();
1042 // Most opcodes have fixed constraints in their MCInstrDesc.
1044 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1046 if (!getOperand(OpIdx).isReg())
1049 // For tied uses on inline asm, get the constraint from the def.
1051 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1054 // Inline asm stores register class constraints in the flag word.
1055 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1059 unsigned Flag = getOperand(FlagIdx).getImm();
1061 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1062 return TRI->getRegClass(RCID);
1064 // Assume that all registers in a memory operand are pointers.
1065 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1066 return TRI->getPointerRegClass(MF);
1071 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1072 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1073 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1074 // Check every operands inside the bundle if we have
1077 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1079 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1080 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1082 // Otherwise, just check the current operands.
1083 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1084 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1089 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1090 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1091 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1092 assert(CurRC && "Invalid initial register class");
1093 // Check if Reg is constrained by some of its use/def from MI.
1094 const MachineOperand &MO = getOperand(OpIdx);
1095 if (!MO.isReg() || MO.getReg() != Reg)
1097 // If yes, accumulate the constraints through the operand.
1098 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1101 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1102 unsigned OpIdx, const TargetRegisterClass *CurRC,
1103 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1104 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1105 const MachineOperand &MO = getOperand(OpIdx);
1106 assert(MO.isReg() &&
1107 "Cannot get register constraints for non-register operand");
1108 assert(CurRC && "Invalid initial register class");
1109 if (unsigned SubIdx = MO.getSubReg()) {
1111 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1113 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1115 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1119 /// Return the number of instructions inside the MI bundle, not counting the
1120 /// header instruction.
1121 unsigned MachineInstr::getBundleSize() const {
1122 MachineBasicBlock::const_instr_iterator I = this;
1124 while (I->isBundledWithSucc())
1129 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1130 /// the specific register or -1 if it is not found. It further tightens
1131 /// the search criteria to a use that kills the register if isKill is true.
1132 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1133 const TargetRegisterInfo *TRI) const {
1134 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1135 const MachineOperand &MO = getOperand(i);
1136 if (!MO.isReg() || !MO.isUse())
1138 unsigned MOReg = MO.getReg();
1143 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1144 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1145 TRI->isSubRegister(MOReg, Reg)))
1146 if (!isKill || MO.isKill())
1152 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1153 /// indicating if this instruction reads or writes Reg. This also considers
1154 /// partial defines.
1155 std::pair<bool,bool>
1156 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1157 SmallVectorImpl<unsigned> *Ops) const {
1158 bool PartDef = false; // Partial redefine.
1159 bool FullDef = false; // Full define.
1162 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1163 const MachineOperand &MO = getOperand(i);
1164 if (!MO.isReg() || MO.getReg() != Reg)
1169 Use |= !MO.isUndef();
1170 else if (MO.getSubReg() && !MO.isUndef())
1171 // A partial <def,undef> doesn't count as reading the register.
1176 // A partial redefine uses Reg unless there is also a full define.
1177 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1180 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1181 /// the specified register or -1 if it is not found. If isDead is true, defs
1182 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1183 /// also checks if there is a def of a super-register.
1185 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1186 const TargetRegisterInfo *TRI) const {
1187 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1188 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1189 const MachineOperand &MO = getOperand(i);
1190 // Accept regmask operands when Overlap is set.
1191 // Ignore them when looking for a specific def operand (Overlap == false).
1192 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1194 if (!MO.isReg() || !MO.isDef())
1196 unsigned MOReg = MO.getReg();
1197 bool Found = (MOReg == Reg);
1198 if (!Found && TRI && isPhys &&
1199 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1201 Found = TRI->regsOverlap(MOReg, Reg);
1203 Found = TRI->isSubRegister(MOReg, Reg);
1205 if (Found && (!isDead || MO.isDead()))
1211 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1212 /// operand list that is used to represent the predicate. It returns -1 if
1214 int MachineInstr::findFirstPredOperandIdx() const {
1215 // Don't call MCID.findFirstPredOperandIdx() because this variant
1216 // is sometimes called on an instruction that's not yet complete, and
1217 // so the number of operands is less than the MCID indicates. In
1218 // particular, the PTX target does this.
1219 const MCInstrDesc &MCID = getDesc();
1220 if (MCID.isPredicable()) {
1221 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1222 if (MCID.OpInfo[i].isPredicate())
1229 // MachineOperand::TiedTo is 4 bits wide.
1230 const unsigned TiedMax = 15;
1232 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1234 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1235 /// field. TiedTo can have these values:
1237 /// 0: Operand is not tied to anything.
1238 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1239 /// TiedMax: Tied to an operand >= TiedMax-1.
1241 /// The tied def must be one of the first TiedMax operands on a normal
1242 /// instruction. INLINEASM instructions allow more tied defs.
1244 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1245 MachineOperand &DefMO = getOperand(DefIdx);
1246 MachineOperand &UseMO = getOperand(UseIdx);
1247 assert(DefMO.isDef() && "DefIdx must be a def operand");
1248 assert(UseMO.isUse() && "UseIdx must be a use operand");
1249 assert(!DefMO.isTied() && "Def is already tied to another use");
1250 assert(!UseMO.isTied() && "Use is already tied to another def");
1252 if (DefIdx < TiedMax)
1253 UseMO.TiedTo = DefIdx + 1;
1255 // Inline asm can use the group descriptors to find tied operands, but on
1256 // normal instruction, the tied def must be within the first TiedMax
1258 assert(isInlineAsm() && "DefIdx out of range");
1259 UseMO.TiedTo = TiedMax;
1262 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1263 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1266 /// Given the index of a tied register operand, find the operand it is tied to.
1267 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1268 /// which must exist.
1269 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1270 const MachineOperand &MO = getOperand(OpIdx);
1271 assert(MO.isTied() && "Operand isn't tied");
1273 // Normally TiedTo is in range.
1274 if (MO.TiedTo < TiedMax)
1275 return MO.TiedTo - 1;
1277 // Uses on normal instructions can be out of range.
1278 if (!isInlineAsm()) {
1279 // Normal tied defs must be in the 0..TiedMax-1 range.
1282 // MO is a def. Search for the tied use.
1283 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1284 const MachineOperand &UseMO = getOperand(i);
1285 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1288 llvm_unreachable("Can't find tied use");
1291 // Now deal with inline asm by parsing the operand group descriptor flags.
1292 // Find the beginning of each operand group.
1293 SmallVector<unsigned, 8> GroupIdx;
1294 unsigned OpIdxGroup = ~0u;
1296 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1298 const MachineOperand &FlagMO = getOperand(i);
1299 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1300 unsigned CurGroup = GroupIdx.size();
1301 GroupIdx.push_back(i);
1302 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1303 // OpIdx belongs to this operand group.
1304 if (OpIdx > i && OpIdx < i + NumOps)
1305 OpIdxGroup = CurGroup;
1307 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1309 // Operands in this group are tied to operands in TiedGroup which must be
1310 // earlier. Find the number of operands between the two groups.
1311 unsigned Delta = i - GroupIdx[TiedGroup];
1313 // OpIdx is a use tied to TiedGroup.
1314 if (OpIdxGroup == CurGroup)
1315 return OpIdx - Delta;
1317 // OpIdx is a def tied to this use group.
1318 if (OpIdxGroup == TiedGroup)
1319 return OpIdx + Delta;
1321 llvm_unreachable("Invalid tied operand on inline asm");
1324 /// clearKillInfo - Clears kill flags on all operands.
1326 void MachineInstr::clearKillInfo() {
1327 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1328 MachineOperand &MO = getOperand(i);
1329 if (MO.isReg() && MO.isUse())
1330 MO.setIsKill(false);
1334 void MachineInstr::substituteRegister(unsigned FromReg,
1337 const TargetRegisterInfo &RegInfo) {
1338 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1340 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1341 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1342 MachineOperand &MO = getOperand(i);
1343 if (!MO.isReg() || MO.getReg() != FromReg)
1345 MO.substPhysReg(ToReg, RegInfo);
1348 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1349 MachineOperand &MO = getOperand(i);
1350 if (!MO.isReg() || MO.getReg() != FromReg)
1352 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1357 /// isSafeToMove - Return true if it is safe to move this instruction. If
1358 /// SawStore is set to true, it means that there is a store (or call) between
1359 /// the instruction's location and its intended destination.
1360 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1362 bool &SawStore) const {
1363 // Ignore stuff that we obviously can't move.
1365 // Treat volatile loads as stores. This is not strictly necessary for
1366 // volatiles, but it is required for atomic loads. It is not allowed to move
1367 // a load across an atomic load with Ordering > Monotonic.
1368 if (mayStore() || isCall() ||
1369 (mayLoad() && hasOrderedMemoryRef())) {
1374 if (isPosition() || isDebugValue() || isTerminator() ||
1375 hasUnmodeledSideEffects())
1378 // See if this instruction does a load. If so, we have to guarantee that the
1379 // loaded value doesn't change between the load and the its intended
1380 // destination. The check for isInvariantLoad gives the targe the chance to
1381 // classify the load as always returning a constant, e.g. a constant pool
1383 if (mayLoad() && !isInvariantLoad(AA))
1384 // Otherwise, this is a real load. If there is a store between the load and
1385 // end of block, we can't move it.
1391 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1392 /// or volatile memory reference, or if the information describing the memory
1393 /// reference is not available. Return false if it is known to have no ordered
1394 /// memory references.
1395 bool MachineInstr::hasOrderedMemoryRef() const {
1396 // An instruction known never to access memory won't have a volatile access.
1400 !hasUnmodeledSideEffects())
1403 // Otherwise, if the instruction has no memory reference information,
1404 // conservatively assume it wasn't preserved.
1405 if (memoperands_empty())
1408 // Check the memory reference information for ordered references.
1409 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1410 if (!(*I)->isUnordered())
1416 /// isInvariantLoad - Return true if this instruction is loading from a
1417 /// location whose value is invariant across the function. For example,
1418 /// loading a value from the constant pool or from the argument area
1419 /// of a function if it does not change. This should only return true of
1420 /// *all* loads the instruction does are invariant (if it does multiple loads).
1421 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1422 // If the instruction doesn't load at all, it isn't an invariant load.
1426 // If the instruction has lost its memoperands, conservatively assume that
1427 // it may not be an invariant load.
1428 if (memoperands_empty())
1431 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1433 for (mmo_iterator I = memoperands_begin(),
1434 E = memoperands_end(); I != E; ++I) {
1435 if ((*I)->isVolatile()) return false;
1436 if ((*I)->isStore()) return false;
1437 if ((*I)->isInvariant()) return true;
1440 // A load from a constant PseudoSourceValue is invariant.
1441 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1442 if (PSV->isConstant(MFI))
1445 if (const Value *V = (*I)->getValue()) {
1446 // If we have an AliasAnalysis, ask it whether the memory is constant.
1447 if (AA && AA->pointsToConstantMemory(
1448 AliasAnalysis::Location(V, (*I)->getSize(),
1449 (*I)->getAAInfo())))
1453 // Otherwise assume conservatively.
1457 // Everything checks out.
1461 /// isConstantValuePHI - If the specified instruction is a PHI that always
1462 /// merges together the same virtual register, return the register, otherwise
1464 unsigned MachineInstr::isConstantValuePHI() const {
1467 assert(getNumOperands() >= 3 &&
1468 "It's illegal to have a PHI without source operands");
1470 unsigned Reg = getOperand(1).getReg();
1471 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1472 if (getOperand(i).getReg() != Reg)
1477 bool MachineInstr::hasUnmodeledSideEffects() const {
1478 if (hasProperty(MCID::UnmodeledSideEffects))
1480 if (isInlineAsm()) {
1481 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1482 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1489 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1491 bool MachineInstr::allDefsAreDead() const {
1492 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1493 const MachineOperand &MO = getOperand(i);
1494 if (!MO.isReg() || MO.isUse())
1502 /// copyImplicitOps - Copy implicit register operands from specified
1503 /// instruction to this instruction.
1504 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1505 const MachineInstr *MI) {
1506 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1508 const MachineOperand &MO = MI->getOperand(i);
1509 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1514 void MachineInstr::dump() const {
1515 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1516 dbgs() << " " << *this;
1520 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1521 raw_ostream &CommentOS) {
1522 const LLVMContext &Ctx = MF->getFunction()->getContext();
1523 DL.print(Ctx, CommentOS);
1526 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1527 bool SkipOpers) const {
1528 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1529 const MachineFunction *MF = nullptr;
1530 const MachineRegisterInfo *MRI = nullptr;
1531 if (const MachineBasicBlock *MBB = getParent()) {
1532 MF = MBB->getParent();
1534 TM = &MF->getTarget();
1536 MRI = &MF->getRegInfo();
1539 // Save a list of virtual registers.
1540 SmallVector<unsigned, 8> VirtRegs;
1542 // Print explicitly defined operands on the left of an assignment syntax.
1543 unsigned StartOp = 0, e = getNumOperands();
1544 for (; StartOp < e && getOperand(StartOp).isReg() &&
1545 getOperand(StartOp).isDef() &&
1546 !getOperand(StartOp).isImplicit();
1548 if (StartOp != 0) OS << ", ";
1549 getOperand(StartOp).print(OS, TM);
1550 unsigned Reg = getOperand(StartOp).getReg();
1551 if (TargetRegisterInfo::isVirtualRegister(Reg))
1552 VirtRegs.push_back(Reg);
1558 // Print the opcode name.
1559 if (TM && TM->getSubtargetImpl()->getInstrInfo())
1560 OS << TM->getSubtargetImpl()->getInstrInfo()->getName(getOpcode());
1567 // Print the rest of the operands.
1568 bool OmittedAnyCallClobbers = false;
1569 bool FirstOp = true;
1570 unsigned AsmDescOp = ~0u;
1571 unsigned AsmOpCount = 0;
1573 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1574 // Print asm string.
1576 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1578 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1579 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1580 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1581 OS << " [sideeffect]";
1582 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1584 if (ExtraInfo & InlineAsm::Extra_MayStore)
1585 OS << " [maystore]";
1586 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1587 OS << " [alignstack]";
1588 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1589 OS << " [attdialect]";
1590 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1591 OS << " [inteldialect]";
1593 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1598 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1599 const MachineOperand &MO = getOperand(i);
1601 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1602 VirtRegs.push_back(MO.getReg());
1604 // Omit call-clobbered registers which aren't used anywhere. This makes
1605 // call instructions much less noisy on targets where calls clobber lots
1606 // of registers. Don't rely on MO.isDead() because we may be called before
1607 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1608 if (MRI && isCall() &&
1609 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1610 unsigned Reg = MO.getReg();
1611 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1612 if (MRI->use_empty(Reg)) {
1613 bool HasAliasLive = false;
1614 for (MCRegAliasIterator AI(
1615 Reg, TM->getSubtargetImpl()->getRegisterInfo(), true);
1616 AI.isValid(); ++AI) {
1617 unsigned AliasReg = *AI;
1618 if (!MRI->use_empty(AliasReg)) {
1619 HasAliasLive = true;
1623 if (!HasAliasLive) {
1624 OmittedAnyCallClobbers = true;
1631 if (FirstOp) FirstOp = false; else OS << ",";
1633 if (i < getDesc().NumOperands) {
1634 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1635 if (MCOI.isPredicate())
1637 if (MCOI.isOptionalDef())
1640 if (isDebugValue() && MO.isMetadata()) {
1641 // Pretty print DBG_VALUE instructions.
1642 const MDNode *MD = MO.getMetadata();
1643 DIDescriptor DI(MD);
1646 if (DI.isVariable() && !DIV.getName().empty())
1647 OS << "!\"" << DIV.getName() << '\"';
1650 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1651 OS << TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIndexName(
1653 } else if (i == AsmDescOp && MO.isImm()) {
1654 // Pretty print the inline asm operand descriptor.
1655 OS << '$' << AsmOpCount++;
1656 unsigned Flag = MO.getImm();
1657 switch (InlineAsm::getKind(Flag)) {
1658 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1659 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1660 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1661 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1662 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1663 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1664 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1668 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1670 const TargetRegisterInfo *TRI =
1671 TM->getSubtargetImpl()->getRegisterInfo();
1673 << TRI->getRegClassName(TRI->getRegClass(RCID));
1675 OS << ":RC" << RCID;
1678 unsigned TiedTo = 0;
1679 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1680 OS << " tiedto:$" << TiedTo;
1684 // Compute the index of the next operand descriptor.
1685 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1690 // Briefly indicate whether any call clobbers were omitted.
1691 if (OmittedAnyCallClobbers) {
1692 if (!FirstOp) OS << ",";
1696 bool HaveSemi = false;
1697 const unsigned PrintableFlags = FrameSetup;
1698 if (Flags & PrintableFlags) {
1699 if (!HaveSemi) OS << ";"; HaveSemi = true;
1702 if (Flags & FrameSetup)
1706 if (!memoperands_empty()) {
1707 if (!HaveSemi) OS << ";"; HaveSemi = true;
1710 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1713 if (std::next(i) != e)
1718 // Print the regclass of any virtual registers encountered.
1719 if (MRI && !VirtRegs.empty()) {
1720 if (!HaveSemi) OS << ";"; HaveSemi = true;
1721 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1722 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1723 OS << " " << MRI->getTargetRegisterInfo()->getRegClassName(RC)
1724 << ':' << PrintReg(VirtRegs[i]);
1725 for (unsigned j = i+1; j != VirtRegs.size();) {
1726 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1730 if (VirtRegs[i] != VirtRegs[j])
1731 OS << "," << PrintReg(VirtRegs[j]);
1732 VirtRegs.erase(VirtRegs.begin()+j);
1737 // Print debug location information.
1738 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1739 if (!HaveSemi) OS << ";";
1740 DIVariable DV(getOperand(e - 1).getMetadata());
1741 OS << " line no:" << DV.getLineNumber();
1742 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1743 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1744 if (!InlinedAtDL.isUnknown() && MF) {
1745 OS << " inlined @[ ";
1746 printDebugLoc(InlinedAtDL, MF, OS);
1750 if (isIndirectDebugValue())
1752 } else if (!debugLoc.isUnknown() && MF) {
1753 if (!HaveSemi) OS << ";";
1755 printDebugLoc(debugLoc, MF, OS);
1761 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1762 const TargetRegisterInfo *RegInfo,
1763 bool AddIfNotFound) {
1764 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1765 bool hasAliases = isPhysReg &&
1766 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1768 SmallVector<unsigned,4> DeadOps;
1769 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1770 MachineOperand &MO = getOperand(i);
1771 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1773 unsigned Reg = MO.getReg();
1777 if (Reg == IncomingReg) {
1780 // The register is already marked kill.
1782 if (isPhysReg && isRegTiedToDefOperand(i))
1783 // Two-address uses of physregs must not be marked kill.
1788 } else if (hasAliases && MO.isKill() &&
1789 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1790 // A super-register kill already exists.
1791 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1793 if (RegInfo->isSubRegister(IncomingReg, Reg))
1794 DeadOps.push_back(i);
1798 // Trim unneeded kill operands.
1799 while (!DeadOps.empty()) {
1800 unsigned OpIdx = DeadOps.back();
1801 if (getOperand(OpIdx).isImplicit())
1802 RemoveOperand(OpIdx);
1804 getOperand(OpIdx).setIsKill(false);
1808 // If not found, this means an alias of one of the operands is killed. Add a
1809 // new implicit operand if required.
1810 if (!Found && AddIfNotFound) {
1811 addOperand(MachineOperand::CreateReg(IncomingReg,
1820 void MachineInstr::clearRegisterKills(unsigned Reg,
1821 const TargetRegisterInfo *RegInfo) {
1822 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1824 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1825 MachineOperand &MO = getOperand(i);
1826 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1828 unsigned OpReg = MO.getReg();
1829 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1830 MO.setIsKill(false);
1834 bool MachineInstr::addRegisterDead(unsigned Reg,
1835 const TargetRegisterInfo *RegInfo,
1836 bool AddIfNotFound) {
1837 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1838 bool hasAliases = isPhysReg &&
1839 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1841 SmallVector<unsigned,4> DeadOps;
1842 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1843 MachineOperand &MO = getOperand(i);
1844 if (!MO.isReg() || !MO.isDef())
1846 unsigned MOReg = MO.getReg();
1853 } else if (hasAliases && MO.isDead() &&
1854 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1855 // There exists a super-register that's marked dead.
1856 if (RegInfo->isSuperRegister(Reg, MOReg))
1858 if (RegInfo->isSubRegister(Reg, MOReg))
1859 DeadOps.push_back(i);
1863 // Trim unneeded dead operands.
1864 while (!DeadOps.empty()) {
1865 unsigned OpIdx = DeadOps.back();
1866 if (getOperand(OpIdx).isImplicit())
1867 RemoveOperand(OpIdx);
1869 getOperand(OpIdx).setIsDead(false);
1873 // If not found, this means an alias of one of the operands is dead. Add a
1874 // new implicit operand if required.
1875 if (Found || !AddIfNotFound)
1878 addOperand(MachineOperand::CreateReg(Reg,
1886 void MachineInstr::clearRegisterDeads(unsigned Reg) {
1887 for (MachineOperand &MO : operands()) {
1888 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
1890 MO.setIsDead(false);
1894 void MachineInstr::addRegisterDefReadUndef(unsigned Reg) {
1895 for (MachineOperand &MO : operands()) {
1896 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
1902 void MachineInstr::addRegisterDefined(unsigned Reg,
1903 const TargetRegisterInfo *RegInfo) {
1904 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1905 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1909 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1910 const MachineOperand &MO = getOperand(i);
1911 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1912 MO.getSubReg() == 0)
1916 addOperand(MachineOperand::CreateReg(Reg,
1921 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1922 const TargetRegisterInfo &TRI) {
1923 bool HasRegMask = false;
1924 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1925 MachineOperand &MO = getOperand(i);
1926 if (MO.isRegMask()) {
1930 if (!MO.isReg() || !MO.isDef()) continue;
1931 unsigned Reg = MO.getReg();
1932 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1934 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1936 if (TRI.regsOverlap(*I, Reg)) {
1940 // If there are no uses, including partial uses, the def is dead.
1941 if (Dead) MO.setIsDead();
1944 // This is a call with a register mask operand.
1945 // Mask clobbers are always dead, so add defs for the non-dead defines.
1947 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1949 addRegisterDefined(*I, &TRI);
1953 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1954 // Build up a buffer of hash code components.
1955 SmallVector<size_t, 8> HashComponents;
1956 HashComponents.reserve(MI->getNumOperands() + 1);
1957 HashComponents.push_back(MI->getOpcode());
1958 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1959 const MachineOperand &MO = MI->getOperand(i);
1960 if (MO.isReg() && MO.isDef() &&
1961 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1962 continue; // Skip virtual register defs.
1964 HashComponents.push_back(hash_value(MO));
1966 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1969 void MachineInstr::emitError(StringRef Msg) const {
1970 // Find the source location cookie.
1971 unsigned LocCookie = 0;
1972 const MDNode *LocMD = nullptr;
1973 for (unsigned i = getNumOperands(); i != 0; --i) {
1974 if (getOperand(i-1).isMetadata() &&
1975 (LocMD = getOperand(i-1).getMetadata()) &&
1976 LocMD->getNumOperands() != 0) {
1977 if (const ConstantInt *CI =
1978 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
1979 LocCookie = CI->getZExtValue();
1985 if (const MachineBasicBlock *MBB = getParent())
1986 if (const MachineFunction *MF = MBB->getParent())
1987 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1988 report_fatal_error(Msg);