1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DebugInfo.h"
17 #include "llvm/Function.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Metadata.h"
21 #include "llvm/Module.h"
22 #include "llvm/Type.h"
23 #include "llvm/Value.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LeakDetector.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/FoldingSet.h"
43 #include "llvm/ADT/Hashing.h"
46 //===----------------------------------------------------------------------===//
47 // MachineOperand Implementation
48 //===----------------------------------------------------------------------===//
50 void MachineOperand::setReg(unsigned Reg) {
51 if (getReg() == Reg) return; // No change.
53 // Otherwise, we have to change the register. If this operand is embedded
54 // into a machine function, we need to update the old and new register's
56 if (MachineInstr *MI = getParent())
57 if (MachineBasicBlock *MBB = MI->getParent())
58 if (MachineFunction *MF = MBB->getParent()) {
59 MachineRegisterInfo &MRI = MF->getRegInfo();
60 MRI.removeRegOperandFromUseList(this);
61 SmallContents.RegNo = Reg;
62 MRI.addRegOperandToUseList(this);
66 // Otherwise, just change the register, no problem. :)
67 SmallContents.RegNo = Reg;
70 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
71 const TargetRegisterInfo &TRI) {
72 assert(TargetRegisterInfo::isVirtualRegister(Reg));
73 if (SubIdx && getSubReg())
74 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
80 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
81 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
83 Reg = TRI.getSubReg(Reg, getSubReg());
84 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
85 // That won't happen in legal code.
91 /// Change a def to a use, or a use to a def.
92 void MachineOperand::setIsDef(bool Val) {
93 assert(isReg() && "Wrong MachineOperand accessor");
94 assert((!Val || !isDebug()) && "Marking a debug operation as def");
97 // MRI may keep uses and defs in different list positions.
98 if (MachineInstr *MI = getParent())
99 if (MachineBasicBlock *MBB = MI->getParent())
100 if (MachineFunction *MF = MBB->getParent()) {
101 MachineRegisterInfo &MRI = MF->getRegInfo();
102 MRI.removeRegOperandFromUseList(this);
104 MRI.addRegOperandToUseList(this);
110 /// ChangeToImmediate - Replace this operand with a new immediate operand of
111 /// the specified value. If an operand is known to be an immediate already,
112 /// the setImm method should be used.
113 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
114 // If this operand is currently a register operand, and if this is in a
115 // function, deregister the operand from the register's use/def list.
116 if (isReg() && isOnRegUseList())
117 if (MachineInstr *MI = getParent())
118 if (MachineBasicBlock *MBB = MI->getParent())
119 if (MachineFunction *MF = MBB->getParent())
120 MF->getRegInfo().removeRegOperandFromUseList(this);
122 OpKind = MO_Immediate;
123 Contents.ImmVal = ImmVal;
126 /// ChangeToRegister - Replace this operand with a new register operand of
127 /// the specified value. If an operand is known to be an register already,
128 /// the setReg method should be used.
129 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
130 bool isKill, bool isDead, bool isUndef,
132 MachineRegisterInfo *RegInfo = 0;
133 if (MachineInstr *MI = getParent())
134 if (MachineBasicBlock *MBB = MI->getParent())
135 if (MachineFunction *MF = MBB->getParent())
136 RegInfo = &MF->getRegInfo();
137 // If this operand is already a register operand, remove it from the
138 // register's use/def lists.
139 if (RegInfo && isReg())
140 RegInfo->removeRegOperandFromUseList(this);
142 // Change this to a register and set the reg#.
143 OpKind = MO_Register;
144 SmallContents.RegNo = Reg;
151 IsInternalRead = false;
152 IsEarlyClobber = false;
154 // Ensure isOnRegUseList() returns false.
155 Contents.Reg.Prev = 0;
157 // If this operand is embedded in a function, add the operand to the
158 // register's use/def list.
160 RegInfo->addRegOperandToUseList(this);
163 /// isIdenticalTo - Return true if this operand is identical to the specified
164 /// operand. Note that this should stay in sync with the hash_value overload
166 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
167 if (getType() != Other.getType() ||
168 getTargetFlags() != Other.getTargetFlags())
172 case MachineOperand::MO_Register:
173 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
174 getSubReg() == Other.getSubReg();
175 case MachineOperand::MO_Immediate:
176 return getImm() == Other.getImm();
177 case MachineOperand::MO_CImmediate:
178 return getCImm() == Other.getCImm();
179 case MachineOperand::MO_FPImmediate:
180 return getFPImm() == Other.getFPImm();
181 case MachineOperand::MO_MachineBasicBlock:
182 return getMBB() == Other.getMBB();
183 case MachineOperand::MO_FrameIndex:
184 return getIndex() == Other.getIndex();
185 case MachineOperand::MO_ConstantPoolIndex:
186 case MachineOperand::MO_TargetIndex:
187 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
188 case MachineOperand::MO_JumpTableIndex:
189 return getIndex() == Other.getIndex();
190 case MachineOperand::MO_GlobalAddress:
191 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
192 case MachineOperand::MO_ExternalSymbol:
193 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
194 getOffset() == Other.getOffset();
195 case MachineOperand::MO_BlockAddress:
196 return getBlockAddress() == Other.getBlockAddress();
197 case MO_RegisterMask:
198 return getRegMask() == Other.getRegMask();
199 case MachineOperand::MO_MCSymbol:
200 return getMCSymbol() == Other.getMCSymbol();
201 case MachineOperand::MO_Metadata:
202 return getMetadata() == Other.getMetadata();
204 llvm_unreachable("Invalid machine operand type");
207 // Note: this must stay exactly in sync with isIdenticalTo above.
208 hash_code llvm::hash_value(const MachineOperand &MO) {
209 switch (MO.getType()) {
210 case MachineOperand::MO_Register:
211 // Register operands don't have target flags.
212 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
213 case MachineOperand::MO_Immediate:
214 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
215 case MachineOperand::MO_CImmediate:
216 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
217 case MachineOperand::MO_FPImmediate:
218 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
219 case MachineOperand::MO_MachineBasicBlock:
220 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
221 case MachineOperand::MO_FrameIndex:
222 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
223 case MachineOperand::MO_ConstantPoolIndex:
224 case MachineOperand::MO_TargetIndex:
225 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
227 case MachineOperand::MO_JumpTableIndex:
228 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
229 case MachineOperand::MO_ExternalSymbol:
230 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
232 case MachineOperand::MO_GlobalAddress:
233 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
235 case MachineOperand::MO_BlockAddress:
236 return hash_combine(MO.getType(), MO.getTargetFlags(),
237 MO.getBlockAddress());
238 case MachineOperand::MO_RegisterMask:
239 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
240 case MachineOperand::MO_Metadata:
241 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
242 case MachineOperand::MO_MCSymbol:
243 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
245 llvm_unreachable("Invalid machine operand type");
248 /// print - Print the specified machine operand.
250 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
251 // If the instruction is embedded into a basic block, we can find the
252 // target info for the instruction.
254 if (const MachineInstr *MI = getParent())
255 if (const MachineBasicBlock *MBB = MI->getParent())
256 if (const MachineFunction *MF = MBB->getParent())
257 TM = &MF->getTarget();
258 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
261 case MachineOperand::MO_Register:
262 OS << PrintReg(getReg(), TRI, getSubReg());
264 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
265 isInternalRead() || isEarlyClobber()) {
267 bool NeedComma = false;
269 if (NeedComma) OS << ',';
270 if (isEarlyClobber())
271 OS << "earlyclobber,";
276 // <def,read-undef> only makes sense when getSubReg() is set.
277 // Don't clutter the output otherwise.
278 if (isUndef() && getSubReg())
280 } else if (isImplicit()) {
285 if (isKill() || isDead() || (isUndef() && isUse()) || isInternalRead()) {
286 if (NeedComma) OS << ',';
296 if (isUndef() && isUse()) {
297 if (NeedComma) OS << ',';
301 if (isInternalRead()) {
302 if (NeedComma) OS << ',';
310 case MachineOperand::MO_Immediate:
313 case MachineOperand::MO_CImmediate:
314 getCImm()->getValue().print(OS, false);
316 case MachineOperand::MO_FPImmediate:
317 if (getFPImm()->getType()->isFloatTy())
318 OS << getFPImm()->getValueAPF().convertToFloat();
320 OS << getFPImm()->getValueAPF().convertToDouble();
322 case MachineOperand::MO_MachineBasicBlock:
323 OS << "<BB#" << getMBB()->getNumber() << ">";
325 case MachineOperand::MO_FrameIndex:
326 OS << "<fi#" << getIndex() << '>';
328 case MachineOperand::MO_ConstantPoolIndex:
329 OS << "<cp#" << getIndex();
330 if (getOffset()) OS << "+" << getOffset();
333 case MachineOperand::MO_TargetIndex:
334 OS << "<ti#" << getIndex();
335 if (getOffset()) OS << "+" << getOffset();
338 case MachineOperand::MO_JumpTableIndex:
339 OS << "<jt#" << getIndex() << '>';
341 case MachineOperand::MO_GlobalAddress:
343 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
344 if (getOffset()) OS << "+" << getOffset();
347 case MachineOperand::MO_ExternalSymbol:
348 OS << "<es:" << getSymbolName();
349 if (getOffset()) OS << "+" << getOffset();
352 case MachineOperand::MO_BlockAddress:
354 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
357 case MachineOperand::MO_RegisterMask:
360 case MachineOperand::MO_Metadata:
362 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
365 case MachineOperand::MO_MCSymbol:
366 OS << "<MCSym=" << *getMCSymbol() << '>';
370 if (unsigned TF = getTargetFlags())
371 OS << "[TF=" << TF << ']';
374 //===----------------------------------------------------------------------===//
375 // MachineMemOperand Implementation
376 //===----------------------------------------------------------------------===//
378 /// getAddrSpace - Return the LLVM IR address space number that this pointer
380 unsigned MachinePointerInfo::getAddrSpace() const {
381 if (V == 0) return 0;
382 return cast<PointerType>(V->getType())->getAddressSpace();
385 /// getConstantPool - Return a MachinePointerInfo record that refers to the
387 MachinePointerInfo MachinePointerInfo::getConstantPool() {
388 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
391 /// getFixedStack - Return a MachinePointerInfo record that refers to the
392 /// the specified FrameIndex.
393 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
394 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
397 MachinePointerInfo MachinePointerInfo::getJumpTable() {
398 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
401 MachinePointerInfo MachinePointerInfo::getGOT() {
402 return MachinePointerInfo(PseudoSourceValue::getGOT());
405 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
406 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
409 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
410 uint64_t s, unsigned int a,
411 const MDNode *TBAAInfo,
412 const MDNode *Ranges)
413 : PtrInfo(ptrinfo), Size(s),
414 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
415 TBAAInfo(TBAAInfo), Ranges(Ranges) {
416 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
417 "invalid pointer value");
418 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
419 assert((isLoad() || isStore()) && "Not a load/store!");
422 /// Profile - Gather unique data for the object.
424 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
425 ID.AddInteger(getOffset());
427 ID.AddPointer(getValue());
428 ID.AddInteger(Flags);
431 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
432 // The Value and Offset may differ due to CSE. But the flags and size
433 // should be the same.
434 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
435 assert(MMO->getSize() == getSize() && "Size mismatch!");
437 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
438 // Update the alignment value.
439 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
440 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
441 // Also update the base and offset, because the new alignment may
442 // not be applicable with the old ones.
443 PtrInfo = MMO->PtrInfo;
447 /// getAlignment - Return the minimum known alignment in bytes of the
448 /// actual memory reference.
449 uint64_t MachineMemOperand::getAlignment() const {
450 return MinAlign(getBaseAlignment(), getOffset());
453 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
454 assert((MMO.isLoad() || MMO.isStore()) &&
455 "SV has to be a load, store or both.");
457 if (MMO.isVolatile())
466 // Print the address information.
471 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
473 // If the alignment of the memory reference itself differs from the alignment
474 // of the base pointer, print the base alignment explicitly, next to the base
476 if (MMO.getBaseAlignment() != MMO.getAlignment())
477 OS << "(align=" << MMO.getBaseAlignment() << ")";
479 if (MMO.getOffset() != 0)
480 OS << "+" << MMO.getOffset();
483 // Print the alignment of the reference.
484 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
485 MMO.getBaseAlignment() != MMO.getSize())
486 OS << "(align=" << MMO.getAlignment() << ")";
489 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
491 if (TBAAInfo->getNumOperands() > 0)
492 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
498 // Print nontemporal info.
499 if (MMO.isNonTemporal())
500 OS << "(nontemporal)";
505 //===----------------------------------------------------------------------===//
506 // MachineInstr Implementation
507 //===----------------------------------------------------------------------===//
509 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
510 /// MCID NULL and no operands.
511 MachineInstr::MachineInstr()
512 : MCID(0), Flags(0), AsmPrinterFlags(0),
513 NumMemRefs(0), MemRefs(0),
515 // Make sure that we get added to a machine basicblock
516 LeakDetector::addGarbageObject(this);
519 void MachineInstr::addImplicitDefUseOperands() {
520 if (MCID->ImplicitDefs)
521 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
522 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
523 if (MCID->ImplicitUses)
524 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
525 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
528 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
529 /// implicit operands. It reserves space for the number of operands specified by
531 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
532 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
533 NumMemRefs(0), MemRefs(0), Parent(0) {
534 unsigned NumImplicitOps = 0;
536 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
537 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
539 addImplicitDefUseOperands();
540 // Make sure that we get added to a machine basicblock
541 LeakDetector::addGarbageObject(this);
544 /// MachineInstr ctor - As above, but with a DebugLoc.
545 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
547 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
548 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
549 unsigned NumImplicitOps = 0;
551 NumImplicitOps = MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
552 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
554 addImplicitDefUseOperands();
555 // Make sure that we get added to a machine basicblock
556 LeakDetector::addGarbageObject(this);
559 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
560 /// that the MachineInstr is created and added to the end of the specified
562 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
563 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
564 NumMemRefs(0), MemRefs(0), Parent(0) {
565 assert(MBB && "Cannot use inserting ctor with null basic block!");
566 unsigned NumImplicitOps =
567 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
568 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
569 addImplicitDefUseOperands();
570 // Make sure that we get added to a machine basicblock
571 LeakDetector::addGarbageObject(this);
572 MBB->push_back(this); // Add instruction to end of basic block!
575 /// MachineInstr ctor - As above, but with a DebugLoc.
577 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
578 const MCInstrDesc &tid)
579 : MCID(&tid), Flags(0), AsmPrinterFlags(0),
580 NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
581 assert(MBB && "Cannot use inserting ctor with null basic block!");
582 unsigned NumImplicitOps =
583 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
584 Operands.reserve(NumImplicitOps + MCID->getNumOperands());
585 addImplicitDefUseOperands();
586 // Make sure that we get added to a machine basicblock
587 LeakDetector::addGarbageObject(this);
588 MBB->push_back(this); // Add instruction to end of basic block!
591 /// MachineInstr ctor - Copies MachineInstr arg exactly
593 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
594 : MCID(&MI.getDesc()), Flags(0), AsmPrinterFlags(0),
595 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
596 Parent(0), debugLoc(MI.getDebugLoc()) {
597 Operands.reserve(MI.getNumOperands());
600 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
601 addOperand(MI.getOperand(i));
603 // Copy all the flags.
606 // Set parent to null.
609 LeakDetector::addGarbageObject(this);
612 MachineInstr::~MachineInstr() {
613 LeakDetector::removeGarbageObject(this);
615 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
616 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
617 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
618 "Reg operand def/use list corrupted");
623 /// getRegInfo - If this instruction is embedded into a MachineFunction,
624 /// return the MachineRegisterInfo object for the current function, otherwise
626 MachineRegisterInfo *MachineInstr::getRegInfo() {
627 if (MachineBasicBlock *MBB = getParent())
628 return &MBB->getParent()->getRegInfo();
632 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
633 /// this instruction from their respective use lists. This requires that the
634 /// operands already be on their use lists.
635 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
636 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
637 if (Operands[i].isReg())
638 MRI.removeRegOperandFromUseList(&Operands[i]);
641 /// AddRegOperandsToUseLists - Add all of the register operands in
642 /// this instruction from their respective use lists. This requires that the
643 /// operands not be on their use lists yet.
644 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
645 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
646 if (Operands[i].isReg())
647 MRI.addRegOperandToUseList(&Operands[i]);
650 /// addOperand - Add the specified operand to the instruction. If it is an
651 /// implicit operand, it is added to the end of the operand list. If it is
652 /// an explicit operand it is added at the end of the explicit operand list
653 /// (before the first implicit operand).
654 void MachineInstr::addOperand(const MachineOperand &Op) {
655 assert(MCID && "Cannot add operands before providing an instr descriptor");
656 bool isImpReg = Op.isReg() && Op.isImplicit();
657 MachineRegisterInfo *RegInfo = getRegInfo();
659 // If the Operands backing store is reallocated, all register operands must
660 // be removed and re-added to RegInfo. It is storing pointers to operands.
661 bool Reallocate = RegInfo &&
662 !Operands.empty() && Operands.size() == Operands.capacity();
664 // Find the insert location for the new operand. Implicit registers go at
665 // the end, everything goes before the implicit regs.
666 unsigned OpNo = Operands.size();
668 // Remove all the implicit operands from RegInfo if they need to be shifted.
669 // FIXME: Allow mixed explicit and implicit operands on inline asm.
670 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
671 // implicit-defs, but they must not be moved around. See the FIXME in
673 if (!isImpReg && !isInlineAsm()) {
674 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
677 RegInfo->removeRegOperandFromUseList(&Operands[OpNo]);
681 // OpNo now points as the desired insertion point. Unless this is a variadic
682 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
683 // RegMask operands go between the explicit and implicit operands.
684 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
685 OpNo < MCID->getNumOperands()) &&
686 "Trying to add an operand to a machine instr that is already done!");
688 // All operands from OpNo have been removed from RegInfo. If the Operands
689 // backing store needs to be reallocated, we also need to remove any other
690 // register operands.
692 for (unsigned i = 0; i != OpNo; ++i)
693 if (Operands[i].isReg())
694 RegInfo->removeRegOperandFromUseList(&Operands[i]);
696 // Insert the new operand at OpNo.
697 Operands.insert(Operands.begin() + OpNo, Op);
698 Operands[OpNo].ParentMI = this;
700 // The Operands backing store has now been reallocated, so we can re-add the
701 // operands before OpNo.
703 for (unsigned i = 0; i != OpNo; ++i)
704 if (Operands[i].isReg())
705 RegInfo->addRegOperandToUseList(&Operands[i]);
707 // When adding a register operand, tell RegInfo about it.
708 if (Operands[OpNo].isReg()) {
709 // Ensure isOnRegUseList() returns false, regardless of Op's status.
710 Operands[OpNo].Contents.Reg.Prev = 0;
711 // Add the new operand to RegInfo.
713 RegInfo->addRegOperandToUseList(&Operands[OpNo]);
714 // If the register operand is flagged as early, mark the operand as such.
715 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
716 Operands[OpNo].setIsEarlyClobber(true);
719 // Re-add all the implicit ops.
721 for (unsigned i = OpNo + 1, e = Operands.size(); i != e; ++i) {
722 assert(Operands[i].isReg() && "Should only be an implicit reg!");
723 RegInfo->addRegOperandToUseList(&Operands[i]);
728 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
729 /// fewer operand than it started with.
731 void MachineInstr::RemoveOperand(unsigned OpNo) {
732 assert(OpNo < Operands.size() && "Invalid operand number");
733 MachineRegisterInfo *RegInfo = getRegInfo();
735 // Special case removing the last one.
736 if (OpNo == Operands.size()-1) {
737 // If needed, remove from the reg def/use list.
738 if (RegInfo && Operands.back().isReg() && Operands.back().isOnRegUseList())
739 RegInfo->removeRegOperandFromUseList(&Operands.back());
745 // Otherwise, we are removing an interior operand. If we have reginfo to
746 // update, remove all operands that will be shifted down from their reg lists,
747 // move everything down, then re-add them.
749 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
750 if (Operands[i].isReg())
751 RegInfo->removeRegOperandFromUseList(&Operands[i]);
755 Operands.erase(Operands.begin()+OpNo);
758 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
759 if (Operands[i].isReg())
760 RegInfo->addRegOperandToUseList(&Operands[i]);
765 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
766 /// This function should be used only occasionally. The setMemRefs function
767 /// is the primary method for setting up a MachineInstr's MemRefs list.
768 void MachineInstr::addMemOperand(MachineFunction &MF,
769 MachineMemOperand *MO) {
770 mmo_iterator OldMemRefs = MemRefs;
771 uint16_t OldNumMemRefs = NumMemRefs;
773 uint16_t NewNum = NumMemRefs + 1;
774 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
776 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
777 NewMemRefs[NewNum - 1] = MO;
779 MemRefs = NewMemRefs;
783 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
784 const MachineBasicBlock *MBB = getParent();
785 MachineBasicBlock::const_instr_iterator MII = *this; ++MII;
786 while (MII != MBB->end() && MII->isInsideBundle()) {
787 if (MII->getDesc().getFlags() & Mask) {
788 if (Type == AnyInBundle)
791 if (Type == AllInBundle)
797 return Type == AllInBundle;
800 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
801 MICheckType Check) const {
802 // If opcodes or number of operands are not the same then the two
803 // instructions are obviously not identical.
804 if (Other->getOpcode() != getOpcode() ||
805 Other->getNumOperands() != getNumOperands())
809 // Both instructions are bundles, compare MIs inside the bundle.
810 MachineBasicBlock::const_instr_iterator I1 = *this;
811 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
812 MachineBasicBlock::const_instr_iterator I2 = *Other;
813 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
814 while (++I1 != E1 && I1->isInsideBundle()) {
816 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
821 // Check operands to make sure they match.
822 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
823 const MachineOperand &MO = getOperand(i);
824 const MachineOperand &OMO = Other->getOperand(i);
826 if (!MO.isIdenticalTo(OMO))
831 // Clients may or may not want to ignore defs when testing for equality.
832 // For example, machine CSE pass only cares about finding common
833 // subexpressions, so it's safe to ignore virtual register defs.
835 if (Check == IgnoreDefs)
837 else if (Check == IgnoreVRegDefs) {
838 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
839 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
840 if (MO.getReg() != OMO.getReg())
843 if (!MO.isIdenticalTo(OMO))
845 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
849 if (!MO.isIdenticalTo(OMO))
851 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
855 // If DebugLoc does not match then two dbg.values are not identical.
857 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
858 && getDebugLoc() != Other->getDebugLoc())
863 /// removeFromParent - This method unlinks 'this' from the containing basic
864 /// block, and returns it, but does not delete it.
865 MachineInstr *MachineInstr::removeFromParent() {
866 assert(getParent() && "Not embedded in a basic block!");
868 // If it's a bundle then remove the MIs inside the bundle as well.
870 MachineBasicBlock *MBB = getParent();
871 MachineBasicBlock::instr_iterator MII = *this; ++MII;
872 MachineBasicBlock::instr_iterator E = MBB->instr_end();
873 while (MII != E && MII->isInsideBundle()) {
874 MachineInstr *MI = &*MII;
879 getParent()->remove(this);
884 /// eraseFromParent - This method unlinks 'this' from the containing basic
885 /// block, and deletes it.
886 void MachineInstr::eraseFromParent() {
887 assert(getParent() && "Not embedded in a basic block!");
888 // If it's a bundle then remove the MIs inside the bundle as well.
890 MachineBasicBlock *MBB = getParent();
891 MachineBasicBlock::instr_iterator MII = *this; ++MII;
892 MachineBasicBlock::instr_iterator E = MBB->instr_end();
893 while (MII != E && MII->isInsideBundle()) {
894 MachineInstr *MI = &*MII;
899 // Erase the individual instruction, which may itself be inside a bundle.
900 getParent()->erase_instr(this);
904 /// getNumExplicitOperands - Returns the number of non-implicit operands.
906 unsigned MachineInstr::getNumExplicitOperands() const {
907 unsigned NumOperands = MCID->getNumOperands();
908 if (!MCID->isVariadic())
911 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
912 const MachineOperand &MO = getOperand(i);
913 if (!MO.isReg() || !MO.isImplicit())
919 /// isBundled - Return true if this instruction part of a bundle. This is true
920 /// if either itself or its following instruction is marked "InsideBundle".
921 bool MachineInstr::isBundled() const {
922 if (isInsideBundle())
924 MachineBasicBlock::const_instr_iterator nextMI = this;
926 return nextMI != Parent->instr_end() && nextMI->isInsideBundle();
929 bool MachineInstr::isStackAligningInlineAsm() const {
931 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
932 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
938 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
939 unsigned *GroupNo) const {
940 assert(isInlineAsm() && "Expected an inline asm instruction");
941 assert(OpIdx < getNumOperands() && "OpIdx out of range");
943 // Ignore queries about the initial operands.
944 if (OpIdx < InlineAsm::MIOp_FirstOperand)
949 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
951 const MachineOperand &FlagMO = getOperand(i);
952 // If we reach the implicit register operands, stop looking.
955 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
956 if (i + NumOps > OpIdx) {
966 const TargetRegisterClass*
967 MachineInstr::getRegClassConstraint(unsigned OpIdx,
968 const TargetInstrInfo *TII,
969 const TargetRegisterInfo *TRI) const {
970 assert(getParent() && "Can't have an MBB reference here!");
971 assert(getParent()->getParent() && "Can't have an MF reference here!");
972 const MachineFunction &MF = *getParent()->getParent();
974 // Most opcodes have fixed constraints in their MCInstrDesc.
976 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
978 if (!getOperand(OpIdx).isReg())
981 // For tied uses on inline asm, get the constraint from the def.
983 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
986 // Inline asm stores register class constraints in the flag word.
987 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
991 unsigned Flag = getOperand(FlagIdx).getImm();
993 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
994 return TRI->getRegClass(RCID);
996 // Assume that all registers in a memory operand are pointers.
997 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
998 return TRI->getPointerRegClass(MF);
1003 /// getBundleSize - Return the number of instructions inside the MI bundle.
1004 unsigned MachineInstr::getBundleSize() const {
1005 assert(isBundle() && "Expecting a bundle");
1007 MachineBasicBlock::const_instr_iterator I = *this;
1009 while ((++I)->isInsideBundle()) {
1012 assert(Size > 1 && "Malformed bundle");
1017 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1018 /// the specific register or -1 if it is not found. It further tightens
1019 /// the search criteria to a use that kills the register if isKill is true.
1020 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1021 const TargetRegisterInfo *TRI) const {
1022 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1023 const MachineOperand &MO = getOperand(i);
1024 if (!MO.isReg() || !MO.isUse())
1026 unsigned MOReg = MO.getReg();
1031 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1032 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1033 TRI->isSubRegister(MOReg, Reg)))
1034 if (!isKill || MO.isKill())
1040 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1041 /// indicating if this instruction reads or writes Reg. This also considers
1042 /// partial defines.
1043 std::pair<bool,bool>
1044 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1045 SmallVectorImpl<unsigned> *Ops) const {
1046 bool PartDef = false; // Partial redefine.
1047 bool FullDef = false; // Full define.
1050 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1051 const MachineOperand &MO = getOperand(i);
1052 if (!MO.isReg() || MO.getReg() != Reg)
1057 Use |= !MO.isUndef();
1058 else if (MO.getSubReg() && !MO.isUndef())
1059 // A partial <def,undef> doesn't count as reading the register.
1064 // A partial redefine uses Reg unless there is also a full define.
1065 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1068 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1069 /// the specified register or -1 if it is not found. If isDead is true, defs
1070 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1071 /// also checks if there is a def of a super-register.
1073 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1074 const TargetRegisterInfo *TRI) const {
1075 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1076 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1077 const MachineOperand &MO = getOperand(i);
1078 // Accept regmask operands when Overlap is set.
1079 // Ignore them when looking for a specific def operand (Overlap == false).
1080 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1082 if (!MO.isReg() || !MO.isDef())
1084 unsigned MOReg = MO.getReg();
1085 bool Found = (MOReg == Reg);
1086 if (!Found && TRI && isPhys &&
1087 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1089 Found = TRI->regsOverlap(MOReg, Reg);
1091 Found = TRI->isSubRegister(MOReg, Reg);
1093 if (Found && (!isDead || MO.isDead()))
1099 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1100 /// operand list that is used to represent the predicate. It returns -1 if
1102 int MachineInstr::findFirstPredOperandIdx() const {
1103 // Don't call MCID.findFirstPredOperandIdx() because this variant
1104 // is sometimes called on an instruction that's not yet complete, and
1105 // so the number of operands is less than the MCID indicates. In
1106 // particular, the PTX target does this.
1107 const MCInstrDesc &MCID = getDesc();
1108 if (MCID.isPredicable()) {
1109 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1110 if (MCID.OpInfo[i].isPredicate())
1117 /// isRegTiedToUseOperand - Given the index of a register def operand,
1118 /// check if the register def is tied to a source operand, due to either
1119 /// two-address elimination or inline assembly constraints. Returns the
1120 /// first tied use operand index by reference is UseOpIdx is not null.
1122 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
1123 if (isInlineAsm()) {
1124 assert(DefOpIdx > InlineAsm::MIOp_FirstOperand);
1125 const MachineOperand &MO = getOperand(DefOpIdx);
1126 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
1128 // Determine the actual operand index that corresponds to this index.
1130 int FlagIdx = findInlineAsmFlagIdx(DefOpIdx, &DefNo);
1134 // Which part of the group is DefOpIdx?
1135 unsigned DefPart = DefOpIdx - (FlagIdx + 1);
1137 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands();
1139 const MachineOperand &FMO = getOperand(i);
1142 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
1145 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
1148 *UseOpIdx = (unsigned)i + 1 + DefPart;
1155 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
1156 const MCInstrDesc &MCID = getDesc();
1157 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
1158 const MachineOperand &MO = getOperand(i);
1159 if (MO.isReg() && MO.isUse() &&
1160 MCID.getOperandConstraint(i, MCOI::TIED_TO) == (int)DefOpIdx) {
1162 *UseOpIdx = (unsigned)i;
1169 /// isRegTiedToDefOperand - Return true if the operand of the specified index
1170 /// is a register use and it is tied to an def operand. It also returns the def
1171 /// operand index by reference.
1173 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
1174 if (isInlineAsm()) {
1175 const MachineOperand &MO = getOperand(UseOpIdx);
1176 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
1179 // Find the flag operand corresponding to UseOpIdx
1180 int FlagIdx = findInlineAsmFlagIdx(UseOpIdx);
1184 const MachineOperand &UFMO = getOperand(FlagIdx);
1186 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
1190 unsigned DefIdx = InlineAsm::MIOp_FirstOperand;
1191 // Remember to adjust the index. First operand is asm string, second is
1192 // the HasSideEffects and AlignStack bits, then there is a flag for each.
1194 const MachineOperand &FMO = getOperand(DefIdx);
1195 assert(FMO.isImm());
1196 // Skip over this def.
1197 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
1200 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
1206 const MCInstrDesc &MCID = getDesc();
1207 if (UseOpIdx >= MCID.getNumOperands())
1209 const MachineOperand &MO = getOperand(UseOpIdx);
1210 if (!MO.isReg() || !MO.isUse())
1212 int DefIdx = MCID.getOperandConstraint(UseOpIdx, MCOI::TIED_TO);
1216 *DefOpIdx = (unsigned)DefIdx;
1220 /// clearKillInfo - Clears kill flags on all operands.
1222 void MachineInstr::clearKillInfo() {
1223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1224 MachineOperand &MO = getOperand(i);
1225 if (MO.isReg() && MO.isUse())
1226 MO.setIsKill(false);
1230 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1232 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1233 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1234 const MachineOperand &MO = MI->getOperand(i);
1235 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1237 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1238 MachineOperand &MOp = getOperand(j);
1239 if (!MOp.isIdenticalTo(MO))
1250 /// copyPredicates - Copies predicate operand(s) from MI.
1251 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1252 assert(!isBundle() && "MachineInstr::copyPredicates() can't handle bundles");
1254 const MCInstrDesc &MCID = MI->getDesc();
1255 if (!MCID.isPredicable())
1257 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1258 if (MCID.OpInfo[i].isPredicate()) {
1259 // Predicated operands must be last operands.
1260 addOperand(MI->getOperand(i));
1265 void MachineInstr::substituteRegister(unsigned FromReg,
1268 const TargetRegisterInfo &RegInfo) {
1269 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1271 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1272 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1273 MachineOperand &MO = getOperand(i);
1274 if (!MO.isReg() || MO.getReg() != FromReg)
1276 MO.substPhysReg(ToReg, RegInfo);
1279 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1280 MachineOperand &MO = getOperand(i);
1281 if (!MO.isReg() || MO.getReg() != FromReg)
1283 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1288 /// isSafeToMove - Return true if it is safe to move this instruction. If
1289 /// SawStore is set to true, it means that there is a store (or call) between
1290 /// the instruction's location and its intended destination.
1291 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1293 bool &SawStore) const {
1294 // Ignore stuff that we obviously can't move.
1295 if (mayStore() || isCall()) {
1300 if (isLabel() || isDebugValue() ||
1301 isTerminator() || hasUnmodeledSideEffects())
1304 // See if this instruction does a load. If so, we have to guarantee that the
1305 // loaded value doesn't change between the load and the its intended
1306 // destination. The check for isInvariantLoad gives the targe the chance to
1307 // classify the load as always returning a constant, e.g. a constant pool
1309 if (mayLoad() && !isInvariantLoad(AA))
1310 // Otherwise, this is a real load. If there is a store between the load and
1311 // end of block, or if the load is volatile, we can't move it.
1312 return !SawStore && !hasVolatileMemoryRef();
1317 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1318 /// instruction which defined the specified register instead of copying it.
1319 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1321 unsigned DstReg) const {
1322 bool SawStore = false;
1323 if (!TII->isTriviallyReMaterializable(this, AA) ||
1324 !isSafeToMove(TII, AA, SawStore))
1326 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1327 const MachineOperand &MO = getOperand(i);
1330 // FIXME: For now, do not remat any instruction with register operands.
1331 // Later on, we can loosen the restriction is the register operands have
1332 // not been modified between the def and use. Note, this is different from
1333 // MachineSink because the code is no longer in two-address form (at least
1337 else if (!MO.isDead() && MO.getReg() != DstReg)
1343 /// hasVolatileMemoryRef - Return true if this instruction may have a
1344 /// volatile memory reference, or if the information describing the
1345 /// memory reference is not available. Return false if it is known to
1346 /// have no volatile memory references.
1347 bool MachineInstr::hasVolatileMemoryRef() const {
1348 // An instruction known never to access memory won't have a volatile access.
1352 !hasUnmodeledSideEffects())
1355 // Otherwise, if the instruction has no memory reference information,
1356 // conservatively assume it wasn't preserved.
1357 if (memoperands_empty())
1360 // Check the memory reference information for volatile references.
1361 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1362 if ((*I)->isVolatile())
1368 /// isInvariantLoad - Return true if this instruction is loading from a
1369 /// location whose value is invariant across the function. For example,
1370 /// loading a value from the constant pool or from the argument area
1371 /// of a function if it does not change. This should only return true of
1372 /// *all* loads the instruction does are invariant (if it does multiple loads).
1373 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1374 // If the instruction doesn't load at all, it isn't an invariant load.
1378 // If the instruction has lost its memoperands, conservatively assume that
1379 // it may not be an invariant load.
1380 if (memoperands_empty())
1383 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1385 for (mmo_iterator I = memoperands_begin(),
1386 E = memoperands_end(); I != E; ++I) {
1387 if ((*I)->isVolatile()) return false;
1388 if ((*I)->isStore()) return false;
1389 if ((*I)->isInvariant()) return true;
1391 if (const Value *V = (*I)->getValue()) {
1392 // A load from a constant PseudoSourceValue is invariant.
1393 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1394 if (PSV->isConstant(MFI))
1396 // If we have an AliasAnalysis, ask it whether the memory is constant.
1397 if (AA && AA->pointsToConstantMemory(
1398 AliasAnalysis::Location(V, (*I)->getSize(),
1399 (*I)->getTBAAInfo())))
1403 // Otherwise assume conservatively.
1407 // Everything checks out.
1411 /// isConstantValuePHI - If the specified instruction is a PHI that always
1412 /// merges together the same virtual register, return the register, otherwise
1414 unsigned MachineInstr::isConstantValuePHI() const {
1417 assert(getNumOperands() >= 3 &&
1418 "It's illegal to have a PHI without source operands");
1420 unsigned Reg = getOperand(1).getReg();
1421 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1422 if (getOperand(i).getReg() != Reg)
1427 bool MachineInstr::hasUnmodeledSideEffects() const {
1428 if (hasProperty(MCID::UnmodeledSideEffects))
1430 if (isInlineAsm()) {
1431 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1432 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1439 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1441 bool MachineInstr::allDefsAreDead() const {
1442 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1443 const MachineOperand &MO = getOperand(i);
1444 if (!MO.isReg() || MO.isUse())
1452 /// copyImplicitOps - Copy implicit register operands from specified
1453 /// instruction to this instruction.
1454 void MachineInstr::copyImplicitOps(const MachineInstr *MI) {
1455 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1457 const MachineOperand &MO = MI->getOperand(i);
1458 if (MO.isReg() && MO.isImplicit())
1463 void MachineInstr::dump() const {
1464 dbgs() << " " << *this;
1467 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1468 raw_ostream &CommentOS) {
1469 const LLVMContext &Ctx = MF->getFunction()->getContext();
1470 if (!DL.isUnknown()) { // Print source line info.
1471 DIScope Scope(DL.getScope(Ctx));
1472 // Omit the directory, because it's likely to be long and uninteresting.
1474 CommentOS << Scope.getFilename();
1476 CommentOS << "<unknown>";
1477 CommentOS << ':' << DL.getLine();
1478 if (DL.getCol() != 0)
1479 CommentOS << ':' << DL.getCol();
1480 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1481 if (!InlinedAtDL.isUnknown()) {
1482 CommentOS << " @[ ";
1483 printDebugLoc(InlinedAtDL, MF, CommentOS);
1489 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1490 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1491 const MachineFunction *MF = 0;
1492 const MachineRegisterInfo *MRI = 0;
1493 if (const MachineBasicBlock *MBB = getParent()) {
1494 MF = MBB->getParent();
1496 TM = &MF->getTarget();
1498 MRI = &MF->getRegInfo();
1501 // Save a list of virtual registers.
1502 SmallVector<unsigned, 8> VirtRegs;
1504 // Print explicitly defined operands on the left of an assignment syntax.
1505 unsigned StartOp = 0, e = getNumOperands();
1506 for (; StartOp < e && getOperand(StartOp).isReg() &&
1507 getOperand(StartOp).isDef() &&
1508 !getOperand(StartOp).isImplicit();
1510 if (StartOp != 0) OS << ", ";
1511 getOperand(StartOp).print(OS, TM);
1512 unsigned Reg = getOperand(StartOp).getReg();
1513 if (TargetRegisterInfo::isVirtualRegister(Reg))
1514 VirtRegs.push_back(Reg);
1520 // Print the opcode name.
1521 if (TM && TM->getInstrInfo())
1522 OS << TM->getInstrInfo()->getName(getOpcode());
1526 // Print the rest of the operands.
1527 bool OmittedAnyCallClobbers = false;
1528 bool FirstOp = true;
1529 unsigned AsmDescOp = ~0u;
1530 unsigned AsmOpCount = 0;
1532 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1533 // Print asm string.
1535 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1537 // Print HasSideEffects, IsAlignStack
1538 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1539 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1540 OS << " [sideeffect]";
1541 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1542 OS << " [alignstack]";
1544 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1549 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1550 const MachineOperand &MO = getOperand(i);
1552 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1553 VirtRegs.push_back(MO.getReg());
1555 // Omit call-clobbered registers which aren't used anywhere. This makes
1556 // call instructions much less noisy on targets where calls clobber lots
1557 // of registers. Don't rely on MO.isDead() because we may be called before
1558 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1559 if (MF && isCall() &&
1560 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1561 unsigned Reg = MO.getReg();
1562 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1563 const MachineRegisterInfo &MRI = MF->getRegInfo();
1564 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1565 bool HasAliasLive = false;
1566 for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
1567 AI.isValid(); ++AI) {
1568 unsigned AliasReg = *AI;
1569 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1570 HasAliasLive = true;
1574 if (!HasAliasLive) {
1575 OmittedAnyCallClobbers = true;
1582 if (FirstOp) FirstOp = false; else OS << ",";
1584 if (i < getDesc().NumOperands) {
1585 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1586 if (MCOI.isPredicate())
1588 if (MCOI.isOptionalDef())
1591 if (isDebugValue() && MO.isMetadata()) {
1592 // Pretty print DBG_VALUE instructions.
1593 const MDNode *MD = MO.getMetadata();
1594 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1595 OS << "!\"" << MDS->getString() << '\"';
1598 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1599 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1600 } else if (i == AsmDescOp && MO.isImm()) {
1601 // Pretty print the inline asm operand descriptor.
1602 OS << '$' << AsmOpCount++;
1603 unsigned Flag = MO.getImm();
1604 switch (InlineAsm::getKind(Flag)) {
1605 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1606 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1607 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1608 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1609 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1610 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1611 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1615 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1617 OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1619 OS << ":RC" << RCID;
1622 unsigned TiedTo = 0;
1623 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1624 OS << " tiedto:$" << TiedTo;
1628 // Compute the index of the next operand descriptor.
1629 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1634 // Briefly indicate whether any call clobbers were omitted.
1635 if (OmittedAnyCallClobbers) {
1636 if (!FirstOp) OS << ",";
1640 bool HaveSemi = false;
1642 if (!HaveSemi) OS << ";"; HaveSemi = true;
1645 if (Flags & FrameSetup)
1649 if (!memoperands_empty()) {
1650 if (!HaveSemi) OS << ";"; HaveSemi = true;
1653 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1656 if (llvm::next(i) != e)
1661 // Print the regclass of any virtual registers encountered.
1662 if (MRI && !VirtRegs.empty()) {
1663 if (!HaveSemi) OS << ";"; HaveSemi = true;
1664 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1665 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1666 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1667 for (unsigned j = i+1; j != VirtRegs.size();) {
1668 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1672 if (VirtRegs[i] != VirtRegs[j])
1673 OS << "," << PrintReg(VirtRegs[j]);
1674 VirtRegs.erase(VirtRegs.begin()+j);
1679 // Print debug location information.
1680 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1681 if (!HaveSemi) OS << ";"; HaveSemi = true;
1682 DIVariable DV(getOperand(e - 1).getMetadata());
1683 OS << " line no:" << DV.getLineNumber();
1684 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1685 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1686 if (!InlinedAtDL.isUnknown()) {
1687 OS << " inlined @[ ";
1688 printDebugLoc(InlinedAtDL, MF, OS);
1692 } else if (!debugLoc.isUnknown() && MF) {
1693 if (!HaveSemi) OS << ";"; HaveSemi = true;
1695 printDebugLoc(debugLoc, MF, OS);
1701 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1702 const TargetRegisterInfo *RegInfo,
1703 bool AddIfNotFound) {
1704 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1705 bool hasAliases = isPhysReg &&
1706 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1708 SmallVector<unsigned,4> DeadOps;
1709 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1710 MachineOperand &MO = getOperand(i);
1711 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1713 unsigned Reg = MO.getReg();
1717 if (Reg == IncomingReg) {
1720 // The register is already marked kill.
1722 if (isPhysReg && isRegTiedToDefOperand(i))
1723 // Two-address uses of physregs must not be marked kill.
1728 } else if (hasAliases && MO.isKill() &&
1729 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1730 // A super-register kill already exists.
1731 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1733 if (RegInfo->isSubRegister(IncomingReg, Reg))
1734 DeadOps.push_back(i);
1738 // Trim unneeded kill operands.
1739 while (!DeadOps.empty()) {
1740 unsigned OpIdx = DeadOps.back();
1741 if (getOperand(OpIdx).isImplicit())
1742 RemoveOperand(OpIdx);
1744 getOperand(OpIdx).setIsKill(false);
1748 // If not found, this means an alias of one of the operands is killed. Add a
1749 // new implicit operand if required.
1750 if (!Found && AddIfNotFound) {
1751 addOperand(MachineOperand::CreateReg(IncomingReg,
1760 void MachineInstr::clearRegisterKills(unsigned Reg,
1761 const TargetRegisterInfo *RegInfo) {
1762 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1764 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1765 MachineOperand &MO = getOperand(i);
1766 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1768 unsigned OpReg = MO.getReg();
1769 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1770 MO.setIsKill(false);
1774 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1775 const TargetRegisterInfo *RegInfo,
1776 bool AddIfNotFound) {
1777 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1778 bool hasAliases = isPhysReg &&
1779 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1781 SmallVector<unsigned,4> DeadOps;
1782 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1783 MachineOperand &MO = getOperand(i);
1784 if (!MO.isReg() || !MO.isDef())
1786 unsigned Reg = MO.getReg();
1790 if (Reg == IncomingReg) {
1793 } else if (hasAliases && MO.isDead() &&
1794 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1795 // There exists a super-register that's marked dead.
1796 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1798 if (RegInfo->isSubRegister(IncomingReg, Reg))
1799 DeadOps.push_back(i);
1803 // Trim unneeded dead operands.
1804 while (!DeadOps.empty()) {
1805 unsigned OpIdx = DeadOps.back();
1806 if (getOperand(OpIdx).isImplicit())
1807 RemoveOperand(OpIdx);
1809 getOperand(OpIdx).setIsDead(false);
1813 // If not found, this means an alias of one of the operands is dead. Add a
1814 // new implicit operand if required.
1815 if (Found || !AddIfNotFound)
1818 addOperand(MachineOperand::CreateReg(IncomingReg,
1826 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1827 const TargetRegisterInfo *RegInfo) {
1828 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1829 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1833 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1834 const MachineOperand &MO = getOperand(i);
1835 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1836 MO.getSubReg() == 0)
1840 addOperand(MachineOperand::CreateReg(IncomingReg,
1845 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1846 const TargetRegisterInfo &TRI) {
1847 bool HasRegMask = false;
1848 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1849 MachineOperand &MO = getOperand(i);
1850 if (MO.isRegMask()) {
1854 if (!MO.isReg() || !MO.isDef()) continue;
1855 unsigned Reg = MO.getReg();
1856 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1858 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1860 if (TRI.regsOverlap(*I, Reg)) {
1864 // If there are no uses, including partial uses, the def is dead.
1865 if (Dead) MO.setIsDead();
1868 // This is a call with a register mask operand.
1869 // Mask clobbers are always dead, so add defs for the non-dead defines.
1871 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1873 addRegisterDefined(*I, &TRI);
1877 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1878 // Build up a buffer of hash code components.
1879 SmallVector<size_t, 8> HashComponents;
1880 HashComponents.reserve(MI->getNumOperands() + 1);
1881 HashComponents.push_back(MI->getOpcode());
1882 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1883 const MachineOperand &MO = MI->getOperand(i);
1884 if (MO.isReg() && MO.isDef() &&
1885 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1886 continue; // Skip virtual register defs.
1888 HashComponents.push_back(hash_value(MO));
1890 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1893 void MachineInstr::emitError(StringRef Msg) const {
1894 // Find the source location cookie.
1895 unsigned LocCookie = 0;
1896 const MDNode *LocMD = 0;
1897 for (unsigned i = getNumOperands(); i != 0; --i) {
1898 if (getOperand(i-1).isMetadata() &&
1899 (LocMD = getOperand(i-1).getMetadata()) &&
1900 LocMD->getNumOperands() != 0) {
1901 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1902 LocCookie = CI->getZExtValue();
1908 if (const MachineBasicBlock *MBB = getParent())
1909 if (const MachineFunction *MF = MBB->getParent())
1910 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1911 report_fatal_error(Msg);