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, live out values are
104 /// typically return values in registers. LiveIn values are allowed to have
105 /// virtual registers associated with them, stored in the second element.
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 /// reg_begin/reg_end - Provide iteration support to walk over all definitions
161 /// and uses of a register within the MachineFunction that corresponds to this
162 /// MachineRegisterInfo object.
163 template<bool Uses, bool Defs, bool SkipDebug>
164 class defusechain_iterator;
166 // Make it a friend so it can access getNextOperandForReg().
167 template<bool, bool, bool> friend class defusechain_iterator;
169 /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
171 typedef defusechain_iterator<true,true,false> reg_iterator;
172 reg_iterator reg_begin(unsigned RegNo) const {
173 return reg_iterator(getRegUseDefListHead(RegNo));
175 static reg_iterator reg_end() { return reg_iterator(0); }
177 /// reg_empty - Return true if there are no instructions using or defining the
178 /// specified register (it may be live-in).
179 bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
181 /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
182 /// of the specified register, skipping those marked as Debug.
183 typedef defusechain_iterator<true,true,true> reg_nodbg_iterator;
184 reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
185 return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
187 static reg_nodbg_iterator reg_nodbg_end() { return reg_nodbg_iterator(0); }
189 /// reg_nodbg_empty - Return true if the only instructions using or defining
190 /// Reg are Debug instructions.
191 bool reg_nodbg_empty(unsigned RegNo) const {
192 return reg_nodbg_begin(RegNo) == reg_nodbg_end();
195 /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
196 typedef defusechain_iterator<false,true,false> def_iterator;
197 def_iterator def_begin(unsigned RegNo) const {
198 return def_iterator(getRegUseDefListHead(RegNo));
200 static def_iterator def_end() { return def_iterator(0); }
202 /// def_empty - Return true if there are no instructions defining the
203 /// specified register (it may be live-in).
204 bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
206 /// hasOneDef - Return true if there is exactly one instruction defining the
207 /// specified register.
208 bool hasOneDef(unsigned RegNo) const {
209 def_iterator DI = def_begin(RegNo);
212 return ++DI == def_end();
215 /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
216 typedef defusechain_iterator<true,false,false> use_iterator;
217 use_iterator use_begin(unsigned RegNo) const {
218 return use_iterator(getRegUseDefListHead(RegNo));
220 static use_iterator use_end() { return use_iterator(0); }
222 /// use_empty - Return true if there are no instructions using the specified
224 bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
226 /// hasOneUse - Return true if there is exactly one instruction using the
227 /// specified register.
228 bool hasOneUse(unsigned RegNo) const {
229 use_iterator UI = use_begin(RegNo);
232 return ++UI == use_end();
235 /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
236 /// specified register, skipping those marked as Debug.
237 typedef defusechain_iterator<true,false,true> use_nodbg_iterator;
238 use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
239 return use_nodbg_iterator(getRegUseDefListHead(RegNo));
241 static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0); }
243 /// use_nodbg_empty - Return true if there are no non-Debug instructions
244 /// using the specified register.
245 bool use_nodbg_empty(unsigned RegNo) const {
246 return use_nodbg_begin(RegNo) == use_nodbg_end();
249 /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
250 /// instruction using the specified register.
251 bool hasOneNonDBGUse(unsigned RegNo) const;
253 /// replaceRegWith - Replace all instances of FromReg with ToReg in the
254 /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
255 /// except that it also changes any definitions of the register as well.
257 /// Note that it is usually necessary to first constrain ToReg's register
258 /// class to match the FromReg constraints using:
260 /// constrainRegClass(ToReg, getRegClass(FromReg))
262 /// That function will return NULL if the virtual registers have incompatible
264 void replaceRegWith(unsigned FromReg, unsigned ToReg);
266 /// getVRegDef - Return the machine instr that defines the specified virtual
267 /// register or null if none is found. This assumes that the code is in SSA
268 /// form, so there should only be one definition.
269 MachineInstr *getVRegDef(unsigned Reg) const;
271 /// getUniqueVRegDef - Return the unique machine instr that defines the
272 /// specified virtual register or null if none is found. If there are
273 /// multiple definitions or no definition, return null.
274 MachineInstr *getUniqueVRegDef(unsigned Reg) const;
276 /// clearKillFlags - Iterate over all the uses of the given register and
277 /// clear the kill flag from the MachineOperand. This function is used by
278 /// optimization passes which extend register lifetimes and need only
279 /// preserve conservative kill flag information.
280 void clearKillFlags(unsigned Reg) const;
283 void dumpUses(unsigned RegNo) const;
286 /// isConstantPhysReg - Returns true if PhysReg is unallocatable and constant
287 /// throughout the function. It is safe to move instructions that read such
289 bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) const;
291 //===--------------------------------------------------------------------===//
292 // Virtual Register Info
293 //===--------------------------------------------------------------------===//
295 /// getRegClass - Return the register class of the specified virtual register.
297 const TargetRegisterClass *getRegClass(unsigned Reg) const {
298 return VRegInfo[Reg].first;
301 /// setRegClass - Set the register class of the specified virtual register.
303 void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
305 /// constrainRegClass - Constrain the register class of the specified virtual
306 /// register to be a common subclass of RC and the current register class,
307 /// but only if the new class has at least MinNumRegs registers. Return the
308 /// new register class, or NULL if no such class exists.
309 /// This should only be used when the constraint is known to be trivial, like
310 /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
312 const TargetRegisterClass *constrainRegClass(unsigned Reg,
313 const TargetRegisterClass *RC,
314 unsigned MinNumRegs = 0);
316 /// recomputeRegClass - Try to find a legal super-class of Reg's register
317 /// class that still satisfies the constraints from the instructions using
318 /// Reg. Returns true if Reg was upgraded.
320 /// This method can be used after constraints have been removed from a
321 /// virtual register, for example after removing instructions or splitting
324 bool recomputeRegClass(unsigned Reg, const TargetMachine&);
326 /// createVirtualRegister - Create and return a new virtual register in the
327 /// function with the specified register class.
329 unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
331 /// getNumVirtRegs - Return the number of virtual registers created.
333 unsigned getNumVirtRegs() const { return VRegInfo.size(); }
335 /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
336 void clearVirtRegs();
338 /// setRegAllocationHint - Specify a register allocation hint for the
339 /// specified virtual register.
340 void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg) {
341 RegAllocHints[Reg].first = Type;
342 RegAllocHints[Reg].second = PrefReg;
345 /// getRegAllocationHint - Return the register allocation hint for the
346 /// specified virtual register.
347 std::pair<unsigned, unsigned>
348 getRegAllocationHint(unsigned Reg) const {
349 return RegAllocHints[Reg];
352 /// getSimpleHint - Return the preferred register allocation hint, or 0 if a
353 /// standard simple hint (Type == 0) is not set.
354 unsigned getSimpleHint(unsigned Reg) const {
355 std::pair<unsigned, unsigned> Hint = getRegAllocationHint(Reg);
356 return Hint.first ? 0 : Hint.second;
360 //===--------------------------------------------------------------------===//
361 // Physical Register Use Info
362 //===--------------------------------------------------------------------===//
364 /// isPhysRegUsed - Return true if the specified register is used in this
365 /// function. Also check for clobbered aliases and registers clobbered by
366 /// function calls with register mask operands.
368 /// This only works after register allocation. It is primarily used by
369 /// PrologEpilogInserter to determine which callee-saved registers need
371 bool isPhysRegUsed(unsigned Reg) const {
372 if (UsedPhysRegMask.test(Reg))
374 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
375 if (UsedRegUnits.test(*Units))
380 /// setPhysRegUsed - Mark the specified register used in this function.
381 /// This should only be called during and after register allocation.
382 void setPhysRegUsed(unsigned Reg) {
383 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
384 UsedRegUnits.set(*Units);
387 /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
388 /// This corresponds to the bit mask attached to register mask operands.
389 void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
390 UsedPhysRegMask.setBitsNotInMask(RegMask);
393 /// setPhysRegUnused - Mark the specified register unused in this function.
394 /// This should only be called during and after register allocation.
395 void setPhysRegUnused(unsigned Reg) {
396 UsedPhysRegMask.reset(Reg);
397 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
398 UsedRegUnits.reset(*Units);
402 //===--------------------------------------------------------------------===//
403 // Reserved Register Info
404 //===--------------------------------------------------------------------===//
406 // The set of reserved registers must be invariant during register
407 // allocation. For example, the target cannot suddenly decide it needs a
408 // frame pointer when the register allocator has already used the frame
409 // pointer register for something else.
411 // These methods can be used by target hooks like hasFP() to avoid changing
412 // the reserved register set during register allocation.
414 /// freezeReservedRegs - Called by the register allocator to freeze the set
415 /// of reserved registers before allocation begins.
416 void freezeReservedRegs(const MachineFunction&);
418 /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
419 /// to ensure the set of reserved registers stays constant.
420 bool reservedRegsFrozen() const {
421 return !ReservedRegs.empty();
424 /// canReserveReg - Returns true if PhysReg can be used as a reserved
425 /// register. Any register can be reserved before freezeReservedRegs() is
427 bool canReserveReg(unsigned PhysReg) const {
428 return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
431 /// getReservedRegs - Returns a reference to the frozen set of reserved
432 /// registers. This method should always be preferred to calling
433 /// TRI::getReservedRegs() when possible.
434 const BitVector &getReservedRegs() const {
435 assert(reservedRegsFrozen() &&
436 "Reserved registers haven't been frozen yet. "
437 "Use TRI::getReservedRegs().");
441 /// isReserved - Returns true when PhysReg is a reserved register.
443 /// Reserved registers may belong to an allocatable register class, but the
444 /// target has explicitly requested that they are not used.
446 bool isReserved(unsigned PhysReg) const {
447 return getReservedRegs().test(PhysReg);
450 /// isAllocatable - Returns true when PhysReg belongs to an allocatable
451 /// register class and it hasn't been reserved.
453 /// Allocatable registers may show up in the allocation order of some virtual
454 /// register, so a register allocator needs to track its liveness and
456 bool isAllocatable(unsigned PhysReg) const {
457 return TRI->isInAllocatableClass(PhysReg) && !isReserved(PhysReg);
460 //===--------------------------------------------------------------------===//
461 // LiveIn/LiveOut Management
462 //===--------------------------------------------------------------------===//
464 /// addLiveIn/Out - Add the specified register as a live in/out. Note that it
465 /// is an error to add the same register to the same set more than once.
466 void addLiveIn(unsigned Reg, unsigned vreg = 0) {
467 LiveIns.push_back(std::make_pair(Reg, vreg));
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(); }
479 bool isLiveIn(unsigned Reg) const;
481 /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
482 /// corresponding live-in physical register.
483 unsigned getLiveInPhysReg(unsigned VReg) const;
485 /// getLiveInVirtReg - If PReg is a live-in physical register, return the
486 /// corresponding live-in physical register.
487 unsigned getLiveInVirtReg(unsigned PReg) const;
489 /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
490 /// into the given entry block.
491 void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
492 const TargetRegisterInfo &TRI,
493 const TargetInstrInfo &TII);
495 /// defusechain_iterator - This class provides iterator support for machine
496 /// operands in the function that use or define a specific register. If
497 /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
498 /// returns defs. If neither are true then you are silly and it always
499 /// returns end(). If SkipDebug is true it skips uses marked Debug
500 /// when incrementing.
501 template<bool ReturnUses, bool ReturnDefs, bool SkipDebug>
502 class defusechain_iterator
503 : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
505 explicit defusechain_iterator(MachineOperand *op) : Op(op) {
506 // If the first node isn't one we're interested in, advance to one that
507 // we are interested in.
509 if ((!ReturnUses && op->isUse()) ||
510 (!ReturnDefs && op->isDef()) ||
511 (SkipDebug && op->isDebug()))
515 friend class MachineRegisterInfo;
517 typedef std::iterator<std::forward_iterator_tag,
518 MachineInstr, ptrdiff_t>::reference reference;
519 typedef std::iterator<std::forward_iterator_tag,
520 MachineInstr, ptrdiff_t>::pointer pointer;
522 defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
523 defusechain_iterator() : Op(0) {}
525 bool operator==(const defusechain_iterator &x) const {
528 bool operator!=(const defusechain_iterator &x) const {
529 return !operator==(x);
532 /// atEnd - return true if this iterator is equal to reg_end() on the value.
533 bool atEnd() const { return Op == 0; }
535 // Iterator traversal: forward iteration only
536 defusechain_iterator &operator++() { // Preincrement
537 assert(Op && "Cannot increment end iterator!");
538 Op = getNextOperandForReg(Op);
540 // All defs come before the uses, so stop def_iterator early.
546 assert(!Op->isDebug() && "Can't have debug defs");
549 // If this is an operand we don't care about, skip it.
550 while (Op && ((!ReturnDefs && Op->isDef()) ||
551 (SkipDebug && Op->isDebug())))
552 Op = getNextOperandForReg(Op);
557 defusechain_iterator operator++(int) { // Postincrement
558 defusechain_iterator tmp = *this; ++*this; return tmp;
561 /// skipInstruction - move forward until reaching a different instruction.
562 /// Return the skipped instruction that is no longer pointed to, or NULL if
563 /// already pointing to end().
564 MachineInstr *skipInstruction() {
566 MachineInstr *MI = Op->getParent();
568 while (Op && Op->getParent() == MI);
572 MachineInstr *skipBundle() {
574 MachineInstr *MI = getBundleStart(Op->getParent());
576 while (Op && getBundleStart(Op->getParent()) == MI);
580 MachineOperand &getOperand() const {
581 assert(Op && "Cannot dereference end iterator!");
585 /// getOperandNo - Return the operand # of this MachineOperand in its
587 unsigned getOperandNo() const {
588 assert(Op && "Cannot dereference end iterator!");
589 return Op - &Op->getParent()->getOperand(0);
592 // Retrieve a reference to the current operand.
593 MachineInstr &operator*() const {
594 assert(Op && "Cannot dereference end iterator!");
595 return *Op->getParent();
598 MachineInstr *operator->() const {
599 assert(Op && "Cannot dereference end iterator!");
600 return Op->getParent();
606 } // End llvm namespace