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/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/Value.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/DebugInfo.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"
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
49 /// AddRegOperandToRegInfo - Add this register operand to the specified
50 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
51 /// explicitly nulled out.
52 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
53 assert(isReg() && "Can only add reg operand to use lists");
55 // If the reginfo pointer is null, just explicitly null out or next/prev
56 // pointers, to ensure they are not garbage.
58 Contents.Reg.Prev = 0;
59 Contents.Reg.Next = 0;
63 // Otherwise, add this operand to the head of the registers use/def list.
64 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
66 // For SSA values, we prefer to keep the definition at the start of the list.
67 // we do this by skipping over the definition if it is at the head of the
69 if (*Head && (*Head)->isDef())
70 Head = &(*Head)->Contents.Reg.Next;
72 Contents.Reg.Next = *Head;
73 if (Contents.Reg.Next) {
74 assert(getReg() == Contents.Reg.Next->getReg() &&
75 "Different regs on the same list!");
76 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
79 Contents.Reg.Prev = Head;
83 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
84 /// MachineRegisterInfo it is linked with.
85 void MachineOperand::RemoveRegOperandFromRegInfo() {
86 assert(isOnRegUseList() && "Reg operand is not on a use list");
87 // Unlink this from the doubly linked list of operands.
88 MachineOperand *NextOp = Contents.Reg.Next;
89 *Contents.Reg.Prev = NextOp;
91 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
92 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
94 Contents.Reg.Prev = 0;
95 Contents.Reg.Next = 0;
98 void MachineOperand::setReg(unsigned Reg) {
99 if (getReg() == Reg) return; // No change.
101 // Otherwise, we have to change the register. If this operand is embedded
102 // into a machine function, we need to update the old and new register's
104 if (MachineInstr *MI = getParent())
105 if (MachineBasicBlock *MBB = MI->getParent())
106 if (MachineFunction *MF = MBB->getParent()) {
107 RemoveRegOperandFromRegInfo();
108 SmallContents.RegNo = Reg;
109 AddRegOperandToRegInfo(&MF->getRegInfo());
113 // Otherwise, just change the register, no problem. :)
114 SmallContents.RegNo = Reg;
117 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
118 const TargetRegisterInfo &TRI) {
119 assert(TargetRegisterInfo::isVirtualRegister(Reg));
120 if (SubIdx && getSubReg())
121 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
127 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
128 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
130 Reg = TRI.getSubReg(Reg, getSubReg());
131 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
132 // That won't happen in legal code.
138 /// ChangeToImmediate - Replace this operand with a new immediate operand of
139 /// the specified value. If an operand is known to be an immediate already,
140 /// the setImm method should be used.
141 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
142 // If this operand is currently a register operand, and if this is in a
143 // function, deregister the operand from the register's use/def list.
144 if (isReg() && getParent() && getParent()->getParent() &&
145 getParent()->getParent()->getParent())
146 RemoveRegOperandFromRegInfo();
148 OpKind = MO_Immediate;
149 Contents.ImmVal = ImmVal;
152 /// ChangeToRegister - Replace this operand with a new register operand of
153 /// the specified value. If an operand is known to be an register already,
154 /// the setReg method should be used.
155 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
156 bool isKill, bool isDead, bool isUndef,
158 // If this operand is already a register operand, use setReg to update the
159 // register's use/def lists.
161 assert(!isEarlyClobber());
164 // Otherwise, change this to a register and set the reg#.
165 OpKind = MO_Register;
166 SmallContents.RegNo = Reg;
168 // If this operand is embedded in a function, add the operand to the
169 // register's use/def list.
170 if (MachineInstr *MI = getParent())
171 if (MachineBasicBlock *MBB = MI->getParent())
172 if (MachineFunction *MF = MBB->getParent())
173 AddRegOperandToRegInfo(&MF->getRegInfo());
181 IsInternalRead = false;
182 IsEarlyClobber = false;
187 /// isIdenticalTo - Return true if this operand is identical to the specified
189 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
190 if (getType() != Other.getType() ||
191 getTargetFlags() != Other.getTargetFlags())
195 case MachineOperand::MO_Register:
196 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
197 getSubReg() == Other.getSubReg();
198 case MachineOperand::MO_Immediate:
199 return getImm() == Other.getImm();
200 case MachineOperand::MO_CImmediate:
201 return getCImm() == Other.getCImm();
202 case MachineOperand::MO_FPImmediate:
203 return getFPImm() == Other.getFPImm();
204 case MachineOperand::MO_MachineBasicBlock:
205 return getMBB() == Other.getMBB();
206 case MachineOperand::MO_FrameIndex:
207 return getIndex() == Other.getIndex();
208 case MachineOperand::MO_ConstantPoolIndex:
209 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
210 case MachineOperand::MO_JumpTableIndex:
211 return getIndex() == Other.getIndex();
212 case MachineOperand::MO_GlobalAddress:
213 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
214 case MachineOperand::MO_ExternalSymbol:
215 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
216 getOffset() == Other.getOffset();
217 case MachineOperand::MO_BlockAddress:
218 return getBlockAddress() == Other.getBlockAddress();
219 case MachineOperand::MO_MCSymbol:
220 return getMCSymbol() == Other.getMCSymbol();
221 case MachineOperand::MO_Metadata:
222 return getMetadata() == Other.getMetadata();
226 /// print - Print the specified machine operand.
228 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
229 // If the instruction is embedded into a basic block, we can find the
230 // target info for the instruction.
232 if (const MachineInstr *MI = getParent())
233 if (const MachineBasicBlock *MBB = MI->getParent())
234 if (const MachineFunction *MF = MBB->getParent())
235 TM = &MF->getTarget();
236 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
239 case MachineOperand::MO_Register:
240 OS << PrintReg(getReg(), TRI, getSubReg());
242 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
243 isInternalRead() || isEarlyClobber()) {
245 bool NeedComma = false;
247 if (NeedComma) OS << ',';
248 if (isEarlyClobber())
249 OS << "earlyclobber,";
254 } else if (isImplicit()) {
259 if (isKill() || isDead() || isUndef() || isInternalRead()) {
260 if (NeedComma) OS << ',';
271 if (NeedComma) OS << ',';
275 if (isInternalRead()) {
276 if (NeedComma) OS << ',';
284 case MachineOperand::MO_Immediate:
287 case MachineOperand::MO_CImmediate:
288 getCImm()->getValue().print(OS, false);
290 case MachineOperand::MO_FPImmediate:
291 if (getFPImm()->getType()->isFloatTy())
292 OS << getFPImm()->getValueAPF().convertToFloat();
294 OS << getFPImm()->getValueAPF().convertToDouble();
296 case MachineOperand::MO_MachineBasicBlock:
297 OS << "<BB#" << getMBB()->getNumber() << ">";
299 case MachineOperand::MO_FrameIndex:
300 OS << "<fi#" << getIndex() << '>';
302 case MachineOperand::MO_ConstantPoolIndex:
303 OS << "<cp#" << getIndex();
304 if (getOffset()) OS << "+" << getOffset();
307 case MachineOperand::MO_JumpTableIndex:
308 OS << "<jt#" << getIndex() << '>';
310 case MachineOperand::MO_GlobalAddress:
312 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
313 if (getOffset()) OS << "+" << getOffset();
316 case MachineOperand::MO_ExternalSymbol:
317 OS << "<es:" << getSymbolName();
318 if (getOffset()) OS << "+" << getOffset();
321 case MachineOperand::MO_BlockAddress:
323 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
326 case MachineOperand::MO_Metadata:
328 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
331 case MachineOperand::MO_MCSymbol:
332 OS << "<MCSym=" << *getMCSymbol() << '>';
336 if (unsigned TF = getTargetFlags())
337 OS << "[TF=" << TF << ']';
340 //===----------------------------------------------------------------------===//
341 // MachineMemOperand Implementation
342 //===----------------------------------------------------------------------===//
344 /// getAddrSpace - Return the LLVM IR address space number that this pointer
346 unsigned MachinePointerInfo::getAddrSpace() const {
347 if (V == 0) return 0;
348 return cast<PointerType>(V->getType())->getAddressSpace();
351 /// getConstantPool - Return a MachinePointerInfo record that refers to the
353 MachinePointerInfo MachinePointerInfo::getConstantPool() {
354 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
357 /// getFixedStack - Return a MachinePointerInfo record that refers to the
358 /// the specified FrameIndex.
359 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
360 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
363 MachinePointerInfo MachinePointerInfo::getJumpTable() {
364 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
367 MachinePointerInfo MachinePointerInfo::getGOT() {
368 return MachinePointerInfo(PseudoSourceValue::getGOT());
371 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
372 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
375 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
376 uint64_t s, unsigned int a,
377 const MDNode *TBAAInfo)
378 : PtrInfo(ptrinfo), Size(s),
379 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
381 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
382 "invalid pointer value");
383 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
384 assert((isLoad() || isStore()) && "Not a load/store!");
387 /// Profile - Gather unique data for the object.
389 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
390 ID.AddInteger(getOffset());
392 ID.AddPointer(getValue());
393 ID.AddInteger(Flags);
396 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
397 // The Value and Offset may differ due to CSE. But the flags and size
398 // should be the same.
399 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
400 assert(MMO->getSize() == getSize() && "Size mismatch!");
402 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
403 // Update the alignment value.
404 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
405 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
406 // Also update the base and offset, because the new alignment may
407 // not be applicable with the old ones.
408 PtrInfo = MMO->PtrInfo;
412 /// getAlignment - Return the minimum known alignment in bytes of the
413 /// actual memory reference.
414 uint64_t MachineMemOperand::getAlignment() const {
415 return MinAlign(getBaseAlignment(), getOffset());
418 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
419 assert((MMO.isLoad() || MMO.isStore()) &&
420 "SV has to be a load, store or both.");
422 if (MMO.isVolatile())
431 // Print the address information.
436 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
438 // If the alignment of the memory reference itself differs from the alignment
439 // of the base pointer, print the base alignment explicitly, next to the base
441 if (MMO.getBaseAlignment() != MMO.getAlignment())
442 OS << "(align=" << MMO.getBaseAlignment() << ")";
444 if (MMO.getOffset() != 0)
445 OS << "+" << MMO.getOffset();
448 // Print the alignment of the reference.
449 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
450 MMO.getBaseAlignment() != MMO.getSize())
451 OS << "(align=" << MMO.getAlignment() << ")";
454 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
456 if (TBAAInfo->getNumOperands() > 0)
457 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
463 // Print nontemporal info.
464 if (MMO.isNonTemporal())
465 OS << "(nontemporal)";
470 //===----------------------------------------------------------------------===//
471 // MachineInstr Implementation
472 //===----------------------------------------------------------------------===//
474 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
475 /// MCID NULL and no operands.
476 MachineInstr::MachineInstr()
477 : MCID(0), Flags(0), AsmPrinterFlags(0),
478 MemRefs(0), MemRefsEnd(0),
480 // Make sure that we get added to a machine basicblock
481 LeakDetector::addGarbageObject(this);
484 void MachineInstr::addImplicitDefUseOperands() {
485 if (MCID->ImplicitDefs)
486 for (const unsigned *ImpDefs = MCID->ImplicitDefs; *ImpDefs; ++ImpDefs)
487 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
488 if (MCID->ImplicitUses)
489 for (const unsigned *ImpUses = MCID->ImplicitUses; *ImpUses; ++ImpUses)
490 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
493 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
494 /// implicit operands. It reserves space for the number of operands specified by
496 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
497 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
498 MemRefs(0), MemRefsEnd(0), Parent(0) {
499 unsigned NumImplicitOps = 0;
501 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
502 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
504 addImplicitDefUseOperands();
505 // Make sure that we get added to a machine basicblock
506 LeakDetector::addGarbageObject(this);
509 /// MachineInstr ctor - As above, but with a DebugLoc.
510 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
512 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
513 MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
514 unsigned NumImplicitOps = 0;
516 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
517 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
519 addImplicitDefUseOperands();
520 // Make sure that we get added to a machine basicblock
521 LeakDetector::addGarbageObject(this);
524 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
525 /// that the MachineInstr is created and added to the end of the specified
527 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
528 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
529 MemRefs(0), MemRefsEnd(0), Parent(0) {
530 assert(MBB && "Cannot use inserting ctor with null basic block!");
531 unsigned NumImplicitOps =
532 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
533 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
534 addImplicitDefUseOperands();
535 // Make sure that we get added to a machine basicblock
536 LeakDetector::addGarbageObject(this);
537 MBB->push_back(this); // Add instruction to end of basic block!
540 /// MachineInstr ctor - As above, but with a DebugLoc.
542 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
543 const MCInstrDesc &tid)
544 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
545 MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
546 assert(MBB && "Cannot use inserting ctor with null basic block!");
547 unsigned NumImplicitOps =
548 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
549 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
550 addImplicitDefUseOperands();
551 // Make sure that we get added to a machine basicblock
552 LeakDetector::addGarbageObject(this);
553 MBB->push_back(this); // Add instruction to end of basic block!
556 /// MachineInstr ctor - Copies MachineInstr arg exactly
558 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
559 : MCID(&MI.getDesc()), Flags(0), AsmPrinterFlags(0),
560 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
561 Parent(0), debugLoc(MI.getDebugLoc()) {
562 Operands.reserve(MI.getNumOperands());
565 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
566 addOperand(MI.getOperand(i));
568 // Copy all the flags.
571 // Set parent to null.
574 LeakDetector::addGarbageObject(this);
577 MachineInstr::~MachineInstr() {
578 LeakDetector::removeGarbageObject(this);
580 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
581 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
582 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
583 "Reg operand def/use list corrupted");
588 /// getRegInfo - If this instruction is embedded into a MachineFunction,
589 /// return the MachineRegisterInfo object for the current function, otherwise
591 MachineRegisterInfo *MachineInstr::getRegInfo() {
592 if (MachineBasicBlock *MBB = getParent())
593 return &MBB->getParent()->getRegInfo();
597 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
598 /// this instruction from their respective use lists. This requires that the
599 /// operands already be on their use lists.
600 void MachineInstr::RemoveRegOperandsFromUseLists() {
601 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
602 if (Operands[i].isReg())
603 Operands[i].RemoveRegOperandFromRegInfo();
607 /// AddRegOperandsToUseLists - Add all of the register operands in
608 /// this instruction from their respective use lists. This requires that the
609 /// operands not be on their use lists yet.
610 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
611 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
612 if (Operands[i].isReg())
613 Operands[i].AddRegOperandToRegInfo(&RegInfo);
618 /// addOperand - Add the specified operand to the instruction. If it is an
619 /// implicit operand, it is added to the end of the operand list. If it is
620 /// an explicit operand it is added at the end of the explicit operand list
621 /// (before the first implicit operand).
622 void MachineInstr::addOperand(const MachineOperand &Op) {
623 assert(MCID && "Cannot add operands before providing an instr descriptor");
624 bool isImpReg = Op.isReg() && Op.isImplicit();
625 MachineRegisterInfo *RegInfo = getRegInfo();
627 // If the Operands backing store is reallocated, all register operands must
628 // be removed and re-added to RegInfo. It is storing pointers to operands.
629 bool Reallocate = RegInfo &&
630 !Operands.empty() && Operands.size() == Operands.capacity();
632 // Find the insert location for the new operand. Implicit registers go at
633 // the end, everything goes before the implicit regs.
634 unsigned OpNo = Operands.size();
636 // Remove all the implicit operands from RegInfo if they need to be shifted.
637 // FIXME: Allow mixed explicit and implicit operands on inline asm.
638 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
639 // implicit-defs, but they must not be moved around. See the FIXME in
641 if (!isImpReg && !isInlineAsm()) {
642 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
645 Operands[OpNo].RemoveRegOperandFromRegInfo();
649 // OpNo now points as the desired insertion point. Unless this is a variadic
650 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
651 assert((isImpReg || MCID->isVariadic() || OpNo < MCID->getNumOperands()) &&
652 "Trying to add an operand to a machine instr that is already done!");
654 // All operands from OpNo have been removed from RegInfo. If the Operands
655 // backing store needs to be reallocated, we also need to remove any other
656 // register operands.
658 for (unsigned i = 0; i != OpNo; ++i)
659 if (Operands[i].isReg())
660 Operands[i].RemoveRegOperandFromRegInfo();
662 // Insert the new operand at OpNo.
663 Operands.insert(Operands.begin() + OpNo, Op);
664 Operands[OpNo].ParentMI = this;
666 // The Operands backing store has now been reallocated, so we can re-add the
667 // operands before OpNo.
669 for (unsigned i = 0; i != OpNo; ++i)
670 if (Operands[i].isReg())
671 Operands[i].AddRegOperandToRegInfo(RegInfo);
673 // When adding a register operand, tell RegInfo about it.
674 if (Operands[OpNo].isReg()) {
675 // Add the new operand to RegInfo, even when RegInfo is NULL.
676 // This will initialize the linked list pointers.
677 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
678 // If the register operand is flagged as early, mark the operand as such.
679 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
680 Operands[OpNo].setIsEarlyClobber(true);
683 // Re-add all the implicit ops.
685 for (unsigned i = OpNo + 1, e = Operands.size(); i != e; ++i) {
686 assert(Operands[i].isReg() && "Should only be an implicit reg!");
687 Operands[i].AddRegOperandToRegInfo(RegInfo);
692 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
693 /// fewer operand than it started with.
695 void MachineInstr::RemoveOperand(unsigned OpNo) {
696 assert(OpNo < Operands.size() && "Invalid operand number");
698 // Special case removing the last one.
699 if (OpNo == Operands.size()-1) {
700 // If needed, remove from the reg def/use list.
701 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
702 Operands.back().RemoveRegOperandFromRegInfo();
708 // Otherwise, we are removing an interior operand. If we have reginfo to
709 // update, remove all operands that will be shifted down from their reg lists,
710 // move everything down, then re-add them.
711 MachineRegisterInfo *RegInfo = getRegInfo();
713 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
714 if (Operands[i].isReg())
715 Operands[i].RemoveRegOperandFromRegInfo();
719 Operands.erase(Operands.begin()+OpNo);
722 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
723 if (Operands[i].isReg())
724 Operands[i].AddRegOperandToRegInfo(RegInfo);
729 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
730 /// This function should be used only occasionally. The setMemRefs function
731 /// is the primary method for setting up a MachineInstr's MemRefs list.
732 void MachineInstr::addMemOperand(MachineFunction &MF,
733 MachineMemOperand *MO) {
734 mmo_iterator OldMemRefs = MemRefs;
735 mmo_iterator OldMemRefsEnd = MemRefsEnd;
737 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
738 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
739 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
741 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
742 NewMemRefs[NewNum - 1] = MO;
744 MemRefs = NewMemRefs;
745 MemRefsEnd = NewMemRefsEnd;
749 MachineInstr::hasProperty(unsigned MCFlag, QueryType Type) const {
750 if (Type == IgnoreBundle || !isBundle())
751 return getDesc().getFlags() & (1 << MCFlag);
753 const MachineBasicBlock *MBB = getParent();
754 MachineBasicBlock::const_instr_iterator MII = *this; ++MII;
755 while (MII != MBB->end() && MII->isInsideBundle()) {
756 if (MII->getDesc().getFlags() & (1 << MCFlag)) {
757 if (Type == AnyInBundle)
760 if (Type == AllInBundle)
766 return Type == AllInBundle;
769 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
770 MICheckType Check) const {
771 // If opcodes or number of operands are not the same then the two
772 // instructions are obviously not identical.
773 if (Other->getOpcode() != getOpcode() ||
774 Other->getNumOperands() != getNumOperands())
778 // Both instructions are bundles, compare MIs inside the bundle.
779 MachineBasicBlock::const_instr_iterator I1 = *this;
780 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
781 MachineBasicBlock::const_instr_iterator I2 = *Other;
782 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
783 while (++I1 != E1 && I1->isInsideBundle()) {
785 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
790 // Check operands to make sure they match.
791 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
792 const MachineOperand &MO = getOperand(i);
793 const MachineOperand &OMO = Other->getOperand(i);
795 if (!MO.isIdenticalTo(OMO))
800 // Clients may or may not want to ignore defs when testing for equality.
801 // For example, machine CSE pass only cares about finding common
802 // subexpressions, so it's safe to ignore virtual register defs.
804 if (Check == IgnoreDefs)
806 else if (Check == IgnoreVRegDefs) {
807 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
808 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
809 if (MO.getReg() != OMO.getReg())
812 if (!MO.isIdenticalTo(OMO))
814 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
818 if (!MO.isIdenticalTo(OMO))
820 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
824 // If DebugLoc does not match then two dbg.values are not identical.
826 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
827 && getDebugLoc() != Other->getDebugLoc())
832 /// removeFromParent - This method unlinks 'this' from the containing basic
833 /// block, and returns it, but does not delete it.
834 MachineInstr *MachineInstr::removeFromParent() {
835 assert(getParent() && "Not embedded in a basic block!");
837 // If it's a bundle then remove the MIs inside the bundle as well.
839 MachineBasicBlock *MBB = getParent();
840 MachineBasicBlock::instr_iterator MII = *this; ++MII;
841 MachineBasicBlock::instr_iterator E = MBB->instr_end();
842 while (MII != E && MII->isInsideBundle()) {
843 MachineInstr *MI = &*MII;
848 getParent()->remove(this);
853 /// eraseFromParent - This method unlinks 'this' from the containing basic
854 /// block, and deletes it.
855 void MachineInstr::eraseFromParent() {
856 assert(getParent() && "Not embedded in a basic block!");
857 // If it's a bundle then remove the MIs inside the bundle as well.
859 MachineBasicBlock *MBB = getParent();
860 MachineBasicBlock::instr_iterator MII = *this; ++MII;
861 MachineBasicBlock::instr_iterator E = MBB->instr_end();
862 while (MII != E && MII->isInsideBundle()) {
863 MachineInstr *MI = &*MII;
868 getParent()->erase(this);
872 /// getNumExplicitOperands - Returns the number of non-implicit operands.
874 unsigned MachineInstr::getNumExplicitOperands() const {
875 unsigned NumOperands = MCID->getNumOperands();
876 if (!MCID->isVariadic())
879 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
880 const MachineOperand &MO = getOperand(i);
881 if (!MO.isReg() || !MO.isImplicit())
887 bool MachineInstr::isStackAligningInlineAsm() const {
889 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
890 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
896 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
897 unsigned *GroupNo) const {
898 assert(isInlineAsm() && "Expected an inline asm instruction");
899 assert(OpIdx < getNumOperands() && "OpIdx out of range");
901 // Ignore queries about the initial operands.
902 if (OpIdx < InlineAsm::MIOp_FirstOperand)
907 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
909 const MachineOperand &FlagMO = getOperand(i);
910 // If we reach the implicit register operands, stop looking.
913 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
914 if (i + NumOps > OpIdx) {
924 const TargetRegisterClass*
925 MachineInstr::getRegClassConstraint(unsigned OpIdx,
926 const TargetInstrInfo *TII,
927 const TargetRegisterInfo *TRI) const {
928 // Most opcodes have fixed constraints in their MCInstrDesc.
930 return TII->getRegClass(getDesc(), OpIdx, TRI);
932 if (!getOperand(OpIdx).isReg())
935 // For tied uses on inline asm, get the constraint from the def.
937 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
940 // Inline asm stores register class constraints in the flag word.
941 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
945 unsigned Flag = getOperand(FlagIdx).getImm();
947 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
948 return TRI->getRegClass(RCID);
950 // Assume that all registers in a memory operand are pointers.
951 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
952 return TRI->getPointerRegClass();
957 /// getBundleSize - Return the number of instructions inside the MI bundle.
958 unsigned MachineInstr::getBundleSize() const {
959 assert(isBundle() && "Expecting a bundle");
961 MachineBasicBlock::const_instr_iterator I = *this;
963 while ((++I)->isInsideBundle()) {
966 assert(Size > 1 && "Malformed bundle");
971 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
972 /// the specific register or -1 if it is not found. It further tightens
973 /// the search criteria to a use that kills the register if isKill is true.
974 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
975 const TargetRegisterInfo *TRI) const {
976 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
977 const MachineOperand &MO = getOperand(i);
978 if (!MO.isReg() || !MO.isUse())
980 unsigned MOReg = MO.getReg();
985 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
986 TargetRegisterInfo::isPhysicalRegister(Reg) &&
987 TRI->isSubRegister(MOReg, Reg)))
988 if (!isKill || MO.isKill())
994 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
995 /// indicating if this instruction reads or writes Reg. This also considers
998 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
999 SmallVectorImpl<unsigned> *Ops) const {
1000 bool PartDef = false; // Partial redefine.
1001 bool FullDef = false; // Full define.
1004 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1005 const MachineOperand &MO = getOperand(i);
1006 if (!MO.isReg() || MO.getReg() != Reg)
1011 Use |= !MO.isUndef();
1012 else if (MO.getSubReg() && !MO.isUndef())
1013 // A partial <def,undef> doesn't count as reading the register.
1018 // A partial redefine uses Reg unless there is also a full define.
1019 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1022 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1023 /// the specified register or -1 if it is not found. If isDead is true, defs
1024 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1025 /// also checks if there is a def of a super-register.
1027 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1028 const TargetRegisterInfo *TRI) const {
1029 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1030 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1031 const MachineOperand &MO = getOperand(i);
1032 if (!MO.isReg() || !MO.isDef())
1034 unsigned MOReg = MO.getReg();
1035 bool Found = (MOReg == Reg);
1036 if (!Found && TRI && isPhys &&
1037 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1039 Found = TRI->regsOverlap(MOReg, Reg);
1041 Found = TRI->isSubRegister(MOReg, Reg);
1043 if (Found && (!isDead || MO.isDead()))
1049 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1050 /// operand list that is used to represent the predicate. It returns -1 if
1052 int MachineInstr::findFirstPredOperandIdx() const {
1053 // Don't call MCID.findFirstPredOperandIdx() because this variant
1054 // is sometimes called on an instruction that's not yet complete, and
1055 // so the number of operands is less than the MCID indicates. In
1056 // particular, the PTX target does this.
1057 const MCInstrDesc &MCID = getDesc();
1058 if (MCID.isPredicable()) {
1059 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1060 if (MCID.OpInfo[i].isPredicate())
1067 /// isRegTiedToUseOperand - Given the index of a register def operand,
1068 /// check if the register def is tied to a source operand, due to either
1069 /// two-address elimination or inline assembly constraints. Returns the
1070 /// first tied use operand index by reference is UseOpIdx is not null.
1072 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
1073 if (isInlineAsm()) {
1074 assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
1075 const MachineOperand &MO = getOperand(DefOpIdx);
1076 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
1078 // Determine the actual operand index that corresponds to this index.
1080 int FlagIdx = findInlineAsmFlagIdx(DefOpIdx, &DefNo);
1084 // Which part of the group is DefOpIdx?
1085 unsigned DefPart = DefOpIdx - (FlagIdx + 1);
1087 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
1089 const MachineOperand &FMO = getOperand(i);
1092 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
1095 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
1098 *UseOpIdx = (unsigned)i + 1 + DefPart;
1105 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
1106 const MCInstrDesc &MCID = getDesc();
1107 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
1108 const MachineOperand &MO = getOperand(i);
1109 if (MO.isReg() && MO.isUse() &&
1110 MCID.getOperandConstraint(i, MCOI::TIED_TO) == (int)DefOpIdx) {
1112 *UseOpIdx = (unsigned)i;
1119 /// isRegTiedToDefOperand - Return true if the operand of the specified index
1120 /// is a register use and it is tied to an def operand. It also returns the def
1121 /// operand index by reference.
1123 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
1124 if (isInlineAsm()) {
1125 const MachineOperand &MO = getOperand(UseOpIdx);
1126 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
1129 // Find the flag operand corresponding to UseOpIdx
1130 int FlagIdx = findInlineAsmFlagIdx(UseOpIdx);
1134 const MachineOperand &UFMO = getOperand(FlagIdx);
1136 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1140 unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1141 // Remember to adjust the index. First operand is asm string, second is
1142 // the HasSideEffects and AlignStack bits, then there is a flag for each.
1144 const MachineOperand &FMO = getOperand(DefIdx);
1145 assert(FMO.isImm());
1146 // Skip over this def.
1147 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1150 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1156 const MCInstrDesc &MCID = getDesc();
1157 if (UseOpIdx >= MCID.getNumOperands())
1159 const MachineOperand &MO = getOperand(UseOpIdx);
1160 if (!MO.isReg() || !MO.isUse())
1162 int DefIdx = MCID.getOperandConstraint(UseOpIdx, MCOI::TIED_TO);
1166 *DefOpIdx = (unsigned)DefIdx;
1170 /// clearKillInfo - Clears kill flags on all operands.
1172 void MachineInstr::clearKillInfo() {
1173 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1174 MachineOperand &MO = getOperand(i);
1175 if (MO.isReg() && MO.isUse())
1176 MO.setIsKill(false);
1180 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1182 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1183 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1184 const MachineOperand &MO = MI->getOperand(i);
1185 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1187 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1188 MachineOperand &MOp = getOperand(j);
1189 if (!MOp.isIdenticalTo(MO))
1200 /// copyPredicates - Copies predicate operand(s) from MI.
1201 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1202 assert(!isBundle() && "MachineInstr::copyPredicates() can't handle bundles");
1204 const MCInstrDesc &MCID = MI->getDesc();
1205 if (!MCID.isPredicable())
1207 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1208 if (MCID.OpInfo[i].isPredicate()) {
1209 // Predicated operands must be last operands.
1210 addOperand(MI->getOperand(i));
1215 void MachineInstr::substituteRegister(unsigned FromReg,
1218 const TargetRegisterInfo &RegInfo) {
1219 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1221 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1222 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1223 MachineOperand &MO = getOperand(i);
1224 if (!MO.isReg() || MO.getReg() != FromReg)
1226 MO.substPhysReg(ToReg, RegInfo);
1229 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1230 MachineOperand &MO = getOperand(i);
1231 if (!MO.isReg() || MO.getReg() != FromReg)
1233 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1238 /// isSafeToMove - Return true if it is safe to move this instruction. If
1239 /// SawStore is set to true, it means that there is a store (or call) between
1240 /// the instruction's location and its intended destination.
1241 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1243 bool &SawStore) const {
1244 // Ignore stuff that we obviously can't move.
1245 if (mayStore() || isCall()) {
1250 if (isLabel() || isDebugValue() ||
1251 isTerminator() || hasUnmodeledSideEffects())
1254 // See if this instruction does a load. If so, we have to guarantee that the
1255 // loaded value doesn't change between the load and the its intended
1256 // destination. The check for isInvariantLoad gives the targe the chance to
1257 // classify the load as always returning a constant, e.g. a constant pool
1259 if (mayLoad() && !isInvariantLoad(AA))
1260 // Otherwise, this is a real load. If there is a store between the load and
1261 // end of block, or if the load is volatile, we can't move it.
1262 return !SawStore && !hasVolatileMemoryRef();
1267 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1268 /// instruction which defined the specified register instead of copying it.
1269 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1271 unsigned DstReg) const {
1272 bool SawStore = false;
1273 if (!TII->isTriviallyReMaterializable(this, AA) ||
1274 !isSafeToMove(TII, AA, SawStore))
1276 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1277 const MachineOperand &MO = getOperand(i);
1280 // FIXME: For now, do not remat any instruction with register operands.
1281 // Later on, we can loosen the restriction is the register operands have
1282 // not been modified between the def and use. Note, this is different from
1283 // MachineSink because the code is no longer in two-address form (at least
1287 else if (!MO.isDead() && MO.getReg() != DstReg)
1293 /// hasVolatileMemoryRef - Return true if this instruction may have a
1294 /// volatile memory reference, or if the information describing the
1295 /// memory reference is not available. Return false if it is known to
1296 /// have no volatile memory references.
1297 bool MachineInstr::hasVolatileMemoryRef() const {
1298 // An instruction known never to access memory won't have a volatile access.
1302 !hasUnmodeledSideEffects())
1305 // Otherwise, if the instruction has no memory reference information,
1306 // conservatively assume it wasn't preserved.
1307 if (memoperands_empty())
1310 // Check the memory reference information for volatile references.
1311 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1312 if ((*I)->isVolatile())
1318 /// isInvariantLoad - Return true if this instruction is loading from a
1319 /// location whose value is invariant across the function. For example,
1320 /// loading a value from the constant pool or from the argument area
1321 /// of a function if it does not change. This should only return true of
1322 /// *all* loads the instruction does are invariant (if it does multiple loads).
1323 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1324 // If the instruction doesn't load at all, it isn't an invariant load.
1328 // If the instruction has lost its memoperands, conservatively assume that
1329 // it may not be an invariant load.
1330 if (memoperands_empty())
1333 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1335 for (mmo_iterator I = memoperands_begin(),
1336 E = memoperands_end(); I != E; ++I) {
1337 if ((*I)->isVolatile()) return false;
1338 if ((*I)->isStore()) return false;
1339 if ((*I)->isInvariant()) return true;
1341 if (const Value *V = (*I)->getValue()) {
1342 // A load from a constant PseudoSourceValue is invariant.
1343 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1344 if (PSV->isConstant(MFI))
1346 // If we have an AliasAnalysis, ask it whether the memory is constant.
1347 if (AA && AA->pointsToConstantMemory(
1348 AliasAnalysis::Location(V, (*I)->getSize(),
1349 (*I)->getTBAAInfo())))
1353 // Otherwise assume conservatively.
1357 // Everything checks out.
1361 /// isConstantValuePHI - If the specified instruction is a PHI that always
1362 /// merges together the same virtual register, return the register, otherwise
1364 unsigned MachineInstr::isConstantValuePHI() const {
1367 assert(getNumOperands() >= 3 &&
1368 "It's illegal to have a PHI without source operands");
1370 unsigned Reg = getOperand(1).getReg();
1371 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1372 if (getOperand(i).getReg() != Reg)
1377 bool MachineInstr::hasUnmodeledSideEffects() const {
1378 if (hasProperty(MCID::UnmodeledSideEffects))
1380 if (isInlineAsm()) {
1381 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1382 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1389 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1391 bool MachineInstr::allDefsAreDead() const {
1392 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1393 const MachineOperand &MO = getOperand(i);
1394 if (!MO.isReg() || MO.isUse())
1402 /// copyImplicitOps - Copy implicit register operands from specified
1403 /// instruction to this instruction.
1404 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1405 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1407 const MachineOperand &MO = MI->getOperand(i);
1408 if (MO.isReg() && MO.isImplicit())
1413 void MachineInstr::dump() const {
1414 dbgs() << " " << *this;
1417 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1418 raw_ostream &CommentOS) {
1419 const LLVMContext &Ctx = MF->getFunction()->getContext();
1420 if (!DL.isUnknown()) { // Print source line info.
1421 DIScope Scope(DL.getScope(Ctx));
1422 // Omit the directory, because it's likely to be long and uninteresting.
1424 CommentOS << Scope.getFilename();
1426 CommentOS << "<unknown>";
1427 CommentOS << ':' << DL.getLine();
1428 if (DL.getCol() != 0)
1429 CommentOS << ':' << DL.getCol();
1430 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1431 if (!InlinedAtDL.isUnknown()) {
1432 CommentOS << " @[ ";
1433 printDebugLoc(InlinedAtDL, MF, CommentOS);
1439 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1440 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1441 const MachineFunction *MF = 0;
1442 const MachineRegisterInfo *MRI = 0;
1443 if (const MachineBasicBlock *MBB = getParent()) {
1444 MF = MBB->getParent();
1446 TM = &MF->getTarget();
1448 MRI = &MF->getRegInfo();
1451 // Save a list of virtual registers.
1452 SmallVector<unsigned, 8> VirtRegs;
1454 // Print explicitly defined operands on the left of an assignment syntax.
1455 unsigned StartOp = 0, e = getNumOperands();
1456 for (; StartOp < e && getOperand(StartOp).isReg() &&
1457 getOperand(StartOp).isDef() &&
1458 !getOperand(StartOp).isImplicit();
1460 if (StartOp != 0) OS << ", ";
1461 getOperand(StartOp).print(OS, TM);
1462 unsigned Reg = getOperand(StartOp).getReg();
1463 if (TargetRegisterInfo::isVirtualRegister(Reg))
1464 VirtRegs.push_back(Reg);
1470 // Print the opcode name.
1471 OS << getDesc().getName();
1473 // Print the rest of the operands.
1474 bool OmittedAnyCallClobbers = false;
1475 bool FirstOp = true;
1476 unsigned AsmDescOp = ~0u;
1477 unsigned AsmOpCount = 0;
1479 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1480 // Print asm string.
1482 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1484 // Print HasSideEffects, IsAlignStack
1485 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1486 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1487 OS << " [sideeffect]";
1488 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1489 OS << " [alignstack]";
1491 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1496 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1497 const MachineOperand &MO = getOperand(i);
1499 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1500 VirtRegs.push_back(MO.getReg());
1502 // Omit call-clobbered registers which aren't used anywhere. This makes
1503 // call instructions much less noisy on targets where calls clobber lots
1504 // of registers. Don't rely on MO.isDead() because we may be called before
1505 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1506 if (MF && isCall() &&
1507 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1508 unsigned Reg = MO.getReg();
1509 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1510 const MachineRegisterInfo &MRI = MF->getRegInfo();
1511 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1512 bool HasAliasLive = false;
1513 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1514 unsigned AliasReg = *Alias; ++Alias)
1515 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1516 HasAliasLive = true;
1519 if (!HasAliasLive) {
1520 OmittedAnyCallClobbers = true;
1527 if (FirstOp) FirstOp = false; else OS << ",";
1529 if (i < getDesc().NumOperands) {
1530 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1531 if (MCOI.isPredicate())
1533 if (MCOI.isOptionalDef())
1536 if (isDebugValue() && MO.isMetadata()) {
1537 // Pretty print DBG_VALUE instructions.
1538 const MDNode *MD = MO.getMetadata();
1539 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1540 OS << "!\"" << MDS->getString() << '\"';
1543 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1544 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1545 } else if (i == AsmDescOp && MO.isImm()) {
1546 // Pretty print the inline asm operand descriptor.
1547 OS << '$' << AsmOpCount++;
1548 unsigned Flag = MO.getImm();
1549 switch (InlineAsm::getKind(Flag)) {
1550 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1551 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1552 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1553 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1554 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1555 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1556 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1560 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1562 OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1564 OS << ":RC" << RCID;
1567 unsigned TiedTo = 0;
1568 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1569 OS << " tiedto:$" << TiedTo;
1573 // Compute the index of the next operand descriptor.
1574 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1579 // Briefly indicate whether any call clobbers were omitted.
1580 if (OmittedAnyCallClobbers) {
1581 if (!FirstOp) OS << ",";
1585 bool HaveSemi = false;
1587 if (!HaveSemi) OS << ";"; HaveSemi = true;
1590 if (Flags & FrameSetup)
1594 if (!memoperands_empty()) {
1595 if (!HaveSemi) OS << ";"; HaveSemi = true;
1598 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1601 if (llvm::next(i) != e)
1606 // Print the regclass of any virtual registers encountered.
1607 if (MRI && !VirtRegs.empty()) {
1608 if (!HaveSemi) OS << ";"; HaveSemi = true;
1609 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1610 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1611 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1612 for (unsigned j = i+1; j != VirtRegs.size();) {
1613 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1617 if (VirtRegs[i] != VirtRegs[j])
1618 OS << "," << PrintReg(VirtRegs[j]);
1619 VirtRegs.erase(VirtRegs.begin()+j);
1624 // Print debug location information.
1625 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1626 if (!HaveSemi) OS << ";"; HaveSemi = true;
1627 DIVariable DV(getOperand(e - 1).getMetadata());
1628 OS << " line no:" << DV.getLineNumber();
1629 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1630 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1631 if (!InlinedAtDL.isUnknown()) {
1632 OS << " inlined @[ ";
1633 printDebugLoc(InlinedAtDL, MF, OS);
1637 } else if (!debugLoc.isUnknown() && MF) {
1638 if (!HaveSemi) OS << ";"; HaveSemi = true;
1640 printDebugLoc(debugLoc, MF, OS);
1646 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1647 const TargetRegisterInfo *RegInfo,
1648 bool AddIfNotFound) {
1649 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1650 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1652 SmallVector<unsigned,4> DeadOps;
1653 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1654 MachineOperand &MO = getOperand(i);
1655 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1657 unsigned Reg = MO.getReg();
1661 if (Reg == IncomingReg) {
1664 // The register is already marked kill.
1666 if (isPhysReg && isRegTiedToDefOperand(i))
1667 // Two-address uses of physregs must not be marked kill.
1672 } else if (hasAliases && MO.isKill() &&
1673 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1674 // A super-register kill already exists.
1675 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1677 if (RegInfo->isSubRegister(IncomingReg, Reg))
1678 DeadOps.push_back(i);
1682 // Trim unneeded kill operands.
1683 while (!DeadOps.empty()) {
1684 unsigned OpIdx = DeadOps.back();
1685 if (getOperand(OpIdx).isImplicit())
1686 RemoveOperand(OpIdx);
1688 getOperand(OpIdx).setIsKill(false);
1692 // If not found, this means an alias of one of the operands is killed. Add a
1693 // new implicit operand if required.
1694 if (!Found && AddIfNotFound) {
1695 addOperand(MachineOperand::CreateReg(IncomingReg,
1704 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1705 const TargetRegisterInfo *RegInfo,
1706 bool AddIfNotFound) {
1707 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1708 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1710 SmallVector<unsigned,4> DeadOps;
1711 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1712 MachineOperand &MO = getOperand(i);
1713 if (!MO.isReg() || !MO.isDef())
1715 unsigned Reg = MO.getReg();
1719 if (Reg == IncomingReg) {
1722 } else if (hasAliases && MO.isDead() &&
1723 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1724 // There exists a super-register that's marked dead.
1725 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1727 if (RegInfo->getSubRegisters(IncomingReg) &&
1728 RegInfo->getSuperRegisters(Reg) &&
1729 RegInfo->isSubRegister(IncomingReg, Reg))
1730 DeadOps.push_back(i);
1734 // Trim unneeded dead operands.
1735 while (!DeadOps.empty()) {
1736 unsigned OpIdx = DeadOps.back();
1737 if (getOperand(OpIdx).isImplicit())
1738 RemoveOperand(OpIdx);
1740 getOperand(OpIdx).setIsDead(false);
1744 // If not found, this means an alias of one of the operands is dead. Add a
1745 // new implicit operand if required.
1746 if (Found || !AddIfNotFound)
1749 addOperand(MachineOperand::CreateReg(IncomingReg,
1757 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1758 const TargetRegisterInfo *RegInfo) {
1759 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1760 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1764 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1765 const MachineOperand &MO = getOperand(i);
1766 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1767 MO.getSubReg() == 0)
1771 addOperand(MachineOperand::CreateReg(IncomingReg,
1776 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1777 const TargetRegisterInfo &TRI) {
1778 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1779 MachineOperand &MO = getOperand(i);
1780 if (!MO.isReg() || !MO.isDef()) continue;
1781 unsigned Reg = MO.getReg();
1782 if (Reg == 0) continue;
1784 for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1785 E = UsedRegs.end(); I != E; ++I)
1786 if (TRI.regsOverlap(*I, Reg)) {
1790 // If there are no uses, including partial uses, the def is dead.
1791 if (Dead) MO.setIsDead();
1796 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1797 unsigned Hash = MI->getOpcode() * 37;
1798 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1799 const MachineOperand &MO = MI->getOperand(i);
1800 uint64_t Key = (uint64_t)MO.getType() << 32;
1801 switch (MO.getType()) {
1803 case MachineOperand::MO_Register:
1804 if (MO.isDef() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1805 continue; // Skip virtual register defs.
1808 case MachineOperand::MO_Immediate:
1811 case MachineOperand::MO_FrameIndex:
1812 case MachineOperand::MO_ConstantPoolIndex:
1813 case MachineOperand::MO_JumpTableIndex:
1814 Key |= MO.getIndex();
1816 case MachineOperand::MO_MachineBasicBlock:
1817 Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1819 case MachineOperand::MO_GlobalAddress:
1820 Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1822 case MachineOperand::MO_BlockAddress:
1823 Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1825 case MachineOperand::MO_MCSymbol:
1826 Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1829 Key += ~(Key << 32);
1831 Key += ~(Key << 13);
1835 Key += ~(Key << 27);
1837 Hash = (unsigned)Key + Hash * 37;
1842 void MachineInstr::emitError(StringRef Msg) const {
1843 // Find the source location cookie.
1844 unsigned LocCookie = 0;
1845 const MDNode *LocMD = 0;
1846 for (unsigned i = getNumOperands(); i != 0; --i) {
1847 if (getOperand(i-1).isMetadata() &&
1848 (LocMD = getOperand(i-1).getMetadata()) &&
1849 LocMD->getNumOperands() != 0) {
1850 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1851 LocCookie = CI->getZExtValue();
1857 if (const MachineBasicBlock *MBB = getParent())
1858 if (const MachineFunction *MF = MBB->getParent())
1859 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1860 report_fatal_error(Msg);