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::eraseFromParentAndMarkDBGValuesForRemoval() {
899 assert(getParent() && "Not embedded in a basic block!");
900 MachineBasicBlock *MBB = getParent();
901 MachineFunction *MF = MBB->getParent();
902 assert(MF && "Not embedded in a function!");
904 MachineInstr *MI = (MachineInstr *)this;
905 MachineRegisterInfo &MRI = MF->getRegInfo();
907 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
908 const MachineOperand &MO = MI->getOperand(i);
909 if (!MO.isReg() || !MO.isDef())
911 unsigned Reg = MO.getReg();
912 if (!TargetRegisterInfo::isVirtualRegister(Reg))
914 MRI.markUsesInDebugValueAsUndef(Reg);
916 MI->eraseFromParent();
919 void MachineInstr::eraseFromBundle() {
920 assert(getParent() && "Not embedded in a basic block!");
921 getParent()->erase_instr(this);
924 /// getNumExplicitOperands - Returns the number of non-implicit operands.
926 unsigned MachineInstr::getNumExplicitOperands() const {
927 unsigned NumOperands = MCID->getNumOperands();
928 if (!MCID->isVariadic())
931 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
932 const MachineOperand &MO = getOperand(i);
933 if (!MO.isReg() || !MO.isImplicit())
939 void MachineInstr::bundleWithPred() {
940 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
941 setFlag(BundledPred);
942 MachineBasicBlock::instr_iterator Pred = this;
944 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
945 Pred->setFlag(BundledSucc);
948 void MachineInstr::bundleWithSucc() {
949 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
950 setFlag(BundledSucc);
951 MachineBasicBlock::instr_iterator Succ = this;
953 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
954 Succ->setFlag(BundledPred);
957 void MachineInstr::unbundleFromPred() {
958 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
959 clearFlag(BundledPred);
960 MachineBasicBlock::instr_iterator Pred = this;
962 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
963 Pred->clearFlag(BundledSucc);
966 void MachineInstr::unbundleFromSucc() {
967 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
968 clearFlag(BundledSucc);
969 MachineBasicBlock::instr_iterator Succ = this;
971 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
972 Succ->clearFlag(BundledPred);
975 bool MachineInstr::isStackAligningInlineAsm() const {
977 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
978 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
984 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
985 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
986 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
987 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
990 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
991 unsigned *GroupNo) const {
992 assert(isInlineAsm() && "Expected an inline asm instruction");
993 assert(OpIdx < getNumOperands() && "OpIdx out of range");
995 // Ignore queries about the initial operands.
996 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1001 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1003 const MachineOperand &FlagMO = getOperand(i);
1004 // If we reach the implicit register operands, stop looking.
1005 if (!FlagMO.isImm())
1007 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1008 if (i + NumOps > OpIdx) {
1018 const TargetRegisterClass*
1019 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1020 const TargetInstrInfo *TII,
1021 const TargetRegisterInfo *TRI) const {
1022 assert(getParent() && "Can't have an MBB reference here!");
1023 assert(getParent()->getParent() && "Can't have an MF reference here!");
1024 const MachineFunction &MF = *getParent()->getParent();
1026 // Most opcodes have fixed constraints in their MCInstrDesc.
1028 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1030 if (!getOperand(OpIdx).isReg())
1033 // For tied uses on inline asm, get the constraint from the def.
1035 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1038 // Inline asm stores register class constraints in the flag word.
1039 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1043 unsigned Flag = getOperand(FlagIdx).getImm();
1045 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1046 return TRI->getRegClass(RCID);
1048 // Assume that all registers in a memory operand are pointers.
1049 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1050 return TRI->getPointerRegClass(MF);
1055 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1056 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1057 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1058 // Check every operands inside the bundle if we have
1061 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1063 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1064 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1066 // Otherwise, just check the current operands.
1067 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1068 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1073 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1074 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1075 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1076 assert(CurRC && "Invalid initial register class");
1077 // Check if Reg is constrained by some of its use/def from MI.
1078 const MachineOperand &MO = getOperand(OpIdx);
1079 if (!MO.isReg() || MO.getReg() != Reg)
1081 // If yes, accumulate the constraints through the operand.
1082 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1085 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1086 unsigned OpIdx, const TargetRegisterClass *CurRC,
1087 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1088 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1089 const MachineOperand &MO = getOperand(OpIdx);
1090 assert(MO.isReg() &&
1091 "Cannot get register constraints for non-register operand");
1092 assert(CurRC && "Invalid initial register class");
1093 if (unsigned SubIdx = MO.getSubReg()) {
1095 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1097 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1099 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1103 /// Return the number of instructions inside the MI bundle, not counting the
1104 /// header instruction.
1105 unsigned MachineInstr::getBundleSize() const {
1106 MachineBasicBlock::const_instr_iterator I = this;
1108 while (I->isBundledWithSucc())
1113 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1114 /// the specific register or -1 if it is not found. It further tightens
1115 /// the search criteria to a use that kills the register if isKill is true.
1116 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1117 const TargetRegisterInfo *TRI) const {
1118 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1119 const MachineOperand &MO = getOperand(i);
1120 if (!MO.isReg() || !MO.isUse())
1122 unsigned MOReg = MO.getReg();
1127 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1128 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1129 TRI->isSubRegister(MOReg, Reg)))
1130 if (!isKill || MO.isKill())
1136 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1137 /// indicating if this instruction reads or writes Reg. This also considers
1138 /// partial defines.
1139 std::pair<bool,bool>
1140 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1141 SmallVectorImpl<unsigned> *Ops) const {
1142 bool PartDef = false; // Partial redefine.
1143 bool FullDef = false; // Full define.
1146 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1147 const MachineOperand &MO = getOperand(i);
1148 if (!MO.isReg() || MO.getReg() != Reg)
1153 Use |= !MO.isUndef();
1154 else if (MO.getSubReg() && !MO.isUndef())
1155 // A partial <def,undef> doesn't count as reading the register.
1160 // A partial redefine uses Reg unless there is also a full define.
1161 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1164 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1165 /// the specified register or -1 if it is not found. If isDead is true, defs
1166 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1167 /// also checks if there is a def of a super-register.
1169 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1170 const TargetRegisterInfo *TRI) const {
1171 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1172 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1173 const MachineOperand &MO = getOperand(i);
1174 // Accept regmask operands when Overlap is set.
1175 // Ignore them when looking for a specific def operand (Overlap == false).
1176 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1178 if (!MO.isReg() || !MO.isDef())
1180 unsigned MOReg = MO.getReg();
1181 bool Found = (MOReg == Reg);
1182 if (!Found && TRI && isPhys &&
1183 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1185 Found = TRI->regsOverlap(MOReg, Reg);
1187 Found = TRI->isSubRegister(MOReg, Reg);
1189 if (Found && (!isDead || MO.isDead()))
1195 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1196 /// operand list that is used to represent the predicate. It returns -1 if
1198 int MachineInstr::findFirstPredOperandIdx() const {
1199 // Don't call MCID.findFirstPredOperandIdx() because this variant
1200 // is sometimes called on an instruction that's not yet complete, and
1201 // so the number of operands is less than the MCID indicates. In
1202 // particular, the PTX target does this.
1203 const MCInstrDesc &MCID = getDesc();
1204 if (MCID.isPredicable()) {
1205 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1206 if (MCID.OpInfo[i].isPredicate())
1213 // MachineOperand::TiedTo is 4 bits wide.
1214 const unsigned TiedMax = 15;
1216 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1218 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1219 /// field. TiedTo can have these values:
1221 /// 0: Operand is not tied to anything.
1222 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1223 /// TiedMax: Tied to an operand >= TiedMax-1.
1225 /// The tied def must be one of the first TiedMax operands on a normal
1226 /// instruction. INLINEASM instructions allow more tied defs.
1228 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1229 MachineOperand &DefMO = getOperand(DefIdx);
1230 MachineOperand &UseMO = getOperand(UseIdx);
1231 assert(DefMO.isDef() && "DefIdx must be a def operand");
1232 assert(UseMO.isUse() && "UseIdx must be a use operand");
1233 assert(!DefMO.isTied() && "Def is already tied to another use");
1234 assert(!UseMO.isTied() && "Use is already tied to another def");
1236 if (DefIdx < TiedMax)
1237 UseMO.TiedTo = DefIdx + 1;
1239 // Inline asm can use the group descriptors to find tied operands, but on
1240 // normal instruction, the tied def must be within the first TiedMax
1242 assert(isInlineAsm() && "DefIdx out of range");
1243 UseMO.TiedTo = TiedMax;
1246 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1247 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1250 /// Given the index of a tied register operand, find the operand it is tied to.
1251 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1252 /// which must exist.
1253 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1254 const MachineOperand &MO = getOperand(OpIdx);
1255 assert(MO.isTied() && "Operand isn't tied");
1257 // Normally TiedTo is in range.
1258 if (MO.TiedTo < TiedMax)
1259 return MO.TiedTo - 1;
1261 // Uses on normal instructions can be out of range.
1262 if (!isInlineAsm()) {
1263 // Normal tied defs must be in the 0..TiedMax-1 range.
1266 // MO is a def. Search for the tied use.
1267 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1268 const MachineOperand &UseMO = getOperand(i);
1269 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1272 llvm_unreachable("Can't find tied use");
1275 // Now deal with inline asm by parsing the operand group descriptor flags.
1276 // Find the beginning of each operand group.
1277 SmallVector<unsigned, 8> GroupIdx;
1278 unsigned OpIdxGroup = ~0u;
1280 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1282 const MachineOperand &FlagMO = getOperand(i);
1283 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1284 unsigned CurGroup = GroupIdx.size();
1285 GroupIdx.push_back(i);
1286 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1287 // OpIdx belongs to this operand group.
1288 if (OpIdx > i && OpIdx < i + NumOps)
1289 OpIdxGroup = CurGroup;
1291 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1293 // Operands in this group are tied to operands in TiedGroup which must be
1294 // earlier. Find the number of operands between the two groups.
1295 unsigned Delta = i - GroupIdx[TiedGroup];
1297 // OpIdx is a use tied to TiedGroup.
1298 if (OpIdxGroup == CurGroup)
1299 return OpIdx - Delta;
1301 // OpIdx is a def tied to this use group.
1302 if (OpIdxGroup == TiedGroup)
1303 return OpIdx + Delta;
1305 llvm_unreachable("Invalid tied operand on inline asm");
1308 /// clearKillInfo - Clears kill flags on all operands.
1310 void MachineInstr::clearKillInfo() {
1311 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1312 MachineOperand &MO = getOperand(i);
1313 if (MO.isReg() && MO.isUse())
1314 MO.setIsKill(false);
1318 void MachineInstr::substituteRegister(unsigned FromReg,
1321 const TargetRegisterInfo &RegInfo) {
1322 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1324 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1325 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1326 MachineOperand &MO = getOperand(i);
1327 if (!MO.isReg() || MO.getReg() != FromReg)
1329 MO.substPhysReg(ToReg, RegInfo);
1332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1333 MachineOperand &MO = getOperand(i);
1334 if (!MO.isReg() || MO.getReg() != FromReg)
1336 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1341 /// isSafeToMove - Return true if it is safe to move this instruction. If
1342 /// SawStore is set to true, it means that there is a store (or call) between
1343 /// the instruction's location and its intended destination.
1344 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1346 bool &SawStore) const {
1347 // Ignore stuff that we obviously can't move.
1349 // Treat volatile loads as stores. This is not strictly necessary for
1350 // volatiles, but it is required for atomic loads. It is not allowed to move
1351 // a load across an atomic load with Ordering > Monotonic.
1352 if (mayStore() || isCall() ||
1353 (mayLoad() && hasOrderedMemoryRef())) {
1358 if (isPosition() || isDebugValue() || isTerminator() ||
1359 hasUnmodeledSideEffects())
1362 // See if this instruction does a load. If so, we have to guarantee that the
1363 // loaded value doesn't change between the load and the its intended
1364 // destination. The check for isInvariantLoad gives the targe the chance to
1365 // classify the load as always returning a constant, e.g. a constant pool
1367 if (mayLoad() && !isInvariantLoad(AA))
1368 // Otherwise, this is a real load. If there is a store between the load and
1369 // end of block, we can't move it.
1375 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1376 /// or volatile memory reference, or if the information describing the memory
1377 /// reference is not available. Return false if it is known to have no ordered
1378 /// memory references.
1379 bool MachineInstr::hasOrderedMemoryRef() const {
1380 // An instruction known never to access memory won't have a volatile access.
1384 !hasUnmodeledSideEffects())
1387 // Otherwise, if the instruction has no memory reference information,
1388 // conservatively assume it wasn't preserved.
1389 if (memoperands_empty())
1392 // Check the memory reference information for ordered references.
1393 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1394 if (!(*I)->isUnordered())
1400 /// isInvariantLoad - Return true if this instruction is loading from a
1401 /// location whose value is invariant across the function. For example,
1402 /// loading a value from the constant pool or from the argument area
1403 /// of a function if it does not change. This should only return true of
1404 /// *all* loads the instruction does are invariant (if it does multiple loads).
1405 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1406 // If the instruction doesn't load at all, it isn't an invariant load.
1410 // If the instruction has lost its memoperands, conservatively assume that
1411 // it may not be an invariant load.
1412 if (memoperands_empty())
1415 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1417 for (mmo_iterator I = memoperands_begin(),
1418 E = memoperands_end(); I != E; ++I) {
1419 if ((*I)->isVolatile()) return false;
1420 if ((*I)->isStore()) return false;
1421 if ((*I)->isInvariant()) return true;
1424 // A load from a constant PseudoSourceValue is invariant.
1425 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
1426 if (PSV->isConstant(MFI))
1429 if (const Value *V = (*I)->getValue()) {
1430 // If we have an AliasAnalysis, ask it whether the memory is constant.
1431 if (AA && AA->pointsToConstantMemory(
1432 AliasAnalysis::Location(V, (*I)->getSize(),
1433 (*I)->getAAInfo())))
1437 // Otherwise assume conservatively.
1441 // Everything checks out.
1445 /// isConstantValuePHI - If the specified instruction is a PHI that always
1446 /// merges together the same virtual register, return the register, otherwise
1448 unsigned MachineInstr::isConstantValuePHI() const {
1451 assert(getNumOperands() >= 3 &&
1452 "It's illegal to have a PHI without source operands");
1454 unsigned Reg = getOperand(1).getReg();
1455 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1456 if (getOperand(i).getReg() != Reg)
1461 bool MachineInstr::hasUnmodeledSideEffects() const {
1462 if (hasProperty(MCID::UnmodeledSideEffects))
1464 if (isInlineAsm()) {
1465 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1466 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1473 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1475 bool MachineInstr::allDefsAreDead() const {
1476 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1477 const MachineOperand &MO = getOperand(i);
1478 if (!MO.isReg() || MO.isUse())
1486 /// copyImplicitOps - Copy implicit register operands from specified
1487 /// instruction to this instruction.
1488 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1489 const MachineInstr *MI) {
1490 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1492 const MachineOperand &MO = MI->getOperand(i);
1493 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1498 void MachineInstr::dump() const {
1499 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1500 dbgs() << " " << *this;
1504 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1505 raw_ostream &CommentOS) {
1506 const LLVMContext &Ctx = MF->getFunction()->getContext();
1507 DL.print(Ctx, CommentOS);
1510 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1511 bool SkipOpers) const {
1512 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1513 const MachineFunction *MF = nullptr;
1514 const MachineRegisterInfo *MRI = nullptr;
1515 if (const MachineBasicBlock *MBB = getParent()) {
1516 MF = MBB->getParent();
1518 TM = &MF->getTarget();
1520 MRI = &MF->getRegInfo();
1523 // Save a list of virtual registers.
1524 SmallVector<unsigned, 8> VirtRegs;
1526 // Print explicitly defined operands on the left of an assignment syntax.
1527 unsigned StartOp = 0, e = getNumOperands();
1528 for (; StartOp < e && getOperand(StartOp).isReg() &&
1529 getOperand(StartOp).isDef() &&
1530 !getOperand(StartOp).isImplicit();
1532 if (StartOp != 0) OS << ", ";
1533 getOperand(StartOp).print(OS, TM);
1534 unsigned Reg = getOperand(StartOp).getReg();
1535 if (TargetRegisterInfo::isVirtualRegister(Reg))
1536 VirtRegs.push_back(Reg);
1542 // Print the opcode name.
1543 if (TM && TM->getSubtargetImpl()->getInstrInfo())
1544 OS << TM->getSubtargetImpl()->getInstrInfo()->getName(getOpcode());
1551 // Print the rest of the operands.
1552 bool OmittedAnyCallClobbers = false;
1553 bool FirstOp = true;
1554 unsigned AsmDescOp = ~0u;
1555 unsigned AsmOpCount = 0;
1557 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1558 // Print asm string.
1560 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1562 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1563 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1564 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1565 OS << " [sideeffect]";
1566 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1568 if (ExtraInfo & InlineAsm::Extra_MayStore)
1569 OS << " [maystore]";
1570 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1571 OS << " [alignstack]";
1572 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1573 OS << " [attdialect]";
1574 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1575 OS << " [inteldialect]";
1577 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1582 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1583 const MachineOperand &MO = getOperand(i);
1585 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1586 VirtRegs.push_back(MO.getReg());
1588 // Omit call-clobbered registers which aren't used anywhere. This makes
1589 // call instructions much less noisy on targets where calls clobber lots
1590 // of registers. Don't rely on MO.isDead() because we may be called before
1591 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1592 if (MF && isCall() &&
1593 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1594 unsigned Reg = MO.getReg();
1595 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1596 const MachineRegisterInfo &MRI = MF->getRegInfo();
1597 if (MRI.use_empty(Reg)) {
1598 bool HasAliasLive = false;
1599 for (MCRegAliasIterator AI(
1600 Reg, TM->getSubtargetImpl()->getRegisterInfo(), true);
1601 AI.isValid(); ++AI) {
1602 unsigned AliasReg = *AI;
1603 if (!MRI.use_empty(AliasReg)) {
1604 HasAliasLive = true;
1608 if (!HasAliasLive) {
1609 OmittedAnyCallClobbers = true;
1616 if (FirstOp) FirstOp = false; else OS << ",";
1618 if (i < getDesc().NumOperands) {
1619 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1620 if (MCOI.isPredicate())
1622 if (MCOI.isOptionalDef())
1625 if (isDebugValue() && MO.isMetadata()) {
1626 // Pretty print DBG_VALUE instructions.
1627 const MDNode *MD = MO.getMetadata();
1628 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1629 OS << "!\"" << MDS->getString() << '\"';
1632 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1633 OS << TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIndexName(
1635 } else if (i == AsmDescOp && MO.isImm()) {
1636 // Pretty print the inline asm operand descriptor.
1637 OS << '$' << AsmOpCount++;
1638 unsigned Flag = MO.getImm();
1639 switch (InlineAsm::getKind(Flag)) {
1640 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1641 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1642 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1643 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1644 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1645 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1646 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1650 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1653 << TM->getSubtargetImpl()
1658 OS << ":RC" << RCID;
1661 unsigned TiedTo = 0;
1662 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1663 OS << " tiedto:$" << TiedTo;
1667 // Compute the index of the next operand descriptor.
1668 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1673 // Briefly indicate whether any call clobbers were omitted.
1674 if (OmittedAnyCallClobbers) {
1675 if (!FirstOp) OS << ",";
1679 bool HaveSemi = false;
1680 const unsigned PrintableFlags = FrameSetup;
1681 if (Flags & PrintableFlags) {
1682 if (!HaveSemi) OS << ";"; HaveSemi = true;
1685 if (Flags & FrameSetup)
1689 if (!memoperands_empty()) {
1690 if (!HaveSemi) OS << ";"; HaveSemi = true;
1693 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1696 if (std::next(i) != e)
1701 // Print the regclass of any virtual registers encountered.
1702 if (MRI && !VirtRegs.empty()) {
1703 if (!HaveSemi) OS << ";"; HaveSemi = true;
1704 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1705 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1706 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1707 for (unsigned j = i+1; j != VirtRegs.size();) {
1708 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1712 if (VirtRegs[i] != VirtRegs[j])
1713 OS << "," << PrintReg(VirtRegs[j]);
1714 VirtRegs.erase(VirtRegs.begin()+j);
1719 // Print debug location information.
1720 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1721 if (!HaveSemi) OS << ";";
1722 DIVariable DV(getOperand(e - 1).getMetadata());
1723 OS << " line no:" << DV.getLineNumber();
1724 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1725 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1726 if (!InlinedAtDL.isUnknown() && MF) {
1727 OS << " inlined @[ ";
1728 printDebugLoc(InlinedAtDL, MF, OS);
1732 } else if (!debugLoc.isUnknown() && MF) {
1733 if (!HaveSemi) OS << ";";
1735 printDebugLoc(debugLoc, MF, OS);
1741 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1742 const TargetRegisterInfo *RegInfo,
1743 bool AddIfNotFound) {
1744 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1745 bool hasAliases = isPhysReg &&
1746 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1748 SmallVector<unsigned,4> DeadOps;
1749 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1750 MachineOperand &MO = getOperand(i);
1751 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1753 unsigned Reg = MO.getReg();
1757 if (Reg == IncomingReg) {
1760 // The register is already marked kill.
1762 if (isPhysReg && isRegTiedToDefOperand(i))
1763 // Two-address uses of physregs must not be marked kill.
1768 } else if (hasAliases && MO.isKill() &&
1769 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1770 // A super-register kill already exists.
1771 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1773 if (RegInfo->isSubRegister(IncomingReg, Reg))
1774 DeadOps.push_back(i);
1778 // Trim unneeded kill operands.
1779 while (!DeadOps.empty()) {
1780 unsigned OpIdx = DeadOps.back();
1781 if (getOperand(OpIdx).isImplicit())
1782 RemoveOperand(OpIdx);
1784 getOperand(OpIdx).setIsKill(false);
1788 // If not found, this means an alias of one of the operands is killed. Add a
1789 // new implicit operand if required.
1790 if (!Found && AddIfNotFound) {
1791 addOperand(MachineOperand::CreateReg(IncomingReg,
1800 void MachineInstr::clearRegisterKills(unsigned Reg,
1801 const TargetRegisterInfo *RegInfo) {
1802 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1804 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1805 MachineOperand &MO = getOperand(i);
1806 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1808 unsigned OpReg = MO.getReg();
1809 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1810 MO.setIsKill(false);
1814 bool MachineInstr::addRegisterDead(unsigned Reg,
1815 const TargetRegisterInfo *RegInfo,
1816 bool AddIfNotFound) {
1817 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1818 bool hasAliases = isPhysReg &&
1819 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1821 SmallVector<unsigned,4> DeadOps;
1822 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1823 MachineOperand &MO = getOperand(i);
1824 if (!MO.isReg() || !MO.isDef())
1826 unsigned MOReg = MO.getReg();
1833 } else if (hasAliases && MO.isDead() &&
1834 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1835 // There exists a super-register that's marked dead.
1836 if (RegInfo->isSuperRegister(Reg, MOReg))
1838 if (RegInfo->isSubRegister(Reg, MOReg))
1839 DeadOps.push_back(i);
1843 // Trim unneeded dead operands.
1844 while (!DeadOps.empty()) {
1845 unsigned OpIdx = DeadOps.back();
1846 if (getOperand(OpIdx).isImplicit())
1847 RemoveOperand(OpIdx);
1849 getOperand(OpIdx).setIsDead(false);
1853 // If not found, this means an alias of one of the operands is dead. Add a
1854 // new implicit operand if required.
1855 if (Found || !AddIfNotFound)
1858 addOperand(MachineOperand::CreateReg(Reg,
1866 void MachineInstr::addRegisterDefined(unsigned Reg,
1867 const TargetRegisterInfo *RegInfo) {
1868 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1869 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1873 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1874 const MachineOperand &MO = getOperand(i);
1875 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1876 MO.getSubReg() == 0)
1880 addOperand(MachineOperand::CreateReg(Reg,
1885 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1886 const TargetRegisterInfo &TRI) {
1887 bool HasRegMask = false;
1888 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1889 MachineOperand &MO = getOperand(i);
1890 if (MO.isRegMask()) {
1894 if (!MO.isReg() || !MO.isDef()) continue;
1895 unsigned Reg = MO.getReg();
1896 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1898 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1900 if (TRI.regsOverlap(*I, Reg)) {
1904 // If there are no uses, including partial uses, the def is dead.
1905 if (Dead) MO.setIsDead();
1908 // This is a call with a register mask operand.
1909 // Mask clobbers are always dead, so add defs for the non-dead defines.
1911 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1913 addRegisterDefined(*I, &TRI);
1917 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1918 // Build up a buffer of hash code components.
1919 SmallVector<size_t, 8> HashComponents;
1920 HashComponents.reserve(MI->getNumOperands() + 1);
1921 HashComponents.push_back(MI->getOpcode());
1922 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1923 const MachineOperand &MO = MI->getOperand(i);
1924 if (MO.isReg() && MO.isDef() &&
1925 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1926 continue; // Skip virtual register defs.
1928 HashComponents.push_back(hash_value(MO));
1930 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1933 void MachineInstr::emitError(StringRef Msg) const {
1934 // Find the source location cookie.
1935 unsigned LocCookie = 0;
1936 const MDNode *LocMD = nullptr;
1937 for (unsigned i = getNumOperands(); i != 0; --i) {
1938 if (getOperand(i-1).isMetadata() &&
1939 (LocMD = getOperand(i-1).getMetadata()) &&
1940 LocMD->getNumOperands() != 0) {
1941 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1942 LocCookie = CI->getZExtValue();
1948 if (const MachineBasicBlock *MBB = getParent())
1949 if (const MachineFunction *MF = MBB->getParent())
1950 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1951 report_fatal_error(Msg);