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 /// ChangeToImmediate - Replace this operand with a new immediate operand of
110 /// the specified value. If an operand is known to be an immediate already,
111 /// the setImm method should be used.
112 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
113 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
114 // If this operand is currently a register operand, and if this is in a
115 // function, deregister the operand from the register's use/def list.
116 if (isReg() && isOnRegUseList())
117 if (MachineInstr *MI = getParent())
118 if (MachineBasicBlock *MBB = MI->getParent())
119 if (MachineFunction *MF = MBB->getParent())
120 MF->getRegInfo().removeRegOperandFromUseList(this);
122 OpKind = MO_Immediate;
123 Contents.ImmVal = ImmVal;
126 /// ChangeToRegister - Replace this operand with a new register operand of
127 /// the specified value. If an operand is known to be an register already,
128 /// the setReg method should be used.
129 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
130 bool isKill, bool isDead, bool isUndef,
132 MachineRegisterInfo *RegInfo = nullptr;
133 if (MachineInstr *MI = getParent())
134 if (MachineBasicBlock *MBB = MI->getParent())
135 if (MachineFunction *MF = MBB->getParent())
136 RegInfo = &MF->getRegInfo();
137 // If this operand is already a register operand, remove it from the
138 // register's use/def lists.
139 bool WasReg = isReg();
140 if (RegInfo && WasReg)
141 RegInfo->removeRegOperandFromUseList(this);
143 // Change this to a register and set the reg#.
144 OpKind = MO_Register;
145 SmallContents.RegNo = Reg;
146 SubReg_TargetFlags = 0;
152 IsInternalRead = false;
153 IsEarlyClobber = false;
155 // Ensure isOnRegUseList() returns false.
156 Contents.Reg.Prev = nullptr;
157 // Preserve the tie when the operand was already a register.
161 // If this operand is embedded in a function, add the operand to the
162 // register's use/def list.
164 RegInfo->addRegOperandToUseList(this);
167 /// isIdenticalTo - Return true if this operand is identical to the specified
168 /// operand. Note that this should stay in sync with the hash_value overload
170 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
171 if (getType() != Other.getType() ||
172 getTargetFlags() != Other.getTargetFlags())
176 case MachineOperand::MO_Register:
177 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
178 getSubReg() == Other.getSubReg();
179 case MachineOperand::MO_Immediate:
180 return getImm() == Other.getImm();
181 case MachineOperand::MO_CImmediate:
182 return getCImm() == Other.getCImm();
183 case MachineOperand::MO_FPImmediate:
184 return getFPImm() == Other.getFPImm();
185 case MachineOperand::MO_MachineBasicBlock:
186 return getMBB() == Other.getMBB();
187 case MachineOperand::MO_FrameIndex:
188 return getIndex() == Other.getIndex();
189 case MachineOperand::MO_ConstantPoolIndex:
190 case MachineOperand::MO_TargetIndex:
191 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
192 case MachineOperand::MO_JumpTableIndex:
193 return getIndex() == Other.getIndex();
194 case MachineOperand::MO_GlobalAddress:
195 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
196 case MachineOperand::MO_ExternalSymbol:
197 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
198 getOffset() == Other.getOffset();
199 case MachineOperand::MO_BlockAddress:
200 return getBlockAddress() == Other.getBlockAddress() &&
201 getOffset() == Other.getOffset();
202 case MachineOperand::MO_RegisterMask:
203 case MachineOperand::MO_RegisterLiveOut:
204 return getRegMask() == Other.getRegMask();
205 case MachineOperand::MO_MCSymbol:
206 return getMCSymbol() == Other.getMCSymbol();
207 case MachineOperand::MO_CFIIndex:
208 return getCFIIndex() == Other.getCFIIndex();
209 case MachineOperand::MO_Metadata:
210 return getMetadata() == Other.getMetadata();
212 llvm_unreachable("Invalid machine operand type");
215 // Note: this must stay exactly in sync with isIdenticalTo above.
216 hash_code llvm::hash_value(const MachineOperand &MO) {
217 switch (MO.getType()) {
218 case MachineOperand::MO_Register:
219 // Register operands don't have target flags.
220 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
221 case MachineOperand::MO_Immediate:
222 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
223 case MachineOperand::MO_CImmediate:
224 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
225 case MachineOperand::MO_FPImmediate:
226 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
227 case MachineOperand::MO_MachineBasicBlock:
228 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
229 case MachineOperand::MO_FrameIndex:
230 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
231 case MachineOperand::MO_ConstantPoolIndex:
232 case MachineOperand::MO_TargetIndex:
233 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
235 case MachineOperand::MO_JumpTableIndex:
236 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
237 case MachineOperand::MO_ExternalSymbol:
238 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
240 case MachineOperand::MO_GlobalAddress:
241 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
243 case MachineOperand::MO_BlockAddress:
244 return hash_combine(MO.getType(), MO.getTargetFlags(),
245 MO.getBlockAddress(), MO.getOffset());
246 case MachineOperand::MO_RegisterMask:
247 case MachineOperand::MO_RegisterLiveOut:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
249 case MachineOperand::MO_Metadata:
250 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
251 case MachineOperand::MO_MCSymbol:
252 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
253 case MachineOperand::MO_CFIIndex:
254 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
256 llvm_unreachable("Invalid machine operand type");
259 /// print - Print the specified machine operand.
261 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
262 // If the instruction is embedded into a basic block, we can find the
263 // target info for the instruction.
265 if (const MachineInstr *MI = getParent())
266 if (const MachineBasicBlock *MBB = MI->getParent())
267 if (const MachineFunction *MF = MBB->getParent())
268 TM = &MF->getTarget();
269 const TargetRegisterInfo *TRI =
270 TM ? TM->getSubtargetImpl()->getRegisterInfo() : nullptr;
273 case MachineOperand::MO_Register:
274 OS << PrintReg(getReg(), TRI, getSubReg());
276 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
277 isInternalRead() || isEarlyClobber() || isTied()) {
279 bool NeedComma = false;
281 if (NeedComma) OS << ',';
282 if (isEarlyClobber())
283 OS << "earlyclobber,";
288 // <def,read-undef> only makes sense when getSubReg() is set.
289 // Don't clutter the output otherwise.
290 if (isUndef() && getSubReg())
292 } else if (isImplicit()) {
298 if (NeedComma) OS << ',';
303 if (NeedComma) OS << ',';
307 if (isUndef() && isUse()) {
308 if (NeedComma) OS << ',';
312 if (isInternalRead()) {
313 if (NeedComma) OS << ',';
318 if (NeedComma) OS << ',';
321 OS << unsigned(TiedTo - 1);
326 case MachineOperand::MO_Immediate:
329 case MachineOperand::MO_CImmediate:
330 getCImm()->getValue().print(OS, false);
332 case MachineOperand::MO_FPImmediate:
333 if (getFPImm()->getType()->isFloatTy())
334 OS << getFPImm()->getValueAPF().convertToFloat();
336 OS << getFPImm()->getValueAPF().convertToDouble();
338 case MachineOperand::MO_MachineBasicBlock:
339 OS << "<BB#" << getMBB()->getNumber() << ">";
341 case MachineOperand::MO_FrameIndex:
342 OS << "<fi#" << getIndex() << '>';
344 case MachineOperand::MO_ConstantPoolIndex:
345 OS << "<cp#" << getIndex();
346 if (getOffset()) OS << "+" << getOffset();
349 case MachineOperand::MO_TargetIndex:
350 OS << "<ti#" << getIndex();
351 if (getOffset()) OS << "+" << getOffset();
354 case MachineOperand::MO_JumpTableIndex:
355 OS << "<jt#" << getIndex() << '>';
357 case MachineOperand::MO_GlobalAddress:
359 getGlobal()->printAsOperand(OS, /*PrintType=*/false);
360 if (getOffset()) OS << "+" << getOffset();
363 case MachineOperand::MO_ExternalSymbol:
364 OS << "<es:" << getSymbolName();
365 if (getOffset()) OS << "+" << getOffset();
368 case MachineOperand::MO_BlockAddress:
370 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false);
371 if (getOffset()) OS << "+" << getOffset();
374 case MachineOperand::MO_RegisterMask:
377 case MachineOperand::MO_RegisterLiveOut:
378 OS << "<regliveout>";
380 case MachineOperand::MO_Metadata:
382 getMetadata()->printAsOperand(OS, /*PrintType=*/false);
385 case MachineOperand::MO_MCSymbol:
386 OS << "<MCSym=" << *getMCSymbol() << '>';
388 case MachineOperand::MO_CFIIndex:
389 OS << "<call frame instruction>";
393 if (unsigned TF = getTargetFlags())
394 OS << "[TF=" << TF << ']';
397 //===----------------------------------------------------------------------===//
398 // MachineMemOperand Implementation
399 //===----------------------------------------------------------------------===//
401 /// getAddrSpace - Return the LLVM IR address space number that this pointer
403 unsigned MachinePointerInfo::getAddrSpace() const {
404 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
405 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
408 /// getConstantPool - Return a MachinePointerInfo record that refers to the
410 MachinePointerInfo MachinePointerInfo::getConstantPool() {
411 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
414 /// getFixedStack - Return a MachinePointerInfo record that refers to the
415 /// the specified FrameIndex.
416 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
417 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
420 MachinePointerInfo MachinePointerInfo::getJumpTable() {
421 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
424 MachinePointerInfo MachinePointerInfo::getGOT() {
425 return MachinePointerInfo(PseudoSourceValue::getGOT());
428 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
429 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
432 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
433 uint64_t s, unsigned int a,
434 const AAMDNodes &AAInfo,
435 const MDNode *Ranges)
436 : PtrInfo(ptrinfo), Size(s),
437 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
438 AAInfo(AAInfo), Ranges(Ranges) {
439 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
440 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
441 "invalid pointer value");
442 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
443 assert((isLoad() || isStore()) && "Not a load/store!");
446 /// Profile - Gather unique data for the object.
448 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
449 ID.AddInteger(getOffset());
451 ID.AddPointer(getOpaqueValue());
452 ID.AddInteger(Flags);
455 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
456 // The Value and Offset may differ due to CSE. But the flags and size
457 // should be the same.
458 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
459 assert(MMO->getSize() == getSize() && "Size mismatch!");
461 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
462 // Update the alignment value.
463 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
464 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
465 // Also update the base and offset, because the new alignment may
466 // not be applicable with the old ones.
467 PtrInfo = MMO->PtrInfo;
471 /// getAlignment - Return the minimum known alignment in bytes of the
472 /// actual memory reference.
473 uint64_t MachineMemOperand::getAlignment() const {
474 return MinAlign(getBaseAlignment(), getOffset());
477 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
478 assert((MMO.isLoad() || MMO.isStore()) &&
479 "SV has to be a load, store or both.");
481 if (MMO.isVolatile())
490 // Print the address information.
492 if (const Value *V = MMO.getValue())
493 V->printAsOperand(OS, /*PrintType=*/false);
494 else if (const PseudoSourceValue *PSV = MMO.getPseudoValue())
495 PSV->printCustom(OS);
499 unsigned AS = MMO.getAddrSpace();
501 OS << "(addrspace=" << AS << ')';
503 // If the alignment of the memory reference itself differs from the alignment
504 // of the base pointer, print the base alignment explicitly, next to the base
506 if (MMO.getBaseAlignment() != MMO.getAlignment())
507 OS << "(align=" << MMO.getBaseAlignment() << ")";
509 if (MMO.getOffset() != 0)
510 OS << "+" << MMO.getOffset();
513 // Print the alignment of the reference.
514 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
515 MMO.getBaseAlignment() != MMO.getSize())
516 OS << "(align=" << MMO.getAlignment() << ")";
519 if (const MDNode *TBAAInfo = MMO.getAAInfo().TBAA) {
521 if (TBAAInfo->getNumOperands() > 0)
522 TBAAInfo->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
528 // Print AA scope info.
529 if (const MDNode *ScopeInfo = MMO.getAAInfo().Scope) {
530 OS << "(alias.scope=";
531 if (ScopeInfo->getNumOperands() > 0)
532 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
533 ScopeInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
542 // Print AA noalias scope info.
543 if (const MDNode *NoAliasInfo = MMO.getAAInfo().NoAlias) {
545 if (NoAliasInfo->getNumOperands() > 0)
546 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
547 NoAliasInfo->getOperand(i)->printAsOperand(OS, /*PrintType=*/false);
556 // Print nontemporal info.
557 if (MMO.isNonTemporal())
558 OS << "(nontemporal)";
563 //===----------------------------------------------------------------------===//
564 // MachineInstr Implementation
565 //===----------------------------------------------------------------------===//
567 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
568 if (MCID->ImplicitDefs)
569 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
570 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
571 if (MCID->ImplicitUses)
572 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
573 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
576 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
577 /// implicit operands. It reserves space for the number of operands specified by
579 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
580 const DebugLoc dl, bool NoImp)
581 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0),
582 Flags(0), AsmPrinterFlags(0),
583 NumMemRefs(0), MemRefs(nullptr), debugLoc(dl) {
584 // Reserve space for the expected number of operands.
585 if (unsigned NumOps = MCID->getNumOperands() +
586 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
587 CapOperands = OperandCapacity::get(NumOps);
588 Operands = MF.allocateOperandArray(CapOperands);
592 addImplicitDefUseOperands(MF);
595 /// MachineInstr ctor - Copies MachineInstr arg exactly
597 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
598 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
599 Flags(0), AsmPrinterFlags(0),
600 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
601 debugLoc(MI.getDebugLoc()) {
602 CapOperands = OperandCapacity::get(MI.getNumOperands());
603 Operands = MF.allocateOperandArray(CapOperands);
606 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
607 addOperand(MF, MI.getOperand(i));
609 // Copy all the sensible flags.
613 /// getRegInfo - If this instruction is embedded into a MachineFunction,
614 /// return the MachineRegisterInfo object for the current function, otherwise
616 MachineRegisterInfo *MachineInstr::getRegInfo() {
617 if (MachineBasicBlock *MBB = getParent())
618 return &MBB->getParent()->getRegInfo();
622 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
623 /// this instruction from their respective use lists. This requires that the
624 /// operands already be on their use lists.
625 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
626 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
627 if (Operands[i].isReg())
628 MRI.removeRegOperandFromUseList(&Operands[i]);
631 /// AddRegOperandsToUseLists - Add all of the register operands in
632 /// this instruction from their respective use lists. This requires that the
633 /// operands not be on their use lists yet.
634 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
635 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
636 if (Operands[i].isReg())
637 MRI.addRegOperandToUseList(&Operands[i]);
640 void MachineInstr::addOperand(const MachineOperand &Op) {
641 MachineBasicBlock *MBB = getParent();
642 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
643 MachineFunction *MF = MBB->getParent();
644 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
648 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
649 /// ranges. If MRI is non-null also update use-def chains.
650 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
651 unsigned NumOps, MachineRegisterInfo *MRI) {
653 return MRI->moveOperands(Dst, Src, NumOps);
655 // Here it would be convenient to call memmove, so that isn't allowed because
656 // MachineOperand has a constructor and so isn't a POD type.
658 for (unsigned i = 0; i != NumOps; ++i)
659 new (Dst + i) MachineOperand(Src[i]);
661 for (unsigned i = NumOps; i ; --i)
662 new (Dst + i - 1) MachineOperand(Src[i - 1]);
665 /// addOperand - Add the specified operand to the instruction. If it is an
666 /// implicit operand, it is added to the end of the operand list. If it is
667 /// an explicit operand it is added at the end of the explicit operand list
668 /// (before the first implicit operand).
669 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
670 assert(MCID && "Cannot add operands before providing an instr descriptor");
672 // Check if we're adding one of our existing operands.
673 if (&Op >= Operands && &Op < Operands + NumOperands) {
674 // This is unusual: MI->addOperand(MI->getOperand(i)).
675 // If adding Op requires reallocating or moving existing operands around,
676 // the Op reference could go stale. Support it by copying Op.
677 MachineOperand CopyOp(Op);
678 return addOperand(MF, CopyOp);
681 // Find the insert location for the new operand. Implicit registers go at
682 // the end, everything else goes before the implicit regs.
684 // FIXME: Allow mixed explicit and implicit operands on inline asm.
685 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
686 // implicit-defs, but they must not be moved around. See the FIXME in
688 unsigned OpNo = getNumOperands();
689 bool isImpReg = Op.isReg() && Op.isImplicit();
690 if (!isImpReg && !isInlineAsm()) {
691 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
693 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
698 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
699 // OpNo now points as the desired insertion point. Unless this is a variadic
700 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
701 // RegMask operands go between the explicit and implicit operands.
702 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
703 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
704 "Trying to add an operand to a machine instr that is already done!");
707 MachineRegisterInfo *MRI = getRegInfo();
709 // Determine if the Operands array needs to be reallocated.
710 // Save the old capacity and operand array.
711 OperandCapacity OldCap = CapOperands;
712 MachineOperand *OldOperands = Operands;
713 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
714 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
715 Operands = MF.allocateOperandArray(CapOperands);
716 // Move the operands before the insertion point.
718 moveOperands(Operands, OldOperands, OpNo, MRI);
721 // Move the operands following the insertion point.
722 if (OpNo != NumOperands)
723 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
727 // Deallocate the old operand array.
728 if (OldOperands != Operands && OldOperands)
729 MF.deallocateOperandArray(OldCap, OldOperands);
731 // Copy Op into place. It still needs to be inserted into the MRI use lists.
732 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
733 NewMO->ParentMI = this;
735 // When adding a register operand, tell MRI about it.
736 if (NewMO->isReg()) {
737 // Ensure isOnRegUseList() returns false, regardless of Op's status.
738 NewMO->Contents.Reg.Prev = nullptr;
739 // Ignore existing ties. This is not a property that can be copied.
741 // Add the new operand to MRI, but only for instructions in an MBB.
743 MRI->addRegOperandToUseList(NewMO);
744 // The MCID operand information isn't accurate until we start adding
745 // explicit operands. The implicit operands are added first, then the
746 // explicits are inserted before them.
748 // Tie uses to defs as indicated in MCInstrDesc.
749 if (NewMO->isUse()) {
750 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
752 tieOperands(DefIdx, OpNo);
754 // If the register operand is flagged as early, mark the operand as such.
755 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
756 NewMO->setIsEarlyClobber(true);
761 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
762 /// fewer operand than it started with.
764 void MachineInstr::RemoveOperand(unsigned OpNo) {
765 assert(OpNo < getNumOperands() && "Invalid operand number");
766 untieRegOperand(OpNo);
769 // Moving tied operands would break the ties.
770 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
771 if (Operands[i].isReg())
772 assert(!Operands[i].isTied() && "Cannot move tied operands");
775 MachineRegisterInfo *MRI = getRegInfo();
776 if (MRI && Operands[OpNo].isReg())
777 MRI->removeRegOperandFromUseList(Operands + OpNo);
779 // Don't call the MachineOperand destructor. A lot of this code depends on
780 // MachineOperand having a trivial destructor anyway, and adding a call here
781 // wouldn't make it 'destructor-correct'.
783 if (unsigned N = NumOperands - 1 - OpNo)
784 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
788 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
789 /// This function should be used only occasionally. The setMemRefs function
790 /// is the primary method for setting up a MachineInstr's MemRefs list.
791 void MachineInstr::addMemOperand(MachineFunction &MF,
792 MachineMemOperand *MO) {
793 mmo_iterator OldMemRefs = MemRefs;
794 unsigned OldNumMemRefs = NumMemRefs;
796 unsigned NewNum = NumMemRefs + 1;
797 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
799 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
800 NewMemRefs[NewNum - 1] = MO;
801 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
804 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
805 assert(!isBundledWithPred() && "Must be called on bundle header");
806 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
807 if (MII->getDesc().getFlags() & Mask) {
808 if (Type == AnyInBundle)
811 if (Type == AllInBundle && !MII->isBundle())
814 // This was the last instruction in the bundle.
815 if (!MII->isBundledWithSucc())
816 return Type == AllInBundle;
820 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
821 MICheckType Check) const {
822 // If opcodes or number of operands are not the same then the two
823 // instructions are obviously not identical.
824 if (Other->getOpcode() != getOpcode() ||
825 Other->getNumOperands() != getNumOperands())
829 // Both instructions are bundles, compare MIs inside the bundle.
830 MachineBasicBlock::const_instr_iterator I1 = *this;
831 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
832 MachineBasicBlock::const_instr_iterator I2 = *Other;
833 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
834 while (++I1 != E1 && I1->isInsideBundle()) {
836 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
841 // Check operands to make sure they match.
842 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
843 const MachineOperand &MO = getOperand(i);
844 const MachineOperand &OMO = Other->getOperand(i);
846 if (!MO.isIdenticalTo(OMO))
851 // Clients may or may not want to ignore defs when testing for equality.
852 // For example, machine CSE pass only cares about finding common
853 // subexpressions, so it's safe to ignore virtual register defs.
855 if (Check == IgnoreDefs)
857 else if (Check == IgnoreVRegDefs) {
858 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
859 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
860 if (MO.getReg() != OMO.getReg())
863 if (!MO.isIdenticalTo(OMO))
865 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
869 if (!MO.isIdenticalTo(OMO))
871 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
875 // If DebugLoc does not match then two dbg.values are not identical.
877 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
878 && getDebugLoc() != Other->getDebugLoc())
883 MachineInstr *MachineInstr::removeFromParent() {
884 assert(getParent() && "Not embedded in a basic block!");
885 return getParent()->remove(this);
888 MachineInstr *MachineInstr::removeFromBundle() {
889 assert(getParent() && "Not embedded in a basic block!");
890 return getParent()->remove_instr(this);
893 void MachineInstr::eraseFromParent() {
894 assert(getParent() && "Not embedded in a basic block!");
895 getParent()->erase(this);
898 void MachineInstr::eraseFromBundle() {
899 assert(getParent() && "Not embedded in a basic block!");
900 getParent()->erase_instr(this);
903 /// getNumExplicitOperands - Returns the number of non-implicit operands.
905 unsigned MachineInstr::getNumExplicitOperands() const {
906 unsigned NumOperands = MCID->getNumOperands();
907 if (!MCID->isVariadic())
910 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
911 const MachineOperand &MO = getOperand(i);
912 if (!MO.isReg() || !MO.isImplicit())
918 void MachineInstr::bundleWithPred() {
919 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
920 setFlag(BundledPred);
921 MachineBasicBlock::instr_iterator Pred = this;
923 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
924 Pred->setFlag(BundledSucc);
927 void MachineInstr::bundleWithSucc() {
928 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
929 setFlag(BundledSucc);
930 MachineBasicBlock::instr_iterator Succ = this;
932 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
933 Succ->setFlag(BundledPred);
936 void MachineInstr::unbundleFromPred() {
937 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
938 clearFlag(BundledPred);
939 MachineBasicBlock::instr_iterator Pred = this;
941 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
942 Pred->clearFlag(BundledSucc);
945 void MachineInstr::unbundleFromSucc() {
946 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
947 clearFlag(BundledSucc);
948 MachineBasicBlock::instr_iterator Succ = this;
950 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
951 Succ->clearFlag(BundledPred);
954 bool MachineInstr::isStackAligningInlineAsm() const {
956 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
957 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
963 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
964 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
965 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
966 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
969 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
970 unsigned *GroupNo) const {
971 assert(isInlineAsm() && "Expected an inline asm instruction");
972 assert(OpIdx < getNumOperands() && "OpIdx out of range");
974 // Ignore queries about the initial operands.
975 if (OpIdx < InlineAsm::MIOp_FirstOperand)
980 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
982 const MachineOperand &FlagMO = getOperand(i);
983 // If we reach the implicit register operands, stop looking.
986 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
987 if (i + NumOps > OpIdx) {
997 const TargetRegisterClass*
998 MachineInstr::getRegClassConstraint(unsigned OpIdx,
999 const TargetInstrInfo *TII,
1000 const TargetRegisterInfo *TRI) const {
1001 assert(getParent() && "Can't have an MBB reference here!");
1002 assert(getParent()->getParent() && "Can't have an MF reference here!");
1003 const MachineFunction &MF = *getParent()->getParent();
1005 // Most opcodes have fixed constraints in their MCInstrDesc.
1007 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1009 if (!getOperand(OpIdx).isReg())
1012 // For tied uses on inline asm, get the constraint from the def.
1014 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1017 // Inline asm stores register class constraints in the flag word.
1018 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1022 unsigned Flag = getOperand(FlagIdx).getImm();
1024 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1025 return TRI->getRegClass(RCID);
1027 // Assume that all registers in a memory operand are pointers.
1028 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1029 return TRI->getPointerRegClass(MF);
1034 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1035 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1036 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1037 // Check every operands inside the bundle if we have
1040 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1042 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1043 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1045 // Otherwise, just check the current operands.
1046 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1047 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1052 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1053 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1054 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1055 assert(CurRC && "Invalid initial register class");
1056 // Check if Reg is constrained by some of its use/def from MI.
1057 const MachineOperand &MO = getOperand(OpIdx);
1058 if (!MO.isReg() || MO.getReg() != Reg)
1060 // If yes, accumulate the constraints through the operand.
1061 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1064 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1065 unsigned OpIdx, const TargetRegisterClass *CurRC,
1066 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1067 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1068 const MachineOperand &MO = getOperand(OpIdx);
1069 assert(MO.isReg() &&
1070 "Cannot get register constraints for non-register operand");
1071 assert(CurRC && "Invalid initial register class");
1072 if (unsigned SubIdx = MO.getSubReg()) {
1074 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1076 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1078 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1082 /// Return the number of instructions inside the MI bundle, not counting the
1083 /// header instruction.
1084 unsigned MachineInstr::getBundleSize() const {
1085 MachineBasicBlock::const_instr_iterator I = this;
1087 while (I->isBundledWithSucc())
1092 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1093 /// the specific register or -1 if it is not found. It further tightens
1094 /// the search criteria to a use that kills the register if isKill is true.
1095 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1096 const TargetRegisterInfo *TRI) const {
1097 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1098 const MachineOperand &MO = getOperand(i);
1099 if (!MO.isReg() || !MO.isUse())
1101 unsigned MOReg = MO.getReg();
1106 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1107 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1108 TRI->isSubRegister(MOReg, Reg)))
1109 if (!isKill || MO.isKill())
1115 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1116 /// indicating if this instruction reads or writes Reg. This also considers
1117 /// partial defines.
1118 std::pair<bool,bool>
1119 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1120 SmallVectorImpl<unsigned> *Ops) const {
1121 bool PartDef = false; // Partial redefine.
1122 bool FullDef = false; // Full define.
1125 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1126 const MachineOperand &MO = getOperand(i);
1127 if (!MO.isReg() || MO.getReg() != Reg)
1132 Use |= !MO.isUndef();
1133 else if (MO.getSubReg() && !MO.isUndef())
1134 // A partial <def,undef> doesn't count as reading the register.
1139 // A partial redefine uses Reg unless there is also a full define.
1140 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1143 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1144 /// the specified register or -1 if it is not found. If isDead is true, defs
1145 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1146 /// also checks if there is a def of a super-register.
1148 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1149 const TargetRegisterInfo *TRI) const {
1150 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1151 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1152 const MachineOperand &MO = getOperand(i);
1153 // Accept regmask operands when Overlap is set.
1154 // Ignore them when looking for a specific def operand (Overlap == false).
1155 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1157 if (!MO.isReg() || !MO.isDef())
1159 unsigned MOReg = MO.getReg();
1160 bool Found = (MOReg == Reg);
1161 if (!Found && TRI && isPhys &&
1162 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1164 Found = TRI->regsOverlap(MOReg, Reg);
1166 Found = TRI->isSubRegister(MOReg, Reg);
1168 if (Found && (!isDead || MO.isDead()))
1174 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1175 /// operand list that is used to represent the predicate. It returns -1 if
1177 int MachineInstr::findFirstPredOperandIdx() const {
1178 // Don't call MCID.findFirstPredOperandIdx() because this variant
1179 // is sometimes called on an instruction that's not yet complete, and
1180 // so the number of operands is less than the MCID indicates. In
1181 // particular, the PTX target does this.
1182 const MCInstrDesc &MCID = getDesc();
1183 if (MCID.isPredicable()) {
1184 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1185 if (MCID.OpInfo[i].isPredicate())
1192 // MachineOperand::TiedTo is 4 bits wide.
1193 const unsigned TiedMax = 15;
1195 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1197 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1198 /// field. TiedTo can have these values:
1200 /// 0: Operand is not tied to anything.
1201 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1202 /// TiedMax: Tied to an operand >= TiedMax-1.
1204 /// The tied def must be one of the first TiedMax operands on a normal
1205 /// instruction. INLINEASM instructions allow more tied defs.
1207 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1208 MachineOperand &DefMO = getOperand(DefIdx);
1209 MachineOperand &UseMO = getOperand(UseIdx);
1210 assert(DefMO.isDef() && "DefIdx must be a def operand");
1211 assert(UseMO.isUse() && "UseIdx must be a use operand");
1212 assert(!DefMO.isTied() && "Def is already tied to another use");
1213 assert(!UseMO.isTied() && "Use is already tied to another def");
1215 if (DefIdx < TiedMax)
1216 UseMO.TiedTo = DefIdx + 1;
1218 // Inline asm can use the group descriptors to find tied operands, but on
1219 // normal instruction, the tied def must be within the first TiedMax
1221 assert(isInlineAsm() && "DefIdx out of range");
1222 UseMO.TiedTo = TiedMax;
1225 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1226 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1229 /// Given the index of a tied register operand, find the operand it is tied to.
1230 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1231 /// which must exist.
1232 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1233 const MachineOperand &MO = getOperand(OpIdx);
1234 assert(MO.isTied() && "Operand isn't tied");
1236 // Normally TiedTo is in range.
1237 if (MO.TiedTo < TiedMax)
1238 return MO.TiedTo - 1;
1240 // Uses on normal instructions can be out of range.
1241 if (!isInlineAsm()) {
1242 // Normal tied defs must be in the 0..TiedMax-1 range.
1245 // MO is a def. Search for the tied use.
1246 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1247 const MachineOperand &UseMO = getOperand(i);
1248 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1251 llvm_unreachable("Can't find tied use");
1254 // Now deal with inline asm by parsing the operand group descriptor flags.
1255 // Find the beginning of each operand group.
1256 SmallVector<unsigned, 8> GroupIdx;
1257 unsigned OpIdxGroup = ~0u;
1259 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1261 const MachineOperand &FlagMO = getOperand(i);
1262 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1263 unsigned CurGroup = GroupIdx.size();
1264 GroupIdx.push_back(i);
1265 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1266 // OpIdx belongs to this operand group.
1267 if (OpIdx > i && OpIdx < i + NumOps)
1268 OpIdxGroup = CurGroup;
1270 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1272 // Operands in this group are tied to operands in TiedGroup which must be
1273 // earlier. Find the number of operands between the two groups.
1274 unsigned Delta = i - GroupIdx[TiedGroup];
1276 // OpIdx is a use tied to TiedGroup.
1277 if (OpIdxGroup == CurGroup)
1278 return OpIdx - Delta;
1280 // OpIdx is a def tied to this use group.
1281 if (OpIdxGroup == TiedGroup)
1282 return OpIdx + Delta;
1284 llvm_unreachable("Invalid tied operand on inline asm");
1287 /// clearKillInfo - Clears kill flags on all operands.
1289 void MachineInstr::clearKillInfo() {
1290 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1291 MachineOperand &MO = getOperand(i);
1292 if (MO.isReg() && MO.isUse())
1293 MO.setIsKill(false);
1297 void MachineInstr::substituteRegister(unsigned FromReg,
1300 const TargetRegisterInfo &RegInfo) {
1301 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1303 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1305 MachineOperand &MO = getOperand(i);
1306 if (!MO.isReg() || MO.getReg() != FromReg)
1308 MO.substPhysReg(ToReg, RegInfo);
1311 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1312 MachineOperand &MO = getOperand(i);
1313 if (!MO.isReg() || MO.getReg() != FromReg)
1315 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1320 /// isSafeToMove - Return true if it is safe to move this instruction. If
1321 /// SawStore is set to true, it means that there is a store (or call) between
1322 /// the instruction's location and its intended destination.
1323 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1325 bool &SawStore) const {
1326 // Ignore stuff that we obviously can't move.
1328 // Treat volatile loads as stores. This is not strictly necessary for
1329 // volatiles, but it is required for atomic loads. It is not allowed to move
1330 // a load across an atomic load with Ordering > Monotonic.
1331 if (mayStore() || isCall() ||
1332 (mayLoad() && hasOrderedMemoryRef())) {
1337 if (isPosition() || isDebugValue() || isTerminator() ||
1338 hasUnmodeledSideEffects())
1341 // See if this instruction does a load. If so, we have to guarantee that the
1342 // loaded value doesn't change between the load and the its intended
1343 // destination. The check for isInvariantLoad gives the targe the chance to
1344 // classify the load as always returning a constant, e.g. a constant pool
1346 if (mayLoad() && !isInvariantLoad(AA))
1347 // Otherwise, this is a real load. If there is a store between the load and
1348 // end of block, we can't move it.
1354 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1355 /// or volatile memory reference, or if the information describing the memory
1356 /// reference is not available. Return false if it is known to have no ordered
1357 /// memory references.
1358 bool MachineInstr::hasOrderedMemoryRef() const {
1359 // An instruction known never to access memory won't have a volatile access.
1363 !hasUnmodeledSideEffects())
1366 // Otherwise, if the instruction has no memory reference information,
1367 // conservatively assume it wasn't preserved.
1368 if (memoperands_empty())
1371 // Check the memory reference information for ordered references.
1372 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1373 if (!(*I)->isUnordered())
1379 /// isInvariantLoad - Return true if this instruction is loading from a
1380 /// location whose value is invariant across the function. For example,
1381 /// loading a value from the constant pool or from the argument area
1382 /// of a function if it does not change. This should only return true of
1383 /// *all* loads the instruction does are invariant (if it does multiple loads).
1384 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1385 // If the instruction doesn't load at all, it isn't an invariant load.
1389 // If the instruction has lost its memoperands, conservatively assume that
1390 // it may not be an invariant load.
1391 if (memoperands_empty())
1394 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1396 for (mmo_iterator I = memoperands_begin(),
1397 E = memoperands_end(); I != E; ++I) {
1398 if ((*I)->isVolatile()) return false;
1399 if ((*I)->isStore()) return false;
1400 if ((*I)->isInvariant()) return true;
1403 // A load from a constant PseudoSourceValue is invariant.
1404 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1405 if (PSV->isConstant(MFI))
1408 if (const Value *V = (*I)->getValue()) {
1409 // If we have an AliasAnalysis, ask it whether the memory is constant.
1410 if (AA && AA->pointsToConstantMemory(
1411 AliasAnalysis::Location(V, (*I)->getSize(),
1412 (*I)->getAAInfo())))
1416 // Otherwise assume conservatively.
1420 // Everything checks out.
1424 /// isConstantValuePHI - If the specified instruction is a PHI that always
1425 /// merges together the same virtual register, return the register, otherwise
1427 unsigned MachineInstr::isConstantValuePHI() const {
1430 assert(getNumOperands() >= 3 &&
1431 "It's illegal to have a PHI without source operands");
1433 unsigned Reg = getOperand(1).getReg();
1434 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1435 if (getOperand(i).getReg() != Reg)
1440 bool MachineInstr::hasUnmodeledSideEffects() const {
1441 if (hasProperty(MCID::UnmodeledSideEffects))
1443 if (isInlineAsm()) {
1444 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1445 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1452 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1454 bool MachineInstr::allDefsAreDead() const {
1455 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1456 const MachineOperand &MO = getOperand(i);
1457 if (!MO.isReg() || MO.isUse())
1465 /// copyImplicitOps - Copy implicit register operands from specified
1466 /// instruction to this instruction.
1467 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1468 const MachineInstr *MI) {
1469 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1471 const MachineOperand &MO = MI->getOperand(i);
1472 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1477 void MachineInstr::dump() const {
1478 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1479 dbgs() << " " << *this;
1483 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1484 raw_ostream &CommentOS) {
1485 const LLVMContext &Ctx = MF->getFunction()->getContext();
1486 DL.print(Ctx, CommentOS);
1489 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1490 bool SkipOpers) const {
1491 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1492 const MachineFunction *MF = nullptr;
1493 const MachineRegisterInfo *MRI = nullptr;
1494 if (const MachineBasicBlock *MBB = getParent()) {
1495 MF = MBB->getParent();
1497 TM = &MF->getTarget();
1499 MRI = &MF->getRegInfo();
1502 // Save a list of virtual registers.
1503 SmallVector<unsigned, 8> VirtRegs;
1505 // Print explicitly defined operands on the left of an assignment syntax.
1506 unsigned StartOp = 0, e = getNumOperands();
1507 for (; StartOp < e && getOperand(StartOp).isReg() &&
1508 getOperand(StartOp).isDef() &&
1509 !getOperand(StartOp).isImplicit();
1511 if (StartOp != 0) OS << ", ";
1512 getOperand(StartOp).print(OS, TM);
1513 unsigned Reg = getOperand(StartOp).getReg();
1514 if (TargetRegisterInfo::isVirtualRegister(Reg))
1515 VirtRegs.push_back(Reg);
1521 // Print the opcode name.
1522 if (TM && TM->getSubtargetImpl()->getInstrInfo())
1523 OS << TM->getSubtargetImpl()->getInstrInfo()->getName(getOpcode());
1530 // Print the rest of the operands.
1531 bool OmittedAnyCallClobbers = false;
1532 bool FirstOp = true;
1533 unsigned AsmDescOp = ~0u;
1534 unsigned AsmOpCount = 0;
1536 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1537 // Print asm string.
1539 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1541 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1542 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1543 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1544 OS << " [sideeffect]";
1545 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1547 if (ExtraInfo & InlineAsm::Extra_MayStore)
1548 OS << " [maystore]";
1549 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1550 OS << " [alignstack]";
1551 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1552 OS << " [attdialect]";
1553 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1554 OS << " [inteldialect]";
1556 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1561 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1562 const MachineOperand &MO = getOperand(i);
1564 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1565 VirtRegs.push_back(MO.getReg());
1567 // Omit call-clobbered registers which aren't used anywhere. This makes
1568 // call instructions much less noisy on targets where calls clobber lots
1569 // of registers. Don't rely on MO.isDead() because we may be called before
1570 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1571 if (MF && isCall() &&
1572 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1573 unsigned Reg = MO.getReg();
1574 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1575 const MachineRegisterInfo &MRI = MF->getRegInfo();
1576 if (MRI.use_empty(Reg)) {
1577 bool HasAliasLive = false;
1578 for (MCRegAliasIterator AI(
1579 Reg, TM->getSubtargetImpl()->getRegisterInfo(), true);
1580 AI.isValid(); ++AI) {
1581 unsigned AliasReg = *AI;
1582 if (!MRI.use_empty(AliasReg)) {
1583 HasAliasLive = true;
1587 if (!HasAliasLive) {
1588 OmittedAnyCallClobbers = true;
1595 if (FirstOp) FirstOp = false; else OS << ",";
1597 if (i < getDesc().NumOperands) {
1598 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1599 if (MCOI.isPredicate())
1601 if (MCOI.isOptionalDef())
1604 if (isDebugValue() && MO.isMetadata()) {
1605 // Pretty print DBG_VALUE instructions.
1606 const MDNode *MD = MO.getMetadata();
1607 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1608 OS << "!\"" << MDS->getString() << '\"';
1611 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1612 OS << TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIndexName(
1614 } else if (i == AsmDescOp && MO.isImm()) {
1615 // Pretty print the inline asm operand descriptor.
1616 OS << '$' << AsmOpCount++;
1617 unsigned Flag = MO.getImm();
1618 switch (InlineAsm::getKind(Flag)) {
1619 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1620 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1621 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1622 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1623 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1624 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1625 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1629 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1632 << TM->getSubtargetImpl()
1637 OS << ":RC" << RCID;
1640 unsigned TiedTo = 0;
1641 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1642 OS << " tiedto:$" << TiedTo;
1646 // Compute the index of the next operand descriptor.
1647 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1652 // Briefly indicate whether any call clobbers were omitted.
1653 if (OmittedAnyCallClobbers) {
1654 if (!FirstOp) OS << ",";
1658 bool HaveSemi = false;
1659 const unsigned PrintableFlags = FrameSetup;
1660 if (Flags & PrintableFlags) {
1661 if (!HaveSemi) OS << ";"; HaveSemi = true;
1664 if (Flags & FrameSetup)
1668 if (!memoperands_empty()) {
1669 if (!HaveSemi) OS << ";"; HaveSemi = true;
1672 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1675 if (std::next(i) != e)
1680 // Print the regclass of any virtual registers encountered.
1681 if (MRI && !VirtRegs.empty()) {
1682 if (!HaveSemi) OS << ";"; HaveSemi = true;
1683 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1684 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1685 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1686 for (unsigned j = i+1; j != VirtRegs.size();) {
1687 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1691 if (VirtRegs[i] != VirtRegs[j])
1692 OS << "," << PrintReg(VirtRegs[j]);
1693 VirtRegs.erase(VirtRegs.begin()+j);
1698 // Print debug location information.
1699 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1700 if (!HaveSemi) OS << ";";
1701 DIVariable DV(getOperand(e - 1).getMetadata());
1702 OS << " line no:" << DV.getLineNumber();
1703 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1704 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1705 if (!InlinedAtDL.isUnknown() && MF) {
1706 OS << " inlined @[ ";
1707 printDebugLoc(InlinedAtDL, MF, OS);
1711 } else if (!debugLoc.isUnknown() && MF) {
1712 if (!HaveSemi) OS << ";";
1714 printDebugLoc(debugLoc, MF, OS);
1720 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1721 const TargetRegisterInfo *RegInfo,
1722 bool AddIfNotFound) {
1723 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1724 bool hasAliases = isPhysReg &&
1725 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1727 SmallVector<unsigned,4> DeadOps;
1728 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1729 MachineOperand &MO = getOperand(i);
1730 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1732 unsigned Reg = MO.getReg();
1736 if (Reg == IncomingReg) {
1739 // The register is already marked kill.
1741 if (isPhysReg && isRegTiedToDefOperand(i))
1742 // Two-address uses of physregs must not be marked kill.
1747 } else if (hasAliases && MO.isKill() &&
1748 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1749 // A super-register kill already exists.
1750 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1752 if (RegInfo->isSubRegister(IncomingReg, Reg))
1753 DeadOps.push_back(i);
1757 // Trim unneeded kill operands.
1758 while (!DeadOps.empty()) {
1759 unsigned OpIdx = DeadOps.back();
1760 if (getOperand(OpIdx).isImplicit())
1761 RemoveOperand(OpIdx);
1763 getOperand(OpIdx).setIsKill(false);
1767 // If not found, this means an alias of one of the operands is killed. Add a
1768 // new implicit operand if required.
1769 if (!Found && AddIfNotFound) {
1770 addOperand(MachineOperand::CreateReg(IncomingReg,
1779 void MachineInstr::clearRegisterKills(unsigned Reg,
1780 const TargetRegisterInfo *RegInfo) {
1781 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1783 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1784 MachineOperand &MO = getOperand(i);
1785 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1787 unsigned OpReg = MO.getReg();
1788 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1789 MO.setIsKill(false);
1793 bool MachineInstr::addRegisterDead(unsigned Reg,
1794 const TargetRegisterInfo *RegInfo,
1795 bool AddIfNotFound) {
1796 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1797 bool hasAliases = isPhysReg &&
1798 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1800 SmallVector<unsigned,4> DeadOps;
1801 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1802 MachineOperand &MO = getOperand(i);
1803 if (!MO.isReg() || !MO.isDef())
1805 unsigned MOReg = MO.getReg();
1812 } else if (hasAliases && MO.isDead() &&
1813 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1814 // There exists a super-register that's marked dead.
1815 if (RegInfo->isSuperRegister(Reg, MOReg))
1817 if (RegInfo->isSubRegister(Reg, MOReg))
1818 DeadOps.push_back(i);
1822 // Trim unneeded dead operands.
1823 while (!DeadOps.empty()) {
1824 unsigned OpIdx = DeadOps.back();
1825 if (getOperand(OpIdx).isImplicit())
1826 RemoveOperand(OpIdx);
1828 getOperand(OpIdx).setIsDead(false);
1832 // If not found, this means an alias of one of the operands is dead. Add a
1833 // new implicit operand if required.
1834 if (Found || !AddIfNotFound)
1837 addOperand(MachineOperand::CreateReg(Reg,
1845 void MachineInstr::addRegisterDefined(unsigned Reg,
1846 const TargetRegisterInfo *RegInfo) {
1847 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1848 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1852 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1853 const MachineOperand &MO = getOperand(i);
1854 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1855 MO.getSubReg() == 0)
1859 addOperand(MachineOperand::CreateReg(Reg,
1864 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1865 const TargetRegisterInfo &TRI) {
1866 bool HasRegMask = false;
1867 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1868 MachineOperand &MO = getOperand(i);
1869 if (MO.isRegMask()) {
1873 if (!MO.isReg() || !MO.isDef()) continue;
1874 unsigned Reg = MO.getReg();
1875 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1877 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1879 if (TRI.regsOverlap(*I, Reg)) {
1883 // If there are no uses, including partial uses, the def is dead.
1884 if (Dead) MO.setIsDead();
1887 // This is a call with a register mask operand.
1888 // Mask clobbers are always dead, so add defs for the non-dead defines.
1890 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1892 addRegisterDefined(*I, &TRI);
1896 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1897 // Build up a buffer of hash code components.
1898 SmallVector<size_t, 8> HashComponents;
1899 HashComponents.reserve(MI->getNumOperands() + 1);
1900 HashComponents.push_back(MI->getOpcode());
1901 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1902 const MachineOperand &MO = MI->getOperand(i);
1903 if (MO.isReg() && MO.isDef() &&
1904 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1905 continue; // Skip virtual register defs.
1907 HashComponents.push_back(hash_value(MO));
1909 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1912 void MachineInstr::emitError(StringRef Msg) const {
1913 // Find the source location cookie.
1914 unsigned LocCookie = 0;
1915 const MDNode *LocMD = nullptr;
1916 for (unsigned i = getNumOperands(); i != 0; --i) {
1917 if (getOperand(i-1).isMetadata() &&
1918 (LocMD = getOperand(i-1).getMetadata()) &&
1919 LocMD->getNumOperands() != 0) {
1920 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1921 LocCookie = CI->getZExtValue();
1927 if (const MachineBasicBlock *MBB = getParent())
1928 if (const MachineFunction *MF = MBB->getParent())
1929 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1930 report_fatal_error(Msg);