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 & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)) {
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 & ((1 << MOMaxBits) - 1)) |
331 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
332 // Also update the base and offset, because the new alignment may
333 // not be applicable with the old ones.
335 Offset = MMO->getOffset();
339 /// getAlignment - Return the minimum known alignment in bytes of the
340 /// actual memory reference.
341 uint64_t MachineMemOperand::getAlignment() const {
342 return MinAlign(getBaseAlignment(), getOffset());
345 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
346 assert((MMO.isLoad() || MMO.isStore()) &&
347 "SV has to be a load, store or both.");
349 if (MMO.isVolatile())
358 // Print the address information.
363 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
365 // If the alignment of the memory reference itself differs from the alignment
366 // of the base pointer, print the base alignment explicitly, next to the base
368 if (MMO.getBaseAlignment() != MMO.getAlignment())
369 OS << "(align=" << MMO.getBaseAlignment() << ")";
371 if (MMO.getOffset() != 0)
372 OS << "+" << MMO.getOffset();
375 // Print the alignment of the reference.
376 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
377 MMO.getBaseAlignment() != MMO.getSize())
378 OS << "(align=" << MMO.getAlignment() << ")";
383 //===----------------------------------------------------------------------===//
384 // MachineInstr Implementation
385 //===----------------------------------------------------------------------===//
387 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
388 /// TID NULL and no operands.
389 MachineInstr::MachineInstr()
390 : TID(0), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
391 Parent(0), debugLoc(DebugLoc::getUnknownLoc()) {
392 // Make sure that we get added to a machine basicblock
393 LeakDetector::addGarbageObject(this);
396 void MachineInstr::addImplicitDefUseOperands() {
397 if (TID->ImplicitDefs)
398 for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
399 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
400 if (TID->ImplicitUses)
401 for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
402 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
405 /// MachineInstr ctor - This constructor create a MachineInstr and add the
406 /// implicit operands. It reserves space for number of operands specified by
407 /// TargetInstrDesc or the numOperands if it is not zero. (for
408 /// instructions with variable number of operands).
409 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
410 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
411 MemRefs(0), MemRefsEnd(0), Parent(0),
412 debugLoc(DebugLoc::getUnknownLoc()) {
413 if (!NoImp && TID->getImplicitDefs())
414 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
416 if (!NoImp && TID->getImplicitUses())
417 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
419 Operands.reserve(NumImplicitOps + TID->getNumOperands());
421 addImplicitDefUseOperands();
422 // Make sure that we get added to a machine basicblock
423 LeakDetector::addGarbageObject(this);
426 /// MachineInstr ctor - As above, but with a DebugLoc.
427 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
429 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
430 Parent(0), debugLoc(dl) {
431 if (!NoImp && TID->getImplicitDefs())
432 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
434 if (!NoImp && TID->getImplicitUses())
435 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
437 Operands.reserve(NumImplicitOps + TID->getNumOperands());
439 addImplicitDefUseOperands();
440 // Make sure that we get added to a machine basicblock
441 LeakDetector::addGarbageObject(this);
444 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
445 /// that the MachineInstr is created and added to the end of the specified
448 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
449 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
450 MemRefs(0), MemRefsEnd(0), Parent(0),
451 debugLoc(DebugLoc::getUnknownLoc()) {
452 assert(MBB && "Cannot use inserting ctor with null basic block!");
453 if (TID->ImplicitDefs)
454 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
456 if (TID->ImplicitUses)
457 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
459 Operands.reserve(NumImplicitOps + TID->getNumOperands());
460 addImplicitDefUseOperands();
461 // Make sure that we get added to a machine basicblock
462 LeakDetector::addGarbageObject(this);
463 MBB->push_back(this); // Add instruction to end of basic block!
466 /// MachineInstr ctor - As above, but with a DebugLoc.
468 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
469 const TargetInstrDesc &tid)
470 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
471 Parent(0), debugLoc(dl) {
472 assert(MBB && "Cannot use inserting ctor with null basic block!");
473 if (TID->ImplicitDefs)
474 for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
476 if (TID->ImplicitUses)
477 for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
479 Operands.reserve(NumImplicitOps + TID->getNumOperands());
480 addImplicitDefUseOperands();
481 // Make sure that we get added to a machine basicblock
482 LeakDetector::addGarbageObject(this);
483 MBB->push_back(this); // Add instruction to end of basic block!
486 /// MachineInstr ctor - Copies MachineInstr arg exactly
488 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
489 : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
490 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
491 Parent(0), debugLoc(MI.getDebugLoc()) {
492 Operands.reserve(MI.getNumOperands());
495 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
496 addOperand(MI.getOperand(i));
497 NumImplicitOps = MI.NumImplicitOps;
499 // Set parent to null.
502 LeakDetector::addGarbageObject(this);
505 MachineInstr::~MachineInstr() {
506 LeakDetector::removeGarbageObject(this);
508 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
509 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
510 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
511 "Reg operand def/use list corrupted");
516 /// getRegInfo - If this instruction is embedded into a MachineFunction,
517 /// return the MachineRegisterInfo object for the current function, otherwise
519 MachineRegisterInfo *MachineInstr::getRegInfo() {
520 if (MachineBasicBlock *MBB = getParent())
521 return &MBB->getParent()->getRegInfo();
525 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
526 /// this instruction from their respective use lists. This requires that the
527 /// operands already be on their use lists.
528 void MachineInstr::RemoveRegOperandsFromUseLists() {
529 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
530 if (Operands[i].isReg())
531 Operands[i].RemoveRegOperandFromRegInfo();
535 /// AddRegOperandsToUseLists - Add all of the register operands in
536 /// this instruction from their respective use lists. This requires that the
537 /// operands not be on their use lists yet.
538 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
539 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
540 if (Operands[i].isReg())
541 Operands[i].AddRegOperandToRegInfo(&RegInfo);
546 /// addOperand - Add the specified operand to the instruction. If it is an
547 /// implicit operand, it is added to the end of the operand list. If it is
548 /// an explicit operand it is added at the end of the explicit operand list
549 /// (before the first implicit operand).
550 void MachineInstr::addOperand(const MachineOperand &Op) {
551 bool isImpReg = Op.isReg() && Op.isImplicit();
552 assert((isImpReg || !OperandsComplete()) &&
553 "Trying to add an operand to a machine instr that is already done!");
555 MachineRegisterInfo *RegInfo = getRegInfo();
557 // If we are adding the operand to the end of the list, our job is simpler.
558 // This is true most of the time, so this is a reasonable optimization.
559 if (isImpReg || NumImplicitOps == 0) {
560 // We can only do this optimization if we know that the operand list won't
562 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
563 Operands.push_back(Op);
565 // Set the parent of the operand.
566 Operands.back().ParentMI = this;
568 // If the operand is a register, update the operand's use list.
570 Operands.back().AddRegOperandToRegInfo(RegInfo);
571 // If the register operand is flagged as early, mark the operand as such
572 unsigned OpNo = Operands.size() - 1;
573 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
574 Operands[OpNo].setIsEarlyClobber(true);
580 // Otherwise, we have to insert a real operand before any implicit ones.
581 unsigned OpNo = Operands.size()-NumImplicitOps;
583 // If this instruction isn't embedded into a function, then we don't need to
584 // update any operand lists.
586 // Simple insertion, no reginfo update needed for other register operands.
587 Operands.insert(Operands.begin()+OpNo, Op);
588 Operands[OpNo].ParentMI = this;
590 // Do explicitly set the reginfo for this operand though, to ensure the
591 // next/prev fields are properly nulled out.
592 if (Operands[OpNo].isReg()) {
593 Operands[OpNo].AddRegOperandToRegInfo(0);
594 // If the register operand is flagged as early, mark the operand as such
595 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
596 Operands[OpNo].setIsEarlyClobber(true);
599 } else if (Operands.size()+1 <= Operands.capacity()) {
600 // Otherwise, we have to remove register operands from their register use
601 // list, add the operand, then add the register operands back to their use
602 // list. This also must handle the case when the operand list reallocates
603 // to somewhere else.
605 // If insertion of this operand won't cause reallocation of the operand
606 // list, just remove the implicit operands, add the operand, then re-add all
607 // the rest of the operands.
608 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
609 assert(Operands[i].isReg() && "Should only be an implicit reg!");
610 Operands[i].RemoveRegOperandFromRegInfo();
613 // Add the operand. If it is a register, add it to the reg list.
614 Operands.insert(Operands.begin()+OpNo, Op);
615 Operands[OpNo].ParentMI = this;
617 if (Operands[OpNo].isReg()) {
618 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
619 // If the register operand is flagged as early, mark the operand as such
620 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
621 Operands[OpNo].setIsEarlyClobber(true);
624 // Re-add all the implicit ops.
625 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
626 assert(Operands[i].isReg() && "Should only be an implicit reg!");
627 Operands[i].AddRegOperandToRegInfo(RegInfo);
630 // Otherwise, we will be reallocating the operand list. Remove all reg
631 // operands from their list, then readd them after the operand list is
633 RemoveRegOperandsFromUseLists();
635 Operands.insert(Operands.begin()+OpNo, Op);
636 Operands[OpNo].ParentMI = this;
638 // Re-add all the operands.
639 AddRegOperandsToUseLists(*RegInfo);
641 // If the register operand is flagged as early, mark the operand as such
642 if (Operands[OpNo].isReg()
643 && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
644 Operands[OpNo].setIsEarlyClobber(true);
648 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
649 /// fewer operand than it started with.
651 void MachineInstr::RemoveOperand(unsigned OpNo) {
652 assert(OpNo < Operands.size() && "Invalid operand number");
654 // Special case removing the last one.
655 if (OpNo == Operands.size()-1) {
656 // If needed, remove from the reg def/use list.
657 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
658 Operands.back().RemoveRegOperandFromRegInfo();
664 // Otherwise, we are removing an interior operand. If we have reginfo to
665 // update, remove all operands that will be shifted down from their reg lists,
666 // move everything down, then re-add them.
667 MachineRegisterInfo *RegInfo = getRegInfo();
669 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
670 if (Operands[i].isReg())
671 Operands[i].RemoveRegOperandFromRegInfo();
675 Operands.erase(Operands.begin()+OpNo);
678 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
679 if (Operands[i].isReg())
680 Operands[i].AddRegOperandToRegInfo(RegInfo);
685 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
686 /// This function should be used only occasionally. The setMemRefs function
687 /// is the primary method for setting up a MachineInstr's MemRefs list.
688 void MachineInstr::addMemOperand(MachineFunction &MF,
689 MachineMemOperand *MO) {
690 mmo_iterator OldMemRefs = MemRefs;
691 mmo_iterator OldMemRefsEnd = MemRefsEnd;
693 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
694 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
695 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
697 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
698 NewMemRefs[NewNum - 1] = MO;
700 MemRefs = NewMemRefs;
701 MemRefsEnd = NewMemRefsEnd;
704 /// removeFromParent - This method unlinks 'this' from the containing basic
705 /// block, and returns it, but does not delete it.
706 MachineInstr *MachineInstr::removeFromParent() {
707 assert(getParent() && "Not embedded in a basic block!");
708 getParent()->remove(this);
713 /// eraseFromParent - This method unlinks 'this' from the containing basic
714 /// block, and deletes it.
715 void MachineInstr::eraseFromParent() {
716 assert(getParent() && "Not embedded in a basic block!");
717 getParent()->erase(this);
721 /// OperandComplete - Return true if it's illegal to add a new operand
723 bool MachineInstr::OperandsComplete() const {
724 unsigned short NumOperands = TID->getNumOperands();
725 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
726 return true; // Broken: we have all the operands of this instruction!
730 /// getNumExplicitOperands - Returns the number of non-implicit operands.
732 unsigned MachineInstr::getNumExplicitOperands() const {
733 unsigned NumOperands = TID->getNumOperands();
734 if (!TID->isVariadic())
737 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
738 const MachineOperand &MO = getOperand(i);
739 if (!MO.isReg() || !MO.isImplicit())
746 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
747 /// the specific register or -1 if it is not found. It further tightens
748 /// the search criteria to a use that kills the register if isKill is true.
749 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
750 const TargetRegisterInfo *TRI) const {
751 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
752 const MachineOperand &MO = getOperand(i);
753 if (!MO.isReg() || !MO.isUse())
755 unsigned MOReg = MO.getReg();
760 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
761 TargetRegisterInfo::isPhysicalRegister(Reg) &&
762 TRI->isSubRegister(MOReg, Reg)))
763 if (!isKill || MO.isKill())
769 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
770 /// the specified register or -1 if it is not found. If isDead is true, defs
771 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
772 /// also checks if there is a def of a super-register.
773 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
774 const TargetRegisterInfo *TRI) const {
775 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
776 const MachineOperand &MO = getOperand(i);
777 if (!MO.isReg() || !MO.isDef())
779 unsigned MOReg = MO.getReg();
782 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
783 TargetRegisterInfo::isPhysicalRegister(Reg) &&
784 TRI->isSubRegister(MOReg, Reg)))
785 if (!isDead || MO.isDead())
791 /// findFirstPredOperandIdx() - Find the index of the first operand in the
792 /// operand list that is used to represent the predicate. It returns -1 if
794 int MachineInstr::findFirstPredOperandIdx() const {
795 const TargetInstrDesc &TID = getDesc();
796 if (TID.isPredicable()) {
797 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
798 if (TID.OpInfo[i].isPredicate())
805 /// isRegTiedToUseOperand - Given the index of a register def operand,
806 /// check if the register def is tied to a source operand, due to either
807 /// two-address elimination or inline assembly constraints. Returns the
808 /// first tied use operand index by reference is UseOpIdx is not null.
810 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
812 assert(DefOpIdx >= 2);
813 const MachineOperand &MO = getOperand(DefOpIdx);
814 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
816 // Determine the actual operand index that corresponds to this index.
818 unsigned DefPart = 0;
819 for (unsigned i = 1, e = getNumOperands(); i < e; ) {
820 const MachineOperand &FMO = getOperand(i);
821 // After the normal asm operands there may be additional imp-def regs.
824 // Skip over this def.
825 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
826 unsigned PrevDef = i + 1;
827 i = PrevDef + NumOps;
829 DefPart = DefOpIdx - PrevDef;
834 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
835 const MachineOperand &FMO = getOperand(i);
838 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
841 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
844 *UseOpIdx = (unsigned)i + 1 + DefPart;
851 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
852 const TargetInstrDesc &TID = getDesc();
853 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
854 const MachineOperand &MO = getOperand(i);
855 if (MO.isReg() && MO.isUse() &&
856 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
858 *UseOpIdx = (unsigned)i;
865 /// isRegTiedToDefOperand - Return true if the operand of the specified index
866 /// is a register use and it is tied to an def operand. It also returns the def
867 /// operand index by reference.
869 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
871 const MachineOperand &MO = getOperand(UseOpIdx);
872 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
875 // Find the flag operand corresponding to UseOpIdx
876 unsigned FlagIdx, NumOps=0;
877 for (FlagIdx = 1; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
878 const MachineOperand &UFMO = getOperand(FlagIdx);
879 // After the normal asm operands there may be additional imp-def regs.
882 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
883 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
884 if (UseOpIdx < FlagIdx+NumOps+1)
887 if (FlagIdx >= UseOpIdx)
889 const MachineOperand &UFMO = getOperand(FlagIdx);
891 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
896 // Remember to adjust the index. First operand is asm string, then there
897 // is a flag for each.
899 const MachineOperand &FMO = getOperand(DefIdx);
901 // Skip over this def.
902 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
905 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
911 const TargetInstrDesc &TID = getDesc();
912 if (UseOpIdx >= TID.getNumOperands())
914 const MachineOperand &MO = getOperand(UseOpIdx);
915 if (!MO.isReg() || !MO.isUse())
917 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
921 *DefOpIdx = (unsigned)DefIdx;
925 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
927 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
928 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
929 const MachineOperand &MO = MI->getOperand(i);
930 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
932 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
933 MachineOperand &MOp = getOperand(j);
934 if (!MOp.isIdenticalTo(MO))
945 /// copyPredicates - Copies predicate operand(s) from MI.
946 void MachineInstr::copyPredicates(const MachineInstr *MI) {
947 const TargetInstrDesc &TID = MI->getDesc();
948 if (!TID.isPredicable())
950 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
951 if (TID.OpInfo[i].isPredicate()) {
952 // Predicated operands must be last operands.
953 addOperand(MI->getOperand(i));
958 /// isSafeToMove - Return true if it is safe to move this instruction. If
959 /// SawStore is set to true, it means that there is a store (or call) between
960 /// the instruction's location and its intended destination.
961 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
963 AliasAnalysis *AA) const {
964 // Ignore stuff that we obviously can't move.
965 if (TID->mayStore() || TID->isCall()) {
969 if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
972 // See if this instruction does a load. If so, we have to guarantee that the
973 // loaded value doesn't change between the load and the its intended
974 // destination. The check for isInvariantLoad gives the targe the chance to
975 // classify the load as always returning a constant, e.g. a constant pool
977 if (TID->mayLoad() && !isInvariantLoad(AA))
978 // Otherwise, this is a real load. If there is a store between the load and
979 // end of block, or if the load is volatile, we can't move it.
980 return !SawStore && !hasVolatileMemoryRef();
985 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
986 /// instruction which defined the specified register instead of copying it.
987 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
989 AliasAnalysis *AA) const {
990 bool SawStore = false;
991 if (!TII->isTriviallyReMaterializable(this, AA) ||
992 !isSafeToMove(TII, SawStore, AA))
994 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
995 const MachineOperand &MO = getOperand(i);
998 // FIXME: For now, do not remat any instruction with register operands.
999 // Later on, we can loosen the restriction is the register operands have
1000 // not been modified between the def and use. Note, this is different from
1001 // MachineSink because the code is no longer in two-address form (at least
1005 else if (!MO.isDead() && MO.getReg() != DstReg)
1011 /// hasVolatileMemoryRef - Return true if this instruction may have a
1012 /// volatile memory reference, or if the information describing the
1013 /// memory reference is not available. Return false if it is known to
1014 /// have no volatile memory references.
1015 bool MachineInstr::hasVolatileMemoryRef() const {
1016 // An instruction known never to access memory won't have a volatile access.
1017 if (!TID->mayStore() &&
1020 !TID->hasUnmodeledSideEffects())
1023 // Otherwise, if the instruction has no memory reference information,
1024 // conservatively assume it wasn't preserved.
1025 if (memoperands_empty())
1028 // Check the memory reference information for volatile references.
1029 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1030 if ((*I)->isVolatile())
1036 /// isInvariantLoad - Return true if this instruction is loading from a
1037 /// location whose value is invariant across the function. For example,
1038 /// loading a value from the constant pool or from the argument area
1039 /// of a function if it does not change. This should only return true of
1040 /// *all* loads the instruction does are invariant (if it does multiple loads).
1041 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1042 // If the instruction doesn't load at all, it isn't an invariant load.
1043 if (!TID->mayLoad())
1046 // If the instruction has lost its memoperands, conservatively assume that
1047 // it may not be an invariant load.
1048 if (memoperands_empty())
1051 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1053 for (mmo_iterator I = memoperands_begin(),
1054 E = memoperands_end(); I != E; ++I) {
1055 if ((*I)->isVolatile()) return false;
1056 if ((*I)->isStore()) return false;
1058 if (const Value *V = (*I)->getValue()) {
1059 // A load from a constant PseudoSourceValue is invariant.
1060 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1061 if (PSV->isConstant(MFI))
1063 // If we have an AliasAnalysis, ask it whether the memory is constant.
1064 if (AA && AA->pointsToConstantMemory(V))
1068 // Otherwise assume conservatively.
1072 // Everything checks out.
1076 /// isConstantValuePHI - If the specified instruction is a PHI that always
1077 /// merges together the same virtual register, return the register, otherwise
1079 unsigned MachineInstr::isConstantValuePHI() const {
1082 assert(getNumOperands() >= 3 &&
1083 "It's illegal to have a PHI without source operands");
1085 unsigned Reg = getOperand(1).getReg();
1086 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1087 if (getOperand(i).getReg() != Reg)
1092 void MachineInstr::dump() const {
1093 dbgs() << " " << *this;
1096 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1097 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1098 const MachineFunction *MF = 0;
1099 if (const MachineBasicBlock *MBB = getParent()) {
1100 MF = MBB->getParent();
1102 TM = &MF->getTarget();
1105 // Print explicitly defined operands on the left of an assignment syntax.
1106 unsigned StartOp = 0, e = getNumOperands();
1107 for (; StartOp < e && getOperand(StartOp).isReg() &&
1108 getOperand(StartOp).isDef() &&
1109 !getOperand(StartOp).isImplicit();
1111 if (StartOp != 0) OS << ", ";
1112 getOperand(StartOp).print(OS, TM);
1118 // Print the opcode name.
1119 OS << getDesc().getName();
1121 // Print the rest of the operands.
1122 bool OmittedAnyCallClobbers = false;
1123 bool FirstOp = true;
1124 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1125 const MachineOperand &MO = getOperand(i);
1127 // Omit call-clobbered registers which aren't used anywhere. This makes
1128 // call instructions much less noisy on targets where calls clobber lots
1129 // of registers. Don't rely on MO.isDead() because we may be called before
1130 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1131 if (MF && getDesc().isCall() &&
1132 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1133 unsigned Reg = MO.getReg();
1134 if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1135 const MachineRegisterInfo &MRI = MF->getRegInfo();
1136 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1137 bool HasAliasLive = false;
1138 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1139 unsigned AliasReg = *Alias; ++Alias)
1140 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1141 HasAliasLive = true;
1144 if (!HasAliasLive) {
1145 OmittedAnyCallClobbers = true;
1152 if (FirstOp) FirstOp = false; else OS << ",";
1154 if (i < getDesc().NumOperands) {
1155 const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1156 if (TOI.isPredicate())
1158 if (TOI.isOptionalDef())
1164 // Briefly indicate whether any call clobbers were omitted.
1165 if (OmittedAnyCallClobbers) {
1166 if (!FirstOp) OS << ",";
1170 bool HaveSemi = false;
1171 if (!memoperands_empty()) {
1172 if (!HaveSemi) OS << ";"; HaveSemi = true;
1175 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1183 if (!debugLoc.isUnknown() && MF) {
1184 if (!HaveSemi) OS << ";";
1186 // TODO: print InlinedAtLoc information
1188 DILocation DLT = MF->getDILocation(debugLoc);
1189 DIScope Scope = DLT.getScope();
1191 // Omit the directory, since it's usually long and uninteresting.
1192 if (!Scope.isNull())
1193 OS << Scope.getFilename();
1196 OS << ':' << DLT.getLineNumber();
1197 if (DLT.getColumnNumber() != 0)
1198 OS << ':' << DLT.getColumnNumber();
1204 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1205 const TargetRegisterInfo *RegInfo,
1206 bool AddIfNotFound) {
1207 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1208 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1210 SmallVector<unsigned,4> DeadOps;
1211 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1212 MachineOperand &MO = getOperand(i);
1213 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1215 unsigned Reg = MO.getReg();
1219 if (Reg == IncomingReg) {
1222 // The register is already marked kill.
1224 if (isPhysReg && isRegTiedToDefOperand(i))
1225 // Two-address uses of physregs must not be marked kill.
1230 } else if (hasAliases && MO.isKill() &&
1231 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1232 // A super-register kill already exists.
1233 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1235 if (RegInfo->isSubRegister(IncomingReg, Reg))
1236 DeadOps.push_back(i);
1240 // Trim unneeded kill operands.
1241 while (!DeadOps.empty()) {
1242 unsigned OpIdx = DeadOps.back();
1243 if (getOperand(OpIdx).isImplicit())
1244 RemoveOperand(OpIdx);
1246 getOperand(OpIdx).setIsKill(false);
1250 // If not found, this means an alias of one of the operands is killed. Add a
1251 // new implicit operand if required.
1252 if (!Found && AddIfNotFound) {
1253 addOperand(MachineOperand::CreateReg(IncomingReg,
1262 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1263 const TargetRegisterInfo *RegInfo,
1264 bool AddIfNotFound) {
1265 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1266 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1268 SmallVector<unsigned,4> DeadOps;
1269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1270 MachineOperand &MO = getOperand(i);
1271 if (!MO.isReg() || !MO.isDef())
1273 unsigned Reg = MO.getReg();
1277 if (Reg == IncomingReg) {
1280 // The register is already marked dead.
1285 } else if (hasAliases && MO.isDead() &&
1286 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1287 // There exists a super-register that's marked dead.
1288 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1290 if (RegInfo->getSubRegisters(IncomingReg) &&
1291 RegInfo->getSuperRegisters(Reg) &&
1292 RegInfo->isSubRegister(IncomingReg, Reg))
1293 DeadOps.push_back(i);
1297 // Trim unneeded dead operands.
1298 while (!DeadOps.empty()) {
1299 unsigned OpIdx = DeadOps.back();
1300 if (getOperand(OpIdx).isImplicit())
1301 RemoveOperand(OpIdx);
1303 getOperand(OpIdx).setIsDead(false);
1307 // If not found, this means an alias of one of the operands is dead. Add a
1308 // new implicit operand if required.
1309 if (Found || !AddIfNotFound)
1312 addOperand(MachineOperand::CreateReg(IncomingReg,
1320 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1321 const TargetRegisterInfo *RegInfo) {
1322 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1323 if (!MO || MO->getSubReg())
1324 addOperand(MachineOperand::CreateReg(IncomingReg,