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/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/DebugInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/IR/Writer.h"
34 #include "llvm/MC/MCInstrDesc.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
45 //===----------------------------------------------------------------------===//
46 // MachineOperand Implementation
47 //===----------------------------------------------------------------------===//
49 void MachineOperand::setReg(unsigned Reg) {
50 if (getReg() == Reg) return; // No change.
52 // Otherwise, we have to change the register. If this operand is embedded
53 // into a machine function, we need to update the old and new register's
55 if (MachineInstr *MI = getParent())
56 if (MachineBasicBlock *MBB = MI->getParent())
57 if (MachineFunction *MF = MBB->getParent()) {
58 MachineRegisterInfo &MRI = MF->getRegInfo();
59 MRI.removeRegOperandFromUseList(this);
60 SmallContents.RegNo = Reg;
61 MRI.addRegOperandToUseList(this);
65 // Otherwise, just change the register, no problem. :)
66 SmallContents.RegNo = Reg;
69 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
70 const TargetRegisterInfo &TRI) {
71 assert(TargetRegisterInfo::isVirtualRegister(Reg));
72 if (SubIdx && getSubReg())
73 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
79 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
80 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
82 Reg = TRI.getSubReg(Reg, getSubReg());
83 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
84 // That won't happen in legal code.
90 /// Change a def to a use, or a use to a def.
91 void MachineOperand::setIsDef(bool Val) {
92 assert(isReg() && "Wrong MachineOperand accessor");
93 assert((!Val || !isDebug()) && "Marking a debug operation as def");
96 // MRI may keep uses and defs in different list positions.
97 if (MachineInstr *MI = getParent())
98 if (MachineBasicBlock *MBB = MI->getParent())
99 if (MachineFunction *MF = MBB->getParent()) {
100 MachineRegisterInfo &MRI = MF->getRegInfo();
101 MRI.removeRegOperandFromUseList(this);
103 MRI.addRegOperandToUseList(this);
109 /// ChangeToImmediate - Replace this operand with a new immediate operand of
110 /// the specified value. If an operand is known to be an immediate already,
111 /// the setImm method should be used.
112 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
113 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
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 bool WasReg = isReg();
140 if (RegInfo && WasReg)
141 RegInfo->removeRegOperandFromUseList(this);
143 // Change this to a register and set the reg#.
144 OpKind = MO_Register;
145 SmallContents.RegNo = Reg;
146 SubReg_TargetFlags = 0;
152 IsInternalRead = false;
153 IsEarlyClobber = false;
155 // Ensure isOnRegUseList() returns false.
156 Contents.Reg.Prev = 0;
157 // Preserve the tie when the operand was already a register.
161 // If this operand is embedded in a function, add the operand to the
162 // register's use/def list.
164 RegInfo->addRegOperandToUseList(this);
167 /// isIdenticalTo - Return true if this operand is identical to the specified
168 /// operand. Note that this should stay in sync with the hash_value overload
170 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
171 if (getType() != Other.getType() ||
172 getTargetFlags() != Other.getTargetFlags())
176 case MachineOperand::MO_Register:
177 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
178 getSubReg() == Other.getSubReg();
179 case MachineOperand::MO_Immediate:
180 return getImm() == Other.getImm();
181 case MachineOperand::MO_CImmediate:
182 return getCImm() == Other.getCImm();
183 case MachineOperand::MO_FPImmediate:
184 return getFPImm() == Other.getFPImm();
185 case MachineOperand::MO_MachineBasicBlock:
186 return getMBB() == Other.getMBB();
187 case MachineOperand::MO_FrameIndex:
188 return getIndex() == Other.getIndex();
189 case MachineOperand::MO_ConstantPoolIndex:
190 case MachineOperand::MO_TargetIndex:
191 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
192 case MachineOperand::MO_JumpTableIndex:
193 return getIndex() == Other.getIndex();
194 case MachineOperand::MO_GlobalAddress:
195 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
196 case MachineOperand::MO_ExternalSymbol:
197 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
198 getOffset() == Other.getOffset();
199 case MachineOperand::MO_BlockAddress:
200 return getBlockAddress() == Other.getBlockAddress() &&
201 getOffset() == Other.getOffset();
202 case MachineOperand::MO_RegisterMask:
203 case MachineOperand::MO_RegisterLiveOut:
204 return getRegMask() == Other.getRegMask();
205 case MachineOperand::MO_MCSymbol:
206 return getMCSymbol() == Other.getMCSymbol();
207 case MachineOperand::MO_Metadata:
208 return getMetadata() == Other.getMetadata();
210 llvm_unreachable("Invalid machine operand type");
213 // Note: this must stay exactly in sync with isIdenticalTo above.
214 hash_code llvm::hash_value(const MachineOperand &MO) {
215 switch (MO.getType()) {
216 case MachineOperand::MO_Register:
217 // Register operands don't have target flags.
218 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
219 case MachineOperand::MO_Immediate:
220 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
221 case MachineOperand::MO_CImmediate:
222 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
223 case MachineOperand::MO_FPImmediate:
224 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
225 case MachineOperand::MO_MachineBasicBlock:
226 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
227 case MachineOperand::MO_FrameIndex:
228 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
229 case MachineOperand::MO_ConstantPoolIndex:
230 case MachineOperand::MO_TargetIndex:
231 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
233 case MachineOperand::MO_JumpTableIndex:
234 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
235 case MachineOperand::MO_ExternalSymbol:
236 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
238 case MachineOperand::MO_GlobalAddress:
239 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
241 case MachineOperand::MO_BlockAddress:
242 return hash_combine(MO.getType(), MO.getTargetFlags(),
243 MO.getBlockAddress(), MO.getOffset());
244 case MachineOperand::MO_RegisterMask:
245 case MachineOperand::MO_RegisterLiveOut:
246 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
247 case MachineOperand::MO_Metadata:
248 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
249 case MachineOperand::MO_MCSymbol:
250 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
252 llvm_unreachable("Invalid machine operand type");
255 /// print - Print the specified machine operand.
257 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
258 // If the instruction is embedded into a basic block, we can find the
259 // target info for the instruction.
261 if (const MachineInstr *MI = getParent())
262 if (const MachineBasicBlock *MBB = MI->getParent())
263 if (const MachineFunction *MF = MBB->getParent())
264 TM = &MF->getTarget();
265 const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
268 case MachineOperand::MO_Register:
269 OS << PrintReg(getReg(), TRI, getSubReg());
271 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
272 isInternalRead() || isEarlyClobber() || isTied()) {
274 bool NeedComma = false;
276 if (NeedComma) OS << ',';
277 if (isEarlyClobber())
278 OS << "earlyclobber,";
283 // <def,read-undef> only makes sense when getSubReg() is set.
284 // Don't clutter the output otherwise.
285 if (isUndef() && getSubReg())
287 } else if (isImplicit()) {
293 if (NeedComma) OS << ',';
298 if (NeedComma) OS << ',';
302 if (isUndef() && isUse()) {
303 if (NeedComma) OS << ',';
307 if (isInternalRead()) {
308 if (NeedComma) OS << ',';
313 if (NeedComma) OS << ',';
316 OS << unsigned(TiedTo - 1);
322 case MachineOperand::MO_Immediate:
325 case MachineOperand::MO_CImmediate:
326 getCImm()->getValue().print(OS, false);
328 case MachineOperand::MO_FPImmediate:
329 if (getFPImm()->getType()->isFloatTy())
330 OS << getFPImm()->getValueAPF().convertToFloat();
332 OS << getFPImm()->getValueAPF().convertToDouble();
334 case MachineOperand::MO_MachineBasicBlock:
335 OS << "<BB#" << getMBB()->getNumber() << ">";
337 case MachineOperand::MO_FrameIndex:
338 OS << "<fi#" << getIndex() << '>';
340 case MachineOperand::MO_ConstantPoolIndex:
341 OS << "<cp#" << getIndex();
342 if (getOffset()) OS << "+" << getOffset();
345 case MachineOperand::MO_TargetIndex:
346 OS << "<ti#" << getIndex();
347 if (getOffset()) OS << "+" << getOffset();
350 case MachineOperand::MO_JumpTableIndex:
351 OS << "<jt#" << getIndex() << '>';
353 case MachineOperand::MO_GlobalAddress:
355 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
356 if (getOffset()) OS << "+" << getOffset();
359 case MachineOperand::MO_ExternalSymbol:
360 OS << "<es:" << getSymbolName();
361 if (getOffset()) OS << "+" << getOffset();
364 case MachineOperand::MO_BlockAddress:
366 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
367 if (getOffset()) OS << "+" << getOffset();
370 case MachineOperand::MO_RegisterMask:
373 case MachineOperand::MO_RegisterLiveOut:
374 OS << "<regliveout>";
376 case MachineOperand::MO_Metadata:
378 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
381 case MachineOperand::MO_MCSymbol:
382 OS << "<MCSym=" << *getMCSymbol() << '>';
386 if (unsigned TF = getTargetFlags())
387 OS << "[TF=" << TF << ']';
390 //===----------------------------------------------------------------------===//
391 // MachineMemOperand Implementation
392 //===----------------------------------------------------------------------===//
394 /// getAddrSpace - Return the LLVM IR address space number that this pointer
396 unsigned MachinePointerInfo::getAddrSpace() const {
397 if (V == 0) return 0;
398 return cast<PointerType>(V->getType())->getAddressSpace();
401 /// getConstantPool - Return a MachinePointerInfo record that refers to the
403 MachinePointerInfo MachinePointerInfo::getConstantPool() {
404 return MachinePointerInfo(PseudoSourceValue::getConstantPool());
407 /// getFixedStack - Return a MachinePointerInfo record that refers to the
408 /// the specified FrameIndex.
409 MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
410 return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
413 MachinePointerInfo MachinePointerInfo::getJumpTable() {
414 return MachinePointerInfo(PseudoSourceValue::getJumpTable());
417 MachinePointerInfo MachinePointerInfo::getGOT() {
418 return MachinePointerInfo(PseudoSourceValue::getGOT());
421 MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
422 return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
425 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
426 uint64_t s, unsigned int a,
427 const MDNode *TBAAInfo,
428 const MDNode *Ranges)
429 : PtrInfo(ptrinfo), Size(s),
430 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
431 TBAAInfo(TBAAInfo), Ranges(Ranges) {
432 assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
433 "invalid pointer value");
434 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
435 assert((isLoad() || isStore()) && "Not a load/store!");
438 /// Profile - Gather unique data for the object.
440 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
441 ID.AddInteger(getOffset());
443 ID.AddPointer(getValue());
444 ID.AddInteger(Flags);
447 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
448 // The Value and Offset may differ due to CSE. But the flags and size
449 // should be the same.
450 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
451 assert(MMO->getSize() == getSize() && "Size mismatch!");
453 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
454 // Update the alignment value.
455 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
456 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
457 // Also update the base and offset, because the new alignment may
458 // not be applicable with the old ones.
459 PtrInfo = MMO->PtrInfo;
463 /// getAlignment - Return the minimum known alignment in bytes of the
464 /// actual memory reference.
465 uint64_t MachineMemOperand::getAlignment() const {
466 return MinAlign(getBaseAlignment(), getOffset());
469 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
470 assert((MMO.isLoad() || MMO.isStore()) &&
471 "SV has to be a load, store or both.");
473 if (MMO.isVolatile())
482 // Print the address information.
487 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
489 unsigned AS = MMO.getAddrSpace();
491 OS << "(addrspace=" << AS << ')';
493 // If the alignment of the memory reference itself differs from the alignment
494 // of the base pointer, print the base alignment explicitly, next to the base
496 if (MMO.getBaseAlignment() != MMO.getAlignment())
497 OS << "(align=" << MMO.getBaseAlignment() << ")";
499 if (MMO.getOffset() != 0)
500 OS << "+" << MMO.getOffset();
503 // Print the alignment of the reference.
504 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
505 MMO.getBaseAlignment() != MMO.getSize())
506 OS << "(align=" << MMO.getAlignment() << ")";
509 if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
511 if (TBAAInfo->getNumOperands() > 0)
512 WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
518 // Print nontemporal info.
519 if (MMO.isNonTemporal())
520 OS << "(nontemporal)";
525 //===----------------------------------------------------------------------===//
526 // MachineInstr Implementation
527 //===----------------------------------------------------------------------===//
529 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
530 if (MCID->ImplicitDefs)
531 for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
532 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
533 if (MCID->ImplicitUses)
534 for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
535 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
538 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
539 /// implicit operands. It reserves space for the number of operands specified by
541 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
542 const DebugLoc dl, bool NoImp)
543 : MCID(&tid), Parent(0), Operands(0), NumOperands(0),
544 Flags(0), AsmPrinterFlags(0),
545 NumMemRefs(0), MemRefs(0), debugLoc(dl) {
546 // Reserve space for the expected number of operands.
547 if (unsigned NumOps = MCID->getNumOperands() +
548 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
549 CapOperands = OperandCapacity::get(NumOps);
550 Operands = MF.allocateOperandArray(CapOperands);
554 addImplicitDefUseOperands(MF);
557 /// MachineInstr ctor - Copies MachineInstr arg exactly
559 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
560 : MCID(&MI.getDesc()), Parent(0), Operands(0), NumOperands(0),
561 Flags(0), AsmPrinterFlags(0),
562 NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
563 debugLoc(MI.getDebugLoc()) {
564 CapOperands = OperandCapacity::get(MI.getNumOperands());
565 Operands = MF.allocateOperandArray(CapOperands);
568 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
569 addOperand(MF, MI.getOperand(i));
571 // Copy all the sensible flags.
575 /// getRegInfo - If this instruction is embedded into a MachineFunction,
576 /// return the MachineRegisterInfo object for the current function, otherwise
578 MachineRegisterInfo *MachineInstr::getRegInfo() {
579 if (MachineBasicBlock *MBB = getParent())
580 return &MBB->getParent()->getRegInfo();
584 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
585 /// this instruction from their respective use lists. This requires that the
586 /// operands already be on their use lists.
587 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
588 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
589 if (Operands[i].isReg())
590 MRI.removeRegOperandFromUseList(&Operands[i]);
593 /// AddRegOperandsToUseLists - Add all of the register operands in
594 /// this instruction from their respective use lists. This requires that the
595 /// operands not be on their use lists yet.
596 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
597 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
598 if (Operands[i].isReg())
599 MRI.addRegOperandToUseList(&Operands[i]);
602 void MachineInstr::addOperand(const MachineOperand &Op) {
603 MachineBasicBlock *MBB = getParent();
604 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
605 MachineFunction *MF = MBB->getParent();
606 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
610 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
611 /// ranges. If MRI is non-null also update use-def chains.
612 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
613 unsigned NumOps, MachineRegisterInfo *MRI) {
615 return MRI->moveOperands(Dst, Src, NumOps);
617 // Here it would be convenient to call memmove, so that isn't allowed because
618 // MachineOperand has a constructor and so isn't a POD type.
620 for (unsigned i = 0; i != NumOps; ++i)
621 new (Dst + i) MachineOperand(Src[i]);
623 for (unsigned i = NumOps; i ; --i)
624 new (Dst + i - 1) MachineOperand(Src[i - 1]);
627 /// addOperand - Add the specified operand to the instruction. If it is an
628 /// implicit operand, it is added to the end of the operand list. If it is
629 /// an explicit operand it is added at the end of the explicit operand list
630 /// (before the first implicit operand).
631 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
632 assert(MCID && "Cannot add operands before providing an instr descriptor");
634 // Check if we're adding one of our existing operands.
635 if (&Op >= Operands && &Op < Operands + NumOperands) {
636 // This is unusual: MI->addOperand(MI->getOperand(i)).
637 // If adding Op requires reallocating or moving existing operands around,
638 // the Op reference could go stale. Support it by copying Op.
639 MachineOperand CopyOp(Op);
640 return addOperand(MF, CopyOp);
643 // Find the insert location for the new operand. Implicit registers go at
644 // the end, everything else goes before the implicit regs.
646 // FIXME: Allow mixed explicit and implicit operands on inline asm.
647 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
648 // implicit-defs, but they must not be moved around. See the FIXME in
650 unsigned OpNo = getNumOperands();
651 bool isImpReg = Op.isReg() && Op.isImplicit();
652 if (!isImpReg && !isInlineAsm()) {
653 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
655 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
660 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
661 // OpNo now points as the desired insertion point. Unless this is a variadic
662 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
663 // RegMask operands go between the explicit and implicit operands.
664 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
665 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
666 "Trying to add an operand to a machine instr that is already done!");
669 MachineRegisterInfo *MRI = getRegInfo();
671 // Determine if the Operands array needs to be reallocated.
672 // Save the old capacity and operand array.
673 OperandCapacity OldCap = CapOperands;
674 MachineOperand *OldOperands = Operands;
675 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
676 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
677 Operands = MF.allocateOperandArray(CapOperands);
678 // Move the operands before the insertion point.
680 moveOperands(Operands, OldOperands, OpNo, MRI);
683 // Move the operands following the insertion point.
684 if (OpNo != NumOperands)
685 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
689 // Deallocate the old operand array.
690 if (OldOperands != Operands && OldOperands)
691 MF.deallocateOperandArray(OldCap, OldOperands);
693 // Copy Op into place. It still needs to be inserted into the MRI use lists.
694 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
695 NewMO->ParentMI = this;
697 // When adding a register operand, tell MRI about it.
698 if (NewMO->isReg()) {
699 // Ensure isOnRegUseList() returns false, regardless of Op's status.
700 NewMO->Contents.Reg.Prev = 0;
701 // Ignore existing ties. This is not a property that can be copied.
703 // Add the new operand to MRI, but only for instructions in an MBB.
705 MRI->addRegOperandToUseList(NewMO);
706 // The MCID operand information isn't accurate until we start adding
707 // explicit operands. The implicit operands are added first, then the
708 // explicits are inserted before them.
710 // Tie uses to defs as indicated in MCInstrDesc.
711 if (NewMO->isUse()) {
712 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
714 tieOperands(DefIdx, OpNo);
716 // If the register operand is flagged as early, mark the operand as such.
717 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
718 NewMO->setIsEarlyClobber(true);
723 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
724 /// fewer operand than it started with.
726 void MachineInstr::RemoveOperand(unsigned OpNo) {
727 assert(OpNo < getNumOperands() && "Invalid operand number");
728 untieRegOperand(OpNo);
731 // Moving tied operands would break the ties.
732 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
733 if (Operands[i].isReg())
734 assert(!Operands[i].isTied() && "Cannot move tied operands");
737 MachineRegisterInfo *MRI = getRegInfo();
738 if (MRI && Operands[OpNo].isReg())
739 MRI->removeRegOperandFromUseList(Operands + OpNo);
741 // Don't call the MachineOperand destructor. A lot of this code depends on
742 // MachineOperand having a trivial destructor anyway, and adding a call here
743 // wouldn't make it 'destructor-correct'.
745 if (unsigned N = NumOperands - 1 - OpNo)
746 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
750 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
751 /// This function should be used only occasionally. The setMemRefs function
752 /// is the primary method for setting up a MachineInstr's MemRefs list.
753 void MachineInstr::addMemOperand(MachineFunction &MF,
754 MachineMemOperand *MO) {
755 mmo_iterator OldMemRefs = MemRefs;
756 unsigned OldNumMemRefs = NumMemRefs;
758 unsigned NewNum = NumMemRefs + 1;
759 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
761 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
762 NewMemRefs[NewNum - 1] = MO;
763 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
766 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
767 assert(!isBundledWithPred() && "Must be called on bundle header");
768 for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
769 if (MII->getDesc().getFlags() & Mask) {
770 if (Type == AnyInBundle)
773 if (Type == AllInBundle && !MII->isBundle())
776 // This was the last instruction in the bundle.
777 if (!MII->isBundledWithSucc())
778 return Type == AllInBundle;
782 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
783 MICheckType Check) const {
784 // If opcodes or number of operands are not the same then the two
785 // instructions are obviously not identical.
786 if (Other->getOpcode() != getOpcode() ||
787 Other->getNumOperands() != getNumOperands())
791 // Both instructions are bundles, compare MIs inside the bundle.
792 MachineBasicBlock::const_instr_iterator I1 = *this;
793 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
794 MachineBasicBlock::const_instr_iterator I2 = *Other;
795 MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
796 while (++I1 != E1 && I1->isInsideBundle()) {
798 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
803 // Check operands to make sure they match.
804 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
805 const MachineOperand &MO = getOperand(i);
806 const MachineOperand &OMO = Other->getOperand(i);
808 if (!MO.isIdenticalTo(OMO))
813 // Clients may or may not want to ignore defs when testing for equality.
814 // For example, machine CSE pass only cares about finding common
815 // subexpressions, so it's safe to ignore virtual register defs.
817 if (Check == IgnoreDefs)
819 else if (Check == IgnoreVRegDefs) {
820 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
821 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
822 if (MO.getReg() != OMO.getReg())
825 if (!MO.isIdenticalTo(OMO))
827 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
831 if (!MO.isIdenticalTo(OMO))
833 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
837 // If DebugLoc does not match then two dbg.values are not identical.
839 if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
840 && getDebugLoc() != Other->getDebugLoc())
845 MachineInstr *MachineInstr::removeFromParent() {
846 assert(getParent() && "Not embedded in a basic block!");
847 return getParent()->remove(this);
850 MachineInstr *MachineInstr::removeFromBundle() {
851 assert(getParent() && "Not embedded in a basic block!");
852 return getParent()->remove_instr(this);
855 void MachineInstr::eraseFromParent() {
856 assert(getParent() && "Not embedded in a basic block!");
857 getParent()->erase(this);
860 void MachineInstr::eraseFromBundle() {
861 assert(getParent() && "Not embedded in a basic block!");
862 getParent()->erase_instr(this);
865 /// getNumExplicitOperands - Returns the number of non-implicit operands.
867 unsigned MachineInstr::getNumExplicitOperands() const {
868 unsigned NumOperands = MCID->getNumOperands();
869 if (!MCID->isVariadic())
872 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
873 const MachineOperand &MO = getOperand(i);
874 if (!MO.isReg() || !MO.isImplicit())
880 void MachineInstr::bundleWithPred() {
881 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
882 setFlag(BundledPred);
883 MachineBasicBlock::instr_iterator Pred = this;
885 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
886 Pred->setFlag(BundledSucc);
889 void MachineInstr::bundleWithSucc() {
890 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
891 setFlag(BundledSucc);
892 MachineBasicBlock::instr_iterator Succ = this;
894 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
895 Succ->setFlag(BundledPred);
898 void MachineInstr::unbundleFromPred() {
899 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
900 clearFlag(BundledPred);
901 MachineBasicBlock::instr_iterator Pred = this;
903 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
904 Pred->clearFlag(BundledSucc);
907 void MachineInstr::unbundleFromSucc() {
908 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
909 clearFlag(BundledSucc);
910 MachineBasicBlock::instr_iterator Succ = this;
912 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
913 Succ->clearFlag(BundledPred);
916 bool MachineInstr::isStackAligningInlineAsm() const {
918 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
919 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
925 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
926 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
927 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
928 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
931 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
932 unsigned *GroupNo) const {
933 assert(isInlineAsm() && "Expected an inline asm instruction");
934 assert(OpIdx < getNumOperands() && "OpIdx out of range");
936 // Ignore queries about the initial operands.
937 if (OpIdx < InlineAsm::MIOp_FirstOperand)
942 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
944 const MachineOperand &FlagMO = getOperand(i);
945 // If we reach the implicit register operands, stop looking.
948 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
949 if (i + NumOps > OpIdx) {
959 const TargetRegisterClass*
960 MachineInstr::getRegClassConstraint(unsigned OpIdx,
961 const TargetInstrInfo *TII,
962 const TargetRegisterInfo *TRI) const {
963 assert(getParent() && "Can't have an MBB reference here!");
964 assert(getParent()->getParent() && "Can't have an MF reference here!");
965 const MachineFunction &MF = *getParent()->getParent();
967 // Most opcodes have fixed constraints in their MCInstrDesc.
969 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
971 if (!getOperand(OpIdx).isReg())
974 // For tied uses on inline asm, get the constraint from the def.
976 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
979 // Inline asm stores register class constraints in the flag word.
980 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
984 unsigned Flag = getOperand(FlagIdx).getImm();
986 if (InlineAsm::hasRegClassConstraint(Flag, RCID))
987 return TRI->getRegClass(RCID);
989 // Assume that all registers in a memory operand are pointers.
990 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
991 return TRI->getPointerRegClass(MF);
996 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
997 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
998 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
999 // Check every operands inside the bundle if we have
1002 for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
1004 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1005 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1007 // Otherwise, just check the current operands.
1008 for (ConstMIOperands OpndIt(this); OpndIt.isValid() && CurRC; ++OpndIt)
1009 CurRC = getRegClassConstraintEffectForVRegImpl(OpndIt.getOperandNo(), Reg,
1014 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1015 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1016 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1017 assert(CurRC && "Invalid initial register class");
1018 // Check if Reg is constrained by some of its use/def from MI.
1019 const MachineOperand &MO = getOperand(OpIdx);
1020 if (!MO.isReg() || MO.getReg() != Reg)
1022 // If yes, accumulate the constraints through the operand.
1023 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1026 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1027 unsigned OpIdx, const TargetRegisterClass *CurRC,
1028 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1029 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1030 const MachineOperand &MO = getOperand(OpIdx);
1031 assert(MO.isReg() &&
1032 "Cannot get register constraints for non-register operand");
1033 assert(CurRC && "Invalid initial register class");
1034 if (unsigned SubIdx = MO.getSubReg()) {
1036 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1038 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1040 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1044 /// Return the number of instructions inside the MI bundle, not counting the
1045 /// header instruction.
1046 unsigned MachineInstr::getBundleSize() const {
1047 MachineBasicBlock::const_instr_iterator I = this;
1049 while (I->isBundledWithSucc())
1054 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1055 /// the specific register or -1 if it is not found. It further tightens
1056 /// the search criteria to a use that kills the register if isKill is true.
1057 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
1058 const TargetRegisterInfo *TRI) const {
1059 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1060 const MachineOperand &MO = getOperand(i);
1061 if (!MO.isReg() || !MO.isUse())
1063 unsigned MOReg = MO.getReg();
1068 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1069 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1070 TRI->isSubRegister(MOReg, Reg)))
1071 if (!isKill || MO.isKill())
1077 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1078 /// indicating if this instruction reads or writes Reg. This also considers
1079 /// partial defines.
1080 std::pair<bool,bool>
1081 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1082 SmallVectorImpl<unsigned> *Ops) const {
1083 bool PartDef = false; // Partial redefine.
1084 bool FullDef = false; // Full define.
1087 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1088 const MachineOperand &MO = getOperand(i);
1089 if (!MO.isReg() || MO.getReg() != Reg)
1094 Use |= !MO.isUndef();
1095 else if (MO.getSubReg() && !MO.isUndef())
1096 // A partial <def,undef> doesn't count as reading the register.
1101 // A partial redefine uses Reg unless there is also a full define.
1102 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1105 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1106 /// the specified register or -1 if it is not found. If isDead is true, defs
1107 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1108 /// also checks if there is a def of a super-register.
1110 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1111 const TargetRegisterInfo *TRI) const {
1112 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1113 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1114 const MachineOperand &MO = getOperand(i);
1115 // Accept regmask operands when Overlap is set.
1116 // Ignore them when looking for a specific def operand (Overlap == false).
1117 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1119 if (!MO.isReg() || !MO.isDef())
1121 unsigned MOReg = MO.getReg();
1122 bool Found = (MOReg == Reg);
1123 if (!Found && TRI && isPhys &&
1124 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1126 Found = TRI->regsOverlap(MOReg, Reg);
1128 Found = TRI->isSubRegister(MOReg, Reg);
1130 if (Found && (!isDead || MO.isDead()))
1136 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1137 /// operand list that is used to represent the predicate. It returns -1 if
1139 int MachineInstr::findFirstPredOperandIdx() const {
1140 // Don't call MCID.findFirstPredOperandIdx() because this variant
1141 // is sometimes called on an instruction that's not yet complete, and
1142 // so the number of operands is less than the MCID indicates. In
1143 // particular, the PTX target does this.
1144 const MCInstrDesc &MCID = getDesc();
1145 if (MCID.isPredicable()) {
1146 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1147 if (MCID.OpInfo[i].isPredicate())
1154 // MachineOperand::TiedTo is 4 bits wide.
1155 const unsigned TiedMax = 15;
1157 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1159 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1160 /// field. TiedTo can have these values:
1162 /// 0: Operand is not tied to anything.
1163 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1164 /// TiedMax: Tied to an operand >= TiedMax-1.
1166 /// The tied def must be one of the first TiedMax operands on a normal
1167 /// instruction. INLINEASM instructions allow more tied defs.
1169 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1170 MachineOperand &DefMO = getOperand(DefIdx);
1171 MachineOperand &UseMO = getOperand(UseIdx);
1172 assert(DefMO.isDef() && "DefIdx must be a def operand");
1173 assert(UseMO.isUse() && "UseIdx must be a use operand");
1174 assert(!DefMO.isTied() && "Def is already tied to another use");
1175 assert(!UseMO.isTied() && "Use is already tied to another def");
1177 if (DefIdx < TiedMax)
1178 UseMO.TiedTo = DefIdx + 1;
1180 // Inline asm can use the group descriptors to find tied operands, but on
1181 // normal instruction, the tied def must be within the first TiedMax
1183 assert(isInlineAsm() && "DefIdx out of range");
1184 UseMO.TiedTo = TiedMax;
1187 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1188 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1191 /// Given the index of a tied register operand, find the operand it is tied to.
1192 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1193 /// which must exist.
1194 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1195 const MachineOperand &MO = getOperand(OpIdx);
1196 assert(MO.isTied() && "Operand isn't tied");
1198 // Normally TiedTo is in range.
1199 if (MO.TiedTo < TiedMax)
1200 return MO.TiedTo - 1;
1202 // Uses on normal instructions can be out of range.
1203 if (!isInlineAsm()) {
1204 // Normal tied defs must be in the 0..TiedMax-1 range.
1207 // MO is a def. Search for the tied use.
1208 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1209 const MachineOperand &UseMO = getOperand(i);
1210 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1213 llvm_unreachable("Can't find tied use");
1216 // Now deal with inline asm by parsing the operand group descriptor flags.
1217 // Find the beginning of each operand group.
1218 SmallVector<unsigned, 8> GroupIdx;
1219 unsigned OpIdxGroup = ~0u;
1221 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1223 const MachineOperand &FlagMO = getOperand(i);
1224 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1225 unsigned CurGroup = GroupIdx.size();
1226 GroupIdx.push_back(i);
1227 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1228 // OpIdx belongs to this operand group.
1229 if (OpIdx > i && OpIdx < i + NumOps)
1230 OpIdxGroup = CurGroup;
1232 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1234 // Operands in this group are tied to operands in TiedGroup which must be
1235 // earlier. Find the number of operands between the two groups.
1236 unsigned Delta = i - GroupIdx[TiedGroup];
1238 // OpIdx is a use tied to TiedGroup.
1239 if (OpIdxGroup == CurGroup)
1240 return OpIdx - Delta;
1242 // OpIdx is a def tied to this use group.
1243 if (OpIdxGroup == TiedGroup)
1244 return OpIdx + Delta;
1246 llvm_unreachable("Invalid tied operand on inline asm");
1249 /// clearKillInfo - Clears kill flags on all operands.
1251 void MachineInstr::clearKillInfo() {
1252 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1253 MachineOperand &MO = getOperand(i);
1254 if (MO.isReg() && MO.isUse())
1255 MO.setIsKill(false);
1259 void MachineInstr::substituteRegister(unsigned FromReg,
1262 const TargetRegisterInfo &RegInfo) {
1263 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1265 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1266 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1267 MachineOperand &MO = getOperand(i);
1268 if (!MO.isReg() || MO.getReg() != FromReg)
1270 MO.substPhysReg(ToReg, RegInfo);
1273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1274 MachineOperand &MO = getOperand(i);
1275 if (!MO.isReg() || MO.getReg() != FromReg)
1277 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1282 /// isSafeToMove - Return true if it is safe to move this instruction. If
1283 /// SawStore is set to true, it means that there is a store (or call) between
1284 /// the instruction's location and its intended destination.
1285 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1287 bool &SawStore) const {
1288 // Ignore stuff that we obviously can't move.
1290 // Treat volatile loads as stores. This is not strictly necessary for
1291 // volatiles, but it is required for atomic loads. It is not allowed to move
1292 // a load across an atomic load with Ordering > Monotonic.
1293 if (mayStore() || isCall() ||
1294 (mayLoad() && hasOrderedMemoryRef())) {
1299 if (isLabel() || isDebugValue() ||
1300 isTerminator() || hasUnmodeledSideEffects())
1303 // See if this instruction does a load. If so, we have to guarantee that the
1304 // loaded value doesn't change between the load and the its intended
1305 // destination. The check for isInvariantLoad gives the targe the chance to
1306 // classify the load as always returning a constant, e.g. a constant pool
1308 if (mayLoad() && !isInvariantLoad(AA))
1309 // Otherwise, this is a real load. If there is a store between the load and
1310 // end of block, we can't move it.
1316 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1317 /// or volatile memory reference, or if the information describing the memory
1318 /// reference is not available. Return false if it is known to have no ordered
1319 /// memory references.
1320 bool MachineInstr::hasOrderedMemoryRef() const {
1321 // An instruction known never to access memory won't have a volatile access.
1325 !hasUnmodeledSideEffects())
1328 // Otherwise, if the instruction has no memory reference information,
1329 // conservatively assume it wasn't preserved.
1330 if (memoperands_empty())
1333 // Check the memory reference information for ordered references.
1334 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1335 if (!(*I)->isUnordered())
1341 /// isInvariantLoad - Return true if this instruction is loading from a
1342 /// location whose value is invariant across the function. For example,
1343 /// loading a value from the constant pool or from the argument area
1344 /// of a function if it does not change. This should only return true of
1345 /// *all* loads the instruction does are invariant (if it does multiple loads).
1346 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1347 // If the instruction doesn't load at all, it isn't an invariant load.
1351 // If the instruction has lost its memoperands, conservatively assume that
1352 // it may not be an invariant load.
1353 if (memoperands_empty())
1356 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1358 for (mmo_iterator I = memoperands_begin(),
1359 E = memoperands_end(); I != E; ++I) {
1360 if ((*I)->isVolatile()) return false;
1361 if ((*I)->isStore()) return false;
1362 if ((*I)->isInvariant()) return true;
1364 if (const Value *V = (*I)->getValue()) {
1365 // A load from a constant PseudoSourceValue is invariant.
1366 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1367 if (PSV->isConstant(MFI))
1369 // If we have an AliasAnalysis, ask it whether the memory is constant.
1370 if (AA && AA->pointsToConstantMemory(
1371 AliasAnalysis::Location(V, (*I)->getSize(),
1372 (*I)->getTBAAInfo())))
1376 // Otherwise assume conservatively.
1380 // Everything checks out.
1384 /// isConstantValuePHI - If the specified instruction is a PHI that always
1385 /// merges together the same virtual register, return the register, otherwise
1387 unsigned MachineInstr::isConstantValuePHI() const {
1390 assert(getNumOperands() >= 3 &&
1391 "It's illegal to have a PHI without source operands");
1393 unsigned Reg = getOperand(1).getReg();
1394 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1395 if (getOperand(i).getReg() != Reg)
1400 bool MachineInstr::hasUnmodeledSideEffects() const {
1401 if (hasProperty(MCID::UnmodeledSideEffects))
1403 if (isInlineAsm()) {
1404 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1405 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1412 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1414 bool MachineInstr::allDefsAreDead() const {
1415 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1416 const MachineOperand &MO = getOperand(i);
1417 if (!MO.isReg() || MO.isUse())
1425 /// copyImplicitOps - Copy implicit register operands from specified
1426 /// instruction to this instruction.
1427 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1428 const MachineInstr *MI) {
1429 for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
1431 const MachineOperand &MO = MI->getOperand(i);
1432 if (MO.isReg() && MO.isImplicit())
1437 void MachineInstr::dump() const {
1438 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1439 dbgs() << " " << *this;
1443 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1444 raw_ostream &CommentOS) {
1445 const LLVMContext &Ctx = MF->getFunction()->getContext();
1446 if (!DL.isUnknown()) { // Print source line info.
1447 DIScope Scope(DL.getScope(Ctx));
1448 assert((!Scope || Scope.isScope()) &&
1449 "Scope of a DebugLoc should be null or a DIScope.");
1450 // Omit the directory, because it's likely to be long and uninteresting.
1452 CommentOS << Scope.getFilename();
1454 CommentOS << "<unknown>";
1455 CommentOS << ':' << DL.getLine();
1456 if (DL.getCol() != 0)
1457 CommentOS << ':' << DL.getCol();
1458 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1459 if (!InlinedAtDL.isUnknown()) {
1460 CommentOS << " @[ ";
1461 printDebugLoc(InlinedAtDL, MF, CommentOS);
1467 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
1468 bool SkipOpers) const {
1469 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1470 const MachineFunction *MF = 0;
1471 const MachineRegisterInfo *MRI = 0;
1472 if (const MachineBasicBlock *MBB = getParent()) {
1473 MF = MBB->getParent();
1475 TM = &MF->getTarget();
1477 MRI = &MF->getRegInfo();
1480 // Save a list of virtual registers.
1481 SmallVector<unsigned, 8> VirtRegs;
1483 // Print explicitly defined operands on the left of an assignment syntax.
1484 unsigned StartOp = 0, e = getNumOperands();
1485 for (; StartOp < e && getOperand(StartOp).isReg() &&
1486 getOperand(StartOp).isDef() &&
1487 !getOperand(StartOp).isImplicit();
1489 if (StartOp != 0) OS << ", ";
1490 getOperand(StartOp).print(OS, TM);
1491 unsigned Reg = getOperand(StartOp).getReg();
1492 if (TargetRegisterInfo::isVirtualRegister(Reg))
1493 VirtRegs.push_back(Reg);
1499 // Print the opcode name.
1500 if (TM && TM->getInstrInfo())
1501 OS << TM->getInstrInfo()->getName(getOpcode());
1508 // Print the rest of the operands.
1509 bool OmittedAnyCallClobbers = false;
1510 bool FirstOp = true;
1511 unsigned AsmDescOp = ~0u;
1512 unsigned AsmOpCount = 0;
1514 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1515 // Print asm string.
1517 getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
1519 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1520 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1521 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1522 OS << " [sideeffect]";
1523 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1525 if (ExtraInfo & InlineAsm::Extra_MayStore)
1526 OS << " [maystore]";
1527 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1528 OS << " [alignstack]";
1529 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1530 OS << " [attdialect]";
1531 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1532 OS << " [inteldialect]";
1534 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1539 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1540 const MachineOperand &MO = getOperand(i);
1542 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1543 VirtRegs.push_back(MO.getReg());
1545 // Omit call-clobbered registers which aren't used anywhere. This makes
1546 // call instructions much less noisy on targets where calls clobber lots
1547 // of registers. Don't rely on MO.isDead() because we may be called before
1548 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1549 if (MF && isCall() &&
1550 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1551 unsigned Reg = MO.getReg();
1552 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1553 const MachineRegisterInfo &MRI = MF->getRegInfo();
1554 if (MRI.use_empty(Reg)) {
1555 bool HasAliasLive = false;
1556 for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
1557 AI.isValid(); ++AI) {
1558 unsigned AliasReg = *AI;
1559 if (!MRI.use_empty(AliasReg)) {
1560 HasAliasLive = true;
1564 if (!HasAliasLive) {
1565 OmittedAnyCallClobbers = true;
1572 if (FirstOp) FirstOp = false; else OS << ",";
1574 if (i < getDesc().NumOperands) {
1575 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1576 if (MCOI.isPredicate())
1578 if (MCOI.isOptionalDef())
1581 if (isDebugValue() && MO.isMetadata()) {
1582 // Pretty print DBG_VALUE instructions.
1583 const MDNode *MD = MO.getMetadata();
1584 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1585 OS << "!\"" << MDS->getString() << '\"';
1588 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1589 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1590 } else if (i == AsmDescOp && MO.isImm()) {
1591 // Pretty print the inline asm operand descriptor.
1592 OS << '$' << AsmOpCount++;
1593 unsigned Flag = MO.getImm();
1594 switch (InlineAsm::getKind(Flag)) {
1595 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1596 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1597 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1598 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1599 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1600 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1601 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1605 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1607 OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
1609 OS << ":RC" << RCID;
1612 unsigned TiedTo = 0;
1613 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1614 OS << " tiedto:$" << TiedTo;
1618 // Compute the index of the next operand descriptor.
1619 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1624 // Briefly indicate whether any call clobbers were omitted.
1625 if (OmittedAnyCallClobbers) {
1626 if (!FirstOp) OS << ",";
1630 bool HaveSemi = false;
1631 const unsigned PrintableFlags = FrameSetup;
1632 if (Flags & PrintableFlags) {
1633 if (!HaveSemi) OS << ";"; HaveSemi = true;
1636 if (Flags & FrameSetup)
1640 if (!memoperands_empty()) {
1641 if (!HaveSemi) OS << ";"; HaveSemi = true;
1644 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1647 if (llvm::next(i) != e)
1652 // Print the regclass of any virtual registers encountered.
1653 if (MRI && !VirtRegs.empty()) {
1654 if (!HaveSemi) OS << ";"; HaveSemi = true;
1655 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1656 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1657 OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
1658 for (unsigned j = i+1; j != VirtRegs.size();) {
1659 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1663 if (VirtRegs[i] != VirtRegs[j])
1664 OS << "," << PrintReg(VirtRegs[j]);
1665 VirtRegs.erase(VirtRegs.begin()+j);
1670 // Print debug location information.
1671 if (isDebugValue() && getOperand(e - 1).isMetadata()) {
1672 if (!HaveSemi) OS << ";"; HaveSemi = true;
1673 DIVariable DV(getOperand(e - 1).getMetadata());
1674 OS << " line no:" << DV.getLineNumber();
1675 if (MDNode *InlinedAt = DV.getInlinedAt()) {
1676 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1677 if (!InlinedAtDL.isUnknown()) {
1678 OS << " inlined @[ ";
1679 printDebugLoc(InlinedAtDL, MF, OS);
1683 } else if (!debugLoc.isUnknown() && MF) {
1684 if (!HaveSemi) OS << ";"; HaveSemi = true;
1686 printDebugLoc(debugLoc, MF, OS);
1692 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1693 const TargetRegisterInfo *RegInfo,
1694 bool AddIfNotFound) {
1695 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1696 bool hasAliases = isPhysReg &&
1697 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
1699 SmallVector<unsigned,4> DeadOps;
1700 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1701 MachineOperand &MO = getOperand(i);
1702 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1704 unsigned Reg = MO.getReg();
1708 if (Reg == IncomingReg) {
1711 // The register is already marked kill.
1713 if (isPhysReg && isRegTiedToDefOperand(i))
1714 // Two-address uses of physregs must not be marked kill.
1719 } else if (hasAliases && MO.isKill() &&
1720 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1721 // A super-register kill already exists.
1722 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1724 if (RegInfo->isSubRegister(IncomingReg, Reg))
1725 DeadOps.push_back(i);
1729 // Trim unneeded kill operands.
1730 while (!DeadOps.empty()) {
1731 unsigned OpIdx = DeadOps.back();
1732 if (getOperand(OpIdx).isImplicit())
1733 RemoveOperand(OpIdx);
1735 getOperand(OpIdx).setIsKill(false);
1739 // If not found, this means an alias of one of the operands is killed. Add a
1740 // new implicit operand if required.
1741 if (!Found && AddIfNotFound) {
1742 addOperand(MachineOperand::CreateReg(IncomingReg,
1751 void MachineInstr::clearRegisterKills(unsigned Reg,
1752 const TargetRegisterInfo *RegInfo) {
1753 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
1755 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1756 MachineOperand &MO = getOperand(i);
1757 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1759 unsigned OpReg = MO.getReg();
1760 if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
1761 MO.setIsKill(false);
1765 bool MachineInstr::addRegisterDead(unsigned Reg,
1766 const TargetRegisterInfo *RegInfo,
1767 bool AddIfNotFound) {
1768 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
1769 bool hasAliases = isPhysReg &&
1770 MCRegAliasIterator(Reg, RegInfo, false).isValid();
1772 SmallVector<unsigned,4> DeadOps;
1773 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1774 MachineOperand &MO = getOperand(i);
1775 if (!MO.isReg() || !MO.isDef())
1777 unsigned MOReg = MO.getReg();
1784 } else if (hasAliases && MO.isDead() &&
1785 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1786 // There exists a super-register that's marked dead.
1787 if (RegInfo->isSuperRegister(Reg, MOReg))
1789 if (RegInfo->isSubRegister(Reg, MOReg))
1790 DeadOps.push_back(i);
1794 // Trim unneeded dead operands.
1795 while (!DeadOps.empty()) {
1796 unsigned OpIdx = DeadOps.back();
1797 if (getOperand(OpIdx).isImplicit())
1798 RemoveOperand(OpIdx);
1800 getOperand(OpIdx).setIsDead(false);
1804 // If not found, this means an alias of one of the operands is dead. Add a
1805 // new implicit operand if required.
1806 if (Found || !AddIfNotFound)
1809 addOperand(MachineOperand::CreateReg(Reg,
1817 void MachineInstr::addRegisterDefined(unsigned Reg,
1818 const TargetRegisterInfo *RegInfo) {
1819 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1820 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
1824 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1825 const MachineOperand &MO = getOperand(i);
1826 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
1827 MO.getSubReg() == 0)
1831 addOperand(MachineOperand::CreateReg(Reg,
1836 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1837 const TargetRegisterInfo &TRI) {
1838 bool HasRegMask = false;
1839 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1840 MachineOperand &MO = getOperand(i);
1841 if (MO.isRegMask()) {
1845 if (!MO.isReg() || !MO.isDef()) continue;
1846 unsigned Reg = MO.getReg();
1847 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1849 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1851 if (TRI.regsOverlap(*I, Reg)) {
1855 // If there are no uses, including partial uses, the def is dead.
1856 if (Dead) MO.setIsDead();
1859 // This is a call with a register mask operand.
1860 // Mask clobbers are always dead, so add defs for the non-dead defines.
1862 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
1864 addRegisterDefined(*I, &TRI);
1868 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1869 // Build up a buffer of hash code components.
1870 SmallVector<size_t, 8> HashComponents;
1871 HashComponents.reserve(MI->getNumOperands() + 1);
1872 HashComponents.push_back(MI->getOpcode());
1873 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1874 const MachineOperand &MO = MI->getOperand(i);
1875 if (MO.isReg() && MO.isDef() &&
1876 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1877 continue; // Skip virtual register defs.
1879 HashComponents.push_back(hash_value(MO));
1881 return hash_combine_range(HashComponents.begin(), HashComponents.end());
1884 void MachineInstr::emitError(StringRef Msg) const {
1885 // Find the source location cookie.
1886 unsigned LocCookie = 0;
1887 const MDNode *LocMD = 0;
1888 for (unsigned i = getNumOperands(); i != 0; --i) {
1889 if (getOperand(i-1).isMetadata() &&
1890 (LocMD = getOperand(i-1).getMetadata()) &&
1891 LocMD->getNumOperands() != 0) {
1892 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
1893 LocCookie = CI->getZExtValue();
1899 if (const MachineBasicBlock *MBB = getParent())
1900 if (const MachineFunction *MF = MBB->getParent())
1901 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
1902 report_fatal_error(Msg);