Silence some -Asserts uninitialized variable warnings.
[llvm.git] / lib / CodeGen / MachineInstr.cpp
blobd43845c2657eb0e6932738567994847e3ae4c8c3
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Metadata.h"
19 #include "llvm/Type.h"
20 #include "llvm/Value.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetInstrDesc.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/LeakDetector.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/FoldingSet.h"
40 using namespace llvm;
42 //===----------------------------------------------------------------------===//
43 // MachineOperand Implementation
44 //===----------------------------------------------------------------------===//
46 /// AddRegOperandToRegInfo - Add this register operand to the specified
47 /// MachineRegisterInfo. If it is null, then the next/prev fields should be
48 /// explicitly nulled out.
49 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
50 assert(isReg() && "Can only add reg operand to use lists");
52 // If the reginfo pointer is null, just explicitly null out or next/prev
53 // pointers, to ensure they are not garbage.
54 if (RegInfo == 0) {
55 Contents.Reg.Prev = 0;
56 Contents.Reg.Next = 0;
57 return;
60 // Otherwise, add this operand to the head of the registers use/def list.
61 MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
63 // For SSA values, we prefer to keep the definition at the start of the list.
64 // we do this by skipping over the definition if it is at the head of the
65 // list.
66 if (*Head && (*Head)->isDef())
67 Head = &(*Head)->Contents.Reg.Next;
69 Contents.Reg.Next = *Head;
70 if (Contents.Reg.Next) {
71 assert(getReg() == Contents.Reg.Next->getReg() &&
72 "Different regs on the same list!");
73 Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
76 Contents.Reg.Prev = Head;
77 *Head = this;
80 /// RemoveRegOperandFromRegInfo - Remove this register operand from the
81 /// MachineRegisterInfo it is linked with.
82 void MachineOperand::RemoveRegOperandFromRegInfo() {
83 assert(isOnRegUseList() && "Reg operand is not on a use list");
84 // Unlink this from the doubly linked list of operands.
85 MachineOperand *NextOp = Contents.Reg.Next;
86 *Contents.Reg.Prev = NextOp;
87 if (NextOp) {
88 assert(NextOp->getReg() == getReg() && "Corrupt reg use/def chain!");
89 NextOp->Contents.Reg.Prev = Contents.Reg.Prev;
91 Contents.Reg.Prev = 0;
92 Contents.Reg.Next = 0;
95 void MachineOperand::setReg(unsigned Reg) {
96 if (getReg() == Reg) return; // No change.
98 // Otherwise, we have to change the register. If this operand is embedded
99 // into a machine function, we need to update the old and new register's
100 // use/def lists.
101 if (MachineInstr *MI = getParent())
102 if (MachineBasicBlock *MBB = MI->getParent())
103 if (MachineFunction *MF = MBB->getParent()) {
104 RemoveRegOperandFromRegInfo();
105 Contents.Reg.RegNo = Reg;
106 AddRegOperandToRegInfo(&MF->getRegInfo());
107 return;
110 // Otherwise, just change the register, no problem. :)
111 Contents.Reg.RegNo = Reg;
114 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
115 const TargetRegisterInfo &TRI) {
116 assert(TargetRegisterInfo::isVirtualRegister(Reg));
117 if (SubIdx && getSubReg())
118 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
119 setReg(Reg);
120 if (SubIdx)
121 setSubReg(SubIdx);
124 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
125 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
126 if (getSubReg()) {
127 Reg = TRI.getSubReg(Reg, getSubReg());
128 assert(Reg && "Invalid SubReg for physical register");
129 setSubReg(0);
131 setReg(Reg);
134 /// ChangeToImmediate - Replace this operand with a new immediate operand of
135 /// the specified value. If an operand is known to be an immediate already,
136 /// the setImm method should be used.
137 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
138 // If this operand is currently a register operand, and if this is in a
139 // function, deregister the operand from the register's use/def list.
140 if (isReg() && getParent() && getParent()->getParent() &&
141 getParent()->getParent()->getParent())
142 RemoveRegOperandFromRegInfo();
144 OpKind = MO_Immediate;
145 Contents.ImmVal = ImmVal;
148 /// ChangeToRegister - Replace this operand with a new register operand of
149 /// the specified value. If an operand is known to be an register already,
150 /// the setReg method should be used.
151 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
152 bool isKill, bool isDead, bool isUndef,
153 bool isDebug) {
154 // If this operand is already a register operand, use setReg to update the
155 // register's use/def lists.
156 if (isReg()) {
157 assert(!isEarlyClobber());
158 setReg(Reg);
159 } else {
160 // Otherwise, change this to a register and set the reg#.
161 OpKind = MO_Register;
162 Contents.Reg.RegNo = Reg;
164 // If this operand is embedded in a function, add the operand to the
165 // register's use/def list.
166 if (MachineInstr *MI = getParent())
167 if (MachineBasicBlock *MBB = MI->getParent())
168 if (MachineFunction *MF = MBB->getParent())
169 AddRegOperandToRegInfo(&MF->getRegInfo());
172 IsDef = isDef;
173 IsImp = isImp;
174 IsKill = isKill;
175 IsDead = isDead;
176 IsUndef = isUndef;
177 IsEarlyClobber = false;
178 IsDebug = isDebug;
179 SubReg = 0;
182 /// isIdenticalTo - Return true if this operand is identical to the specified
183 /// operand.
184 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
185 if (getType() != Other.getType() ||
186 getTargetFlags() != Other.getTargetFlags())
187 return false;
189 switch (getType()) {
190 default: llvm_unreachable("Unrecognized operand type");
191 case MachineOperand::MO_Register:
192 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
193 getSubReg() == Other.getSubReg();
194 case MachineOperand::MO_Immediate:
195 return getImm() == Other.getImm();
196 case MachineOperand::MO_FPImmediate:
197 return getFPImm() == Other.getFPImm();
198 case MachineOperand::MO_MachineBasicBlock:
199 return getMBB() == Other.getMBB();
200 case MachineOperand::MO_FrameIndex:
201 return getIndex() == Other.getIndex();
202 case MachineOperand::MO_ConstantPoolIndex:
203 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
204 case MachineOperand::MO_JumpTableIndex:
205 return getIndex() == Other.getIndex();
206 case MachineOperand::MO_GlobalAddress:
207 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
208 case MachineOperand::MO_ExternalSymbol:
209 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
210 getOffset() == Other.getOffset();
211 case MachineOperand::MO_BlockAddress:
212 return getBlockAddress() == Other.getBlockAddress();
213 case MachineOperand::MO_MCSymbol:
214 return getMCSymbol() == Other.getMCSymbol();
215 case MachineOperand::MO_Metadata:
216 return getMetadata() == Other.getMetadata();
220 /// print - Print the specified machine operand.
222 void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
223 // If the instruction is embedded into a basic block, we can find the
224 // target info for the instruction.
225 if (!TM)
226 if (const MachineInstr *MI = getParent())
227 if (const MachineBasicBlock *MBB = MI->getParent())
228 if (const MachineFunction *MF = MBB->getParent())
229 TM = &MF->getTarget();
231 switch (getType()) {
232 case MachineOperand::MO_Register:
233 if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
234 OS << "%reg" << getReg();
235 } else {
236 if (TM)
237 OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
238 else
239 OS << "%physreg" << getReg();
242 if (getSubReg() != 0) {
243 if (TM)
244 OS << ':' << TM->getRegisterInfo()->getSubRegIndexName(getSubReg());
245 else
246 OS << ':' << getSubReg();
249 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
250 isEarlyClobber()) {
251 OS << '<';
252 bool NeedComma = false;
253 if (isDef()) {
254 if (NeedComma) OS << ',';
255 if (isEarlyClobber())
256 OS << "earlyclobber,";
257 if (isImplicit())
258 OS << "imp-";
259 OS << "def";
260 NeedComma = true;
261 } else if (isImplicit()) {
262 OS << "imp-use";
263 NeedComma = true;
266 if (isKill() || isDead() || isUndef()) {
267 if (NeedComma) OS << ',';
268 if (isKill()) OS << "kill";
269 if (isDead()) OS << "dead";
270 if (isUndef()) {
271 if (isKill() || isDead())
272 OS << ',';
273 OS << "undef";
276 OS << '>';
278 break;
279 case MachineOperand::MO_Immediate:
280 OS << getImm();
281 break;
282 case MachineOperand::MO_FPImmediate:
283 if (getFPImm()->getType()->isFloatTy())
284 OS << getFPImm()->getValueAPF().convertToFloat();
285 else
286 OS << getFPImm()->getValueAPF().convertToDouble();
287 break;
288 case MachineOperand::MO_MachineBasicBlock:
289 OS << "<BB#" << getMBB()->getNumber() << ">";
290 break;
291 case MachineOperand::MO_FrameIndex:
292 OS << "<fi#" << getIndex() << '>';
293 break;
294 case MachineOperand::MO_ConstantPoolIndex:
295 OS << "<cp#" << getIndex();
296 if (getOffset()) OS << "+" << getOffset();
297 OS << '>';
298 break;
299 case MachineOperand::MO_JumpTableIndex:
300 OS << "<jt#" << getIndex() << '>';
301 break;
302 case MachineOperand::MO_GlobalAddress:
303 OS << "<ga:";
304 WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
305 if (getOffset()) OS << "+" << getOffset();
306 OS << '>';
307 break;
308 case MachineOperand::MO_ExternalSymbol:
309 OS << "<es:" << getSymbolName();
310 if (getOffset()) OS << "+" << getOffset();
311 OS << '>';
312 break;
313 case MachineOperand::MO_BlockAddress:
314 OS << '<';
315 WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
316 OS << '>';
317 break;
318 case MachineOperand::MO_Metadata:
319 OS << '<';
320 WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
321 OS << '>';
322 break;
323 case MachineOperand::MO_MCSymbol:
324 OS << "<MCSym=" << *getMCSymbol() << '>';
325 break;
326 default:
327 llvm_unreachable("Unrecognized operand type");
330 if (unsigned TF = getTargetFlags())
331 OS << "[TF=" << TF << ']';
334 //===----------------------------------------------------------------------===//
335 // MachineMemOperand Implementation
336 //===----------------------------------------------------------------------===//
338 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
339 int64_t o, uint64_t s, unsigned int a)
340 : Offset(o), Size(s), V(v),
341 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)) {
342 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
343 assert((isLoad() || isStore()) && "Not a load/store!");
346 /// Profile - Gather unique data for the object.
348 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
349 ID.AddInteger(Offset);
350 ID.AddInteger(Size);
351 ID.AddPointer(V);
352 ID.AddInteger(Flags);
355 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
356 // The Value and Offset may differ due to CSE. But the flags and size
357 // should be the same.
358 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
359 assert(MMO->getSize() == getSize() && "Size mismatch!");
361 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
362 // Update the alignment value.
363 Flags = (Flags & ((1 << MOMaxBits) - 1)) |
364 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
365 // Also update the base and offset, because the new alignment may
366 // not be applicable with the old ones.
367 V = MMO->getValue();
368 Offset = MMO->getOffset();
372 /// getAlignment - Return the minimum known alignment in bytes of the
373 /// actual memory reference.
374 uint64_t MachineMemOperand::getAlignment() const {
375 return MinAlign(getBaseAlignment(), getOffset());
378 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
379 assert((MMO.isLoad() || MMO.isStore()) &&
380 "SV has to be a load, store or both.");
382 if (MMO.isVolatile())
383 OS << "Volatile ";
385 if (MMO.isLoad())
386 OS << "LD";
387 if (MMO.isStore())
388 OS << "ST";
389 OS << MMO.getSize();
391 // Print the address information.
392 OS << "[";
393 if (!MMO.getValue())
394 OS << "<unknown>";
395 else
396 WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
398 // If the alignment of the memory reference itself differs from the alignment
399 // of the base pointer, print the base alignment explicitly, next to the base
400 // pointer.
401 if (MMO.getBaseAlignment() != MMO.getAlignment())
402 OS << "(align=" << MMO.getBaseAlignment() << ")";
404 if (MMO.getOffset() != 0)
405 OS << "+" << MMO.getOffset();
406 OS << "]";
408 // Print the alignment of the reference.
409 if (MMO.getBaseAlignment() != MMO.getAlignment() ||
410 MMO.getBaseAlignment() != MMO.getSize())
411 OS << "(align=" << MMO.getAlignment() << ")";
413 return OS;
416 //===----------------------------------------------------------------------===//
417 // MachineInstr Implementation
418 //===----------------------------------------------------------------------===//
420 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
421 /// TID NULL and no operands.
422 MachineInstr::MachineInstr()
423 : TID(0), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
424 Parent(0) {
425 // Make sure that we get added to a machine basicblock
426 LeakDetector::addGarbageObject(this);
429 void MachineInstr::addImplicitDefUseOperands() {
430 if (TID->ImplicitDefs)
431 for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
432 addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
433 if (TID->ImplicitUses)
434 for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
435 addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
438 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
439 /// implicit operands. It reserves space for the number of operands specified by
440 /// the TargetInstrDesc.
441 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
442 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
443 MemRefs(0), MemRefsEnd(0), Parent(0) {
444 if (!NoImp)
445 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
446 Operands.reserve(NumImplicitOps + TID->getNumOperands());
447 if (!NoImp)
448 addImplicitDefUseOperands();
449 // Make sure that we get added to a machine basicblock
450 LeakDetector::addGarbageObject(this);
453 /// MachineInstr ctor - As above, but with a DebugLoc.
454 MachineInstr::MachineInstr(const TargetInstrDesc &tid, const DebugLoc dl,
455 bool NoImp)
456 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
457 Parent(0), debugLoc(dl) {
458 if (!NoImp)
459 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
460 Operands.reserve(NumImplicitOps + TID->getNumOperands());
461 if (!NoImp)
462 addImplicitDefUseOperands();
463 // Make sure that we get added to a machine basicblock
464 LeakDetector::addGarbageObject(this);
467 /// MachineInstr ctor - Work exactly the same as the ctor two above, except
468 /// that the MachineInstr is created and added to the end of the specified
469 /// basic block.
470 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const TargetInstrDesc &tid)
471 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0),
472 MemRefs(0), MemRefsEnd(0), Parent(0) {
473 assert(MBB && "Cannot use inserting ctor with null basic block!");
474 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
475 Operands.reserve(NumImplicitOps + TID->getNumOperands());
476 addImplicitDefUseOperands();
477 // Make sure that we get added to a machine basicblock
478 LeakDetector::addGarbageObject(this);
479 MBB->push_back(this); // Add instruction to end of basic block!
482 /// MachineInstr ctor - As above, but with a DebugLoc.
484 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
485 const TargetInstrDesc &tid)
486 : TID(&tid), NumImplicitOps(0), AsmPrinterFlags(0), MemRefs(0), MemRefsEnd(0),
487 Parent(0), debugLoc(dl) {
488 assert(MBB && "Cannot use inserting ctor with null basic block!");
489 NumImplicitOps = TID->getNumImplicitDefs() + TID->getNumImplicitUses();
490 Operands.reserve(NumImplicitOps + TID->getNumOperands());
491 addImplicitDefUseOperands();
492 // Make sure that we get added to a machine basicblock
493 LeakDetector::addGarbageObject(this);
494 MBB->push_back(this); // Add instruction to end of basic block!
497 /// MachineInstr ctor - Copies MachineInstr arg exactly
499 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
500 : TID(&MI.getDesc()), NumImplicitOps(0), AsmPrinterFlags(0),
501 MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
502 Parent(0), debugLoc(MI.getDebugLoc()) {
503 Operands.reserve(MI.getNumOperands());
505 // Add operands
506 for (unsigned i = 0; i != MI.getNumOperands(); ++i)
507 addOperand(MI.getOperand(i));
508 NumImplicitOps = MI.NumImplicitOps;
510 // Set parent to null.
511 Parent = 0;
513 LeakDetector::addGarbageObject(this);
516 MachineInstr::~MachineInstr() {
517 LeakDetector::removeGarbageObject(this);
518 #ifndef NDEBUG
519 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
520 assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
521 assert((!Operands[i].isReg() || !Operands[i].isOnRegUseList()) &&
522 "Reg operand def/use list corrupted");
524 #endif
527 /// getRegInfo - If this instruction is embedded into a MachineFunction,
528 /// return the MachineRegisterInfo object for the current function, otherwise
529 /// return null.
530 MachineRegisterInfo *MachineInstr::getRegInfo() {
531 if (MachineBasicBlock *MBB = getParent())
532 return &MBB->getParent()->getRegInfo();
533 return 0;
536 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
537 /// this instruction from their respective use lists. This requires that the
538 /// operands already be on their use lists.
539 void MachineInstr::RemoveRegOperandsFromUseLists() {
540 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
541 if (Operands[i].isReg())
542 Operands[i].RemoveRegOperandFromRegInfo();
546 /// AddRegOperandsToUseLists - Add all of the register operands in
547 /// this instruction from their respective use lists. This requires that the
548 /// operands not be on their use lists yet.
549 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
550 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
551 if (Operands[i].isReg())
552 Operands[i].AddRegOperandToRegInfo(&RegInfo);
557 /// addOperand - Add the specified operand to the instruction. If it is an
558 /// implicit operand, it is added to the end of the operand list. If it is
559 /// an explicit operand it is added at the end of the explicit operand list
560 /// (before the first implicit operand).
561 void MachineInstr::addOperand(const MachineOperand &Op) {
562 bool isImpReg = Op.isReg() && Op.isImplicit();
563 assert((isImpReg || !OperandsComplete()) &&
564 "Trying to add an operand to a machine instr that is already done!");
566 MachineRegisterInfo *RegInfo = getRegInfo();
568 // If we are adding the operand to the end of the list, our job is simpler.
569 // This is true most of the time, so this is a reasonable optimization.
570 if (isImpReg || NumImplicitOps == 0) {
571 // We can only do this optimization if we know that the operand list won't
572 // reallocate.
573 if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
574 Operands.push_back(Op);
576 // Set the parent of the operand.
577 Operands.back().ParentMI = this;
579 // If the operand is a register, update the operand's use list.
580 if (Op.isReg()) {
581 Operands.back().AddRegOperandToRegInfo(RegInfo);
582 // If the register operand is flagged as early, mark the operand as such
583 unsigned OpNo = Operands.size() - 1;
584 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
585 Operands[OpNo].setIsEarlyClobber(true);
587 return;
591 // Otherwise, we have to insert a real operand before any implicit ones.
592 unsigned OpNo = Operands.size()-NumImplicitOps;
594 // If this instruction isn't embedded into a function, then we don't need to
595 // update any operand lists.
596 if (RegInfo == 0) {
597 // Simple insertion, no reginfo update needed for other register operands.
598 Operands.insert(Operands.begin()+OpNo, Op);
599 Operands[OpNo].ParentMI = this;
601 // Do explicitly set the reginfo for this operand though, to ensure the
602 // next/prev fields are properly nulled out.
603 if (Operands[OpNo].isReg()) {
604 Operands[OpNo].AddRegOperandToRegInfo(0);
605 // If the register operand is flagged as early, mark the operand as such
606 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
607 Operands[OpNo].setIsEarlyClobber(true);
610 } else if (Operands.size()+1 <= Operands.capacity()) {
611 // Otherwise, we have to remove register operands from their register use
612 // list, add the operand, then add the register operands back to their use
613 // list. This also must handle the case when the operand list reallocates
614 // to somewhere else.
616 // If insertion of this operand won't cause reallocation of the operand
617 // list, just remove the implicit operands, add the operand, then re-add all
618 // the rest of the operands.
619 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
620 assert(Operands[i].isReg() && "Should only be an implicit reg!");
621 Operands[i].RemoveRegOperandFromRegInfo();
624 // Add the operand. If it is a register, add it to the reg list.
625 Operands.insert(Operands.begin()+OpNo, Op);
626 Operands[OpNo].ParentMI = this;
628 if (Operands[OpNo].isReg()) {
629 Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
630 // If the register operand is flagged as early, mark the operand as such
631 if (TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
632 Operands[OpNo].setIsEarlyClobber(true);
635 // Re-add all the implicit ops.
636 for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
637 assert(Operands[i].isReg() && "Should only be an implicit reg!");
638 Operands[i].AddRegOperandToRegInfo(RegInfo);
640 } else {
641 // Otherwise, we will be reallocating the operand list. Remove all reg
642 // operands from their list, then readd them after the operand list is
643 // reallocated.
644 RemoveRegOperandsFromUseLists();
646 Operands.insert(Operands.begin()+OpNo, Op);
647 Operands[OpNo].ParentMI = this;
649 // Re-add all the operands.
650 AddRegOperandsToUseLists(*RegInfo);
652 // If the register operand is flagged as early, mark the operand as such
653 if (Operands[OpNo].isReg()
654 && TID->getOperandConstraint(OpNo, TOI::EARLY_CLOBBER) != -1)
655 Operands[OpNo].setIsEarlyClobber(true);
659 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
660 /// fewer operand than it started with.
662 void MachineInstr::RemoveOperand(unsigned OpNo) {
663 assert(OpNo < Operands.size() && "Invalid operand number");
665 // Special case removing the last one.
666 if (OpNo == Operands.size()-1) {
667 // If needed, remove from the reg def/use list.
668 if (Operands.back().isReg() && Operands.back().isOnRegUseList())
669 Operands.back().RemoveRegOperandFromRegInfo();
671 Operands.pop_back();
672 return;
675 // Otherwise, we are removing an interior operand. If we have reginfo to
676 // update, remove all operands that will be shifted down from their reg lists,
677 // move everything down, then re-add them.
678 MachineRegisterInfo *RegInfo = getRegInfo();
679 if (RegInfo) {
680 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
681 if (Operands[i].isReg())
682 Operands[i].RemoveRegOperandFromRegInfo();
686 Operands.erase(Operands.begin()+OpNo);
688 if (RegInfo) {
689 for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
690 if (Operands[i].isReg())
691 Operands[i].AddRegOperandToRegInfo(RegInfo);
696 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
697 /// This function should be used only occasionally. The setMemRefs function
698 /// is the primary method for setting up a MachineInstr's MemRefs list.
699 void MachineInstr::addMemOperand(MachineFunction &MF,
700 MachineMemOperand *MO) {
701 mmo_iterator OldMemRefs = MemRefs;
702 mmo_iterator OldMemRefsEnd = MemRefsEnd;
704 size_t NewNum = (MemRefsEnd - MemRefs) + 1;
705 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
706 mmo_iterator NewMemRefsEnd = NewMemRefs + NewNum;
708 std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
709 NewMemRefs[NewNum - 1] = MO;
711 MemRefs = NewMemRefs;
712 MemRefsEnd = NewMemRefsEnd;
715 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
716 MICheckType Check) const {
717 // If opcodes or number of operands are not the same then the two
718 // instructions are obviously not identical.
719 if (Other->getOpcode() != getOpcode() ||
720 Other->getNumOperands() != getNumOperands())
721 return false;
723 // Check operands to make sure they match.
724 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
725 const MachineOperand &MO = getOperand(i);
726 const MachineOperand &OMO = Other->getOperand(i);
727 // Clients may or may not want to ignore defs when testing for equality.
728 // For example, machine CSE pass only cares about finding common
729 // subexpressions, so it's safe to ignore virtual register defs.
730 if (Check != CheckDefs && MO.isReg() && MO.isDef()) {
731 if (Check == IgnoreDefs)
732 continue;
733 // Check == IgnoreVRegDefs
734 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
735 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
736 if (MO.getReg() != OMO.getReg())
737 return false;
738 } else if (!MO.isIdenticalTo(OMO))
739 return false;
741 return true;
744 /// removeFromParent - This method unlinks 'this' from the containing basic
745 /// block, and returns it, but does not delete it.
746 MachineInstr *MachineInstr::removeFromParent() {
747 assert(getParent() && "Not embedded in a basic block!");
748 getParent()->remove(this);
749 return this;
753 /// eraseFromParent - This method unlinks 'this' from the containing basic
754 /// block, and deletes it.
755 void MachineInstr::eraseFromParent() {
756 assert(getParent() && "Not embedded in a basic block!");
757 getParent()->erase(this);
761 /// OperandComplete - Return true if it's illegal to add a new operand
763 bool MachineInstr::OperandsComplete() const {
764 unsigned short NumOperands = TID->getNumOperands();
765 if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
766 return true; // Broken: we have all the operands of this instruction!
767 return false;
770 /// getNumExplicitOperands - Returns the number of non-implicit operands.
772 unsigned MachineInstr::getNumExplicitOperands() const {
773 unsigned NumOperands = TID->getNumOperands();
774 if (!TID->isVariadic())
775 return NumOperands;
777 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
778 const MachineOperand &MO = getOperand(i);
779 if (!MO.isReg() || !MO.isImplicit())
780 NumOperands++;
782 return NumOperands;
786 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
787 /// the specific register or -1 if it is not found. It further tightens
788 /// the search criteria to a use that kills the register if isKill is true.
789 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
790 const TargetRegisterInfo *TRI) const {
791 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
792 const MachineOperand &MO = getOperand(i);
793 if (!MO.isReg() || !MO.isUse())
794 continue;
795 unsigned MOReg = MO.getReg();
796 if (!MOReg)
797 continue;
798 if (MOReg == Reg ||
799 (TRI &&
800 TargetRegisterInfo::isPhysicalRegister(MOReg) &&
801 TargetRegisterInfo::isPhysicalRegister(Reg) &&
802 TRI->isSubRegister(MOReg, Reg)))
803 if (!isKill || MO.isKill())
804 return i;
806 return -1;
809 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
810 /// indicating if this instruction reads or writes Reg. This also considers
811 /// partial defines.
812 std::pair<bool,bool>
813 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
814 SmallVectorImpl<unsigned> *Ops) const {
815 bool PartDef = false; // Partial redefine.
816 bool FullDef = false; // Full define.
817 bool Use = false;
819 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
820 const MachineOperand &MO = getOperand(i);
821 if (!MO.isReg() || MO.getReg() != Reg)
822 continue;
823 if (Ops)
824 Ops->push_back(i);
825 if (MO.isUse())
826 Use |= !MO.isUndef();
827 else if (MO.getSubReg())
828 PartDef = true;
829 else
830 FullDef = true;
832 // A partial redefine uses Reg unless there is also a full define.
833 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
836 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
837 /// the specified register or -1 if it is not found. If isDead is true, defs
838 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
839 /// also checks if there is a def of a super-register.
841 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
842 const TargetRegisterInfo *TRI) const {
843 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
844 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
845 const MachineOperand &MO = getOperand(i);
846 if (!MO.isReg() || !MO.isDef())
847 continue;
848 unsigned MOReg = MO.getReg();
849 bool Found = (MOReg == Reg);
850 if (!Found && TRI && isPhys &&
851 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
852 if (Overlap)
853 Found = TRI->regsOverlap(MOReg, Reg);
854 else
855 Found = TRI->isSubRegister(MOReg, Reg);
857 if (Found && (!isDead || MO.isDead()))
858 return i;
860 return -1;
863 /// findFirstPredOperandIdx() - Find the index of the first operand in the
864 /// operand list that is used to represent the predicate. It returns -1 if
865 /// none is found.
866 int MachineInstr::findFirstPredOperandIdx() const {
867 const TargetInstrDesc &TID = getDesc();
868 if (TID.isPredicable()) {
869 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
870 if (TID.OpInfo[i].isPredicate())
871 return i;
874 return -1;
877 /// isRegTiedToUseOperand - Given the index of a register def operand,
878 /// check if the register def is tied to a source operand, due to either
879 /// two-address elimination or inline assembly constraints. Returns the
880 /// first tied use operand index by reference is UseOpIdx is not null.
881 bool MachineInstr::
882 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx) const {
883 if (isInlineAsm()) {
884 assert(DefOpIdx >= 3);
885 const MachineOperand &MO = getOperand(DefOpIdx);
886 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0)
887 return false;
888 // Determine the actual operand index that corresponds to this index.
889 unsigned DefNo = 0;
890 unsigned DefPart = 0;
891 for (unsigned i = 2, e = getNumOperands(); i < e; ) {
892 const MachineOperand &FMO = getOperand(i);
893 // After the normal asm operands there may be additional imp-def regs.
894 if (!FMO.isImm())
895 return false;
896 // Skip over this def.
897 unsigned NumOps = InlineAsm::getNumOperandRegisters(FMO.getImm());
898 unsigned PrevDef = i + 1;
899 i = PrevDef + NumOps;
900 if (i > DefOpIdx) {
901 DefPart = DefOpIdx - PrevDef;
902 break;
904 ++DefNo;
906 for (unsigned i = 2, e = getNumOperands(); i != e; ++i) {
907 const MachineOperand &FMO = getOperand(i);
908 if (!FMO.isImm())
909 continue;
910 if (i+1 >= e || !getOperand(i+1).isReg() || !getOperand(i+1).isUse())
911 continue;
912 unsigned Idx;
913 if (InlineAsm::isUseOperandTiedToDef(FMO.getImm(), Idx) &&
914 Idx == DefNo) {
915 if (UseOpIdx)
916 *UseOpIdx = (unsigned)i + 1 + DefPart;
917 return true;
920 return false;
923 assert(getOperand(DefOpIdx).isDef() && "DefOpIdx is not a def!");
924 const TargetInstrDesc &TID = getDesc();
925 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
926 const MachineOperand &MO = getOperand(i);
927 if (MO.isReg() && MO.isUse() &&
928 TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefOpIdx) {
929 if (UseOpIdx)
930 *UseOpIdx = (unsigned)i;
931 return true;
934 return false;
937 /// isRegTiedToDefOperand - Return true if the operand of the specified index
938 /// is a register use and it is tied to an def operand. It also returns the def
939 /// operand index by reference.
940 bool MachineInstr::
941 isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx) const {
942 if (isInlineAsm()) {
943 const MachineOperand &MO = getOperand(UseOpIdx);
944 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0)
945 return false;
947 // Find the flag operand corresponding to UseOpIdx
948 unsigned FlagIdx, NumOps=0;
949 for (FlagIdx = 2; FlagIdx < UseOpIdx; FlagIdx += NumOps+1) {
950 const MachineOperand &UFMO = getOperand(FlagIdx);
951 // After the normal asm operands there may be additional imp-def regs.
952 if (!UFMO.isImm())
953 return false;
954 NumOps = InlineAsm::getNumOperandRegisters(UFMO.getImm());
955 assert(NumOps < getNumOperands() && "Invalid inline asm flag");
956 if (UseOpIdx < FlagIdx+NumOps+1)
957 break;
959 if (FlagIdx >= UseOpIdx)
960 return false;
961 const MachineOperand &UFMO = getOperand(FlagIdx);
962 unsigned DefNo;
963 if (InlineAsm::isUseOperandTiedToDef(UFMO.getImm(), DefNo)) {
964 if (!DefOpIdx)
965 return true;
967 unsigned DefIdx = 2;
968 // Remember to adjust the index. First operand is asm string, second is
969 // the AlignStack bit, then there is a flag for each.
970 while (DefNo) {
971 const MachineOperand &FMO = getOperand(DefIdx);
972 assert(FMO.isImm());
973 // Skip over this def.
974 DefIdx += InlineAsm::getNumOperandRegisters(FMO.getImm()) + 1;
975 --DefNo;
977 *DefOpIdx = DefIdx + UseOpIdx - FlagIdx;
978 return true;
980 return false;
983 const TargetInstrDesc &TID = getDesc();
984 if (UseOpIdx >= TID.getNumOperands())
985 return false;
986 const MachineOperand &MO = getOperand(UseOpIdx);
987 if (!MO.isReg() || !MO.isUse())
988 return false;
989 int DefIdx = TID.getOperandConstraint(UseOpIdx, TOI::TIED_TO);
990 if (DefIdx == -1)
991 return false;
992 if (DefOpIdx)
993 *DefOpIdx = (unsigned)DefIdx;
994 return true;
997 /// clearKillInfo - Clears kill flags on all operands.
999 void MachineInstr::clearKillInfo() {
1000 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1001 MachineOperand &MO = getOperand(i);
1002 if (MO.isReg() && MO.isUse())
1003 MO.setIsKill(false);
1007 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
1009 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
1010 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1011 const MachineOperand &MO = MI->getOperand(i);
1012 if (!MO.isReg() || (!MO.isKill() && !MO.isDead()))
1013 continue;
1014 for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
1015 MachineOperand &MOp = getOperand(j);
1016 if (!MOp.isIdenticalTo(MO))
1017 continue;
1018 if (MO.isKill())
1019 MOp.setIsKill();
1020 else
1021 MOp.setIsDead();
1022 break;
1027 /// copyPredicates - Copies predicate operand(s) from MI.
1028 void MachineInstr::copyPredicates(const MachineInstr *MI) {
1029 const TargetInstrDesc &TID = MI->getDesc();
1030 if (!TID.isPredicable())
1031 return;
1032 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1033 if (TID.OpInfo[i].isPredicate()) {
1034 // Predicated operands must be last operands.
1035 addOperand(MI->getOperand(i));
1040 void MachineInstr::substituteRegister(unsigned FromReg,
1041 unsigned ToReg,
1042 unsigned SubIdx,
1043 const TargetRegisterInfo &RegInfo) {
1044 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1045 if (SubIdx)
1046 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1047 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1048 MachineOperand &MO = getOperand(i);
1049 if (!MO.isReg() || MO.getReg() != FromReg)
1050 continue;
1051 MO.substPhysReg(ToReg, RegInfo);
1053 } else {
1054 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1055 MachineOperand &MO = getOperand(i);
1056 if (!MO.isReg() || MO.getReg() != FromReg)
1057 continue;
1058 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1063 /// isSafeToMove - Return true if it is safe to move this instruction. If
1064 /// SawStore is set to true, it means that there is a store (or call) between
1065 /// the instruction's location and its intended destination.
1066 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
1067 AliasAnalysis *AA,
1068 bool &SawStore) const {
1069 // Ignore stuff that we obviously can't move.
1070 if (TID->mayStore() || TID->isCall()) {
1071 SawStore = true;
1072 return false;
1074 if (TID->isTerminator() || TID->hasUnmodeledSideEffects())
1075 return false;
1077 // See if this instruction does a load. If so, we have to guarantee that the
1078 // loaded value doesn't change between the load and the its intended
1079 // destination. The check for isInvariantLoad gives the targe the chance to
1080 // classify the load as always returning a constant, e.g. a constant pool
1081 // load.
1082 if (TID->mayLoad() && !isInvariantLoad(AA))
1083 // Otherwise, this is a real load. If there is a store between the load and
1084 // end of block, or if the load is volatile, we can't move it.
1085 return !SawStore && !hasVolatileMemoryRef();
1087 return true;
1090 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
1091 /// instruction which defined the specified register instead of copying it.
1092 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
1093 AliasAnalysis *AA,
1094 unsigned DstReg) const {
1095 bool SawStore = false;
1096 if (!TII->isTriviallyReMaterializable(this, AA) ||
1097 !isSafeToMove(TII, AA, SawStore))
1098 return false;
1099 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1100 const MachineOperand &MO = getOperand(i);
1101 if (!MO.isReg())
1102 continue;
1103 // FIXME: For now, do not remat any instruction with register operands.
1104 // Later on, we can loosen the restriction is the register operands have
1105 // not been modified between the def and use. Note, this is different from
1106 // MachineSink because the code is no longer in two-address form (at least
1107 // partially).
1108 if (MO.isUse())
1109 return false;
1110 else if (!MO.isDead() && MO.getReg() != DstReg)
1111 return false;
1113 return true;
1116 /// hasVolatileMemoryRef - Return true if this instruction may have a
1117 /// volatile memory reference, or if the information describing the
1118 /// memory reference is not available. Return false if it is known to
1119 /// have no volatile memory references.
1120 bool MachineInstr::hasVolatileMemoryRef() const {
1121 // An instruction known never to access memory won't have a volatile access.
1122 if (!TID->mayStore() &&
1123 !TID->mayLoad() &&
1124 !TID->isCall() &&
1125 !TID->hasUnmodeledSideEffects())
1126 return false;
1128 // Otherwise, if the instruction has no memory reference information,
1129 // conservatively assume it wasn't preserved.
1130 if (memoperands_empty())
1131 return true;
1133 // Check the memory reference information for volatile references.
1134 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
1135 if ((*I)->isVolatile())
1136 return true;
1138 return false;
1141 /// isInvariantLoad - Return true if this instruction is loading from a
1142 /// location whose value is invariant across the function. For example,
1143 /// loading a value from the constant pool or from the argument area
1144 /// of a function if it does not change. This should only return true of
1145 /// *all* loads the instruction does are invariant (if it does multiple loads).
1146 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
1147 // If the instruction doesn't load at all, it isn't an invariant load.
1148 if (!TID->mayLoad())
1149 return false;
1151 // If the instruction has lost its memoperands, conservatively assume that
1152 // it may not be an invariant load.
1153 if (memoperands_empty())
1154 return false;
1156 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
1158 for (mmo_iterator I = memoperands_begin(),
1159 E = memoperands_end(); I != E; ++I) {
1160 if ((*I)->isVolatile()) return false;
1161 if ((*I)->isStore()) return false;
1163 if (const Value *V = (*I)->getValue()) {
1164 // A load from a constant PseudoSourceValue is invariant.
1165 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
1166 if (PSV->isConstant(MFI))
1167 continue;
1168 // If we have an AliasAnalysis, ask it whether the memory is constant.
1169 if (AA && AA->pointsToConstantMemory(V))
1170 continue;
1173 // Otherwise assume conservatively.
1174 return false;
1177 // Everything checks out.
1178 return true;
1181 /// isConstantValuePHI - If the specified instruction is a PHI that always
1182 /// merges together the same virtual register, return the register, otherwise
1183 /// return 0.
1184 unsigned MachineInstr::isConstantValuePHI() const {
1185 if (!isPHI())
1186 return 0;
1187 assert(getNumOperands() >= 3 &&
1188 "It's illegal to have a PHI without source operands");
1190 unsigned Reg = getOperand(1).getReg();
1191 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1192 if (getOperand(i).getReg() != Reg)
1193 return 0;
1194 return Reg;
1197 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1199 bool MachineInstr::allDefsAreDead() const {
1200 for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
1201 const MachineOperand &MO = getOperand(i);
1202 if (!MO.isReg() || MO.isUse())
1203 continue;
1204 if (!MO.isDead())
1205 return false;
1207 return true;
1210 void MachineInstr::dump() const {
1211 dbgs() << " " << *this;
1214 static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
1215 raw_ostream &CommentOS) {
1216 const LLVMContext &Ctx = MF->getFunction()->getContext();
1217 if (!DL.isUnknown()) { // Print source line info.
1218 DIScope Scope(DL.getScope(Ctx));
1219 // Omit the directory, because it's likely to be long and uninteresting.
1220 if (Scope.Verify())
1221 CommentOS << Scope.getFilename();
1222 else
1223 CommentOS << "<unknown>";
1224 CommentOS << ':' << DL.getLine();
1225 if (DL.getCol() != 0)
1226 CommentOS << ':' << DL.getCol();
1227 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1228 if (!InlinedAtDL.isUnknown()) {
1229 CommentOS << " @[ ";
1230 printDebugLoc(InlinedAtDL, MF, CommentOS);
1231 CommentOS << " ]";
1236 void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM) const {
1237 // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
1238 const MachineFunction *MF = 0;
1239 const MachineRegisterInfo *MRI = 0;
1240 if (const MachineBasicBlock *MBB = getParent()) {
1241 MF = MBB->getParent();
1242 if (!TM && MF)
1243 TM = &MF->getTarget();
1244 if (MF)
1245 MRI = &MF->getRegInfo();
1248 // Save a list of virtual registers.
1249 SmallVector<unsigned, 8> VirtRegs;
1251 // Print explicitly defined operands on the left of an assignment syntax.
1252 unsigned StartOp = 0, e = getNumOperands();
1253 for (; StartOp < e && getOperand(StartOp).isReg() &&
1254 getOperand(StartOp).isDef() &&
1255 !getOperand(StartOp).isImplicit();
1256 ++StartOp) {
1257 if (StartOp != 0) OS << ", ";
1258 getOperand(StartOp).print(OS, TM);
1259 unsigned Reg = getOperand(StartOp).getReg();
1260 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
1261 VirtRegs.push_back(Reg);
1264 if (StartOp != 0)
1265 OS << " = ";
1267 // Print the opcode name.
1268 OS << getDesc().getName();
1270 // Print the rest of the operands.
1271 bool OmittedAnyCallClobbers = false;
1272 bool FirstOp = true;
1273 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1274 const MachineOperand &MO = getOperand(i);
1276 if (MO.isReg() && MO.getReg() &&
1277 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1278 VirtRegs.push_back(MO.getReg());
1280 // Omit call-clobbered registers which aren't used anywhere. This makes
1281 // call instructions much less noisy on targets where calls clobber lots
1282 // of registers. Don't rely on MO.isDead() because we may be called before
1283 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1284 if (MF && getDesc().isCall() &&
1285 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1286 unsigned Reg = MO.getReg();
1287 if (Reg != 0 && TargetRegisterInfo::isPhysicalRegister(Reg)) {
1288 const MachineRegisterInfo &MRI = MF->getRegInfo();
1289 if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
1290 bool HasAliasLive = false;
1291 for (const unsigned *Alias = TM->getRegisterInfo()->getAliasSet(Reg);
1292 unsigned AliasReg = *Alias; ++Alias)
1293 if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
1294 HasAliasLive = true;
1295 break;
1297 if (!HasAliasLive) {
1298 OmittedAnyCallClobbers = true;
1299 continue;
1305 if (FirstOp) FirstOp = false; else OS << ",";
1306 OS << " ";
1307 if (i < getDesc().NumOperands) {
1308 const TargetOperandInfo &TOI = getDesc().OpInfo[i];
1309 if (TOI.isPredicate())
1310 OS << "pred:";
1311 if (TOI.isOptionalDef())
1312 OS << "opt:";
1314 if (isDebugValue() && MO.isMetadata()) {
1315 // Pretty print DBG_VALUE instructions.
1316 const MDNode *MD = MO.getMetadata();
1317 if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
1318 OS << "!\"" << MDS->getString() << '\"';
1319 else
1320 MO.print(OS, TM);
1321 } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
1322 OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
1323 } else
1324 MO.print(OS, TM);
1327 // Briefly indicate whether any call clobbers were omitted.
1328 if (OmittedAnyCallClobbers) {
1329 if (!FirstOp) OS << ",";
1330 OS << " ...";
1333 bool HaveSemi = false;
1334 if (!memoperands_empty()) {
1335 if (!HaveSemi) OS << ";"; HaveSemi = true;
1337 OS << " mem:";
1338 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
1339 i != e; ++i) {
1340 OS << **i;
1341 if (next(i) != e)
1342 OS << " ";
1346 // Print the regclass of any virtual registers encountered.
1347 if (MRI && !VirtRegs.empty()) {
1348 if (!HaveSemi) OS << ";"; HaveSemi = true;
1349 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
1350 const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
1351 OS << " " << RC->getName() << ":%reg" << VirtRegs[i];
1352 for (unsigned j = i+1; j != VirtRegs.size();) {
1353 if (MRI->getRegClass(VirtRegs[j]) != RC) {
1354 ++j;
1355 continue;
1357 if (VirtRegs[i] != VirtRegs[j])
1358 OS << "," << VirtRegs[j];
1359 VirtRegs.erase(VirtRegs.begin()+j);
1364 if (!debugLoc.isUnknown() && MF) {
1365 if (!HaveSemi) OS << ";";
1366 OS << " dbg:";
1367 printDebugLoc(debugLoc, MF, OS);
1370 OS << "\n";
1373 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
1374 const TargetRegisterInfo *RegInfo,
1375 bool AddIfNotFound) {
1376 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1377 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1378 bool Found = false;
1379 SmallVector<unsigned,4> DeadOps;
1380 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1381 MachineOperand &MO = getOperand(i);
1382 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
1383 continue;
1384 unsigned Reg = MO.getReg();
1385 if (!Reg)
1386 continue;
1388 if (Reg == IncomingReg) {
1389 if (!Found) {
1390 if (MO.isKill())
1391 // The register is already marked kill.
1392 return true;
1393 if (isPhysReg && isRegTiedToDefOperand(i))
1394 // Two-address uses of physregs must not be marked kill.
1395 return true;
1396 MO.setIsKill();
1397 Found = true;
1399 } else if (hasAliases && MO.isKill() &&
1400 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1401 // A super-register kill already exists.
1402 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1403 return true;
1404 if (RegInfo->isSubRegister(IncomingReg, Reg))
1405 DeadOps.push_back(i);
1409 // Trim unneeded kill operands.
1410 while (!DeadOps.empty()) {
1411 unsigned OpIdx = DeadOps.back();
1412 if (getOperand(OpIdx).isImplicit())
1413 RemoveOperand(OpIdx);
1414 else
1415 getOperand(OpIdx).setIsKill(false);
1416 DeadOps.pop_back();
1419 // If not found, this means an alias of one of the operands is killed. Add a
1420 // new implicit operand if required.
1421 if (!Found && AddIfNotFound) {
1422 addOperand(MachineOperand::CreateReg(IncomingReg,
1423 false /*IsDef*/,
1424 true /*IsImp*/,
1425 true /*IsKill*/));
1426 return true;
1428 return Found;
1431 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
1432 const TargetRegisterInfo *RegInfo,
1433 bool AddIfNotFound) {
1434 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
1435 bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
1436 bool Found = false;
1437 SmallVector<unsigned,4> DeadOps;
1438 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1439 MachineOperand &MO = getOperand(i);
1440 if (!MO.isReg() || !MO.isDef())
1441 continue;
1442 unsigned Reg = MO.getReg();
1443 if (!Reg)
1444 continue;
1446 if (Reg == IncomingReg) {
1447 if (!Found) {
1448 if (MO.isDead())
1449 // The register is already marked dead.
1450 return true;
1451 MO.setIsDead();
1452 Found = true;
1454 } else if (hasAliases && MO.isDead() &&
1455 TargetRegisterInfo::isPhysicalRegister(Reg)) {
1456 // There exists a super-register that's marked dead.
1457 if (RegInfo->isSuperRegister(IncomingReg, Reg))
1458 return true;
1459 if (RegInfo->getSubRegisters(IncomingReg) &&
1460 RegInfo->getSuperRegisters(Reg) &&
1461 RegInfo->isSubRegister(IncomingReg, Reg))
1462 DeadOps.push_back(i);
1466 // Trim unneeded dead operands.
1467 while (!DeadOps.empty()) {
1468 unsigned OpIdx = DeadOps.back();
1469 if (getOperand(OpIdx).isImplicit())
1470 RemoveOperand(OpIdx);
1471 else
1472 getOperand(OpIdx).setIsDead(false);
1473 DeadOps.pop_back();
1476 // If not found, this means an alias of one of the operands is dead. Add a
1477 // new implicit operand if required.
1478 if (Found || !AddIfNotFound)
1479 return Found;
1481 addOperand(MachineOperand::CreateReg(IncomingReg,
1482 true /*IsDef*/,
1483 true /*IsImp*/,
1484 false /*IsKill*/,
1485 true /*IsDead*/));
1486 return true;
1489 void MachineInstr::addRegisterDefined(unsigned IncomingReg,
1490 const TargetRegisterInfo *RegInfo) {
1491 if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
1492 MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
1493 if (MO)
1494 return;
1495 } else {
1496 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1497 const MachineOperand &MO = getOperand(i);
1498 if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
1499 MO.getSubReg() == 0)
1500 return;
1503 addOperand(MachineOperand::CreateReg(IncomingReg,
1504 true /*IsDef*/,
1505 true /*IsImp*/));
1508 void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
1509 const TargetRegisterInfo &TRI) {
1510 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1511 MachineOperand &MO = getOperand(i);
1512 if (!MO.isReg() || !MO.isDef()) continue;
1513 unsigned Reg = MO.getReg();
1514 if (Reg == 0) continue;
1515 bool Dead = true;
1516 for (SmallVectorImpl<unsigned>::const_iterator I = UsedRegs.begin(),
1517 E = UsedRegs.end(); I != E; ++I)
1518 if (TRI.regsOverlap(*I, Reg)) {
1519 Dead = false;
1520 break;
1522 // If there are no uses, including partial uses, the def is dead.
1523 if (Dead) MO.setIsDead();
1527 unsigned
1528 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
1529 unsigned Hash = MI->getOpcode() * 37;
1530 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1531 const MachineOperand &MO = MI->getOperand(i);
1532 uint64_t Key = (uint64_t)MO.getType() << 32;
1533 switch (MO.getType()) {
1534 default: break;
1535 case MachineOperand::MO_Register:
1536 if (MO.isDef() && MO.getReg() &&
1537 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1538 continue; // Skip virtual register defs.
1539 Key |= MO.getReg();
1540 break;
1541 case MachineOperand::MO_Immediate:
1542 Key |= MO.getImm();
1543 break;
1544 case MachineOperand::MO_FrameIndex:
1545 case MachineOperand::MO_ConstantPoolIndex:
1546 case MachineOperand::MO_JumpTableIndex:
1547 Key |= MO.getIndex();
1548 break;
1549 case MachineOperand::MO_MachineBasicBlock:
1550 Key |= DenseMapInfo<void*>::getHashValue(MO.getMBB());
1551 break;
1552 case MachineOperand::MO_GlobalAddress:
1553 Key |= DenseMapInfo<void*>::getHashValue(MO.getGlobal());
1554 break;
1555 case MachineOperand::MO_BlockAddress:
1556 Key |= DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
1557 break;
1558 case MachineOperand::MO_MCSymbol:
1559 Key |= DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
1560 break;
1562 Key += ~(Key << 32);
1563 Key ^= (Key >> 22);
1564 Key += ~(Key << 13);
1565 Key ^= (Key >> 8);
1566 Key += (Key << 3);
1567 Key ^= (Key >> 15);
1568 Key += ~(Key << 27);
1569 Key ^= (Key >> 31);
1570 Hash = (unsigned)Key + Hash * 37;
1572 return Hash;