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/TargetMachine.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
26 /// MachineRegisterInfo - Keep track of information for virtual and physical
27 /// registers, including vreg register classes, use/def chains for registers,
29 class MachineRegisterInfo {
33 virtual void MRI_NoteNewVirtualRegister(unsigned Reg) {}
35 virtual ~Delegate() {}
39 const TargetMachine &TM;
40 Delegate *TheDelegate;
42 /// IsSSA - True when the machine function is in SSA form and virtual
43 /// registers have a single def.
46 /// TracksLiveness - True while register liveness is being tracked accurately.
47 /// Basic block live-in lists, kill flags, and implicit defs may not be
48 /// accurate when after this flag is cleared.
51 /// VRegInfo - Information we keep for each virtual register.
53 /// Each element in this list contains the register class of the vreg and the
54 /// start of the use/def list for the register.
55 IndexedMap<std::pair<const TargetRegisterClass*, MachineOperand*>,
56 VirtReg2IndexFunctor> VRegInfo;
58 /// RegAllocHints - This vector records register allocation hints for virtual
59 /// registers. For each virtual register, it keeps a register and hint type
60 /// pair making up the allocation hint. Hint type is target specific except
61 /// for the value 0 which means the second value of the pair is the preferred
62 /// register for allocation. For example, if the hint is <0, 1024>, it means
63 /// the allocator should prefer the physical register allocated to the virtual
64 /// register of the hint.
65 IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAllocHints;
67 /// PhysRegUseDefLists - This is an array of the head of the use/def list for
68 /// physical registers.
69 MachineOperand **PhysRegUseDefLists;
71 /// getRegUseDefListHead - Return the head pointer for the register use/def
72 /// list for the specified virtual or physical register.
73 MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
74 if (TargetRegisterInfo::isVirtualRegister(RegNo))
75 return VRegInfo[RegNo].second;
76 return PhysRegUseDefLists[RegNo];
79 MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
80 if (TargetRegisterInfo::isVirtualRegister(RegNo))
81 return VRegInfo[RegNo].second;
82 return PhysRegUseDefLists[RegNo];
85 /// Get the next element in the use-def chain.
86 static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
87 assert(MO && MO->isReg() && "This is not a register operand!");
88 return MO->Contents.Reg.Next;
91 /// UsedRegUnits - This is a bit vector that is computed and set by the
92 /// register allocator, and must be kept up to date by passes that run after
93 /// register allocation (though most don't modify this). This is used
94 /// so that the code generator knows which callee save registers to save and
95 /// for other target specific uses.
96 /// This vector has bits set for register units that are modified in the
97 /// current function. It doesn't include registers clobbered by function
98 /// calls with register mask operands.
99 BitVector UsedRegUnits;
101 /// UsedPhysRegMask - Additional used physregs including aliases.
102 /// This bit vector represents all the registers clobbered by function calls.
103 /// It can model things that UsedRegUnits can't, such as function calls that
104 /// clobber ymm7 but preserve the low half in xmm7.
105 BitVector UsedPhysRegMask;
107 /// ReservedRegs - This is a bit vector of reserved registers. The target
108 /// may change its mind about which registers should be reserved. This
109 /// vector is the frozen set of reserved registers when register allocation
111 BitVector ReservedRegs;
113 /// Keep track of the physical registers that are live in to the function.
114 /// Live in values are typically arguments in registers. LiveIn values are
115 /// allowed to have virtual registers associated with them, stored in the
117 std::vector<std::pair<unsigned, unsigned> > LiveIns;
119 MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
120 void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
122 explicit MachineRegisterInfo(const TargetMachine &TM);
123 ~MachineRegisterInfo();
125 const TargetRegisterInfo *getTargetRegisterInfo() const {
126 return TM.getRegisterInfo();
129 void resetDelegate(Delegate *delegate) {
130 // Ensure another delegate does not take over unless the current
131 // delegate first unattaches itself. If we ever need to multicast
132 // notifications, we will need to change to using a list.
133 assert(TheDelegate == delegate &&
134 "Only the current delegate can perform reset!");
138 void setDelegate(Delegate *delegate) {
139 assert(delegate && !TheDelegate &&
140 "Attempted to set delegate to null, or to change it without "
141 "first resetting it!");
143 TheDelegate = delegate;
146 //===--------------------------------------------------------------------===//
148 //===--------------------------------------------------------------------===//
150 // isSSA - Returns true when the machine function is in SSA form. Early
151 // passes require the machine function to be in SSA form where every virtual
152 // register has a single defining instruction.
154 // The TwoAddressInstructionPass and PHIElimination passes take the machine
155 // function out of SSA form when they introduce multiple defs per virtual
157 bool isSSA() const { return IsSSA; }
159 // leaveSSA - Indicates that the machine function is no longer in SSA form.
160 void leaveSSA() { IsSSA = false; }
162 /// tracksLiveness - Returns true when tracking register liveness accurately.
164 /// While this flag is true, register liveness information in basic block
165 /// live-in lists and machine instruction operands is accurate. This means it
166 /// can be used to change the code in ways that affect the values in
167 /// registers, for example by the register scavenger.
169 /// When this flag is false, liveness is no longer reliable.
170 bool tracksLiveness() const { return TracksLiveness; }
172 /// invalidateLiveness - Indicates that register liveness is no longer being
173 /// tracked accurately.
175 /// This should be called by late passes that invalidate the liveness
177 void invalidateLiveness() { TracksLiveness = false; }
179 //===--------------------------------------------------------------------===//
181 //===--------------------------------------------------------------------===//
183 // Strictly for use by MachineInstr.cpp.
184 void addRegOperandToUseList(MachineOperand *MO);
186 // Strictly for use by MachineInstr.cpp.
187 void removeRegOperandFromUseList(MachineOperand *MO);
189 // Strictly for use by MachineInstr.cpp.
190 void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
192 /// Verify the sanity of the use list for Reg.
193 void verifyUseList(unsigned Reg) const;
195 /// Verify the use list of all registers.
196 void verifyUseLists() const;
198 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
199 /// and uses of a register within the MachineFunction that corresponds to this
200 /// MachineRegisterInfo object.
201 template<bool Uses, bool Defs, bool SkipDebug>
202 class defusechain_iterator;
204 // Make it a friend so it can access getNextOperandForReg().
205 template<bool, bool, bool> friend class defusechain_iterator;
207 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
209 typedef defusechain_iterator<true,true,false> reg_iterator;
210 reg_iterator reg_begin(unsigned RegNo) const {
211 return reg_iterator(getRegUseDefListHead(RegNo));
213 static reg_iterator reg_end() { return reg_iterator(0); }
215 /// reg_empty - Return true if there are no instructions using or defining the
216 /// specified register (it may be live-in).
217 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
219 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
220 /// of the specified register, skipping those marked as Debug.
221 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
222 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
223 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
225 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
227 /// reg_nodbg_empty - Return true if the only instructions using or defining
228 /// Reg are Debug instructions.
229 bool reg_nodbg_empty(unsigned RegNo) const {
230 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
233 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
234 typedef defusechain_iterator<false,true,false> def_iterator;
235 def_iterator def_begin(unsigned RegNo) const {
236 return def_iterator(getRegUseDefListHead(RegNo));
238 static def_iterator def_end() { return def_iterator(0); }
240 /// def_empty - Return true if there are no instructions defining the
241 /// specified register (it may be live-in).
242 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
244 /// hasOneDef - Return true if there is exactly one instruction defining the
245 /// specified register.
246 bool hasOneDef(unsigned RegNo) const {
247 def_iterator DI = def_begin(RegNo);
250 return ++DI == def_end();
253 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
254 typedef defusechain_iterator<true,false,false> use_iterator;
255 use_iterator use_begin(unsigned RegNo) const {
256 return use_iterator(getRegUseDefListHead(RegNo));
258 static use_iterator use_end() { return use_iterator(0); }
260 /// use_empty - Return true if there are no instructions using the specified
262 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
264 /// hasOneUse - Return true if there is exactly one instruction using the
265 /// specified register.
266 bool hasOneUse(unsigned RegNo) const {
267 use_iterator UI = use_begin(RegNo);
270 return ++UI == use_end();
273 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
274 /// specified register, skipping those marked as Debug.
275 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
276 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
277 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
279 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
281 /// use_nodbg_empty - Return true if there are no non-Debug instructions
282 /// using the specified register.
283 bool use_nodbg_empty(unsigned RegNo) const {
284 return use_nodbg_begin(RegNo) == use_nodbg_end();
287 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
288 /// instruction using the specified register.
289 bool hasOneNonDBGUse(unsigned RegNo) const;
291 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
292 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
293 /// except that it also changes any definitions of the register as well.
295 /// Note that it is usually necessary to first constrain ToReg's register
296 /// class to match the FromReg constraints using:
298 /// constrainRegClass(ToReg, getRegClass(FromReg))
300 /// That function will return NULL if the virtual registers have incompatible
302 void replaceRegWith(unsigned FromReg, unsigned ToReg);
304 /// getVRegDef - Return the machine instr that defines the specified virtual
305 /// register or null if none is found. This assumes that the code is in SSA
306 /// form, so there should only be one definition.
307 MachineInstr *getVRegDef(unsigned Reg) const;
309 /// getUniqueVRegDef - Return the unique machine instr that defines the
310 /// specified virtual register or null if none is found. If there are
311 /// multiple definitions or no definition, return null.
312 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
314 /// clearKillFlags - Iterate over all the uses of the given register and
315 /// clear the kill flag from the MachineOperand. This function is used by
316 /// optimization passes which extend register lifetimes and need only
317 /// preserve conservative kill flag information.
318 void clearKillFlags(unsigned Reg) const;
321 void dumpUses(unsigned RegNo) const;
324 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
325 /// throughout the function. It is safe to move instructions that read such
327 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
329 //===--------------------------------------------------------------------===//
330 // Virtual Register Info
331 //===--------------------------------------------------------------------===//
333 /// getRegClass - Return the register class of the specified virtual register.
335 const TargetRegisterClass *getRegClass(unsigned Reg) const {
336 return VRegInfo[Reg].first;
339 /// setRegClass - Set the register class of the specified virtual register.
341 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
343 /// constrainRegClass - Constrain the register class of the specified virtual
344 /// register to be a common subclass of RC and the current register class,
345 /// but only if the new class has at least MinNumRegs registers. Return the
346 /// new register class, or NULL if no such class exists.
347 /// This should only be used when the constraint is known to be trivial, like
348 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
350 const TargetRegisterClass *constrainRegClass(unsigned Reg,
351 const TargetRegisterClass *RC,
352 unsigned MinNumRegs = 0);
354 /// recomputeRegClass - Try to find a legal super-class of Reg's register
355 /// class that still satisfies the constraints from the instructions using
356 /// Reg. Returns true if Reg was upgraded.
358 /// This method can be used after constraints have been removed from a
359 /// virtual register, for example after removing instructions or splitting
362 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
364 /// createVirtualRegister - Create and return a new virtual register in the
365 /// function with the specified register class.
367 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
369 /// getNumVirtRegs - Return the number of virtual registers created.
371 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
373 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
374 void clearVirtRegs();
376 /// setRegAllocationHint - Specify a register allocation hint for the
377 /// specified virtual register.
378 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
379 RegAllocHints[Reg].first = Type;
380 RegAllocHints[Reg].second = PrefReg;
383 /// getRegAllocationHint - Return the register allocation hint for the
384 /// specified virtual register.
385 std::pair<unsigned, unsigned>
386 getRegAllocationHint(unsigned Reg) const {
387 return RegAllocHints[Reg];
390 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
391 /// standard simple hint (Type == 0) is not set.
392 unsigned getSimpleHint(unsigned Reg) const {
393 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
394 return Hint.first ? 0 : Hint.second;
398 //===--------------------------------------------------------------------===//
399 // Physical Register Use Info
400 //===--------------------------------------------------------------------===//
402 /// isPhysRegUsed - Return true if the specified register is used in this
403 /// function. Also check for clobbered aliases and registers clobbered by
404 /// function calls with register mask operands.
406 /// This only works after register allocation. It is primarily used by
407 /// PrologEpilogInserter to determine which callee-saved registers need
409 bool isPhysRegUsed(unsigned Reg) const {
410 if (UsedPhysRegMask.test(Reg))
412 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
413 Units.isValid(); ++Units)
414 if (UsedRegUnits.test(*Units))
419 /// Mark the specified register unit as used in this function.
420 /// This should only be called during and after register allocation.
421 void setRegUnitUsed(unsigned RegUnit) {
422 UsedRegUnits.set(RegUnit);
425 /// setPhysRegUsed - Mark the specified register used in this function.
426 /// This should only be called during and after register allocation.
427 void setPhysRegUsed(unsigned Reg) {
428 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
429 Units.isValid(); ++Units)
430 UsedRegUnits.set(*Units);
433 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
434 /// This corresponds to the bit mask attached to register mask operands.
435 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
436 UsedPhysRegMask.setBitsNotInMask(RegMask);
439 /// setPhysRegUnused - Mark the specified register unused in this function.
440 /// This should only be called during and after register allocation.
441 void setPhysRegUnused(unsigned Reg) {
442 UsedPhysRegMask.reset(Reg);
443 for (MCRegUnitIterator Units(Reg, getTargetRegisterInfo());
444 Units.isValid(); ++Units)
445 UsedRegUnits.reset(*Units);
449 //===--------------------------------------------------------------------===//
450 // Reserved Register Info
451 //===--------------------------------------------------------------------===//
453 // The set of reserved registers must be invariant during register
454 // allocation. For example, the target cannot suddenly decide it needs a
455 // frame pointer when the register allocator has already used the frame
456 // pointer register for something else.
458 // These methods can be used by target hooks like hasFP() to avoid changing
459 // the reserved register set during register allocation.
461 /// freezeReservedRegs - Called by the register allocator to freeze the set
462 /// of reserved registers before allocation begins.
463 void freezeReservedRegs(const MachineFunction&);
465 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
466 /// to ensure the set of reserved registers stays constant.
467 bool reservedRegsFrozen() const {
468 return !ReservedRegs.empty();
471 /// canReserveReg - Returns true if PhysReg can be used as a reserved
472 /// register. Any register can be reserved before freezeReservedRegs() is
474 bool canReserveReg(unsigned PhysReg) const {
475 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
478 /// getReservedRegs - Returns a reference to the frozen set of reserved
479 /// registers. This method should always be preferred to calling
480 /// TRI::getReservedRegs() when possible.
481 const BitVector &getReservedRegs() const {
482 assert(reservedRegsFrozen() &&
483 "Reserved registers haven't been frozen yet. "
484 "Use TRI::getReservedRegs().");
488 /// isReserved - Returns true when PhysReg is a reserved register.
490 /// Reserved registers may belong to an allocatable register class, but the
491 /// target has explicitly requested that they are not used.
493 bool isReserved(unsigned PhysReg) const {
494 return getReservedRegs().test(PhysReg);
497 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
498 /// register class and it hasn't been reserved.
500 /// Allocatable registers may show up in the allocation order of some virtual
501 /// register, so a register allocator needs to track its liveness and
503 bool isAllocatable(unsigned PhysReg) const {
504 return getTargetRegisterInfo()->isInAllocatableClass(PhysReg) &&
505 !isReserved(PhysReg);
508 //===--------------------------------------------------------------------===//
510 //===--------------------------------------------------------------------===//
512 /// addLiveIn - Add the specified register as a live-in. Note that it
513 /// is an error to add the same register to the same set more than once.
514 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
515 LiveIns.push_back(std::make_pair(Reg, vreg));
518 // Iteration support for the live-ins set. It's kept in sorted order
519 // by register number.
520 typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
522 livein_iterator livein_begin() const { return LiveIns.begin(); }
523 livein_iterator livein_end() const { return LiveIns.end(); }
524 bool livein_empty() const { return LiveIns.empty(); }
526 bool isLiveIn(unsigned Reg) const;
528 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
529 /// corresponding live-in physical register.
530 unsigned getLiveInPhysReg(unsigned VReg) const;
532 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
533 /// corresponding live-in physical register.
534 unsigned getLiveInVirtReg(unsigned PReg) const;
536 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
537 /// into the given entry block.
538 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
539 const TargetRegisterInfo &TRI,
540 const TargetInstrInfo &TII);
542 /// defusechain_iterator - This class provides iterator support for machine
543 /// operands in the function that use or define a specific register. If
544 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
545 /// returns defs. If neither are true then you are silly and it always
546 /// returns end(). If SkipDebug is true it skips uses marked Debug
547 /// when incrementing.
548 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
549 class defusechain_iterator
550 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
552 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
553 // If the first node isn't one we're interested in, advance to one that
554 // we are interested in.
556 if ((!ReturnUses && op->isUse()) ||
557 (!ReturnDefs && op->isDef()) ||
558 (SkipDebug && op->isDebug()))
562 friend class MachineRegisterInfo;
564 typedef std::iterator<std::forward_iterator_tag,
565 MachineInstr, ptrdiff_t>::reference reference;
566 typedef std::iterator<std::forward_iterator_tag,
567 MachineInstr, ptrdiff_t>::pointer pointer;
569 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
570 defusechain_iterator() : Op(0) {}
572 bool operator==(const defusechain_iterator &x) const {
575 bool operator!=(const defusechain_iterator &x) const {
576 return !operator==(x);
579 /// atEnd - return true if this iterator is equal to reg_end() on the value.
580 bool atEnd() const { return Op == 0; }
582 // Iterator traversal: forward iteration only
583 defusechain_iterator &operator++() { // Preincrement
584 assert(Op && "Cannot increment end iterator!");
585 Op = getNextOperandForReg(Op);
587 // All defs come before the uses, so stop def_iterator early.
593 assert(!Op->isDebug() && "Can't have debug defs");
596 // If this is an operand we don't care about, skip it.
597 while (Op && ((!ReturnDefs && Op->isDef()) ||
598 (SkipDebug && Op->isDebug())))
599 Op = getNextOperandForReg(Op);
604 defusechain_iterator operator++(int) { // Postincrement
605 defusechain_iterator tmp = *this; ++*this; return tmp;
608 /// skipInstruction - move forward until reaching a different instruction.
609 /// Return the skipped instruction that is no longer pointed to, or NULL if
610 /// already pointing to end().
611 MachineInstr *skipInstruction() {
613 MachineInstr *MI = Op->getParent();
615 while (Op && Op->getParent() == MI);
619 MachineInstr *skipBundle() {
621 MachineInstr *MI = getBundleStart(Op->getParent());
623 while (Op && getBundleStart(Op->getParent()) == MI);
627 MachineOperand &getOperand() const {
628 assert(Op && "Cannot dereference end iterator!");
632 /// getOperandNo - Return the operand # of this MachineOperand in its
634 unsigned getOperandNo() const {
635 assert(Op && "Cannot dereference end iterator!");
636 return Op - &Op->getParent()->getOperand(0);
639 // Retrieve a reference to the current operand.
640 MachineInstr &operator*() const {
641 assert(Op && "Cannot dereference end iterator!");
642 return *Op->getParent();
645 MachineInstr *operator->() const {
646 assert(Op && "Cannot dereference end iterator!");
647 return Op->getParent();
653 } // End llvm namespace