xref: /llvm-project/llvm/lib/CodeGen/MachineInstr.cpp (revision 7c59ed6ff820ad834c7f72c69b92cafb569a1ee1)
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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Constants.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/Value.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/PseudoSourceValue.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetInstrDesc.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include <ostream>
30 using namespace llvm;
31 
32 //===----------------------------------------------------------------------===//
33 // MachineOperand Implementation
34 //===----------------------------------------------------------------------===//
35 
36 /// AddRegOperandToRegInfo - Add this register operand to the specified
37 /// MachineRegisterInfo.  If it is null, then the next/prev fields should be
38 /// explicitly nulled out.
39 void MachineOperand::AddRegOperandToRegInfo(MachineRegisterInfo *RegInfo) {
40   assert(isRegister() && "Can only add reg operand to use lists");
41 
42   // If the reginfo pointer is null, just explicitly null out or next/prev
43   // pointers, to ensure they are not garbage.
44   if (RegInfo == 0) {
45     Contents.Reg.Prev = 0;
46     Contents.Reg.Next = 0;
47     return;
48   }
49 
50   // Otherwise, add this operand to the head of the registers use/def list.
51   MachineOperand **Head = &RegInfo->getRegUseDefListHead(getReg());
52 
53   // For SSA values, we prefer to keep the definition at the start of the list.
54   // we do this by skipping over the definition if it is at the head of the
55   // list.
56   if (*Head && (*Head)->isDef())
57     Head = &(*Head)->Contents.Reg.Next;
58 
59   Contents.Reg.Next = *Head;
60   if (Contents.Reg.Next) {
61     assert(getReg() == Contents.Reg.Next->getReg() &&
62            "Different regs on the same list!");
63     Contents.Reg.Next->Contents.Reg.Prev = &Contents.Reg.Next;
64   }
65 
66   Contents.Reg.Prev = Head;
67   *Head = this;
68 }
69 
70 void MachineOperand::setReg(unsigned Reg) {
71   if (getReg() == Reg) return; // No change.
72 
73   // Otherwise, we have to change the register.  If this operand is embedded
74   // into a machine function, we need to update the old and new register's
75   // use/def lists.
76   if (MachineInstr *MI = getParent())
77     if (MachineBasicBlock *MBB = MI->getParent())
78       if (MachineFunction *MF = MBB->getParent()) {
79         RemoveRegOperandFromRegInfo();
80         Contents.Reg.RegNo = Reg;
81         AddRegOperandToRegInfo(&MF->getRegInfo());
82         return;
83       }
84 
85   // Otherwise, just change the register, no problem.  :)
86   Contents.Reg.RegNo = Reg;
87 }
88 
89 /// ChangeToImmediate - Replace this operand with a new immediate operand of
90 /// the specified value.  If an operand is known to be an immediate already,
91 /// the setImm method should be used.
92 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
93   // If this operand is currently a register operand, and if this is in a
94   // function, deregister the operand from the register's use/def list.
95   if (isRegister() && getParent() && getParent()->getParent() &&
96       getParent()->getParent()->getParent())
97     RemoveRegOperandFromRegInfo();
98 
99   OpKind = MO_Immediate;
100   Contents.ImmVal = ImmVal;
101 }
102 
103 /// ChangeToRegister - Replace this operand with a new register operand of
104 /// the specified value.  If an operand is known to be an register already,
105 /// the setReg method should be used.
106 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
107                                       bool isKill, bool isDead) {
108   // If this operand is already a register operand, use setReg to update the
109   // register's use/def lists.
110   if (isRegister()) {
111     assert(!isEarlyClobber());
112     assert(!isEarlyClobber() && !overlapsEarlyClobber());
113     setReg(Reg);
114   } else {
115     // Otherwise, change this to a register and set the reg#.
116     OpKind = MO_Register;
117     Contents.Reg.RegNo = Reg;
118 
119     // If this operand is embedded in a function, add the operand to the
120     // register's use/def list.
121     if (MachineInstr *MI = getParent())
122       if (MachineBasicBlock *MBB = MI->getParent())
123         if (MachineFunction *MF = MBB->getParent())
124           AddRegOperandToRegInfo(&MF->getRegInfo());
125   }
126 
127   IsDef = isDef;
128   IsImp = isImp;
129   IsKill = isKill;
130   IsDead = isDead;
131   IsEarlyClobber = false;
132   OverlapsEarlyClobber = false;
133   SubReg = 0;
134 }
135 
136 /// isIdenticalTo - Return true if this operand is identical to the specified
137 /// operand.
138 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
139   if (getType() != Other.getType()) return false;
140 
141   switch (getType()) {
142   default: assert(0 && "Unrecognized operand type");
143   case MachineOperand::MO_Register:
144     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
145            getSubReg() == Other.getSubReg();
146   case MachineOperand::MO_Immediate:
147     return getImm() == Other.getImm();
148   case MachineOperand::MO_FPImmediate:
149     return getFPImm() == Other.getFPImm();
150   case MachineOperand::MO_MachineBasicBlock:
151     return getMBB() == Other.getMBB();
152   case MachineOperand::MO_FrameIndex:
153     return getIndex() == Other.getIndex();
154   case MachineOperand::MO_ConstantPoolIndex:
155     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
156   case MachineOperand::MO_JumpTableIndex:
157     return getIndex() == Other.getIndex();
158   case MachineOperand::MO_GlobalAddress:
159     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
160   case MachineOperand::MO_ExternalSymbol:
161     return !strcmp(getSymbolName(), Other.getSymbolName()) &&
162            getOffset() == Other.getOffset();
163   }
164 }
165 
166 /// print - Print the specified machine operand.
167 ///
168 void MachineOperand::print(std::ostream &OS, const TargetMachine *TM) const {
169   switch (getType()) {
170   case MachineOperand::MO_Register:
171     if (getReg() == 0 || TargetRegisterInfo::isVirtualRegister(getReg())) {
172       OS << "%reg" << getReg();
173     } else {
174       // If the instruction is embedded into a basic block, we can find the
175       // target info for the instruction.
176       if (TM == 0)
177         if (const MachineInstr *MI = getParent())
178           if (const MachineBasicBlock *MBB = MI->getParent())
179             if (const MachineFunction *MF = MBB->getParent())
180               TM = &MF->getTarget();
181 
182       if (TM)
183         OS << "%" << TM->getRegisterInfo()->get(getReg()).Name;
184       else
185         OS << "%mreg" << getReg();
186     }
187 
188     if (isDef() || isKill() || isDead() || isImplicit() || isEarlyClobber() ||
189         overlapsEarlyClobber()) {
190       OS << "<";
191       bool NeedComma = false;
192       if (overlapsEarlyClobber()) {
193         NeedComma = true;
194         OS << "overlapsearly";
195       }
196       if (isImplicit()) {
197         if (NeedComma) OS << ",";
198         OS << (isDef() ? "imp-def" : "imp-use");
199         NeedComma = true;
200       } else if (isDef()) {
201         if (NeedComma) OS << ",";
202         if (isEarlyClobber())
203           OS << "earlyclobber,";
204         OS << "def";
205         NeedComma = true;
206       }
207       if (isKill() || isDead()) {
208         if (NeedComma) OS << ",";
209         if (isKill())  OS << "kill";
210         if (isDead())  OS << "dead";
211       }
212       OS << ">";
213     }
214     break;
215   case MachineOperand::MO_Immediate:
216     OS << getImm();
217     break;
218   case MachineOperand::MO_FPImmediate:
219     if (getFPImm()->getType() == Type::FloatTy) {
220       OS << getFPImm()->getValueAPF().convertToFloat();
221     } else {
222       OS << getFPImm()->getValueAPF().convertToDouble();
223     }
224     break;
225   case MachineOperand::MO_MachineBasicBlock:
226     OS << "mbb<"
227        << ((Value*)getMBB()->getBasicBlock())->getName()
228        << "," << (void*)getMBB() << ">";
229     break;
230   case MachineOperand::MO_FrameIndex:
231     OS << "<fi#" << getIndex() << ">";
232     break;
233   case MachineOperand::MO_ConstantPoolIndex:
234     OS << "<cp#" << getIndex();
235     if (getOffset()) OS << "+" << getOffset();
236     OS << ">";
237     break;
238   case MachineOperand::MO_JumpTableIndex:
239     OS << "<jt#" << getIndex() << ">";
240     break;
241   case MachineOperand::MO_GlobalAddress:
242     OS << "<ga:" << ((Value*)getGlobal())->getName();
243     if (getOffset()) OS << "+" << getOffset();
244     OS << ">";
245     break;
246   case MachineOperand::MO_ExternalSymbol:
247     OS << "<es:" << getSymbolName();
248     if (getOffset()) OS << "+" << getOffset();
249     OS << ">";
250     break;
251   default:
252     assert(0 && "Unrecognized operand type");
253   }
254 }
255 
256 //===----------------------------------------------------------------------===//
257 // MachineMemOperand Implementation
258 //===----------------------------------------------------------------------===//
259 
260 MachineMemOperand::MachineMemOperand(const Value *v, unsigned int f,
261                                      int64_t o, uint64_t s, unsigned int a)
262   : Offset(o), Size(s), V(v),
263     Flags((f & 7) | ((Log2_32(a) + 1) << 3)) {
264   assert(isPowerOf2_32(a) && "Alignment is not a power of 2!");
265   assert((isLoad() || isStore()) && "Not a load/store!");
266 }
267 
268 /// Profile - Gather unique data for the object.
269 ///
270 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
271   ID.AddInteger(Offset);
272   ID.AddInteger(Size);
273   ID.AddPointer(V);
274   ID.AddInteger(Flags);
275 }
276 
277 //===----------------------------------------------------------------------===//
278 // MachineInstr Implementation
279 //===----------------------------------------------------------------------===//
280 
281 /// MachineInstr ctor - This constructor creates a dummy MachineInstr with
282 /// TID NULL and no operands.
283 MachineInstr::MachineInstr()
284   : TID(0), NumImplicitOps(0), Parent(0) {
285   // Make sure that we get added to a machine basicblock
286   LeakDetector::addGarbageObject(this);
287 }
288 
289 void MachineInstr::addImplicitDefUseOperands() {
290   if (TID->ImplicitDefs)
291     for (const unsigned *ImpDefs = TID->ImplicitDefs; *ImpDefs; ++ImpDefs)
292       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
293   if (TID->ImplicitUses)
294     for (const unsigned *ImpUses = TID->ImplicitUses; *ImpUses; ++ImpUses)
295       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
296 }
297 
298 /// MachineInstr ctor - This constructor create a MachineInstr and add the
299 /// implicit operands. It reserves space for number of operands specified by
300 /// TargetInstrDesc or the numOperands if it is not zero. (for
301 /// instructions with variable number of operands).
302 MachineInstr::MachineInstr(const TargetInstrDesc &tid, bool NoImp)
303   : TID(&tid), NumImplicitOps(0), Parent(0) {
304   if (!NoImp && TID->getImplicitDefs())
305     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
306       NumImplicitOps++;
307   if (!NoImp && TID->getImplicitUses())
308     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
309       NumImplicitOps++;
310   Operands.reserve(NumImplicitOps + TID->getNumOperands());
311   if (!NoImp)
312     addImplicitDefUseOperands();
313   // Make sure that we get added to a machine basicblock
314   LeakDetector::addGarbageObject(this);
315 }
316 
317 /// MachineInstr ctor - Work exactly the same as the ctor above, except that the
318 /// MachineInstr is created and added to the end of the specified basic block.
319 ///
320 MachineInstr::MachineInstr(MachineBasicBlock *MBB,
321                            const TargetInstrDesc &tid)
322   : TID(&tid), NumImplicitOps(0), Parent(0) {
323   assert(MBB && "Cannot use inserting ctor with null basic block!");
324   if (TID->ImplicitDefs)
325     for (const unsigned *ImpDefs = TID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
326       NumImplicitOps++;
327   if (TID->ImplicitUses)
328     for (const unsigned *ImpUses = TID->getImplicitUses(); *ImpUses; ++ImpUses)
329       NumImplicitOps++;
330   Operands.reserve(NumImplicitOps + TID->getNumOperands());
331   addImplicitDefUseOperands();
332   // Make sure that we get added to a machine basicblock
333   LeakDetector::addGarbageObject(this);
334   MBB->push_back(this);  // Add instruction to end of basic block!
335 }
336 
337 /// MachineInstr ctor - Copies MachineInstr arg exactly
338 ///
339 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
340   : TID(&MI.getDesc()), NumImplicitOps(0), Parent(0) {
341   Operands.reserve(MI.getNumOperands());
342 
343   // Add operands
344   for (unsigned i = 0; i != MI.getNumOperands(); ++i)
345     addOperand(MI.getOperand(i));
346   NumImplicitOps = MI.NumImplicitOps;
347 
348   // Add memory operands.
349   for (std::list<MachineMemOperand>::const_iterator i = MI.memoperands_begin(),
350        j = MI.memoperands_end(); i != j; ++i)
351     addMemOperand(MF, *i);
352 
353   // Set parent to null.
354   Parent = 0;
355 
356   LeakDetector::addGarbageObject(this);
357 }
358 
359 MachineInstr::~MachineInstr() {
360   LeakDetector::removeGarbageObject(this);
361   assert(MemOperands.empty() &&
362          "MachineInstr being deleted with live memoperands!");
363 #ifndef NDEBUG
364   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
365     assert(Operands[i].ParentMI == this && "ParentMI mismatch!");
366     assert((!Operands[i].isRegister() || !Operands[i].isOnRegUseList()) &&
367            "Reg operand def/use list corrupted");
368   }
369 #endif
370 }
371 
372 /// getRegInfo - If this instruction is embedded into a MachineFunction,
373 /// return the MachineRegisterInfo object for the current function, otherwise
374 /// return null.
375 MachineRegisterInfo *MachineInstr::getRegInfo() {
376   if (MachineBasicBlock *MBB = getParent())
377     return &MBB->getParent()->getRegInfo();
378   return 0;
379 }
380 
381 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
382 /// this instruction from their respective use lists.  This requires that the
383 /// operands already be on their use lists.
384 void MachineInstr::RemoveRegOperandsFromUseLists() {
385   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
386     if (Operands[i].isRegister())
387       Operands[i].RemoveRegOperandFromRegInfo();
388   }
389 }
390 
391 /// AddRegOperandsToUseLists - Add all of the register operands in
392 /// this instruction from their respective use lists.  This requires that the
393 /// operands not be on their use lists yet.
394 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo) {
395   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
396     if (Operands[i].isRegister())
397       Operands[i].AddRegOperandToRegInfo(&RegInfo);
398   }
399 }
400 
401 
402 /// addOperand - Add the specified operand to the instruction.  If it is an
403 /// implicit operand, it is added to the end of the operand list.  If it is
404 /// an explicit operand it is added at the end of the explicit operand list
405 /// (before the first implicit operand).
406 void MachineInstr::addOperand(const MachineOperand &Op) {
407   bool isImpReg = Op.isRegister() && Op.isImplicit();
408   assert((isImpReg || !OperandsComplete()) &&
409          "Trying to add an operand to a machine instr that is already done!");
410 
411   // If we are adding the operand to the end of the list, our job is simpler.
412   // This is true most of the time, so this is a reasonable optimization.
413   if (isImpReg || NumImplicitOps == 0) {
414     // We can only do this optimization if we know that the operand list won't
415     // reallocate.
416     if (Operands.empty() || Operands.size()+1 <= Operands.capacity()) {
417       Operands.push_back(Op);
418 
419       // Set the parent of the operand.
420       Operands.back().ParentMI = this;
421 
422       // If the operand is a register, update the operand's use list.
423       if (Op.isRegister())
424         Operands.back().AddRegOperandToRegInfo(getRegInfo());
425       return;
426     }
427   }
428 
429   // Otherwise, we have to insert a real operand before any implicit ones.
430   unsigned OpNo = Operands.size()-NumImplicitOps;
431 
432   MachineRegisterInfo *RegInfo = getRegInfo();
433 
434   // If this instruction isn't embedded into a function, then we don't need to
435   // update any operand lists.
436   if (RegInfo == 0) {
437     // Simple insertion, no reginfo update needed for other register operands.
438     Operands.insert(Operands.begin()+OpNo, Op);
439     Operands[OpNo].ParentMI = this;
440 
441     // Do explicitly set the reginfo for this operand though, to ensure the
442     // next/prev fields are properly nulled out.
443     if (Operands[OpNo].isRegister())
444       Operands[OpNo].AddRegOperandToRegInfo(0);
445 
446   } else if (Operands.size()+1 <= Operands.capacity()) {
447     // Otherwise, we have to remove register operands from their register use
448     // list, add the operand, then add the register operands back to their use
449     // list.  This also must handle the case when the operand list reallocates
450     // to somewhere else.
451 
452     // If insertion of this operand won't cause reallocation of the operand
453     // list, just remove the implicit operands, add the operand, then re-add all
454     // the rest of the operands.
455     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
456       assert(Operands[i].isRegister() && "Should only be an implicit reg!");
457       Operands[i].RemoveRegOperandFromRegInfo();
458     }
459 
460     // Add the operand.  If it is a register, add it to the reg list.
461     Operands.insert(Operands.begin()+OpNo, Op);
462     Operands[OpNo].ParentMI = this;
463 
464     if (Operands[OpNo].isRegister())
465       Operands[OpNo].AddRegOperandToRegInfo(RegInfo);
466 
467     // Re-add all the implicit ops.
468     for (unsigned i = OpNo+1, e = Operands.size(); i != e; ++i) {
469       assert(Operands[i].isRegister() && "Should only be an implicit reg!");
470       Operands[i].AddRegOperandToRegInfo(RegInfo);
471     }
472   } else {
473     // Otherwise, we will be reallocating the operand list.  Remove all reg
474     // operands from their list, then readd them after the operand list is
475     // reallocated.
476     RemoveRegOperandsFromUseLists();
477 
478     Operands.insert(Operands.begin()+OpNo, Op);
479     Operands[OpNo].ParentMI = this;
480 
481     // Re-add all the operands.
482     AddRegOperandsToUseLists(*RegInfo);
483   }
484 }
485 
486 /// RemoveOperand - Erase an operand  from an instruction, leaving it with one
487 /// fewer operand than it started with.
488 ///
489 void MachineInstr::RemoveOperand(unsigned OpNo) {
490   assert(OpNo < Operands.size() && "Invalid operand number");
491 
492   // Special case removing the last one.
493   if (OpNo == Operands.size()-1) {
494     // If needed, remove from the reg def/use list.
495     if (Operands.back().isRegister() && Operands.back().isOnRegUseList())
496       Operands.back().RemoveRegOperandFromRegInfo();
497 
498     Operands.pop_back();
499     return;
500   }
501 
502   // Otherwise, we are removing an interior operand.  If we have reginfo to
503   // update, remove all operands that will be shifted down from their reg lists,
504   // move everything down, then re-add them.
505   MachineRegisterInfo *RegInfo = getRegInfo();
506   if (RegInfo) {
507     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
508       if (Operands[i].isRegister())
509         Operands[i].RemoveRegOperandFromRegInfo();
510     }
511   }
512 
513   Operands.erase(Operands.begin()+OpNo);
514 
515   if (RegInfo) {
516     for (unsigned i = OpNo, e = Operands.size(); i != e; ++i) {
517       if (Operands[i].isRegister())
518         Operands[i].AddRegOperandToRegInfo(RegInfo);
519     }
520   }
521 }
522 
523 /// addMemOperand - Add a MachineMemOperand to the machine instruction,
524 /// referencing arbitrary storage.
525 void MachineInstr::addMemOperand(MachineFunction &MF,
526                                  const MachineMemOperand &MO) {
527   MemOperands.push_back(MO);
528 }
529 
530 /// clearMemOperands - Erase all of this MachineInstr's MachineMemOperands.
531 void MachineInstr::clearMemOperands(MachineFunction &MF) {
532   MemOperands.clear();
533 }
534 
535 
536 /// removeFromParent - This method unlinks 'this' from the containing basic
537 /// block, and returns it, but does not delete it.
538 MachineInstr *MachineInstr::removeFromParent() {
539   assert(getParent() && "Not embedded in a basic block!");
540   getParent()->remove(this);
541   return this;
542 }
543 
544 
545 /// eraseFromParent - This method unlinks 'this' from the containing basic
546 /// block, and deletes it.
547 void MachineInstr::eraseFromParent() {
548   assert(getParent() && "Not embedded in a basic block!");
549   getParent()->erase(this);
550 }
551 
552 
553 /// OperandComplete - Return true if it's illegal to add a new operand
554 ///
555 bool MachineInstr::OperandsComplete() const {
556   unsigned short NumOperands = TID->getNumOperands();
557   if (!TID->isVariadic() && getNumOperands()-NumImplicitOps >= NumOperands)
558     return true;  // Broken: we have all the operands of this instruction!
559   return false;
560 }
561 
562 /// getNumExplicitOperands - Returns the number of non-implicit operands.
563 ///
564 unsigned MachineInstr::getNumExplicitOperands() const {
565   unsigned NumOperands = TID->getNumOperands();
566   if (!TID->isVariadic())
567     return NumOperands;
568 
569   for (unsigned e = getNumOperands(); NumOperands != e; ++NumOperands) {
570     const MachineOperand &MO = getOperand(NumOperands);
571     if (!MO.isRegister() || !MO.isImplicit())
572       NumOperands++;
573   }
574   return NumOperands;
575 }
576 
577 
578 /// isLabel - Returns true if the MachineInstr represents a label.
579 ///
580 bool MachineInstr::isLabel() const {
581   return getOpcode() == TargetInstrInfo::DBG_LABEL ||
582          getOpcode() == TargetInstrInfo::EH_LABEL ||
583          getOpcode() == TargetInstrInfo::GC_LABEL;
584 }
585 
586 /// isDebugLabel - Returns true if the MachineInstr represents a debug label.
587 ///
588 bool MachineInstr::isDebugLabel() const {
589   return getOpcode() == TargetInstrInfo::DBG_LABEL;
590 }
591 
592 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
593 /// the specific register or -1 if it is not found. It further tightening
594 /// the search criteria to a use that kills the register if isKill is true.
595 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
596                                           const TargetRegisterInfo *TRI) const {
597   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
598     const MachineOperand &MO = getOperand(i);
599     if (!MO.isRegister() || !MO.isUse())
600       continue;
601     unsigned MOReg = MO.getReg();
602     if (!MOReg)
603       continue;
604     if (MOReg == Reg ||
605         (TRI &&
606          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
607          TargetRegisterInfo::isPhysicalRegister(Reg) &&
608          TRI->isSubRegister(MOReg, Reg)))
609       if (!isKill || MO.isKill())
610         return i;
611   }
612   return -1;
613 }
614 
615 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
616 /// the specified register or -1 if it is not found. If isDead is true, defs
617 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
618 /// also checks if there is a def of a super-register.
619 int MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead,
620                                           const TargetRegisterInfo *TRI) const {
621   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
622     const MachineOperand &MO = getOperand(i);
623     if (!MO.isRegister() || !MO.isDef())
624       continue;
625     unsigned MOReg = MO.getReg();
626     if (MOReg == Reg ||
627         (TRI &&
628          TargetRegisterInfo::isPhysicalRegister(MOReg) &&
629          TargetRegisterInfo::isPhysicalRegister(Reg) &&
630          TRI->isSubRegister(MOReg, Reg)))
631       if (!isDead || MO.isDead())
632         return i;
633   }
634   return -1;
635 }
636 
637 /// findFirstPredOperandIdx() - Find the index of the first operand in the
638 /// operand list that is used to represent the predicate. It returns -1 if
639 /// none is found.
640 int MachineInstr::findFirstPredOperandIdx() const {
641   const TargetInstrDesc &TID = getDesc();
642   if (TID.isPredicable()) {
643     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
644       if (TID.OpInfo[i].isPredicate())
645         return i;
646   }
647 
648   return -1;
649 }
650 
651 /// isRegReDefinedByTwoAddr - Given the defined register and the operand index,
652 /// check if the register def is a re-definition due to two addr elimination.
653 bool MachineInstr::isRegReDefinedByTwoAddr(unsigned Reg, unsigned DefIdx) const{
654   const TargetInstrDesc &TID = getDesc();
655   for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
656     const MachineOperand &MO = getOperand(i);
657     if (MO.isRegister() && MO.isUse() && MO.getReg() == Reg &&
658         TID.getOperandConstraint(i, TOI::TIED_TO) == (int)DefIdx)
659       return true;
660   }
661   return false;
662 }
663 
664 /// copyKillDeadInfo - Copies kill / dead operand properties from MI.
665 ///
666 void MachineInstr::copyKillDeadInfo(const MachineInstr *MI) {
667   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
668     const MachineOperand &MO = MI->getOperand(i);
669     if (!MO.isRegister() || (!MO.isKill() && !MO.isDead()))
670       continue;
671     for (unsigned j = 0, ee = getNumOperands(); j != ee; ++j) {
672       MachineOperand &MOp = getOperand(j);
673       if (!MOp.isIdenticalTo(MO))
674         continue;
675       if (MO.isKill())
676         MOp.setIsKill();
677       else
678         MOp.setIsDead();
679       break;
680     }
681   }
682 }
683 
684 /// copyPredicates - Copies predicate operand(s) from MI.
685 void MachineInstr::copyPredicates(const MachineInstr *MI) {
686   const TargetInstrDesc &TID = MI->getDesc();
687   if (!TID.isPredicable())
688     return;
689   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
690     if (TID.OpInfo[i].isPredicate()) {
691       // Predicated operands must be last operands.
692       addOperand(MI->getOperand(i));
693     }
694   }
695 }
696 
697 /// isSafeToMove - Return true if it is safe to move this instruction. If
698 /// SawStore is set to true, it means that there is a store (or call) between
699 /// the instruction's location and its intended destination.
700 bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII, bool &SawStore) {
701   // Ignore stuff that we obviously can't move.
702   if (TID->mayStore() || TID->isCall()) {
703     SawStore = true;
704     return false;
705   }
706   if (TID->isReturn() || TID->isBranch() || TID->hasUnmodeledSideEffects())
707     return false;
708 
709   // See if this instruction does a load.  If so, we have to guarantee that the
710   // loaded value doesn't change between the load and the its intended
711   // destination. The check for isInvariantLoad gives the targe the chance to
712   // classify the load as always returning a constant, e.g. a constant pool
713   // load.
714   if (TID->mayLoad() && !TII->isInvariantLoad(this))
715     // Otherwise, this is a real load.  If there is a store between the load and
716     // end of block, or if the laod is volatile, we can't move it.
717     return SawStore || hasVolatileMemoryRef();
718 
719   return true;
720 }
721 
722 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
723 /// instruction which defined the specified register instead of copying it.
724 bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII, unsigned DstReg) {
725   bool SawStore = false;
726   if (!getDesc().isRematerializable() ||
727       !TII->isTriviallyReMaterializable(this) ||
728       !isSafeToMove(TII, SawStore))
729     return false;
730   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
731     MachineOperand &MO = getOperand(i);
732     if (!MO.isRegister())
733       continue;
734     // FIXME: For now, do not remat any instruction with register operands.
735     // Later on, we can loosen the restriction is the register operands have
736     // not been modified between the def and use. Note, this is different from
737     // MachineSink because the code is no longer in two-address form (at least
738     // partially).
739     if (MO.isUse())
740       return false;
741     else if (!MO.isDead() && MO.getReg() != DstReg)
742       return false;
743   }
744   return true;
745 }
746 
747 /// hasVolatileMemoryRef - Return true if this instruction may have a
748 /// volatile memory reference, or if the information describing the
749 /// memory reference is not available. Return false if it is known to
750 /// have no volatile memory references.
751 bool MachineInstr::hasVolatileMemoryRef() const {
752   // An instruction known never to access memory won't have a volatile access.
753   if (!TID->mayStore() &&
754       !TID->mayLoad() &&
755       !TID->isCall() &&
756       !TID->hasUnmodeledSideEffects())
757     return false;
758 
759   // Otherwise, if the instruction has no memory reference information,
760   // conservatively assume it wasn't preserved.
761   if (memoperands_empty())
762     return true;
763 
764   // Check the memory reference information for volatile references.
765   for (std::list<MachineMemOperand>::const_iterator I = memoperands_begin(),
766        E = memoperands_end(); I != E; ++I)
767     if (I->isVolatile())
768       return true;
769 
770   return false;
771 }
772 
773 void MachineInstr::dump() const {
774   cerr << "  " << *this;
775 }
776 
777 void MachineInstr::print(std::ostream &OS, const TargetMachine *TM) const {
778   // Specialize printing if op#0 is definition
779   unsigned StartOp = 0;
780   if (getNumOperands() && getOperand(0).isRegister() && getOperand(0).isDef()) {
781     getOperand(0).print(OS, TM);
782     OS << " = ";
783     ++StartOp;   // Don't print this operand again!
784   }
785 
786   OS << getDesc().getName();
787 
788   for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
789     if (i != StartOp)
790       OS << ",";
791     OS << " ";
792     getOperand(i).print(OS, TM);
793   }
794 
795   if (!memoperands_empty()) {
796     OS << ", Mem:";
797     for (std::list<MachineMemOperand>::const_iterator i = memoperands_begin(),
798          e = memoperands_end(); i != e; ++i) {
799       const MachineMemOperand &MRO = *i;
800       const Value *V = MRO.getValue();
801 
802       assert((MRO.isLoad() || MRO.isStore()) &&
803              "SV has to be a load, store or both.");
804 
805       if (MRO.isVolatile())
806         OS << "Volatile ";
807 
808       if (MRO.isLoad())
809         OS << "LD";
810       if (MRO.isStore())
811         OS << "ST";
812 
813       OS << "(" << MRO.getSize() << "," << MRO.getAlignment() << ") [";
814 
815       if (!V)
816         OS << "<unknown>";
817       else if (!V->getName().empty())
818         OS << V->getName();
819       else if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
820         raw_os_ostream OSS(OS);
821         PSV->print(OSS);
822       } else
823         OS << V;
824 
825       OS << " + " << MRO.getOffset() << "]";
826     }
827   }
828 
829   OS << "\n";
830 }
831 
832 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
833                                      const TargetRegisterInfo *RegInfo,
834                                      bool AddIfNotFound) {
835   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
836   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
837   bool Found = false;
838   SmallVector<unsigned,4> DeadOps;
839   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
840     MachineOperand &MO = getOperand(i);
841     if (!MO.isRegister() || !MO.isUse())
842       continue;
843     unsigned Reg = MO.getReg();
844     if (!Reg)
845       continue;
846 
847     if (Reg == IncomingReg) {
848       if (!Found) {
849         if (MO.isKill())
850           // The register is already marked kill.
851           return true;
852         MO.setIsKill();
853         Found = true;
854       }
855     } else if (hasAliases && MO.isKill() &&
856                TargetRegisterInfo::isPhysicalRegister(Reg)) {
857       // A super-register kill already exists.
858       if (RegInfo->isSuperRegister(IncomingReg, Reg))
859         return true;
860       if (RegInfo->isSubRegister(IncomingReg, Reg))
861         DeadOps.push_back(i);
862     }
863   }
864 
865   // Trim unneeded kill operands.
866   while (!DeadOps.empty()) {
867     unsigned OpIdx = DeadOps.back();
868     if (getOperand(OpIdx).isImplicit())
869       RemoveOperand(OpIdx);
870     else
871       getOperand(OpIdx).setIsKill(false);
872     DeadOps.pop_back();
873   }
874 
875   // If not found, this means an alias of one of the operands is killed. Add a
876   // new implicit operand if required.
877   if (!Found && AddIfNotFound) {
878     addOperand(MachineOperand::CreateReg(IncomingReg,
879                                          false /*IsDef*/,
880                                          true  /*IsImp*/,
881                                          true  /*IsKill*/));
882     return true;
883   }
884   return Found;
885 }
886 
887 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
888                                    const TargetRegisterInfo *RegInfo,
889                                    bool AddIfNotFound) {
890   bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
891   bool hasAliases = isPhysReg && RegInfo->getAliasSet(IncomingReg);
892   bool Found = false;
893   SmallVector<unsigned,4> DeadOps;
894   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
895     MachineOperand &MO = getOperand(i);
896     if (!MO.isRegister() || !MO.isDef())
897       continue;
898     unsigned Reg = MO.getReg();
899     if (!Reg)
900       continue;
901 
902     if (Reg == IncomingReg) {
903       if (!Found) {
904         if (MO.isDead())
905           // The register is already marked dead.
906           return true;
907         MO.setIsDead();
908         Found = true;
909       }
910     } else if (hasAliases && MO.isDead() &&
911                TargetRegisterInfo::isPhysicalRegister(Reg)) {
912       // There exists a super-register that's marked dead.
913       if (RegInfo->isSuperRegister(IncomingReg, Reg))
914         return true;
915       if (RegInfo->getSubRegisters(IncomingReg) &&
916           RegInfo->getSuperRegisters(Reg) &&
917           RegInfo->isSubRegister(IncomingReg, Reg))
918         DeadOps.push_back(i);
919     }
920   }
921 
922   // Trim unneeded dead operands.
923   while (!DeadOps.empty()) {
924     unsigned OpIdx = DeadOps.back();
925     if (getOperand(OpIdx).isImplicit())
926       RemoveOperand(OpIdx);
927     else
928       getOperand(OpIdx).setIsDead(false);
929     DeadOps.pop_back();
930   }
931 
932   // If not found, this means an alias of one of the operands is dead. Add a
933   // new implicit operand if required.
934   if (!Found && AddIfNotFound) {
935     addOperand(MachineOperand::CreateReg(IncomingReg,
936                                          true  /*IsDef*/,
937                                          true  /*IsImp*/,
938                                          false /*IsKill*/,
939                                          true  /*IsDead*/));
940     return true;
941   }
942   return Found;
943 }
944