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/Type.h"
19 #include "llvm/Value.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetInstrDesc.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/DebugInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LeakDetector.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/FoldingSet.h"
37 #include "llvm/Metadata.h"
40 //===----------------------------------------------------------------------===//
41 // MachineOperand Implementation
42 //===----------------------------------------------------------------------===//
44 /// AddRegOperandToRegInfo - Add this register operand to the specified
45 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
46 /// explicitly nulled out.
47 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
48 assert(isReg() && "Can only add reg operand to use lists");
50 // If the reginfo pointer is null, just explicitly null out or next/prev
51 // pointers, to ensure they are not garbage.
53 Contents.Reg.Prev = 0;
54 Contents.Reg.Next = 0;
58 // Otherwise, add this operand to the head of the registers use/def list.
59 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
61 // For SSA values, we prefer to keep the definition at the start of the list.
62 // we do this by skipping over the definition if it is at the head of the
64 if (*Head && (*Head)->isDef())
65 Head = &(*Head)->Contents.Reg.Next;
67 Contents.Reg.Next = *Head;
68 if (Contents.Reg.Next) {
69 assert(getReg() == Contents.Reg.Next->getReg() &&
70 "Different regs on the same list!");
71 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
74 Contents.Reg.Prev = Head;
78 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
79 /// MachineRegisterInfo it is linked with.
80 void MachineOperand::RemoveRegOperandFromRegInfo() {
81 assert(isOnRegUseList() && "Reg operand is not on a use list");
82 // Unlink this from the doubly linked list of operands.
83 MachineOperand *NextOp = Contents.Reg.Next;
84 *Contents.Reg.Prev = NextOp;
86 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
87 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
89 Contents.Reg.Prev = 0;
90 Contents.Reg.Next = 0;
93 void MachineOperand::setReg(unsigned Reg) {
94 if (getReg() == Reg) return; // No change.
96 // Otherwise, we have to change the register. If this operand is embedded
97 // into a machine function, we need to update the old and new register's
99 if (MachineInstr *MI = getParent())
100 if (MachineBasicBlock *MBB = MI->getParent())
101 if (MachineFunction *MF = MBB->getParent()) {
102 RemoveRegOperandFromRegInfo();
103 Contents.Reg.RegNo = Reg;
104 AddRegOperandToRegInfo(&MF->getRegInfo());
108 // Otherwise, just change the register, no problem. :)
109 Contents.Reg.RegNo = Reg;
112 /// ChangeToImmediate - Replace this operand with a new immediate operand of
113 /// the specified value. If an operand is known to be an immediate already,
114 /// the setImm method should be used.
115 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
116 // If this operand is currently a register operand, and if this is in a
117 // function, deregister the operand from the register's use/def list.
118 if (isReg() && getParent() && getParent()->getParent() &&
119 getParent()->getParent()->getParent())
120 RemoveRegOperandFromRegInfo();
122 OpKind = MO_Immediate;
123 Contents.ImmVal = ImmVal;
126 /// ChangeToRegister - Replace this operand with a new register operand of
127 /// the specified value. If an operand is known to be an register already,
128 /// the setReg method should be used.
129 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
130 bool isKill, bool isDead, bool isUndef,
132 // If this operand is already a register operand, use setReg to update the
133 // register's use/def lists.
135 assert(!isEarlyClobber());
138 // Otherwise, change this to a register and set the reg#.
139 OpKind = MO_Register;
140 Contents.Reg.RegNo = Reg;
142 // If this operand is embedded in a function, add the operand to the
143 // register's use/def list.
144 if (MachineInstr *MI = getParent())
145 if (MachineBasicBlock *MBB = MI->getParent())
146 if (MachineFunction *MF = MBB->getParent())
147 AddRegOperandToRegInfo(&MF->getRegInfo());
155 IsEarlyClobber = false;
160 /// isIdenticalTo - Return true if this operand is identical to the specified
162 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
163 if (getType() != Other.getType() ||
164 getTargetFlags() != Other.getTargetFlags())
168 default: llvm_unreachable("Unrecognized operand type");
169 case MachineOperand::MO_Register:
170 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
171 getSubReg() == Other.getSubReg();
172 case MachineOperand::MO_Immediate:
173 return getImm() == Other.getImm();
174 case MachineOperand::MO_FPImmediate:
175 return getFPImm() == Other.getFPImm();
176 case MachineOperand::MO_MachineBasicBlock:
177 return getMBB() == Other.getMBB();
178 case MachineOperand::MO_FrameIndex:
179 return getIndex() == Other.getIndex();
180 case MachineOperand::MO_ConstantPoolIndex:
181 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
182 case MachineOperand::MO_JumpTableIndex:
183 return getIndex() == Other.getIndex();
184 case MachineOperand::MO_GlobalAddress:
185 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
186 case MachineOperand::MO_ExternalSymbol:
187 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
188 getOffset() == Other.getOffset();
189 case MachineOperand::MO_BlockAddress:
190 return getBlockAddress() == Other.getBlockAddress();
194 /// print - Print the specified machine operand.
196 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
197 // If the instruction is embedded into a basic block, we can find the
198 // target info for the instruction.
200 if (const MachineInstr *MI = getParent())
201 if (const MachineBasicBlock *MBB = MI->getParent())
202 if (const MachineFunction *MF = MBB->getParent())
203 TM = &MF->getTarget();
206 case MachineOperand::MO_Register:
207 if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
208 OS << "%reg" << getReg();
211 OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
213 OS << "%physreg" << getReg();
216 if (getSubReg() != 0)
217 OS << ':' << getSubReg();
219 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
222 bool NeedComma = false;
224 if (NeedComma) OS << ',';
225 if (isEarlyClobber())
226 OS << "earlyclobber,";
231 } else if (isImplicit()) {
236 if (isKill() || isDead() || isUndef()) {
237 if (NeedComma) OS << ',';
238 if (isKill()) OS << "kill";
239 if (isDead()) OS << "dead";
241 if (isKill() || isDead())
249 case MachineOperand::MO_Immediate:
252 case MachineOperand::MO_FPImmediate:
253 if (getFPImm()->getType()->isFloatTy())
254 OS << getFPImm()->getValueAPF().convertToFloat();
256 OS << getFPImm()->getValueAPF().convertToDouble();
258 case MachineOperand::MO_MachineBasicBlock:
259 OS << "<BB#" << getMBB()->getNumber() << ">";
261 case MachineOperand::MO_FrameIndex:
262 OS << "<fi#" << getIndex() << '>';
264 case MachineOperand::MO_ConstantPoolIndex:
265 OS << "<cp#" << getIndex();
266 if (getOffset()) OS << "+" << getOffset();
269 case MachineOperand::MO_JumpTableIndex:
270 OS << "<jt#" << getIndex() << '>';
272 case MachineOperand::MO_GlobalAddress:
274 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
275 if (getOffset()) OS << "+" << getOffset();
278 case MachineOperand::MO_ExternalSymbol:
279 OS << "<es:" << getSymbolName();
280 if (getOffset()) OS << "+" << getOffset();
283 case MachineOperand::MO_BlockAddress:
285 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
288 case MachineOperand::MO_Metadata:
290 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
294 llvm_unreachable("Unrecognized operand type");
297 if (unsigned TF = getTargetFlags())
298 OS << "[TF=" << TF << ']';
301 //===----------------------------------------------------------------------===//
302 // MachineMemOperand Implementation
303 //===----------------------------------------------------------------------===//
305 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
306 int64_t o, uint64_t s, unsigned int a)
307 : Offset(o), Size(s), V(v),
308 Flags((f & 7) | ((Log2_32(a) + 1) << 3)) {
309 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
310 assert((isLoad() || isStore()) && "Not a load/store!");
313 /// Profile - Gather unique data for the object.
315 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
316 ID.AddInteger(Offset);
319 ID.AddInteger(Flags);
322 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
323 // The Value and Offset may differ due to CSE. But the flags and size
324 // should be the same.
325 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
326 assert(MMO->getSize() == getSize() && "Size mismatch!");
328 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
329 // Update the alignment value.
330 Flags = (Flags & 7) | ((Log2_32(MMO->getBaseAlignment()) + 1) << 3);
331 // Also update the base and offset, because the new alignment may
332 // not be applicable with the old ones.
334 Offset = MMO->getOffset();
338 /// getAlignment - Return the minimum known alignment in bytes of the
339 /// actual memory reference.
340 uint64_t MachineMemOperand::getAlignment() const {
341 return MinAlign(getBaseAlignment(), getOffset());
344 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
345 assert((MMO.isLoad() || MMO.isStore()) &&
346 "SV has to be a load, store or both.");
348 if (MMO.isVolatile())
357 // Print the address information.
362 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
364 // If the alignment of the memory reference itself differs from the alignment
365 // of the base pointer, print the base alignment explicitly, next to the base
367 if (MMO.getBaseAlignment() != MMO.getAlignment())
368 OS << "(align=" << MMO.getBaseAlignment() << ")";
370 if (MMO.getOffset() != 0)
371 OS << "+" << MMO.getOffset();
374 // Print the alignment of the reference.
375 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
376 MMO.getBaseAlignment() != MMO.getSize())
377 OS << "(align=" << MMO.getAlignment() << ")";
382 //===----------------------------------------------------------------------===//
383 // MachineInstr Implementation
384 //===----------------------------------------------------------------------===//
386 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
387 /// TID NULL and no operands.
388 MachineInstr::MachineInstr()
389 : TID(0), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
390 Parent(0), debugLoc(DebugLoc::getUnknownLoc()) {
391 // Make sure that we get added to a machine basicblock
392 LeakDetector::addGarbageObject(this);
395 void MachineInstr::addImplicitDefUseOperands() {
396 if (TID->ImplicitDefs)
397 for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
398 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
399 if (TID->ImplicitUses)
400 for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
401 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
404 /// MachineInstr ctor - This constructor create a MachineInstr and add the
405 /// implicit operands. It reserves space for number of operands specified by
406 /// TargetInstrDesc or the numOperands if it is not zero. (for
407 /// instructions with variable number of operands).
408 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
409 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
410 MemRefs(0), MemRefsEnd(0), Parent(0),
411 debugLoc(DebugLoc::getUnknownLoc()) {
412 if (!NoImp && TID->getImplicitDefs())
413 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
415 if (!NoImp && TID->getImplicitUses())
416 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
418 Operands.reserve(NumImplicitOps + TID->getNumOperands());
420 addImplicitDefUseOperands();
421 // Make sure that we get added to a machine basicblock
422 LeakDetector::addGarbageObject(this);
425 /// MachineInstr ctor - As above, but with a DebugLoc.
426 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
428 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
429 Parent(0), debugLoc(dl) {
430 if (!NoImp && TID->getImplicitDefs())
431 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
433 if (!NoImp && TID->getImplicitUses())
434 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
436 Operands.reserve(NumImplicitOps + TID->getNumOperands());
438 addImplicitDefUseOperands();
439 // Make sure that we get added to a machine basicblock
440 LeakDetector::addGarbageObject(this);
443 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
444 /// that the MachineInstr is created and added to the end of the specified
447 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
448 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
449 MemRefs(0), MemRefsEnd(0), Parent(0),
450 debugLoc(DebugLoc::getUnknownLoc()) {
451 assert(MBB && "Cannot use inserting ctor with null basic block!");
452 if (TID->ImplicitDefs)
453 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
455 if (TID->ImplicitUses)
456 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
458 Operands.reserve(NumImplicitOps + TID->getNumOperands());
459 addImplicitDefUseOperands();
460 // Make sure that we get added to a machine basicblock
461 LeakDetector::addGarbageObject(this);
462 MBB->push_back(this); // Add instruction to end of basic block!
465 /// MachineInstr ctor - As above, but with a DebugLoc.
467 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
468 const TargetInstrDesc &tid)
469 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
470 Parent(0), debugLoc(dl) {
471 assert(MBB && "Cannot use inserting ctor with null basic block!");
472 if (TID->ImplicitDefs)
473 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
475 if (TID->ImplicitUses)
476 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
478 Operands.reserve(NumImplicitOps + TID->getNumOperands());
479 addImplicitDefUseOperands();
480 // Make sure that we get added to a machine basicblock
481 LeakDetector::addGarbageObject(this);
482 MBB->push_back(this); // Add instruction to end of basic block!
485 /// MachineInstr ctor - Copies MachineInstr arg exactly
487 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
488 : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
489 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
490 Parent(0), debugLoc(MI.getDebugLoc()) {
491 Operands.reserve(MI.getNumOperands());
494 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
495 addOperand(MI.getOperand(i));
496 NumImplicitOps = MI.NumImplicitOps;
498 // Set parent to null.
501 LeakDetector::addGarbageObject(this);
504 MachineInstr::~MachineInstr() {
505 LeakDetector::removeGarbageObject(this);
507 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
508 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
509 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
510 "Reg operand def/use list corrupted");
515 /// getRegInfo - If this instruction is embedded into a MachineFunction,
516 /// return the MachineRegisterInfo object for the current function, otherwise
518 MachineRegisterInfo *MachineInstr::getRegInfo() {
519 if (MachineBasicBlock *MBB = getParent())
520 return &MBB->getParent()->getRegInfo();
524 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
525 /// this instruction from their respective use lists. This requires that the
526 /// operands already be on their use lists.
527 void MachineInstr::RemoveRegOperandsFromUseLists() {
528 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
529 if (Operands[i].isReg())
530 Operands[i].RemoveRegOperandFromRegInfo();
534 /// AddRegOperandsToUseLists - Add all of the register operands in
535 /// this instruction from their respective use lists. This requires that the
536 /// operands not be on their use lists yet.
537 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
538 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
539 if (Operands[i].isReg())
540 Operands[i].AddRegOperandToRegInfo(&RegInfo);
545 /// addOperand - Add the specified operand to the instruction. If it is an
546 /// implicit operand, it is added to the end of the operand list. If it is
547 /// an explicit operand it is added at the end of the explicit operand list
548 /// (before the first implicit operand).
549 void MachineInstr::addOperand(const MachineOperand &Op) {
550 bool isImpReg = Op.isReg() && Op.isImplicit();
551 assert((isImpReg || !OperandsComplete()) &&
552 "Trying to add an operand to a machine instr that is already done!");
554 MachineRegisterInfo *RegInfo = getRegInfo();
556 // If we are adding the operand to the end of the list, our job is simpler.
557 // This is true most of the time, so this is a reasonable optimization.
558 if (isImpReg || NumImplicitOps == 0) {
559 // We can only do this optimization if we know that the operand list won't
561 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
562 Operands.push_back(Op);
564 // Set the parent of the operand.
565 Operands.back().ParentMI = this;
567 // If the operand is a register, update the operand's use list.
569 Operands.back().AddRegOperandToRegInfo(RegInfo);
570 // If the register operand is flagged as early, mark the operand as such
571 unsigned OpNo = Operands.size() - 1;
572 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
573 Operands[OpNo].setIsEarlyClobber(true);
579 // Otherwise, we have to insert a real operand before any implicit ones.
580 unsigned OpNo = Operands.size()-NumImplicitOps;
582 // If this instruction isn't embedded into a function, then we don't need to
583 // update any operand lists.
585 // Simple insertion, no reginfo update needed for other register operands.
586 Operands.insert(Operands.begin()+OpNo, Op);
587 Operands[OpNo].ParentMI = this;
589 // Do explicitly set the reginfo for this operand though, to ensure the
590 // next/prev fields are properly nulled out.
591 if (Operands[OpNo].isReg()) {
592 Operands[OpNo].AddRegOperandToRegInfo(0);
593 // If the register operand is flagged as early, mark the operand as such
594 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
595 Operands[OpNo].setIsEarlyClobber(true);
598 } else if (Operands.size()+1 <= Operands.capacity()) {
599 // Otherwise, we have to remove register operands from their register use
600 // list, add the operand, then add the register operands back to their use
601 // list. This also must handle the case when the operand list reallocates
602 // to somewhere else.
604 // If insertion of this operand won't cause reallocation of the operand
605 // list, just remove the implicit operands, add the operand, then re-add all
606 // the rest of the operands.
607 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
608 assert(Operands[i].isReg() && "Should only be an implicit reg!");
609 Operands[i].RemoveRegOperandFromRegInfo();
612 // Add the operand. If it is a register, add it to the reg list.
613 Operands.insert(Operands.begin()+OpNo, Op);
614 Operands[OpNo].ParentMI = this;
616 if (Operands[OpNo].isReg()) {
617 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
618 // If the register operand is flagged as early, mark the operand as such
619 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
620 Operands[OpNo].setIsEarlyClobber(true);
623 // Re-add all the implicit ops.
624 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
625 assert(Operands[i].isReg() && "Should only be an implicit reg!");
626 Operands[i].AddRegOperandToRegInfo(RegInfo);
629 // Otherwise, we will be reallocating the operand list. Remove all reg
630 // operands from their list, then readd them after the operand list is
632 RemoveRegOperandsFromUseLists();
634 Operands.insert(Operands.begin()+OpNo, Op);
635 Operands[OpNo].ParentMI = this;
637 // Re-add all the operands.
638 AddRegOperandsToUseLists(*RegInfo);
640 // If the register operand is flagged as early, mark the operand as such
641 if (Operands[OpNo].isReg()
642 && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
643 Operands[OpNo].setIsEarlyClobber(true);
647 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
648 /// fewer operand than it started with.
650 void MachineInstr::RemoveOperand(unsigned OpNo) {
651 assert(OpNo < Operands.size() && "Invalid operand number");
653 // Special case removing the last one.
654 if (OpNo == Operands.size()-1) {
655 // If needed, remove from the reg def/use list.
656 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
657 Operands.back().RemoveRegOperandFromRegInfo();
663 // Otherwise, we are removing an interior operand. If we have reginfo to
664 // update, remove all operands that will be shifted down from their reg lists,
665 // move everything down, then re-add them.
666 MachineRegisterInfo *RegInfo = getRegInfo();
668 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
669 if (Operands[i].isReg())
670 Operands[i].RemoveRegOperandFromRegInfo();
674 Operands.erase(Operands.begin()+OpNo);
677 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
678 if (Operands[i].isReg())
679 Operands[i].AddRegOperandToRegInfo(RegInfo);
684 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
685 /// This function should be used only occasionally. The setMemRefs function
686 /// is the primary method for setting up a MachineInstr's MemRefs list.
687 void MachineInstr::addMemOperand(MachineFunction &MF,
688 MachineMemOperand *MO) {
689 mmo_iterator OldMemRefs = MemRefs;
690 mmo_iterator OldMemRefsEnd = MemRefsEnd;
692 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
693 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
694 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
696 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
697 NewMemRefs[NewNum - 1] = MO;
699 MemRefs = NewMemRefs;
700 MemRefsEnd = NewMemRefsEnd;
703 /// removeFromParent - This method unlinks 'this' from the containing basic
704 /// block, and returns it, but does not delete it.
705 MachineInstr *MachineInstr::removeFromParent() {
706 assert(getParent() && "Not embedded in a basic block!");
707 getParent()->remove(this);
712 /// eraseFromParent - This method unlinks 'this' from the containing basic
713 /// block, and deletes it.
714 void MachineInstr::eraseFromParent() {
715 assert(getParent() && "Not embedded in a basic block!");
716 getParent()->erase(this);
720 /// OperandComplete - Return true if it's illegal to add a new operand
722 bool MachineInstr::OperandsComplete() const {
723 unsigned short NumOperands = TID->getNumOperands();
724 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
725 return true; // Broken: we have all the operands of this instruction!
729 /// getNumExplicitOperands - Returns the number of non-implicit operands.
731 unsigned MachineInstr::getNumExplicitOperands() const {
732 unsigned NumOperands = TID->getNumOperands();
733 if (!TID->isVariadic())
736 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
737 const MachineOperand &MO = getOperand(i);
738 if (!MO.isReg() || !MO.isImplicit())
745 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
746 /// the specific register or -1 if it is not found. It further tightens
747 /// the search criteria to a use that kills the register if isKill is true.
748 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
749 const TargetRegisterInfo *TRI) const {
750 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
751 const MachineOperand &MO = getOperand(i);
752 if (!MO.isReg() || !MO.isUse())
754 unsigned MOReg = MO.getReg();
759 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
760 TargetRegisterInfo::isPhysicalRegister(Reg) &&
761 TRI->isSubRegister(MOReg, Reg)))
762 if (!isKill || MO.isKill())
768 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
769 /// the specified register or -1 if it is not found. If isDead is true, defs
770 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
771 /// also checks if there is a def of a super-register.
772 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
773 const TargetRegisterInfo *TRI) const {
774 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
775 const MachineOperand &MO = getOperand(i);
776 if (!MO.isReg() || !MO.isDef())
778 unsigned MOReg = MO.getReg();
781 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
782 TargetRegisterInfo::isPhysicalRegister(Reg) &&
783 TRI->isSubRegister(MOReg, Reg)))
784 if (!isDead || MO.isDead())
790 /// findFirstPredOperandIdx() - Find the index of the first operand in the
791 /// operand list that is used to represent the predicate. It returns -1 if
793 int MachineInstr::findFirstPredOperandIdx() const {
794 const TargetInstrDesc &TID = getDesc();
795 if (TID.isPredicable()) {
796 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
797 if (TID.OpInfo[i].isPredicate())
804 /// isRegTiedToUseOperand - Given the index of a register def operand,
805 /// check if the register def is tied to a source operand, due to either
806 /// two-address elimination or inline assembly constraints. Returns the
807 /// first tied use operand index by reference is UseOpIdx is not null.
809 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
811 assert(DefOpIdx >= 2);
812 const MachineOperand &MO = getOperand(DefOpIdx);
813 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
815 // Determine the actual operand index that corresponds to this index.
817 unsigned DefPart = 0;
818 for (unsigned i = 1, e = getNumOperands(); i < e; ) {
819 const MachineOperand &FMO = getOperand(i);
820 // After the normal asm operands there may be additional imp-def regs.
823 // Skip over this def.
824 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
825 unsigned PrevDef = i + 1;
826 i = PrevDef + NumOps;
828 DefPart = DefOpIdx - PrevDef;
833 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
834 const MachineOperand &FMO = getOperand(i);
837 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
840 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
843 *UseOpIdx = (unsigned)i + 1 + DefPart;
850 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
851 const TargetInstrDesc &TID = getDesc();
852 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
853 const MachineOperand &MO = getOperand(i);
854 if (MO.isReg() && MO.isUse() &&
855 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
857 *UseOpIdx = (unsigned)i;
864 /// isRegTiedToDefOperand - Return true if the operand of the specified index
865 /// is a register use and it is tied to an def operand. It also returns the def
866 /// operand index by reference.
868 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
870 const MachineOperand &MO = getOperand(UseOpIdx);
871 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
874 // Find the flag operand corresponding to UseOpIdx
875 unsigned FlagIdx, NumOps=0;
876 for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
877 const MachineOperand &UFMO = getOperand(FlagIdx);
878 // After the normal asm operands there may be additional imp-def regs.
881 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
882 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
883 if (UseOpIdx < FlagIdx+NumOps+1)
886 if (FlagIdx >= UseOpIdx)
888 const MachineOperand &UFMO = getOperand(FlagIdx);
890 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
895 // Remember to adjust the index. First operand is asm string, then there
896 // is a flag for each.
898 const MachineOperand &FMO = getOperand(DefIdx);
900 // Skip over this def.
901 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
904 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
910 const TargetInstrDesc &TID = getDesc();
911 if (UseOpIdx >= TID.getNumOperands())
913 const MachineOperand &MO = getOperand(UseOpIdx);
914 if (!MO.isReg() || !MO.isUse())
916 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
920 *DefOpIdx = (unsigned)DefIdx;
924 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
926 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
927 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
928 const MachineOperand &MO = MI->getOperand(i);
929 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
931 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
932 MachineOperand &MOp = getOperand(j);
933 if (!MOp.isIdenticalTo(MO))
944 /// copyPredicates - Copies predicate operand(s) from MI.
945 void MachineInstr::copyPredicates(const MachineInstr *MI) {
946 const TargetInstrDesc &TID = MI->getDesc();
947 if (!TID.isPredicable())
949 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
950 if (TID.OpInfo[i].isPredicate()) {
951 // Predicated operands must be last operands.
952 addOperand(MI->getOperand(i));
957 /// isSafeToMove - Return true if it is safe to move this instruction. If
958 /// SawStore is set to true, it means that there is a store (or call) between
959 /// the instruction's location and its intended destination.
960 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
962 AliasAnalysis *AA) const {
963 // Ignore stuff that we obviously can't move.
964 if (TID->mayStore() || TID->isCall()) {
968 if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
971 // See if this instruction does a load. If so, we have to guarantee that the
972 // loaded value doesn't change between the load and the its intended
973 // destination. The check for isInvariantLoad gives the targe the chance to
974 // classify the load as always returning a constant, e.g. a constant pool
976 if (TID->mayLoad() && !isInvariantLoad(AA))
977 // Otherwise, this is a real load. If there is a store between the load and
978 // end of block, or if the load is volatile, we can't move it.
979 return !SawStore && !hasVolatileMemoryRef();
984 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
985 /// instruction which defined the specified register instead of copying it.
986 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
988 AliasAnalysis *AA) const {
989 bool SawStore = false;
990 if (!TII->isTriviallyReMaterializable(this, AA) ||
991 !isSafeToMove(TII, SawStore, AA))
993 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
994 const MachineOperand &MO = getOperand(i);
997 // FIXME: For now, do not remat any instruction with register operands.
998 // Later on, we can loosen the restriction is the register operands have
999 // not been modified between the def and use. Note, this is different from
1000 // MachineSink because the code is no longer in two-address form (at least
1004 else if (!MO.isDead() && MO.getReg() != DstReg)
1010 /// hasVolatileMemoryRef - Return true if this instruction may have a
1011 /// volatile memory reference, or if the information describing the
1012 /// memory reference is not available. Return false if it is known to
1013 /// have no volatile memory references.
1014 bool MachineInstr::hasVolatileMemoryRef() const {
1015 // An instruction known never to access memory won't have a volatile access.
1016 if (!TID->mayStore() &&
1019 !TID->hasUnmodeledSideEffects())
1022 // Otherwise, if the instruction has no memory reference information,
1023 // conservatively assume it wasn't preserved.
1024 if (memoperands_empty())
1027 // Check the memory reference information for volatile references.
1028 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1029 if ((*I)->isVolatile())
1035 /// isInvariantLoad - Return true if this instruction is loading from a
1036 /// location whose value is invariant across the function. For example,
1037 /// loading a value from the constant pool or from the argument area
1038 /// of a function if it does not change. This should only return true of
1039 /// *all* loads the instruction does are invariant (if it does multiple loads).
1040 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1041 // If the instruction doesn't load at all, it isn't an invariant load.
1042 if (!TID->mayLoad())
1045 // If the instruction has lost its memoperands, conservatively assume that
1046 // it may not be an invariant load.
1047 if (memoperands_empty())
1050 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1052 for (mmo_iterator I = memoperands_begin(),
1053 E = memoperands_end(); I != E; ++I) {
1054 if ((*I)->isVolatile()) return false;
1055 if ((*I)->isStore()) return false;
1057 if (const Value *V = (*I)->getValue()) {
1058 // A load from a constant PseudoSourceValue is invariant.
1059 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1060 if (PSV->isConstant(MFI))
1062 // If we have an AliasAnalysis, ask it whether the memory is constant.
1063 if (AA && AA->pointsToConstantMemory(V))
1067 // Otherwise assume conservatively.
1071 // Everything checks out.
1075 /// isConstantValuePHI - If the specified instruction is a PHI that always
1076 /// merges together the same virtual register, return the register, otherwise
1078 unsigned MachineInstr::isConstantValuePHI() const {
1081 assert(getNumOperands() >= 3 &&
1082 "It's illegal to have a PHI without source operands");
1084 unsigned Reg = getOperand(1).getReg();
1085 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1086 if (getOperand(i).getReg() != Reg)
1091 void MachineInstr::dump() const {
1092 dbgs() << " " << *this;
1095 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1096 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1097 const MachineFunction *MF = 0;
1098 if (const MachineBasicBlock *MBB = getParent()) {
1099 MF = MBB->getParent();
1101 TM = &MF->getTarget();
1104 // Print explicitly defined operands on the left of an assignment syntax.
1105 unsigned StartOp = 0, e = getNumOperands();
1106 for (; StartOp < e && getOperand(StartOp).isReg() &&
1107 getOperand(StartOp).isDef() &&
1108 !getOperand(StartOp).isImplicit();
1110 if (StartOp != 0) OS << ", ";
1111 getOperand(StartOp).print(OS, TM);
1117 // Print the opcode name.
1118 OS << getDesc().getName();
1120 // Print the rest of the operands.
1121 bool OmittedAnyCallClobbers = false;
1122 bool FirstOp = true;
1123 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1124 const MachineOperand &MO = getOperand(i);
1126 // Omit call-clobbered registers which aren't used anywhere. This makes
1127 // call instructions much less noisy on targets where calls clobber lots
1128 // of registers. Don't rely on MO.isDead() because we may be called before
1129 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1130 if (MF && getDesc().isCall() &&
1131 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1132 unsigned Reg = MO.getReg();
1133 if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1134 const MachineRegisterInfo &MRI = MF->getRegInfo();
1135 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1136 bool HasAliasLive = false;
1137 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1138 unsigned AliasReg = *Alias; ++Alias)
1139 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1140 HasAliasLive = true;
1143 if (!HasAliasLive) {
1144 OmittedAnyCallClobbers = true;
1151 if (FirstOp) FirstOp = false; else OS << ",";
1153 if (i < getDesc().NumOperands) {
1154 const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1155 if (TOI.isPredicate())
1157 if (TOI.isOptionalDef())
1163 // Briefly indicate whether any call clobbers were omitted.
1164 if (OmittedAnyCallClobbers) {
1165 if (!FirstOp) OS << ",";
1169 bool HaveSemi = false;
1170 if (!memoperands_empty()) {
1171 if (!HaveSemi) OS << ";"; HaveSemi = true;
1174 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1182 if (!debugLoc.isUnknown() && MF) {
1183 if (!HaveSemi) OS << ";";
1185 // TODO: print InlinedAtLoc information
1187 DILocation DLT = MF->getDILocation(debugLoc);
1188 DIScope Scope = DLT.getScope();
1190 // Omit the directory, since it's usually long and uninteresting.
1191 if (!Scope.isNull())
1192 OS << Scope.getFilename();
1195 OS << ':' << DLT.getLineNumber();
1196 if (DLT.getColumnNumber() != 0)
1197 OS << ':' << DLT.getColumnNumber();
1203 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1204 const TargetRegisterInfo *RegInfo,
1205 bool AddIfNotFound) {
1206 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1207 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1209 SmallVector<unsigned,4> DeadOps;
1210 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1211 MachineOperand &MO = getOperand(i);
1212 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1214 unsigned Reg = MO.getReg();
1218 if (Reg == IncomingReg) {
1221 // The register is already marked kill.
1223 if (isPhysReg && isRegTiedToDefOperand(i))
1224 // Two-address uses of physregs must not be marked kill.
1229 } else if (hasAliases && MO.isKill() &&
1230 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1231 // A super-register kill already exists.
1232 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1234 if (RegInfo->isSubRegister(IncomingReg, Reg))
1235 DeadOps.push_back(i);
1239 // Trim unneeded kill operands.
1240 while (!DeadOps.empty()) {
1241 unsigned OpIdx = DeadOps.back();
1242 if (getOperand(OpIdx).isImplicit())
1243 RemoveOperand(OpIdx);
1245 getOperand(OpIdx).setIsKill(false);
1249 // If not found, this means an alias of one of the operands is killed. Add a
1250 // new implicit operand if required.
1251 if (!Found && AddIfNotFound) {
1252 addOperand(MachineOperand::CreateReg(IncomingReg,
1261 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1262 const TargetRegisterInfo *RegInfo,
1263 bool AddIfNotFound) {
1264 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1265 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1267 SmallVector<unsigned,4> DeadOps;
1268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1269 MachineOperand &MO = getOperand(i);
1270 if (!MO.isReg() || !MO.isDef())
1272 unsigned Reg = MO.getReg();
1276 if (Reg == IncomingReg) {
1279 // The register is already marked dead.
1284 } else if (hasAliases && MO.isDead() &&
1285 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1286 // There exists a super-register that's marked dead.
1287 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1289 if (RegInfo->getSubRegisters(IncomingReg) &&
1290 RegInfo->getSuperRegisters(Reg) &&
1291 RegInfo->isSubRegister(IncomingReg, Reg))
1292 DeadOps.push_back(i);
1296 // Trim unneeded dead operands.
1297 while (!DeadOps.empty()) {
1298 unsigned OpIdx = DeadOps.back();
1299 if (getOperand(OpIdx).isImplicit())
1300 RemoveOperand(OpIdx);
1302 getOperand(OpIdx).setIsDead(false);
1306 // If not found, this means an alias of one of the operands is dead. Add a
1307 // new implicit operand if required.
1308 if (Found || !AddIfNotFound)
1311 addOperand(MachineOperand::CreateReg(IncomingReg,
1319 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1320 const TargetRegisterInfo *RegInfo) {
1321 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1322 if (!MO || MO->getSubReg())
1323 addOperand(MachineOperand::CreateReg(IncomingReg,