1 //===-- llvm/CodeGen/MachineRegisterInfo.h ----------------------*- C++ -*-===//
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 // This file defines the MachineRegisterInfo class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
15 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/CodeGen/MachineInstrBundle.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
25 /// MachineRegisterInfo - Keep track of information for virtual and physical
26 /// registers, including vreg register classes, use/def chains for registers,
28 class MachineRegisterInfo {
29 const TargetRegisterInfo *const TRI;
31 /// IsSSA - True when the machine function is in SSA form and virtual
32 /// registers have a single def.
35 /// TracksLiveness - True while register liveness is being tracked accurately.
36 /// Basic block live-in lists, kill flags, and implicit defs may not be
37 /// accurate when after this flag is cleared.
40 /// VRegInfo - Information we keep for each virtual register.
42 /// Each element in this list contains the register class of the vreg and the
43 /// start of the use/def list for the register.
44 IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
45 VirtReg2IndexFunctor> VRegInfo;
47 /// RegAllocHints - This vector records register allocation hints for virtual
48 /// registers. For each virtual register, it keeps a register and hint type
49 /// pair making up the allocation hint. Hint type is target specific except
50 /// for the value 0 which means the second value of the pair is the preferred
51 /// register for allocation. For example, if the hint is <0, 1024>, it means
52 /// the allocator should prefer the physical register allocated to the virtual
53 /// register of the hint.
54 IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
56 /// PhysRegUseDefLists - This is an array of the head of the use/def list for
57 /// physical registers.
58 MachineOperand **PhysRegUseDefLists;
60 /// getRegUseDefListHead - Return the head pointer for the register use/def
61 /// list for the specified virtual or physical register.
62 MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
63 if (TargetRegisterInfo::isVirtualRegister(RegNo))
64 return VRegInfo[RegNo].second;
65 return PhysRegUseDefLists[RegNo];
68 MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
69 if (TargetRegisterInfo::isVirtualRegister(RegNo))
70 return VRegInfo[RegNo].second;
71 return PhysRegUseDefLists[RegNo];
74 /// Get the next element in the use-def chain.
75 static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
76 assert(MO && MO->isReg() && "This is not a register operand!");
77 return MO->Contents.Reg.Next;
80 /// UsedRegUnits - This is a bit vector that is computed and set by the
81 /// register allocator, and must be kept up to date by passes that run after
82 /// register allocation (though most don't modify this). This is used
83 /// so that the code generator knows which callee save registers to save and
84 /// for other target specific uses.
85 /// This vector has bits set for register units that are modified in the
86 /// current function. It doesn't include registers clobbered by function
87 /// calls with register mask operands.
88 BitVector UsedRegUnits;
90 /// UsedPhysRegMask - Additional used physregs including aliases.
91 /// This bit vector represents all the registers clobbered by function calls.
92 /// It can model things that UsedRegUnits can't, such as function calls that
93 /// clobber ymm7 but preserve the low half in xmm7.
94 BitVector UsedPhysRegMask;
96 /// ReservedRegs - This is a bit vector of reserved registers. The target
97 /// may change its mind about which registers should be reserved. This
98 /// vector is the frozen set of reserved registers when register allocation
100 BitVector ReservedRegs;
102 /// Keep track of the physical registers that are live in to the function.
103 /// Live in values are typically arguments in registers. LiveIn values are
104 /// allowed to have virtual registers associated with them, stored in the
106 std::vector<std::pair<unsigned, unsigned> > LiveIns;
108 MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
109 void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
111 explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
112 ~MachineRegisterInfo();
114 //===--------------------------------------------------------------------===//
116 //===--------------------------------------------------------------------===//
118 // isSSA - Returns true when the machine function is in SSA form. Early
119 // passes require the machine function to be in SSA form where every virtual
120 // register has a single defining instruction.
122 // The TwoAddressInstructionPass and PHIElimination passes take the machine
123 // function out of SSA form when they introduce multiple defs per virtual
125 bool isSSA() const { return IsSSA; }
127 // leaveSSA - Indicates that the machine function is no longer in SSA form.
128 void leaveSSA() { IsSSA = false; }
130 /// tracksLiveness - Returns true when tracking register liveness accurately.
132 /// While this flag is true, register liveness information in basic block
133 /// live-in lists and machine instruction operands is accurate. This means it
134 /// can be used to change the code in ways that affect the values in
135 /// registers, for example by the register scavenger.
137 /// When this flag is false, liveness is no longer reliable.
138 bool tracksLiveness() const { return TracksLiveness; }
140 /// invalidateLiveness - Indicates that register liveness is no longer being
141 /// tracked accurately.
143 /// This should be called by late passes that invalidate the liveness
145 void invalidateLiveness() { TracksLiveness = false; }
147 //===--------------------------------------------------------------------===//
149 //===--------------------------------------------------------------------===//
151 // Strictly for use by MachineInstr.cpp.
152 void addRegOperandToUseList(MachineOperand *MO);
154 // Strictly for use by MachineInstr.cpp.
155 void removeRegOperandFromUseList(MachineOperand *MO);
157 // Strictly for use by MachineInstr.cpp.
158 void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
160 /// Verify the sanity of the use list for Reg.
161 void verifyUseList(unsigned Reg) const;
163 /// Verify the use list of all registers.
164 void verifyUseLists() const;
166 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
167 /// and uses of a register within the MachineFunction that corresponds to this
168 /// MachineRegisterInfo object.
169 template<bool Uses, bool Defs, bool SkipDebug>
170 class defusechain_iterator;
172 // Make it a friend so it can access getNextOperandForReg().
173 template<bool, bool, bool> friend class defusechain_iterator;
175 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
177 typedef defusechain_iterator<true,true,false> reg_iterator;
178 reg_iterator reg_begin(unsigned RegNo) const {
179 return reg_iterator(getRegUseDefListHead(RegNo));
181 static reg_iterator reg_end() { return reg_iterator(0); }
183 /// reg_empty - Return true if there are no instructions using or defining the
184 /// specified register (it may be live-in).
185 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
187 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
188 /// of the specified register, skipping those marked as Debug.
189 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
190 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
191 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
193 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
195 /// reg_nodbg_empty - Return true if the only instructions using or defining
196 /// Reg are Debug instructions.
197 bool reg_nodbg_empty(unsigned RegNo) const {
198 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
201 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
202 typedef defusechain_iterator<false,true,false> def_iterator;
203 def_iterator def_begin(unsigned RegNo) const {
204 return def_iterator(getRegUseDefListHead(RegNo));
206 static def_iterator def_end() { return def_iterator(0); }
208 /// def_empty - Return true if there are no instructions defining the
209 /// specified register (it may be live-in).
210 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
212 /// hasOneDef - Return true if there is exactly one instruction defining the
213 /// specified register.
214 bool hasOneDef(unsigned RegNo) const {
215 def_iterator DI = def_begin(RegNo);
218 return ++DI == def_end();
221 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
222 typedef defusechain_iterator<true,false,false> use_iterator;
223 use_iterator use_begin(unsigned RegNo) const {
224 return use_iterator(getRegUseDefListHead(RegNo));
226 static use_iterator use_end() { return use_iterator(0); }
228 /// use_empty - Return true if there are no instructions using the specified
230 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
232 /// hasOneUse - Return true if there is exactly one instruction using the
233 /// specified register.
234 bool hasOneUse(unsigned RegNo) const {
235 use_iterator UI = use_begin(RegNo);
238 return ++UI == use_end();
241 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
242 /// specified register, skipping those marked as Debug.
243 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
244 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
245 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
247 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
249 /// use_nodbg_empty - Return true if there are no non-Debug instructions
250 /// using the specified register.
251 bool use_nodbg_empty(unsigned RegNo) const {
252 return use_nodbg_begin(RegNo) == use_nodbg_end();
255 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
256 /// instruction using the specified register.
257 bool hasOneNonDBGUse(unsigned RegNo) const;
259 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
260 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
261 /// except that it also changes any definitions of the register as well.
263 /// Note that it is usually necessary to first constrain ToReg's register
264 /// class to match the FromReg constraints using:
266 /// constrainRegClass(ToReg, getRegClass(FromReg))
268 /// That function will return NULL if the virtual registers have incompatible
270 void replaceRegWith(unsigned FromReg, unsigned ToReg);
272 /// getVRegDef - Return the machine instr that defines the specified virtual
273 /// register or null if none is found. This assumes that the code is in SSA
274 /// form, so there should only be one definition.
275 MachineInstr *getVRegDef(unsigned Reg) const;
277 /// getUniqueVRegDef - Return the unique machine instr that defines the
278 /// specified virtual register or null if none is found. If there are
279 /// multiple definitions or no definition, return null.
280 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
282 /// clearKillFlags - Iterate over all the uses of the given register and
283 /// clear the kill flag from the MachineOperand. This function is used by
284 /// optimization passes which extend register lifetimes and need only
285 /// preserve conservative kill flag information.
286 void clearKillFlags(unsigned Reg) const;
289 void dumpUses(unsigned RegNo) const;
292 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
293 /// throughout the function. It is safe to move instructions that read such
295 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
297 //===--------------------------------------------------------------------===//
298 // Virtual Register Info
299 //===--------------------------------------------------------------------===//
301 /// getRegClass - Return the register class of the specified virtual register.
303 const TargetRegisterClass *getRegClass(unsigned Reg) const {
304 return VRegInfo[Reg].first;
307 /// setRegClass - Set the register class of the specified virtual register.
309 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
311 /// constrainRegClass - Constrain the register class of the specified virtual
312 /// register to be a common subclass of RC and the current register class,
313 /// but only if the new class has at least MinNumRegs registers. Return the
314 /// new register class, or NULL if no such class exists.
315 /// This should only be used when the constraint is known to be trivial, like
316 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
318 const TargetRegisterClass *constrainRegClass(unsigned Reg,
319 const TargetRegisterClass *RC,
320 unsigned MinNumRegs = 0);
322 /// recomputeRegClass - Try to find a legal super-class of Reg's register
323 /// class that still satisfies the constraints from the instructions using
324 /// Reg. Returns true if Reg was upgraded.
326 /// This method can be used after constraints have been removed from a
327 /// virtual register, for example after removing instructions or splitting
330 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
332 /// createVirtualRegister - Create and return a new virtual register in the
333 /// function with the specified register class.
335 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
337 /// getNumVirtRegs - Return the number of virtual registers created.
339 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
341 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
342 void clearVirtRegs();
344 /// setRegAllocationHint - Specify a register allocation hint for the
345 /// specified virtual register.
346 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
347 RegAllocHints[Reg].first = Type;
348 RegAllocHints[Reg].second = PrefReg;
351 /// getRegAllocationHint - Return the register allocation hint for the
352 /// specified virtual register.
353 std::pair<unsigned, unsigned>
354 getRegAllocationHint(unsigned Reg) const {
355 return RegAllocHints[Reg];
358 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
359 /// standard simple hint (Type == 0) is not set.
360 unsigned getSimpleHint(unsigned Reg) const {
361 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
362 return Hint.first ? 0 : Hint.second;
366 //===--------------------------------------------------------------------===//
367 // Physical Register Use Info
368 //===--------------------------------------------------------------------===//
370 /// isPhysRegUsed - Return true if the specified register is used in this
371 /// function. Also check for clobbered aliases and registers clobbered by
372 /// function calls with register mask operands.
374 /// This only works after register allocation. It is primarily used by
375 /// PrologEpilogInserter to determine which callee-saved registers need
377 bool isPhysRegUsed(unsigned Reg) const {
378 if (UsedPhysRegMask.test(Reg))
380 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
381 if (UsedRegUnits.test(*Units))
386 /// Mark the specified register unit as used in this function.
387 /// This should only be called during and after register allocation.
388 void setRegUnitUsed(unsigned RegUnit) {
389 UsedRegUnits.set(RegUnit);
392 /// setPhysRegUsed - Mark the specified register used in this function.
393 /// This should only be called during and after register allocation.
394 void setPhysRegUsed(unsigned Reg) {
395 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
396 UsedRegUnits.set(*Units);
399 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
400 /// This corresponds to the bit mask attached to register mask operands.
401 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
402 UsedPhysRegMask.setBitsNotInMask(RegMask);
405 /// setPhysRegUnused - Mark the specified register unused in this function.
406 /// This should only be called during and after register allocation.
407 void setPhysRegUnused(unsigned Reg) {
408 UsedPhysRegMask.reset(Reg);
409 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
410 UsedRegUnits.reset(*Units);
414 //===--------------------------------------------------------------------===//
415 // Reserved Register Info
416 //===--------------------------------------------------------------------===//
418 // The set of reserved registers must be invariant during register
419 // allocation. For example, the target cannot suddenly decide it needs a
420 // frame pointer when the register allocator has already used the frame
421 // pointer register for something else.
423 // These methods can be used by target hooks like hasFP() to avoid changing
424 // the reserved register set during register allocation.
426 /// freezeReservedRegs - Called by the register allocator to freeze the set
427 /// of reserved registers before allocation begins.
428 void freezeReservedRegs(const MachineFunction&);
430 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
431 /// to ensure the set of reserved registers stays constant.
432 bool reservedRegsFrozen() const {
433 return !ReservedRegs.empty();
436 /// canReserveReg - Returns true if PhysReg can be used as a reserved
437 /// register. Any register can be reserved before freezeReservedRegs() is
439 bool canReserveReg(unsigned PhysReg) const {
440 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
443 /// getReservedRegs - Returns a reference to the frozen set of reserved
444 /// registers. This method should always be preferred to calling
445 /// TRI::getReservedRegs() when possible.
446 const BitVector &getReservedRegs() const {
447 assert(reservedRegsFrozen() &&
448 "Reserved registers haven't been frozen yet. "
449 "Use TRI::getReservedRegs().");
453 /// isReserved - Returns true when PhysReg is a reserved register.
455 /// Reserved registers may belong to an allocatable register class, but the
456 /// target has explicitly requested that they are not used.
458 bool isReserved(unsigned PhysReg) const {
459 return getReservedRegs().test(PhysReg);
462 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
463 /// register class and it hasn't been reserved.
465 /// Allocatable registers may show up in the allocation order of some virtual
466 /// register, so a register allocator needs to track its liveness and
468 bool isAllocatable(unsigned PhysReg) const {
469 return TRI->isInAllocatableClass(PhysReg) && !isReserved(PhysReg);
472 //===--------------------------------------------------------------------===//
474 //===--------------------------------------------------------------------===//
476 /// addLiveIn - Add the specified register as a live-in. Note that it
477 /// is an error to add the same register to the same set more than once.
478 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
479 LiveIns.push_back(std::make_pair(Reg, vreg));
482 // Iteration support for the live-ins set. It's kept in sorted order
483 // by register number.
484 typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
486 livein_iterator livein_begin() const { return LiveIns.begin(); }
487 livein_iterator livein_end() const { return LiveIns.end(); }
488 bool livein_empty() const { return LiveIns.empty(); }
490 bool isLiveIn(unsigned Reg) const;
492 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
493 /// corresponding live-in physical register.
494 unsigned getLiveInPhysReg(unsigned VReg) const;
496 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
497 /// corresponding live-in physical register.
498 unsigned getLiveInVirtReg(unsigned PReg) const;
500 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
501 /// into the given entry block.
502 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
503 const TargetRegisterInfo &TRI,
504 const TargetInstrInfo &TII);
506 /// defusechain_iterator - This class provides iterator support for machine
507 /// operands in the function that use or define a specific register. If
508 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
509 /// returns defs. If neither are true then you are silly and it always
510 /// returns end(). If SkipDebug is true it skips uses marked Debug
511 /// when incrementing.
512 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
513 class defusechain_iterator
514 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
516 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
517 // If the first node isn't one we're interested in, advance to one that
518 // we are interested in.
520 if ((!ReturnUses && op->isUse()) ||
521 (!ReturnDefs && op->isDef()) ||
522 (SkipDebug && op->isDebug()))
526 friend class MachineRegisterInfo;
528 typedef std::iterator<std::forward_iterator_tag,
529 MachineInstr, ptrdiff_t>::reference reference;
530 typedef std::iterator<std::forward_iterator_tag,
531 MachineInstr, ptrdiff_t>::pointer pointer;
533 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
534 defusechain_iterator() : Op(0) {}
536 bool operator==(const defusechain_iterator &x) const {
539 bool operator!=(const defusechain_iterator &x) const {
540 return !operator==(x);
543 /// atEnd - return true if this iterator is equal to reg_end() on the value.
544 bool atEnd() const { return Op == 0; }
546 // Iterator traversal: forward iteration only
547 defusechain_iterator &operator++() { // Preincrement
548 assert(Op && "Cannot increment end iterator!");
549 Op = getNextOperandForReg(Op);
551 // All defs come before the uses, so stop def_iterator early.
557 assert(!Op->isDebug() && "Can't have debug defs");
560 // If this is an operand we don't care about, skip it.
561 while (Op && ((!ReturnDefs && Op->isDef()) ||
562 (SkipDebug && Op->isDebug())))
563 Op = getNextOperandForReg(Op);
568 defusechain_iterator operator++(int) { // Postincrement
569 defusechain_iterator tmp = *this; ++*this; return tmp;
572 /// skipInstruction - move forward until reaching a different instruction.
573 /// Return the skipped instruction that is no longer pointed to, or NULL if
574 /// already pointing to end().
575 MachineInstr *skipInstruction() {
577 MachineInstr *MI = Op->getParent();
579 while (Op && Op->getParent() == MI);
583 MachineInstr *skipBundle() {
585 MachineInstr *MI = getBundleStart(Op->getParent());
587 while (Op && getBundleStart(Op->getParent()) == MI);
591 MachineOperand &getOperand() const {
592 assert(Op && "Cannot dereference end iterator!");
596 /// getOperandNo - Return the operand # of this MachineOperand in its
598 unsigned getOperandNo() const {
599 assert(Op && "Cannot dereference end iterator!");
600 return Op - &Op->getParent()->getOperand(0);
603 // Retrieve a reference to the current operand.
604 MachineInstr &operator*() const {
605 assert(Op && "Cannot dereference end iterator!");
606 return *Op->getParent();
609 MachineInstr *operator->() const {
610 assert(Op && "Cannot dereference end iterator!");
611 return Op->getParent();
617 } // End llvm namespace