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/Target/TargetRegisterInfo.h"
18 #include "llvm/CodeGen/MachineInstrBundle.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/IndexedMap.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 /// LiveIns/LiveOuts - Keep track of the physical registers that are
103 /// livein/liveout of the function. Live in values are typically arguments in
104 /// registers, live out values are typically return values in registers.
105 /// LiveIn values are allowed to have virtual registers associated with them,
106 /// stored in the second element.
107 std::vector<std::pair<unsigned, unsigned> > LiveIns;
108 std::vector<unsigned> LiveOuts;
110 MachineRegisterInfo(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
111 void operator=(const MachineRegisterInfo&) LLVM_DELETED_FUNCTION;
113 explicit MachineRegisterInfo(const TargetRegisterInfo &TRI);
114 ~MachineRegisterInfo();
116 //===--------------------------------------------------------------------===//
118 //===--------------------------------------------------------------------===//
120 // isSSA - Returns true when the machine function is in SSA form. Early
121 // passes require the machine function to be in SSA form where every virtual
122 // register has a single defining instruction.
124 // The TwoAddressInstructionPass and PHIElimination passes take the machine
125 // function out of SSA form when they introduce multiple defs per virtual
127 bool isSSA() const { return IsSSA; }
129 // leaveSSA - Indicates that the machine function is no longer in SSA form.
130 void leaveSSA() { IsSSA = false; }
132 /// tracksLiveness - Returns true when tracking register liveness accurately.
134 /// While this flag is true, register liveness information in basic block
135 /// live-in lists and machine instruction operands is accurate. This means it
136 /// can be used to change the code in ways that affect the values in
137 /// registers, for example by the register scavenger.
139 /// When this flag is false, liveness is no longer reliable.
140 bool tracksLiveness() const { return TracksLiveness; }
142 /// invalidateLiveness - Indicates that register liveness is no longer being
143 /// tracked accurately.
145 /// This should be called by late passes that invalidate the liveness
147 void invalidateLiveness() { TracksLiveness = false; }
149 //===--------------------------------------------------------------------===//
151 //===--------------------------------------------------------------------===//
153 // Strictly for use by MachineInstr.cpp.
154 void addRegOperandToUseList(MachineOperand *MO);
156 // Strictly for use by MachineInstr.cpp.
157 void removeRegOperandFromUseList(MachineOperand *MO);
159 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
160 /// and uses of a register within the MachineFunction that corresponds to this
161 /// MachineRegisterInfo object.
162 template<bool Uses, bool Defs, bool SkipDebug>
163 class defusechain_iterator;
165 // Make it a friend so it can access getNextOperandForReg().
166 template<bool, bool, bool> friend class defusechain_iterator;
168 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
170 typedef defusechain_iterator<true,true,false> reg_iterator;
171 reg_iterator reg_begin(unsigned RegNo) const {
172 return reg_iterator(getRegUseDefListHead(RegNo));
174 static reg_iterator reg_end() { return reg_iterator(0); }
176 /// reg_empty - Return true if there are no instructions using or defining the
177 /// specified register (it may be live-in).
178 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
180 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
181 /// of the specified register, skipping those marked as Debug.
182 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
183 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
184 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
186 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
188 /// reg_nodbg_empty - Return true if the only instructions using or defining
189 /// Reg are Debug instructions.
190 bool reg_nodbg_empty(unsigned RegNo) const {
191 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
194 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
195 typedef defusechain_iterator<false,true,false> def_iterator;
196 def_iterator def_begin(unsigned RegNo) const {
197 return def_iterator(getRegUseDefListHead(RegNo));
199 static def_iterator def_end() { return def_iterator(0); }
201 /// def_empty - Return true if there are no instructions defining the
202 /// specified register (it may be live-in).
203 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
205 /// hasOneDef - Return true if there is exactly one instruction defining the
206 /// specified register.
207 bool hasOneDef(unsigned RegNo) const {
208 def_iterator DI = def_begin(RegNo);
211 return ++DI == def_end();
214 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
215 typedef defusechain_iterator<true,false,false> use_iterator;
216 use_iterator use_begin(unsigned RegNo) const {
217 return use_iterator(getRegUseDefListHead(RegNo));
219 static use_iterator use_end() { return use_iterator(0); }
221 /// use_empty - Return true if there are no instructions using the specified
223 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
225 /// hasOneUse - Return true if there is exactly one instruction using the
226 /// specified register.
227 bool hasOneUse(unsigned RegNo) const {
228 use_iterator UI = use_begin(RegNo);
231 return ++UI == use_end();
234 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
235 /// specified register, skipping those marked as Debug.
236 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
237 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
238 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
240 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
242 /// use_nodbg_empty - Return true if there are no non-Debug instructions
243 /// using the specified register.
244 bool use_nodbg_empty(unsigned RegNo) const {
245 return use_nodbg_begin(RegNo) == use_nodbg_end();
248 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
249 /// instruction using the specified register.
250 bool hasOneNonDBGUse(unsigned RegNo) const;
252 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
253 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
254 /// except that it also changes any definitions of the register as well.
256 /// Note that it is usually necessary to first constrain ToReg's register
257 /// class to match the FromReg constraints using:
259 /// constrainRegClass(ToReg, getRegClass(FromReg))
261 /// That function will return NULL if the virtual registers have incompatible
263 void replaceRegWith(unsigned FromReg, unsigned ToReg);
265 /// getVRegDef - Return the machine instr that defines the specified virtual
266 /// register or null if none is found. This assumes that the code is in SSA
267 /// form, so there should only be one definition.
268 MachineInstr *getVRegDef(unsigned Reg) const;
270 /// getUniqueVRegDef - Return the unique machine instr that defines the
271 /// specified virtual register or null if none is found. If there are
272 /// multiple definitions or no definition, return null.
273 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
275 /// clearKillFlags - Iterate over all the uses of the given register and
276 /// clear the kill flag from the MachineOperand. This function is used by
277 /// optimization passes which extend register lifetimes and need only
278 /// preserve conservative kill flag information.
279 void clearKillFlags(unsigned Reg) const;
282 void dumpUses(unsigned RegNo) const;
285 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
286 /// throughout the function. It is safe to move instructions that read such
288 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
290 //===--------------------------------------------------------------------===//
291 // Virtual Register Info
292 //===--------------------------------------------------------------------===//
294 /// getRegClass - Return the register class of the specified virtual register.
296 const TargetRegisterClass *getRegClass(unsigned Reg) const {
297 return VRegInfo[Reg].first;
300 /// setRegClass - Set the register class of the specified virtual register.
302 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
304 /// constrainRegClass - Constrain the register class of the specified virtual
305 /// register to be a common subclass of RC and the current register class,
306 /// but only if the new class has at least MinNumRegs registers. Return the
307 /// new register class, or NULL if no such class exists.
308 /// This should only be used when the constraint is known to be trivial, like
309 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
311 const TargetRegisterClass *constrainRegClass(unsigned Reg,
312 const TargetRegisterClass *RC,
313 unsigned MinNumRegs = 0);
315 /// recomputeRegClass - Try to find a legal super-class of Reg's register
316 /// class that still satisfies the constraints from the instructions using
317 /// Reg. Returns true if Reg was upgraded.
319 /// This method can be used after constraints have been removed from a
320 /// virtual register, for example after removing instructions or splitting
323 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
325 /// createVirtualRegister - Create and return a new virtual register in the
326 /// function with the specified register class.
328 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
330 /// getNumVirtRegs - Return the number of virtual registers created.
332 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
334 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
335 void clearVirtRegs();
337 /// setRegAllocationHint - Specify a register allocation hint for the
338 /// specified virtual register.
339 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
340 RegAllocHints[Reg].first = Type;
341 RegAllocHints[Reg].second = PrefReg;
344 /// getRegAllocationHint - Return the register allocation hint for the
345 /// specified virtual register.
346 std::pair<unsigned, unsigned>
347 getRegAllocationHint(unsigned Reg) const {
348 return RegAllocHints[Reg];
351 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
352 /// standard simple hint (Type == 0) is not set.
353 unsigned getSimpleHint(unsigned Reg) const {
354 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
355 return Hint.first ? 0 : Hint.second;
359 //===--------------------------------------------------------------------===//
360 // Physical Register Use Info
361 //===--------------------------------------------------------------------===//
363 /// isPhysRegUsed - Return true if the specified register is used in this
364 /// function. Also check for clobbered aliases and registers clobbered by
365 /// function calls with register mask operands.
367 /// This only works after register allocation. It is primarily used by
368 /// PrologEpilogInserter to determine which callee-saved registers need
370 bool isPhysRegUsed(unsigned Reg) const {
371 if (UsedPhysRegMask.test(Reg))
373 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
374 if (UsedRegUnits.test(*Units))
379 /// setPhysRegUsed - Mark the specified register used in this function.
380 /// This should only be called during and after register allocation.
381 void setPhysRegUsed(unsigned Reg) {
382 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
383 UsedRegUnits.set(*Units);
386 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
387 /// This corresponds to the bit mask attached to register mask operands.
388 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
389 UsedPhysRegMask.setBitsNotInMask(RegMask);
392 /// setPhysRegUnused - Mark the specified register unused in this function.
393 /// This should only be called during and after register allocation.
394 void setPhysRegUnused(unsigned Reg) {
395 UsedPhysRegMask.reset(Reg);
396 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
397 UsedRegUnits.reset(*Units);
401 //===--------------------------------------------------------------------===//
402 // Reserved Register Info
403 //===--------------------------------------------------------------------===//
405 // The set of reserved registers must be invariant during register
406 // allocation. For example, the target cannot suddenly decide it needs a
407 // frame pointer when the register allocator has already used the frame
408 // pointer register for something else.
410 // These methods can be used by target hooks like hasFP() to avoid changing
411 // the reserved register set during register allocation.
413 /// freezeReservedRegs - Called by the register allocator to freeze the set
414 /// of reserved registers before allocation begins.
415 void freezeReservedRegs(const MachineFunction&);
417 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
418 /// to ensure the set of reserved registers stays constant.
419 bool reservedRegsFrozen() const {
420 return !ReservedRegs.empty();
423 /// canReserveReg - Returns true if PhysReg can be used as a reserved
424 /// register. Any register can be reserved before freezeReservedRegs() is
426 bool canReserveReg(unsigned PhysReg) const {
427 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
430 /// getReservedRegs - Returns a reference to the frozen set of reserved
431 /// registers. This method should always be preferred to calling
432 /// TRI::getReservedRegs() when possible.
433 const BitVector &getReservedRegs() const {
434 assert(reservedRegsFrozen() &&
435 "Reserved registers haven't been frozen yet. "
436 "Use TRI::getReservedRegs().");
440 /// isReserved - Returns true when PhysReg is a reserved register.
442 /// Reserved registers may belong to an allocatable register class, but the
443 /// target has explicitly requested that they are not used.
445 bool isReserved(unsigned PhysReg) const {
446 return getReservedRegs().test(PhysReg);
449 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
450 /// register class and it hasn't been reserved.
452 /// Allocatable registers may show up in the allocation order of some virtual
453 /// register, so a register allocator needs to track its liveness and
455 bool isAllocatable(unsigned PhysReg) const {
456 return TRI->isInAllocatableClass(PhysReg) && !isReserved(PhysReg);
459 //===--------------------------------------------------------------------===//
460 // LiveIn/LiveOut Management
461 //===--------------------------------------------------------------------===//
463 /// addLiveIn/Out - Add the specified register as a live in/out. Note that it
464 /// is an error to add the same register to the same set more than once.
465 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
466 LiveIns.push_back(std::make_pair(Reg, vreg));
468 void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
470 // Iteration support for live in/out sets. These sets are kept in sorted
471 // order by their register number.
472 typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
474 typedef std::vector<unsigned>::const_iterator liveout_iterator;
475 livein_iterator livein_begin() const { return LiveIns.begin(); }
476 livein_iterator livein_end() const { return LiveIns.end(); }
477 bool livein_empty() const { return LiveIns.empty(); }
478 liveout_iterator liveout_begin() const { return LiveOuts.begin(); }
479 liveout_iterator liveout_end() const { return LiveOuts.end(); }
480 bool liveout_empty() const { return LiveOuts.empty(); }
482 bool isLiveIn(unsigned Reg) const;
483 bool isLiveOut(unsigned Reg) const;
485 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
486 /// corresponding live-in physical register.
487 unsigned getLiveInPhysReg(unsigned VReg) const;
489 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
490 /// corresponding live-in physical register.
491 unsigned getLiveInVirtReg(unsigned PReg) const;
493 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
494 /// into the given entry block.
495 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
496 const TargetRegisterInfo &TRI,
497 const TargetInstrInfo &TII);
499 /// defusechain_iterator - This class provides iterator support for machine
500 /// operands in the function that use or define a specific register. If
501 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
502 /// returns defs. If neither are true then you are silly and it always
503 /// returns end(). If SkipDebug is true it skips uses marked Debug
504 /// when incrementing.
505 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
506 class defusechain_iterator
507 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
509 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
510 // If the first node isn't one we're interested in, advance to one that
511 // we are interested in.
513 if ((!ReturnUses && op->isUse()) ||
514 (!ReturnDefs && op->isDef()) ||
515 (SkipDebug && op->isDebug()))
519 friend class MachineRegisterInfo;
521 typedef std::iterator<std::forward_iterator_tag,
522 MachineInstr, ptrdiff_t>::reference reference;
523 typedef std::iterator<std::forward_iterator_tag,
524 MachineInstr, ptrdiff_t>::pointer pointer;
526 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
527 defusechain_iterator() : Op(0) {}
529 bool operator==(const defusechain_iterator &x) const {
532 bool operator!=(const defusechain_iterator &x) const {
533 return !operator==(x);
536 /// atEnd - return true if this iterator is equal to reg_end() on the value.
537 bool atEnd() const { return Op == 0; }
539 // Iterator traversal: forward iteration only
540 defusechain_iterator &operator++() { // Preincrement
541 assert(Op && "Cannot increment end iterator!");
542 Op = getNextOperandForReg(Op);
544 // All defs come before the uses, so stop def_iterator early.
550 assert(!Op->isDebug() && "Can't have debug defs");
553 // If this is an operand we don't care about, skip it.
554 while (Op && ((!ReturnDefs && Op->isDef()) ||
555 (SkipDebug && Op->isDebug())))
556 Op = getNextOperandForReg(Op);
561 defusechain_iterator operator++(int) { // Postincrement
562 defusechain_iterator tmp = *this; ++*this; return tmp;
565 /// skipInstruction - move forward until reaching a different instruction.
566 /// Return the skipped instruction that is no longer pointed to, or NULL if
567 /// already pointing to end().
568 MachineInstr *skipInstruction() {
570 MachineInstr *MI = Op->getParent();
572 while (Op && Op->getParent() == MI);
576 MachineInstr *skipBundle() {
578 MachineInstr *MI = getBundleStart(Op->getParent());
580 while (Op && getBundleStart(Op->getParent()) == MI);
584 MachineOperand &getOperand() const {
585 assert(Op && "Cannot dereference end iterator!");
589 /// getOperandNo - Return the operand # of this MachineOperand in its
591 unsigned getOperandNo() const {
592 assert(Op && "Cannot dereference end iterator!");
593 return Op - &Op->getParent()->getOperand(0);
596 // Retrieve a reference to the current operand.
597 MachineInstr &operator*() const {
598 assert(Op && "Cannot dereference end iterator!");
599 return *Op->getParent();
602 MachineInstr *operator->() const {
603 assert(Op && "Cannot dereference end iterator!");
604 return Op->getParent();
610 } // End llvm namespace