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/Constants.h"
16 #include "llvm/DebugInfo.h"
17 #include "llvm/Function.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Metadata.h"
21 #include "llvm/Module.h"
22 #include "llvm/Type.h"
23 #include "llvm/Value.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LeakDetector.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/Hashing.h"
46 //===----------------------------------------------------------------------===//
47 // MachineOperand Implementation
48 //===----------------------------------------------------------------------===//
50 /// AddRegOperandToRegInfo - Add this register operand to the specified
51 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
52 /// explicitly nulled out.
53 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
54 assert(isReg() && "Can only add reg operand to use lists");
56 // If the reginfo pointer is null, just explicitly null out or next/prev
57 // pointers, to ensure they are not garbage.
59 Contents.Reg.Prev = 0;
60 Contents.Reg.Next = 0;
64 // Otherwise, add this operand to the head of the registers use/def list.
65 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
67 // For SSA values, we prefer to keep the definition at the start of the list.
68 // we do this by skipping over the definition if it is at the head of the
70 if (*Head && (*Head)->isDef())
71 Head = &(*Head)->Contents.Reg.Next;
73 Contents.Reg.Next = *Head;
74 if (Contents.Reg.Next) {
75 assert(getReg() == Contents.Reg.Next->getReg() &&
76 "Different regs on the same list!");
77 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
80 Contents.Reg.Prev = Head;
84 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
85 /// MachineRegisterInfo it is linked with.
86 void MachineOperand::RemoveRegOperandFromRegInfo() {
87 assert(isOnRegUseList() && "Reg operand is not on a use list");
88 // Unlink this from the doubly linked list of operands.
89 MachineOperand *NextOp = Contents.Reg.Next;
90 *Contents.Reg.Prev = NextOp;
92 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
93 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
95 Contents.Reg.Prev = 0;
96 Contents.Reg.Next = 0;
99 void MachineOperand::setReg(unsigned Reg) {
100 if (getReg() == Reg) return; // No change.
102 // Otherwise, we have to change the register. If this operand is embedded
103 // into a machine function, we need to update the old and new register's
105 if (MachineInstr *MI = getParent())
106 if (MachineBasicBlock *MBB = MI->getParent())
107 if (MachineFunction *MF = MBB->getParent()) {
108 RemoveRegOperandFromRegInfo();
109 SmallContents.RegNo = Reg;
110 AddRegOperandToRegInfo(&MF->getRegInfo());
114 // Otherwise, just change the register, no problem. :)
115 SmallContents.RegNo = Reg;
118 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
119 const TargetRegisterInfo &TRI) {
120 assert(TargetRegisterInfo::isVirtualRegister(Reg));
121 if (SubIdx && getSubReg())
122 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
128 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
129 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
131 Reg = TRI.getSubReg(Reg, getSubReg());
132 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
133 // That won't happen in legal code.
139 /// ChangeToImmediate - Replace this operand with a new immediate operand of
140 /// the specified value. If an operand is known to be an immediate already,
141 /// the setImm method should be used.
142 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
143 // If this operand is currently a register operand, and if this is in a
144 // function, deregister the operand from the register's use/def list.
145 if (isReg() && getParent() && getParent()->getParent() &&
146 getParent()->getParent()->getParent())
147 RemoveRegOperandFromRegInfo();
149 OpKind = MO_Immediate;
150 Contents.ImmVal = ImmVal;
153 /// ChangeToRegister - Replace this operand with a new register operand of
154 /// the specified value. If an operand is known to be an register already,
155 /// the setReg method should be used.
156 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
157 bool isKill, bool isDead, bool isUndef,
159 // If this operand is already a register operand, use setReg to update the
160 // register's use/def lists.
162 assert(!isEarlyClobber());
165 // Otherwise, change this to a register and set the reg#.
166 OpKind = MO_Register;
167 SmallContents.RegNo = Reg;
169 // If this operand is embedded in a function, add the operand to the
170 // register's use/def list.
171 if (MachineInstr *MI = getParent())
172 if (MachineBasicBlock *MBB = MI->getParent())
173 if (MachineFunction *MF = MBB->getParent())
174 AddRegOperandToRegInfo(&MF->getRegInfo());
182 IsInternalRead = false;
183 IsEarlyClobber = false;
188 /// isIdenticalTo - Return true if this operand is identical to the specified
189 /// operand. Note that this should stay in sync with the hash_value overload
191 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
192 if (getType() != Other.getType() ||
193 getTargetFlags() != Other.getTargetFlags())
197 case MachineOperand::MO_Register:
198 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
199 getSubReg() == Other.getSubReg();
200 case MachineOperand::MO_Immediate:
201 return getImm() == Other.getImm();
202 case MachineOperand::MO_CImmediate:
203 return getCImm() == Other.getCImm();
204 case MachineOperand::MO_FPImmediate:
205 return getFPImm() == Other.getFPImm();
206 case MachineOperand::MO_MachineBasicBlock:
207 return getMBB() == Other.getMBB();
208 case MachineOperand::MO_FrameIndex:
209 return getIndex() == Other.getIndex();
210 case MachineOperand::MO_ConstantPoolIndex:
211 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
212 case MachineOperand::MO_JumpTableIndex:
213 return getIndex() == Other.getIndex();
214 case MachineOperand::MO_GlobalAddress:
215 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
216 case MachineOperand::MO_ExternalSymbol:
217 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
218 getOffset() == Other.getOffset();
219 case MachineOperand::MO_BlockAddress:
220 return getBlockAddress() == Other.getBlockAddress();
221 case MO_RegisterMask:
222 return getRegMask() == Other.getRegMask();
223 case MachineOperand::MO_MCSymbol:
224 return getMCSymbol() == Other.getMCSymbol();
225 case MachineOperand::MO_Metadata:
226 return getMetadata() == Other.getMetadata();
228 llvm_unreachable("Invalid machine operand type");
231 // Note: this must stay exactly in sync with isIdenticalTo above.
232 hash_code llvm::hash_value(const MachineOperand &MO) {
233 switch (MO.getType()) {
234 case MachineOperand::MO_Register:
235 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getReg(),
236 MO.getSubReg(), MO.isDef());
237 case MachineOperand::MO_Immediate:
238 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
239 case MachineOperand::MO_CImmediate:
240 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
241 case MachineOperand::MO_FPImmediate:
242 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
243 case MachineOperand::MO_MachineBasicBlock:
244 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
245 case MachineOperand::MO_FrameIndex:
246 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
247 case MachineOperand::MO_ConstantPoolIndex:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
250 case MachineOperand::MO_JumpTableIndex:
251 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
252 case MachineOperand::MO_ExternalSymbol:
253 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
255 case MachineOperand::MO_GlobalAddress:
256 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
258 case MachineOperand::MO_BlockAddress:
259 return hash_combine(MO.getType(), MO.getTargetFlags(),
260 MO.getBlockAddress());
261 case MachineOperand::MO_RegisterMask:
262 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
263 case MachineOperand::MO_Metadata:
264 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
265 case MachineOperand::MO_MCSymbol:
266 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
268 llvm_unreachable("Invalid machine operand type");
271 /// print - Print the specified machine operand.
273 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
274 // If the instruction is embedded into a basic block, we can find the
275 // target info for the instruction.
277 if (const MachineInstr *MI = getParent())
278 if (const MachineBasicBlock *MBB = MI->getParent())
279 if (const MachineFunction *MF = MBB->getParent())
280 TM = &MF->getTarget();
281 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
284 case MachineOperand::MO_Register:
285 OS << PrintReg(getReg(), TRI, getSubReg());
287 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
288 isInternalRead() || isEarlyClobber()) {
290 bool NeedComma = false;
292 if (NeedComma) OS << ',';
293 if (isEarlyClobber())
294 OS << "earlyclobber,";
299 // <def,read-undef> only makes sense when getSubReg() is set.
300 // Don't clutter the output otherwise.
301 if (isUndef() && getSubReg())
303 } else if (isImplicit()) {
308 if (isKill() || isDead() || (isUndef() && isUse()) || isInternalRead()) {
309 if (NeedComma) OS << ',';
319 if (isUndef() && isUse()) {
320 if (NeedComma) OS << ',';
324 if (isInternalRead()) {
325 if (NeedComma) OS << ',';
333 case MachineOperand::MO_Immediate:
336 case MachineOperand::MO_CImmediate:
337 getCImm()->getValue().print(OS, false);
339 case MachineOperand::MO_FPImmediate:
340 if (getFPImm()->getType()->isFloatTy())
341 OS << getFPImm()->getValueAPF().convertToFloat();
343 OS << getFPImm()->getValueAPF().convertToDouble();
345 case MachineOperand::MO_MachineBasicBlock:
346 OS << "<BB#" << getMBB()->getNumber() << ">";
348 case MachineOperand::MO_FrameIndex:
349 OS << "<fi#" << getIndex() << '>';
351 case MachineOperand::MO_ConstantPoolIndex:
352 OS << "<cp#" << getIndex();
353 if (getOffset()) OS << "+" << getOffset();
356 case MachineOperand::MO_JumpTableIndex:
357 OS << "<jt#" << getIndex() << '>';
359 case MachineOperand::MO_GlobalAddress:
361 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
362 if (getOffset()) OS << "+" << getOffset();
365 case MachineOperand::MO_ExternalSymbol:
366 OS << "<es:" << getSymbolName();
367 if (getOffset()) OS << "+" << getOffset();
370 case MachineOperand::MO_BlockAddress:
372 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
375 case MachineOperand::MO_RegisterMask:
378 case MachineOperand::MO_Metadata:
380 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
383 case MachineOperand::MO_MCSymbol:
384 OS << "<MCSym=" << *getMCSymbol() << '>';
388 if (unsigned TF = getTargetFlags())
389 OS << "[TF=" << TF << ']';
392 //===----------------------------------------------------------------------===//
393 // MachineMemOperand Implementation
394 //===----------------------------------------------------------------------===//
396 /// getAddrSpace - Return the LLVM IR address space number that this pointer
398 unsigned MachinePointerInfo::getAddrSpace() const {
399 if (V == 0) return 0;
400 return cast<PointerType>(V->getType())->getAddressSpace();
403 /// getConstantPool - Return a MachinePointerInfo record that refers to the
405 MachinePointerInfo MachinePointerInfo::getConstantPool() {
406 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
409 /// getFixedStack - Return a MachinePointerInfo record that refers to the
410 /// the specified FrameIndex.
411 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
412 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
415 MachinePointerInfo MachinePointerInfo::getJumpTable() {
416 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
419 MachinePointerInfo MachinePointerInfo::getGOT() {
420 return MachinePointerInfo(PseudoSourceValue::getGOT());
423 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
424 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
427 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
428 uint64_t s, unsigned int a,
429 const MDNode *TBAAInfo,
430 const MDNode *Ranges)
431 : PtrInfo(ptrinfo), Size(s),
432 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
433 TBAAInfo(TBAAInfo), Ranges(Ranges) {
434 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
435 "invalid pointer value");
436 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
437 assert((isLoad() || isStore()) && "Not a load/store!");
440 /// Profile - Gather unique data for the object.
442 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
443 ID.AddInteger(getOffset());
445 ID.AddPointer(getValue());
446 ID.AddInteger(Flags);
449 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
450 // The Value and Offset may differ due to CSE. But the flags and size
451 // should be the same.
452 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
453 assert(MMO->getSize() == getSize() && "Size mismatch!");
455 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
456 // Update the alignment value.
457 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
458 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
459 // Also update the base and offset, because the new alignment may
460 // not be applicable with the old ones.
461 PtrInfo = MMO->PtrInfo;
465 /// getAlignment - Return the minimum known alignment in bytes of the
466 /// actual memory reference.
467 uint64_t MachineMemOperand::getAlignment() const {
468 return MinAlign(getBaseAlignment(), getOffset());
471 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
472 assert((MMO.isLoad() || MMO.isStore()) &&
473 "SV has to be a load, store or both.");
475 if (MMO.isVolatile())
484 // Print the address information.
489 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
491 // If the alignment of the memory reference itself differs from the alignment
492 // of the base pointer, print the base alignment explicitly, next to the base
494 if (MMO.getBaseAlignment() != MMO.getAlignment())
495 OS << "(align=" << MMO.getBaseAlignment() << ")";
497 if (MMO.getOffset() != 0)
498 OS << "+" << MMO.getOffset();
501 // Print the alignment of the reference.
502 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
503 MMO.getBaseAlignment() != MMO.getSize())
504 OS << "(align=" << MMO.getAlignment() << ")";
507 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
509 if (TBAAInfo->getNumOperands() > 0)
510 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
516 // Print nontemporal info.
517 if (MMO.isNonTemporal())
518 OS << "(nontemporal)";
523 //===----------------------------------------------------------------------===//
524 // MachineInstr Implementation
525 //===----------------------------------------------------------------------===//
527 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
528 /// MCID NULL and no operands.
529 MachineInstr::MachineInstr()
530 : MCID(0), Flags(0), AsmPrinterFlags(0),
531 NumMemRefs(0), MemRefs(0),
533 // Make sure that we get added to a machine basicblock
534 LeakDetector::addGarbageObject(this);
537 void MachineInstr::addImplicitDefUseOperands() {
538 if (MCID->ImplicitDefs)
539 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
540 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
541 if (MCID->ImplicitUses)
542 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
543 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
546 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
547 /// implicit operands. It reserves space for the number of operands specified by
549 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
550 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
551 NumMemRefs(0), MemRefs(0), Parent(0) {
552 unsigned NumImplicitOps = 0;
554 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
555 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
557 addImplicitDefUseOperands();
558 // Make sure that we get added to a machine basicblock
559 LeakDetector::addGarbageObject(this);
562 /// MachineInstr ctor - As above, but with a DebugLoc.
563 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
565 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
566 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
567 unsigned NumImplicitOps = 0;
569 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
570 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
572 addImplicitDefUseOperands();
573 // Make sure that we get added to a machine basicblock
574 LeakDetector::addGarbageObject(this);
577 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
578 /// that the MachineInstr is created and added to the end of the specified
580 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
581 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
582 NumMemRefs(0), MemRefs(0), Parent(0) {
583 assert(MBB && "Cannot use inserting ctor with null basic block!");
584 unsigned NumImplicitOps =
585 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
586 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
587 addImplicitDefUseOperands();
588 // Make sure that we get added to a machine basicblock
589 LeakDetector::addGarbageObject(this);
590 MBB->push_back(this); // Add instruction to end of basic block!
593 /// MachineInstr ctor - As above, but with a DebugLoc.
595 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
596 const MCInstrDesc &tid)
597 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
598 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
599 assert(MBB && "Cannot use inserting ctor with null basic block!");
600 unsigned NumImplicitOps =
601 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
602 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
603 addImplicitDefUseOperands();
604 // Make sure that we get added to a machine basicblock
605 LeakDetector::addGarbageObject(this);
606 MBB->push_back(this); // Add instruction to end of basic block!
609 /// MachineInstr ctor - Copies MachineInstr arg exactly
611 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
612 : MCID(&MI.getDesc()), Flags(0), AsmPrinterFlags(0),
613 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
614 Parent(0), debugLoc(MI.getDebugLoc()) {
615 Operands.reserve(MI.getNumOperands());
618 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
619 addOperand(MI.getOperand(i));
621 // Copy all the flags.
624 // Set parent to null.
627 LeakDetector::addGarbageObject(this);
630 MachineInstr::~MachineInstr() {
631 LeakDetector::removeGarbageObject(this);
633 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
634 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
635 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
636 "Reg operand def/use list corrupted");
641 /// getRegInfo - If this instruction is embedded into a MachineFunction,
642 /// return the MachineRegisterInfo object for the current function, otherwise
644 MachineRegisterInfo *MachineInstr::getRegInfo() {
645 if (MachineBasicBlock *MBB = getParent())
646 return &MBB->getParent()->getRegInfo();
650 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
651 /// this instruction from their respective use lists. This requires that the
652 /// operands already be on their use lists.
653 void MachineInstr::RemoveRegOperandsFromUseLists() {
654 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
655 if (Operands[i].isReg())
656 Operands[i].RemoveRegOperandFromRegInfo();
660 /// AddRegOperandsToUseLists - Add all of the register operands in
661 /// this instruction from their respective use lists. This requires that the
662 /// operands not be on their use lists yet.
663 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
664 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
665 if (Operands[i].isReg())
666 Operands[i].AddRegOperandToRegInfo(&RegInfo);
671 /// addOperand - Add the specified operand to the instruction. If it is an
672 /// implicit operand, it is added to the end of the operand list. If it is
673 /// an explicit operand it is added at the end of the explicit operand list
674 /// (before the first implicit operand).
675 void MachineInstr::addOperand(const MachineOperand &Op) {
676 assert(MCID && "Cannot add operands before providing an instr descriptor");
677 bool isImpReg = Op.isReg() && Op.isImplicit();
678 MachineRegisterInfo *RegInfo = getRegInfo();
680 // If the Operands backing store is reallocated, all register operands must
681 // be removed and re-added to RegInfo. It is storing pointers to operands.
682 bool Reallocate = RegInfo &&
683 !Operands.empty() && Operands.size() == Operands.capacity();
685 // Find the insert location for the new operand. Implicit registers go at
686 // the end, everything goes before the implicit regs.
687 unsigned OpNo = Operands.size();
689 // Remove all the implicit operands from RegInfo if they need to be shifted.
690 // FIXME: Allow mixed explicit and implicit operands on inline asm.
691 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
692 // implicit-defs, but they must not be moved around. See the FIXME in
694 if (!isImpReg && !isInlineAsm()) {
695 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
698 Operands[OpNo].RemoveRegOperandFromRegInfo();
702 // OpNo now points as the desired insertion point. Unless this is a variadic
703 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
704 // RegMask operands go between the explicit and implicit operands.
705 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
706 OpNo < MCID->getNumOperands()) &&
707 "Trying to add an operand to a machine instr that is already done!");
709 // All operands from OpNo have been removed from RegInfo. If the Operands
710 // backing store needs to be reallocated, we also need to remove any other
711 // register operands.
713 for (unsigned i = 0; i != OpNo; ++i)
714 if (Operands[i].isReg())
715 Operands[i].RemoveRegOperandFromRegInfo();
717 // Insert the new operand at OpNo.
718 Operands.insert(Operands.begin() + OpNo, Op);
719 Operands[OpNo].ParentMI = this;
721 // The Operands backing store has now been reallocated, so we can re-add the
722 // operands before OpNo.
724 for (unsigned i = 0; i != OpNo; ++i)
725 if (Operands[i].isReg())
726 Operands[i].AddRegOperandToRegInfo(RegInfo);
728 // When adding a register operand, tell RegInfo about it.
729 if (Operands[OpNo].isReg()) {
730 // Add the new operand to RegInfo, even when RegInfo is NULL.
731 // This will initialize the linked list pointers.
732 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
733 // If the register operand is flagged as early, mark the operand as such.
734 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
735 Operands[OpNo].setIsEarlyClobber(true);
738 // Re-add all the implicit ops.
740 for (unsigned i = OpNo + 1, e = Operands.size(); i != e; ++i) {
741 assert(Operands[i].isReg() && "Should only be an implicit reg!");
742 Operands[i].AddRegOperandToRegInfo(RegInfo);
747 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
748 /// fewer operand than it started with.
750 void MachineInstr::RemoveOperand(unsigned OpNo) {
751 assert(OpNo < Operands.size() && "Invalid operand number");
753 // Special case removing the last one.
754 if (OpNo == Operands.size()-1) {
755 // If needed, remove from the reg def/use list.
756 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
757 Operands.back().RemoveRegOperandFromRegInfo();
763 // Otherwise, we are removing an interior operand. If we have reginfo to
764 // update, remove all operands that will be shifted down from their reg lists,
765 // move everything down, then re-add them.
766 MachineRegisterInfo *RegInfo = getRegInfo();
768 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
769 if (Operands[i].isReg())
770 Operands[i].RemoveRegOperandFromRegInfo();
774 Operands.erase(Operands.begin()+OpNo);
777 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
778 if (Operands[i].isReg())
779 Operands[i].AddRegOperandToRegInfo(RegInfo);
784 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
785 /// This function should be used only occasionally. The setMemRefs function
786 /// is the primary method for setting up a MachineInstr's MemRefs list.
787 void MachineInstr::addMemOperand(MachineFunction &MF,
788 MachineMemOperand *MO) {
789 mmo_iterator OldMemRefs = MemRefs;
790 uint16_t OldNumMemRefs = NumMemRefs;
792 uint16_t NewNum = NumMemRefs + 1;
793 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
795 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
796 NewMemRefs[NewNum - 1] = MO;
798 MemRefs = NewMemRefs;
802 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
803 const MachineBasicBlock *MBB = getParent();
804 MachineBasicBlock::const_instr_iterator MII = *this; ++MII;
805 while (MII != MBB->end() && MII->isInsideBundle()) {
806 if (MII->getDesc().getFlags() & Mask) {
807 if (Type == AnyInBundle)
810 if (Type == AllInBundle)
816 return Type == AllInBundle;
819 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
820 MICheckType Check) const {
821 // If opcodes or number of operands are not the same then the two
822 // instructions are obviously not identical.
823 if (Other->getOpcode() != getOpcode() ||
824 Other->getNumOperands() != getNumOperands())
828 // Both instructions are bundles, compare MIs inside the bundle.
829 MachineBasicBlock::const_instr_iterator I1 = *this;
830 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
831 MachineBasicBlock::const_instr_iterator I2 = *Other;
832 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
833 while (++I1 != E1 && I1->isInsideBundle()) {
835 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
840 // Check operands to make sure they match.
841 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
842 const MachineOperand &MO = getOperand(i);
843 const MachineOperand &OMO = Other->getOperand(i);
845 if (!MO.isIdenticalTo(OMO))
850 // Clients may or may not want to ignore defs when testing for equality.
851 // For example, machine CSE pass only cares about finding common
852 // subexpressions, so it's safe to ignore virtual register defs.
854 if (Check == IgnoreDefs)
856 else if (Check == IgnoreVRegDefs) {
857 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
858 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
859 if (MO.getReg() != OMO.getReg())
862 if (!MO.isIdenticalTo(OMO))
864 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
868 if (!MO.isIdenticalTo(OMO))
870 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
874 // If DebugLoc does not match then two dbg.values are not identical.
876 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
877 && getDebugLoc() != Other->getDebugLoc())
882 /// removeFromParent - This method unlinks 'this' from the containing basic
883 /// block, and returns it, but does not delete it.
884 MachineInstr *MachineInstr::removeFromParent() {
885 assert(getParent() && "Not embedded in a basic block!");
887 // If it's a bundle then remove the MIs inside the bundle as well.
889 MachineBasicBlock *MBB = getParent();
890 MachineBasicBlock::instr_iterator MII = *this; ++MII;
891 MachineBasicBlock::instr_iterator E = MBB->instr_end();
892 while (MII != E && MII->isInsideBundle()) {
893 MachineInstr *MI = &*MII;
898 getParent()->remove(this);
903 /// eraseFromParent - This method unlinks 'this' from the containing basic
904 /// block, and deletes it.
905 void MachineInstr::eraseFromParent() {
906 assert(getParent() && "Not embedded in a basic block!");
907 // If it's a bundle then remove the MIs inside the bundle as well.
909 MachineBasicBlock *MBB = getParent();
910 MachineBasicBlock::instr_iterator MII = *this; ++MII;
911 MachineBasicBlock::instr_iterator E = MBB->instr_end();
912 while (MII != E && MII->isInsideBundle()) {
913 MachineInstr *MI = &*MII;
918 // Erase the individual instruction, which may itself be inside a bundle.
919 getParent()->erase_instr(this);
923 /// getNumExplicitOperands - Returns the number of non-implicit operands.
925 unsigned MachineInstr::getNumExplicitOperands() const {
926 unsigned NumOperands = MCID->getNumOperands();
927 if (!MCID->isVariadic())
930 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
931 const MachineOperand &MO = getOperand(i);
932 if (!MO.isReg() || !MO.isImplicit())
938 /// isBundled - Return true if this instruction part of a bundle. This is true
939 /// if either itself or its following instruction is marked "InsideBundle".
940 bool MachineInstr::isBundled() const {
941 if (isInsideBundle())
943 MachineBasicBlock::const_instr_iterator nextMI = this;
945 return nextMI != Parent->instr_end() && nextMI->isInsideBundle();
948 bool MachineInstr::isStackAligningInlineAsm() const {
950 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
951 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
957 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
958 unsigned *GroupNo) const {
959 assert(isInlineAsm() && "Expected an inline asm instruction");
960 assert(OpIdx < getNumOperands() && "OpIdx out of range");
962 // Ignore queries about the initial operands.
963 if (OpIdx < InlineAsm::MIOp_FirstOperand)
968 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
970 const MachineOperand &FlagMO = getOperand(i);
971 // If we reach the implicit register operands, stop looking.
974 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
975 if (i + NumOps > OpIdx) {
985 const TargetRegisterClass*
986 MachineInstr::getRegClassConstraint(unsigned OpIdx,
987 const TargetInstrInfo *TII,
988 const TargetRegisterInfo *TRI) const {
989 assert(getParent() && "Can't have an MBB reference here!");
990 assert(getParent()->getParent() && "Can't have an MF reference here!");
991 const MachineFunction &MF = *getParent()->getParent();
993 // Most opcodes have fixed constraints in their MCInstrDesc.
995 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
997 if (!getOperand(OpIdx).isReg())
1000 // For tied uses on inline asm, get the constraint from the def.
1002 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1005 // Inline asm stores register class constraints in the flag word.
1006 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1010 unsigned Flag = getOperand(FlagIdx).getImm();
1012 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
1013 return TRI->getRegClass(RCID);
1015 // Assume that all registers in a memory operand are pointers.
1016 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1017 return TRI->getPointerRegClass(MF);
1022 /// getBundleSize - Return the number of instructions inside the MI bundle.
1023 unsigned MachineInstr::getBundleSize() const {
1024 assert(isBundle() && "Expecting a bundle");
1026 MachineBasicBlock::const_instr_iterator I = *this;
1028 while ((++I)->isInsideBundle()) {
1031 assert(Size > 1 && "Malformed bundle");
1036 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1037 /// the specific register or -1 if it is not found. It further tightens
1038 /// the search criteria to a use that kills the register if isKill is true.
1039 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1040 const TargetRegisterInfo *TRI) const {
1041 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1042 const MachineOperand &MO = getOperand(i);
1043 if (!MO.isReg() || !MO.isUse())
1045 unsigned MOReg = MO.getReg();
1050 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1051 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1052 TRI->isSubRegister(MOReg, Reg)))
1053 if (!isKill || MO.isKill())
1059 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1060 /// indicating if this instruction reads or writes Reg. This also considers
1061 /// partial defines.
1062 std::pair<bool,bool>
1063 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1064 SmallVectorImpl<unsigned> *Ops) const {
1065 bool PartDef = false; // Partial redefine.
1066 bool FullDef = false; // Full define.
1069 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1070 const MachineOperand &MO = getOperand(i);
1071 if (!MO.isReg() || MO.getReg() != Reg)
1076 Use |= !MO.isUndef();
1077 else if (MO.getSubReg() && !MO.isUndef())
1078 // A partial <def,undef> doesn't count as reading the register.
1083 // A partial redefine uses Reg unless there is also a full define.
1084 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1087 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1088 /// the specified register or -1 if it is not found. If isDead is true, defs
1089 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1090 /// also checks if there is a def of a super-register.
1092 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1093 const TargetRegisterInfo *TRI) const {
1094 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1095 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1096 const MachineOperand &MO = getOperand(i);
1097 // Accept regmask operands when Overlap is set.
1098 // Ignore them when looking for a specific def operand (Overlap == false).
1099 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1101 if (!MO.isReg() || !MO.isDef())
1103 unsigned MOReg = MO.getReg();
1104 bool Found = (MOReg == Reg);
1105 if (!Found && TRI && isPhys &&
1106 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1108 Found = TRI->regsOverlap(MOReg, Reg);
1110 Found = TRI->isSubRegister(MOReg, Reg);
1112 if (Found && (!isDead || MO.isDead()))
1118 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1119 /// operand list that is used to represent the predicate. It returns -1 if
1121 int MachineInstr::findFirstPredOperandIdx() const {
1122 // Don't call MCID.findFirstPredOperandIdx() because this variant
1123 // is sometimes called on an instruction that's not yet complete, and
1124 // so the number of operands is less than the MCID indicates. In
1125 // particular, the PTX target does this.
1126 const MCInstrDesc &MCID = getDesc();
1127 if (MCID.isPredicable()) {
1128 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1129 if (MCID.OpInfo[i].isPredicate())
1136 /// isRegTiedToUseOperand - Given the index of a register def operand,
1137 /// check if the register def is tied to a source operand, due to either
1138 /// two-address elimination or inline assembly constraints. Returns the
1139 /// first tied use operand index by reference is UseOpIdx is not null.
1141 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
1142 if (isInlineAsm()) {
1143 assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
1144 const MachineOperand &MO = getOperand(DefOpIdx);
1145 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
1147 // Determine the actual operand index that corresponds to this index.
1149 int FlagIdx = findInlineAsmFlagIdx(DefOpIdx, &DefNo);
1153 // Which part of the group is DefOpIdx?
1154 unsigned DefPart = DefOpIdx - (FlagIdx + 1);
1156 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
1158 const MachineOperand &FMO = getOperand(i);
1161 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
1164 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
1167 *UseOpIdx = (unsigned)i + 1 + DefPart;
1174 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
1175 const MCInstrDesc &MCID = getDesc();
1176 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
1177 const MachineOperand &MO = getOperand(i);
1178 if (MO.isReg() && MO.isUse() &&
1179 MCID.getOperandConstraint(i, MCOI::TIED_TO) == (int)DefOpIdx) {
1181 *UseOpIdx = (unsigned)i;
1188 /// isRegTiedToDefOperand - Return true if the operand of the specified index
1189 /// is a register use and it is tied to an def operand. It also returns the def
1190 /// operand index by reference.
1192 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
1193 if (isInlineAsm()) {
1194 const MachineOperand &MO = getOperand(UseOpIdx);
1195 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
1198 // Find the flag operand corresponding to UseOpIdx
1199 int FlagIdx = findInlineAsmFlagIdx(UseOpIdx);
1203 const MachineOperand &UFMO = getOperand(FlagIdx);
1205 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1209 unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1210 // Remember to adjust the index. First operand is asm string, second is
1211 // the HasSideEffects and AlignStack bits, then there is a flag for each.
1213 const MachineOperand &FMO = getOperand(DefIdx);
1214 assert(FMO.isImm());
1215 // Skip over this def.
1216 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1219 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1225 const MCInstrDesc &MCID = getDesc();
1226 if (UseOpIdx >= MCID.getNumOperands())
1228 const MachineOperand &MO = getOperand(UseOpIdx);
1229 if (!MO.isReg() || !MO.isUse())
1231 int DefIdx = MCID.getOperandConstraint(UseOpIdx, MCOI::TIED_TO);
1235 *DefOpIdx = (unsigned)DefIdx;
1239 /// clearKillInfo - Clears kill flags on all operands.
1241 void MachineInstr::clearKillInfo() {
1242 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1243 MachineOperand &MO = getOperand(i);
1244 if (MO.isReg() && MO.isUse())
1245 MO.setIsKill(false);
1249 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1251 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1252 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1253 const MachineOperand &MO = MI->getOperand(i);
1254 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1256 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1257 MachineOperand &MOp = getOperand(j);
1258 if (!MOp.isIdenticalTo(MO))
1269 /// copyPredicates - Copies predicate operand(s) from MI.
1270 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1271 assert(!isBundle() && "MachineInstr::copyPredicates() can't handle bundles");
1273 const MCInstrDesc &MCID = MI->getDesc();
1274 if (!MCID.isPredicable())
1276 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1277 if (MCID.OpInfo[i].isPredicate()) {
1278 // Predicated operands must be last operands.
1279 addOperand(MI->getOperand(i));
1284 void MachineInstr::substituteRegister(unsigned FromReg,
1287 const TargetRegisterInfo &RegInfo) {
1288 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1290 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1292 MachineOperand &MO = getOperand(i);
1293 if (!MO.isReg() || MO.getReg() != FromReg)
1295 MO.substPhysReg(ToReg, RegInfo);
1298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1299 MachineOperand &MO = getOperand(i);
1300 if (!MO.isReg() || MO.getReg() != FromReg)
1302 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1307 /// isSafeToMove - Return true if it is safe to move this instruction. If
1308 /// SawStore is set to true, it means that there is a store (or call) between
1309 /// the instruction's location and its intended destination.
1310 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1312 bool &SawStore) const {
1313 // Ignore stuff that we obviously can't move.
1314 if (mayStore() || isCall()) {
1319 if (isLabel() || isDebugValue() ||
1320 isTerminator() || hasUnmodeledSideEffects())
1323 // See if this instruction does a load. If so, we have to guarantee that the
1324 // loaded value doesn't change between the load and the its intended
1325 // destination. The check for isInvariantLoad gives the targe the chance to
1326 // classify the load as always returning a constant, e.g. a constant pool
1328 if (mayLoad() && !isInvariantLoad(AA))
1329 // Otherwise, this is a real load. If there is a store between the load and
1330 // end of block, or if the load is volatile, we can't move it.
1331 return !SawStore && !hasVolatileMemoryRef();
1336 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1337 /// instruction which defined the specified register instead of copying it.
1338 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1340 unsigned DstReg) const {
1341 bool SawStore = false;
1342 if (!TII->isTriviallyReMaterializable(this, AA) ||
1343 !isSafeToMove(TII, AA, SawStore))
1345 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1346 const MachineOperand &MO = getOperand(i);
1349 // FIXME: For now, do not remat any instruction with register operands.
1350 // Later on, we can loosen the restriction is the register operands have
1351 // not been modified between the def and use. Note, this is different from
1352 // MachineSink because the code is no longer in two-address form (at least
1356 else if (!MO.isDead() && MO.getReg() != DstReg)
1362 /// hasVolatileMemoryRef - Return true if this instruction may have a
1363 /// volatile memory reference, or if the information describing the
1364 /// memory reference is not available. Return false if it is known to
1365 /// have no volatile memory references.
1366 bool MachineInstr::hasVolatileMemoryRef() const {
1367 // An instruction known never to access memory won't have a volatile access.
1371 !hasUnmodeledSideEffects())
1374 // Otherwise, if the instruction has no memory reference information,
1375 // conservatively assume it wasn't preserved.
1376 if (memoperands_empty())
1379 // Check the memory reference information for volatile references.
1380 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1381 if ((*I)->isVolatile())
1387 /// isInvariantLoad - Return true if this instruction is loading from a
1388 /// location whose value is invariant across the function. For example,
1389 /// loading a value from the constant pool or from the argument area
1390 /// of a function if it does not change. This should only return true of
1391 /// *all* loads the instruction does are invariant (if it does multiple loads).
1392 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1393 // If the instruction doesn't load at all, it isn't an invariant load.
1397 // If the instruction has lost its memoperands, conservatively assume that
1398 // it may not be an invariant load.
1399 if (memoperands_empty())
1402 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1404 for (mmo_iterator I = memoperands_begin(),
1405 E = memoperands_end(); I != E; ++I) {
1406 if ((*I)->isVolatile()) return false;
1407 if ((*I)->isStore()) return false;
1408 if ((*I)->isInvariant()) return true;
1410 if (const Value *V = (*I)->getValue()) {
1411 // A load from a constant PseudoSourceValue is invariant.
1412 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1413 if (PSV->isConstant(MFI))
1415 // If we have an AliasAnalysis, ask it whether the memory is constant.
1416 if (AA && AA->pointsToConstantMemory(
1417 AliasAnalysis::Location(V, (*I)->getSize(),
1418 (*I)->getTBAAInfo())))
1422 // Otherwise assume conservatively.
1426 // Everything checks out.
1430 /// isConstantValuePHI - If the specified instruction is a PHI that always
1431 /// merges together the same virtual register, return the register, otherwise
1433 unsigned MachineInstr::isConstantValuePHI() const {
1436 assert(getNumOperands() >= 3 &&
1437 "It's illegal to have a PHI without source operands");
1439 unsigned Reg = getOperand(1).getReg();
1440 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1441 if (getOperand(i).getReg() != Reg)
1446 bool MachineInstr::hasUnmodeledSideEffects() const {
1447 if (hasProperty(MCID::UnmodeledSideEffects))
1449 if (isInlineAsm()) {
1450 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1451 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1458 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1460 bool MachineInstr::allDefsAreDead() const {
1461 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1462 const MachineOperand &MO = getOperand(i);
1463 if (!MO.isReg() || MO.isUse())
1471 /// copyImplicitOps - Copy implicit register operands from specified
1472 /// instruction to this instruction.
1473 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1474 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1476 const MachineOperand &MO = MI->getOperand(i);
1477 if (MO.isReg() && MO.isImplicit())
1482 void MachineInstr::dump() const {
1483 dbgs() << " " << *this;
1486 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1487 raw_ostream &CommentOS) {
1488 const LLVMContext &Ctx = MF->getFunction()->getContext();
1489 if (!DL.isUnknown()) { // Print source line info.
1490 DIScope Scope(DL.getScope(Ctx));
1491 // Omit the directory, because it's likely to be long and uninteresting.
1493 CommentOS << Scope.getFilename();
1495 CommentOS << "<unknown>";
1496 CommentOS << ':' << DL.getLine();
1497 if (DL.getCol() != 0)
1498 CommentOS << ':' << DL.getCol();
1499 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1500 if (!InlinedAtDL.isUnknown()) {
1501 CommentOS << " @[ ";
1502 printDebugLoc(InlinedAtDL, MF, CommentOS);
1508 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1509 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1510 const MachineFunction *MF = 0;
1511 const MachineRegisterInfo *MRI = 0;
1512 if (const MachineBasicBlock *MBB = getParent()) {
1513 MF = MBB->getParent();
1515 TM = &MF->getTarget();
1517 MRI = &MF->getRegInfo();
1520 // Save a list of virtual registers.
1521 SmallVector<unsigned, 8> VirtRegs;
1523 // Print explicitly defined operands on the left of an assignment syntax.
1524 unsigned StartOp = 0, e = getNumOperands();
1525 for (; StartOp < e && getOperand(StartOp).isReg() &&
1526 getOperand(StartOp).isDef() &&
1527 !getOperand(StartOp).isImplicit();
1529 if (StartOp != 0) OS << ", ";
1530 getOperand(StartOp).print(OS, TM);
1531 unsigned Reg = getOperand(StartOp).getReg();
1532 if (TargetRegisterInfo::isVirtualRegister(Reg))
1533 VirtRegs.push_back(Reg);
1539 // Print the opcode name.
1540 if (TM && TM->getInstrInfo())
1541 OS << TM->getInstrInfo()->getName(getOpcode());
1545 // Print the rest of the operands.
1546 bool OmittedAnyCallClobbers = false;
1547 bool FirstOp = true;
1548 unsigned AsmDescOp = ~0u;
1549 unsigned AsmOpCount = 0;
1551 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1552 // Print asm string.
1554 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1556 // Print HasSideEffects, IsAlignStack
1557 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1558 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1559 OS << " [sideeffect]";
1560 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1561 OS << " [alignstack]";
1563 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1568 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1569 const MachineOperand &MO = getOperand(i);
1571 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1572 VirtRegs.push_back(MO.getReg());
1574 // Omit call-clobbered registers which aren't used anywhere. This makes
1575 // call instructions much less noisy on targets where calls clobber lots
1576 // of registers. Don't rely on MO.isDead() because we may be called before
1577 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1578 if (MF && isCall() &&
1579 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1580 unsigned Reg = MO.getReg();
1581 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1582 const MachineRegisterInfo &MRI = MF->getRegInfo();
1583 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1584 bool HasAliasLive = false;
1585 for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
1586 AI.isValid(); ++AI) {
1587 unsigned AliasReg = *AI;
1588 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1589 HasAliasLive = true;
1593 if (!HasAliasLive) {
1594 OmittedAnyCallClobbers = true;
1601 if (FirstOp) FirstOp = false; else OS << ",";
1603 if (i < getDesc().NumOperands) {
1604 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1605 if (MCOI.isPredicate())
1607 if (MCOI.isOptionalDef())
1610 if (isDebugValue() && MO.isMetadata()) {
1611 // Pretty print DBG_VALUE instructions.
1612 const MDNode *MD = MO.getMetadata();
1613 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1614 OS << "!\"" << MDS->getString() << '\"';
1617 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1618 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1619 } else if (i == AsmDescOp && MO.isImm()) {
1620 // Pretty print the inline asm operand descriptor.
1621 OS << '$' << AsmOpCount++;
1622 unsigned Flag = MO.getImm();
1623 switch (InlineAsm::getKind(Flag)) {
1624 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1625 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1626 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1627 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1628 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1629 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1630 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1634 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1636 OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1638 OS << ":RC" << RCID;
1641 unsigned TiedTo = 0;
1642 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1643 OS << " tiedto:$" << TiedTo;
1647 // Compute the index of the next operand descriptor.
1648 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1653 // Briefly indicate whether any call clobbers were omitted.
1654 if (OmittedAnyCallClobbers) {
1655 if (!FirstOp) OS << ",";
1659 bool HaveSemi = false;
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 (llvm::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 << ";"; HaveSemi = true;
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()) {
1706 OS << " inlined @[ ";
1707 printDebugLoc(InlinedAtDL, MF, OS);
1711 } else if (!debugLoc.isUnknown() && MF) {
1712 if (!HaveSemi) OS << ";"; HaveSemi = true;
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 IncomingReg,
1794 const TargetRegisterInfo *RegInfo,
1795 bool AddIfNotFound) {
1796 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1797 bool hasAliases = isPhysReg &&
1798 MCRegAliasIterator(IncomingReg, 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 Reg = MO.getReg();
1809 if (Reg == IncomingReg) {
1812 } else if (hasAliases && MO.isDead() &&
1813 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1814 // There exists a super-register that's marked dead.
1815 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1817 if (RegInfo->isSubRegister(IncomingReg, Reg))
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(IncomingReg,
1845 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1846 const TargetRegisterInfo *RegInfo) {
1847 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1848 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1852 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1853 const MachineOperand &MO = getOperand(i);
1854 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1855 MO.getSubReg() == 0)
1859 addOperand(MachineOperand::CreateReg(IncomingReg,
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 = 0;
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);