1 //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 /// \file This register allocator allocates registers to a basic block at a
10 /// time, attempting to keep values in registers and reusing registers as
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegAllocRegistry.h"
31 #include "llvm/CodeGen/RegisterClassInfo.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/MC/MCInstrDesc.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
52 #define DEBUG_TYPE "regalloc"
54 STATISTIC(NumStores
, "Number of stores added");
55 STATISTIC(NumLoads
, "Number of loads added");
56 STATISTIC(NumCoalesced
, "Number of copies coalesced");
58 static RegisterRegAlloc
59 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator
);
63 class RegAllocFast
: public MachineFunctionPass
{
67 RegAllocFast() : MachineFunctionPass(ID
), StackSlotForVirtReg(-1) {}
70 MachineFrameInfo
*MFI
;
71 MachineRegisterInfo
*MRI
;
72 const TargetRegisterInfo
*TRI
;
73 const TargetInstrInfo
*TII
;
74 RegisterClassInfo RegClassInfo
;
76 /// Basic block currently being allocated.
77 MachineBasicBlock
*MBB
;
79 /// Maps virtual regs to the frame index where these values are spilled.
80 IndexedMap
<int, VirtReg2IndexFunctor
> StackSlotForVirtReg
;
82 /// Everything we know about a live virtual register.
84 MachineInstr
*LastUse
= nullptr; ///< Last instr to use reg.
85 unsigned VirtReg
; ///< Virtual register number.
86 MCPhysReg PhysReg
= 0; ///< Currently held here.
87 unsigned short LastOpNum
= 0; ///< OpNum on LastUse.
88 bool Dirty
= false; ///< Register needs spill.
90 explicit LiveReg(unsigned VirtReg
) : VirtReg(VirtReg
) {}
92 unsigned getSparseSetIndex() const {
93 return TargetRegisterInfo::virtReg2Index(VirtReg
);
97 using LiveRegMap
= SparseSet
<LiveReg
>;
98 /// This map contains entries for each virtual register that is currently
99 /// available in a physical register.
100 LiveRegMap LiveVirtRegs
;
102 DenseMap
<unsigned, SmallVector
<MachineInstr
*, 2>> LiveDbgValueMap
;
104 /// Has a bit set for every virtual register for which it was determined
105 /// that it is alive across blocks.
106 BitVector MayLiveAcrossBlocks
;
108 /// State of a physical register.
110 /// A disabled register is not available for allocation, but an alias may
111 /// be in use. A register can only be moved out of the disabled state if
112 /// all aliases are disabled.
115 /// A free register is not currently in use and can be allocated
116 /// immediately without checking aliases.
119 /// A reserved register has been assigned explicitly (e.g., setting up a
120 /// call parameter), and it remains reserved until it is used.
123 /// A register state may also be a virtual register number, indication
124 /// that the physical register is currently allocated to a virtual
125 /// register. In that case, LiveVirtRegs contains the inverse mapping.
128 /// Maps each physical register to a RegState enum or a virtual register.
129 std::vector
<unsigned> PhysRegState
;
131 SmallVector
<unsigned, 16> VirtDead
;
132 SmallVector
<MachineInstr
*, 32> Coalesced
;
134 using RegUnitSet
= SparseSet
<uint16_t, identity
<uint16_t>>;
135 /// Set of register units that are used in the current instruction, and so
136 /// cannot be allocated.
137 RegUnitSet UsedInInstr
;
139 void setPhysRegState(MCPhysReg PhysReg
, unsigned NewState
);
141 /// Mark a physreg as used in this instruction.
142 void markRegUsedInInstr(MCPhysReg PhysReg
) {
143 for (MCRegUnitIterator
Units(PhysReg
, TRI
); Units
.isValid(); ++Units
)
144 UsedInInstr
.insert(*Units
);
147 /// Check if a physreg or any of its aliases are used in this instruction.
148 bool isRegUsedInInstr(MCPhysReg PhysReg
) const {
149 for (MCRegUnitIterator
Units(PhysReg
, TRI
); Units
.isValid(); ++Units
)
150 if (UsedInInstr
.count(*Units
))
159 spillImpossible
= ~0u
163 StringRef
getPassName() const override
{ return "Fast Register Allocator"; }
165 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
166 AU
.setPreservesCFG();
167 MachineFunctionPass::getAnalysisUsage(AU
);
170 MachineFunctionProperties
getRequiredProperties() const override
{
171 return MachineFunctionProperties().set(
172 MachineFunctionProperties::Property::NoPHIs
);
175 MachineFunctionProperties
getSetProperties() const override
{
176 return MachineFunctionProperties().set(
177 MachineFunctionProperties::Property::NoVRegs
);
181 bool runOnMachineFunction(MachineFunction
&MF
) override
;
183 void allocateBasicBlock(MachineBasicBlock
&MBB
);
184 void allocateInstruction(MachineInstr
&MI
);
185 void handleDebugValue(MachineInstr
&MI
);
186 void handleThroughOperands(MachineInstr
&MI
,
187 SmallVectorImpl
<unsigned> &VirtDead
);
188 bool isLastUseOfLocalReg(const MachineOperand
&MO
) const;
190 void addKillFlag(const LiveReg
&LRI
);
191 void killVirtReg(LiveReg
&LR
);
192 void killVirtReg(unsigned VirtReg
);
193 void spillVirtReg(MachineBasicBlock::iterator MI
, LiveReg
&LR
);
194 void spillVirtReg(MachineBasicBlock::iterator MI
, unsigned VirtReg
);
196 void usePhysReg(MachineOperand
&MO
);
197 void definePhysReg(MachineBasicBlock::iterator MI
, MCPhysReg PhysReg
,
199 unsigned calcSpillCost(MCPhysReg PhysReg
) const;
200 void assignVirtToPhysReg(LiveReg
&, MCPhysReg PhysReg
);
202 LiveRegMap::iterator
findLiveVirtReg(unsigned VirtReg
) {
203 return LiveVirtRegs
.find(TargetRegisterInfo::virtReg2Index(VirtReg
));
206 LiveRegMap::const_iterator
findLiveVirtReg(unsigned VirtReg
) const {
207 return LiveVirtRegs
.find(TargetRegisterInfo::virtReg2Index(VirtReg
));
210 void allocVirtReg(MachineInstr
&MI
, LiveReg
&LR
, unsigned Hint
);
211 void allocVirtRegUndef(MachineOperand
&MO
);
212 MCPhysReg
defineVirtReg(MachineInstr
&MI
, unsigned OpNum
, unsigned VirtReg
,
214 LiveReg
&reloadVirtReg(MachineInstr
&MI
, unsigned OpNum
, unsigned VirtReg
,
216 void spillAll(MachineBasicBlock::iterator MI
, bool OnlyLiveOut
);
217 bool setPhysReg(MachineInstr
&MI
, MachineOperand
&MO
, MCPhysReg PhysReg
);
219 unsigned traceCopies(unsigned VirtReg
) const;
220 unsigned traceCopyChain(unsigned Reg
) const;
222 int getStackSpaceFor(unsigned VirtReg
);
223 void spill(MachineBasicBlock::iterator Before
, unsigned VirtReg
,
224 MCPhysReg AssignedReg
, bool Kill
);
225 void reload(MachineBasicBlock::iterator Before
, unsigned VirtReg
,
228 bool mayLiveOut(unsigned VirtReg
);
229 bool mayLiveIn(unsigned VirtReg
);
234 } // end anonymous namespace
236 char RegAllocFast::ID
= 0;
238 INITIALIZE_PASS(RegAllocFast
, "regallocfast", "Fast Register Allocator", false,
241 void RegAllocFast::setPhysRegState(MCPhysReg PhysReg
, unsigned NewState
) {
242 PhysRegState
[PhysReg
] = NewState
;
245 /// This allocates space for the specified virtual register to be held on the
247 int RegAllocFast::getStackSpaceFor(unsigned VirtReg
) {
248 // Find the location Reg would belong...
249 int SS
= StackSlotForVirtReg
[VirtReg
];
250 // Already has space allocated?
254 // Allocate a new stack object for this spill location...
255 const TargetRegisterClass
&RC
= *MRI
->getRegClass(VirtReg
);
256 unsigned Size
= TRI
->getSpillSize(RC
);
257 unsigned Align
= TRI
->getSpillAlignment(RC
);
258 int FrameIdx
= MFI
->CreateSpillStackObject(Size
, Align
);
261 StackSlotForVirtReg
[VirtReg
] = FrameIdx
;
265 /// Returns false if \p VirtReg is known to not live out of the current block.
266 bool RegAllocFast::mayLiveOut(unsigned VirtReg
) {
267 if (MayLiveAcrossBlocks
.test(TargetRegisterInfo::virtReg2Index(VirtReg
))) {
268 // Cannot be live-out if there are no successors.
269 return !MBB
->succ_empty();
272 // If this block loops back to itself, it would be necessary to check whether
273 // the use comes after the def.
274 if (MBB
->isSuccessor(MBB
)) {
275 MayLiveAcrossBlocks
.set(TargetRegisterInfo::virtReg2Index(VirtReg
));
279 // See if the first \p Limit uses of the register are all in the current
281 static const unsigned Limit
= 8;
283 for (const MachineInstr
&UseInst
: MRI
->reg_nodbg_instructions(VirtReg
)) {
284 if (UseInst
.getParent() != MBB
|| ++C
>= Limit
) {
285 MayLiveAcrossBlocks
.set(TargetRegisterInfo::virtReg2Index(VirtReg
));
286 // Cannot be live-out if there are no successors.
287 return !MBB
->succ_empty();
294 /// Returns false if \p VirtReg is known to not be live into the current block.
295 bool RegAllocFast::mayLiveIn(unsigned VirtReg
) {
296 if (MayLiveAcrossBlocks
.test(TargetRegisterInfo::virtReg2Index(VirtReg
)))
297 return !MBB
->pred_empty();
299 // See if the first \p Limit def of the register are all in the current block.
300 static const unsigned Limit
= 8;
302 for (const MachineInstr
&DefInst
: MRI
->def_instructions(VirtReg
)) {
303 if (DefInst
.getParent() != MBB
|| ++C
>= Limit
) {
304 MayLiveAcrossBlocks
.set(TargetRegisterInfo::virtReg2Index(VirtReg
));
305 return !MBB
->pred_empty();
312 /// Insert spill instruction for \p AssignedReg before \p Before. Update
313 /// DBG_VALUEs with \p VirtReg operands with the stack slot.
314 void RegAllocFast::spill(MachineBasicBlock::iterator Before
, unsigned VirtReg
,
315 MCPhysReg AssignedReg
, bool Kill
) {
316 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg
, TRI
)
317 << " in " << printReg(AssignedReg
, TRI
));
318 int FI
= getStackSpaceFor(VirtReg
);
319 LLVM_DEBUG(dbgs() << " to stack slot #" << FI
<< '\n');
321 const TargetRegisterClass
&RC
= *MRI
->getRegClass(VirtReg
);
322 TII
->storeRegToStackSlot(*MBB
, Before
, AssignedReg
, Kill
, FI
, &RC
, TRI
);
325 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
326 // identify spilled location as the place to find corresponding variable's
328 SmallVectorImpl
<MachineInstr
*> &LRIDbgValues
= LiveDbgValueMap
[VirtReg
];
329 for (MachineInstr
*DBG
: LRIDbgValues
) {
330 MachineInstr
*NewDV
= buildDbgValueForSpill(*MBB
, Before
, *DBG
, FI
);
331 assert(NewDV
->getParent() == MBB
&& "dangling parent pointer");
333 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV
);
335 // Now this register is spilled there is should not be any DBG_VALUE
336 // pointing to this register because they are all pointing to spilled value
338 LRIDbgValues
.clear();
341 /// Insert reload instruction for \p PhysReg before \p Before.
342 void RegAllocFast::reload(MachineBasicBlock::iterator Before
, unsigned VirtReg
,
344 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg
, TRI
) << " into "
345 << printReg(PhysReg
, TRI
) << '\n');
346 int FI
= getStackSpaceFor(VirtReg
);
347 const TargetRegisterClass
&RC
= *MRI
->getRegClass(VirtReg
);
348 TII
->loadRegFromStackSlot(*MBB
, Before
, PhysReg
, FI
, &RC
, TRI
);
352 /// Return true if MO is the only remaining reference to its virtual register,
353 /// and it is guaranteed to be a block-local register.
354 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand
&MO
) const {
355 // If the register has ever been spilled or reloaded, we conservatively assume
356 // it is a global register used in multiple blocks.
357 if (StackSlotForVirtReg
[MO
.getReg()] != -1)
360 // Check that the use/def chain has exactly one operand - MO.
361 MachineRegisterInfo::reg_nodbg_iterator I
= MRI
->reg_nodbg_begin(MO
.getReg());
364 return ++I
== MRI
->reg_nodbg_end();
367 /// Set kill flags on last use of a virtual register.
368 void RegAllocFast::addKillFlag(const LiveReg
&LR
) {
369 if (!LR
.LastUse
) return;
370 MachineOperand
&MO
= LR
.LastUse
->getOperand(LR
.LastOpNum
);
371 if (MO
.isUse() && !LR
.LastUse
->isRegTiedToDefOperand(LR
.LastOpNum
)) {
372 if (MO
.getReg() == LR
.PhysReg
)
374 // else, don't do anything we are problably redefining a
375 // subreg of this register and given we don't track which
376 // lanes are actually dead, we cannot insert a kill flag here.
377 // Otherwise we may end up in a situation like this:
378 // ... = (MO) physreg:sub1, implicit killed physreg
379 // ... <== Here we would allow later pass to reuse physreg:sub1
380 // which is potentially wrong.
382 // ... = LR.sub1 <== This is going to use physreg:sub1
386 /// Mark virtreg as no longer available.
387 void RegAllocFast::killVirtReg(LiveReg
&LR
) {
389 assert(PhysRegState
[LR
.PhysReg
] == LR
.VirtReg
&&
390 "Broken RegState mapping");
391 setPhysRegState(LR
.PhysReg
, regFree
);
395 /// Mark virtreg as no longer available.
396 void RegAllocFast::killVirtReg(unsigned VirtReg
) {
397 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) &&
398 "killVirtReg needs a virtual register");
399 LiveRegMap::iterator LRI
= findLiveVirtReg(VirtReg
);
400 if (LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
)
404 /// This method spills the value specified by VirtReg into the corresponding
405 /// stack slot if needed.
406 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI
,
408 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) &&
409 "Spilling a physical register is illegal!");
410 LiveRegMap::iterator LRI
= findLiveVirtReg(VirtReg
);
411 assert(LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
&&
412 "Spilling unmapped virtual register");
413 spillVirtReg(MI
, *LRI
);
416 /// Do the actual work of spilling.
417 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI
, LiveReg
&LR
) {
418 assert(PhysRegState
[LR
.PhysReg
] == LR
.VirtReg
&& "Broken RegState mapping");
421 // If this physreg is used by the instruction, we want to kill it on the
422 // instruction, not on the spill.
423 bool SpillKill
= MachineBasicBlock::iterator(LR
.LastUse
) != MI
;
426 spill(MI
, LR
.VirtReg
, LR
.PhysReg
, SpillKill
);
429 LR
.LastUse
= nullptr; // Don't kill register again
434 /// Spill all dirty virtregs without killing them.
435 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI
, bool OnlyLiveOut
) {
436 if (LiveVirtRegs
.empty())
438 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
439 // of spilling here is deterministic, if arbitrary.
440 for (LiveReg
&LR
: LiveVirtRegs
) {
443 if (OnlyLiveOut
&& !mayLiveOut(LR
.VirtReg
))
445 spillVirtReg(MI
, LR
);
447 LiveVirtRegs
.clear();
450 /// Handle the direct use of a physical register. Check that the register is
451 /// not used by a virtreg. Kill the physreg, marking it free. This may add
452 /// implicit kills to MO->getParent() and invalidate MO.
453 void RegAllocFast::usePhysReg(MachineOperand
&MO
) {
454 // Ignore undef uses.
458 unsigned PhysReg
= MO
.getReg();
459 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg
) &&
460 "Bad usePhysReg operand");
462 markRegUsedInInstr(PhysReg
);
463 switch (PhysRegState
[PhysReg
]) {
467 PhysRegState
[PhysReg
] = regFree
;
473 // The physreg was allocated to a virtual register. That means the value we
474 // wanted has been clobbered.
475 llvm_unreachable("Instruction uses an allocated register");
478 // Maybe a superregister is reserved?
479 for (MCRegAliasIterator
AI(PhysReg
, TRI
, false); AI
.isValid(); ++AI
) {
480 MCPhysReg Alias
= *AI
;
481 switch (PhysRegState
[Alias
]) {
485 // Either PhysReg is a subregister of Alias and we mark the
486 // whole register as free, or PhysReg is the superregister of
487 // Alias and we mark all the aliases as disabled before freeing
489 // In the latter case, since PhysReg was disabled, this means that
490 // its value is defined only by physical sub-registers. This check
491 // is performed by the assert of the default case in this loop.
492 // Note: The value of the superregister may only be partial
493 // defined, that is why regDisabled is a valid state for aliases.
494 assert((TRI
->isSuperRegister(PhysReg
, Alias
) ||
495 TRI
->isSuperRegister(Alias
, PhysReg
)) &&
496 "Instruction is not using a subregister of a reserved register");
499 if (TRI
->isSuperRegister(PhysReg
, Alias
)) {
500 // Leave the superregister in the working set.
501 setPhysRegState(Alias
, regFree
);
502 MO
.getParent()->addRegisterKilled(Alias
, TRI
, true);
505 // Some other alias was in the working set - clear it.
506 setPhysRegState(Alias
, regDisabled
);
509 llvm_unreachable("Instruction uses an alias of an allocated register");
513 // All aliases are disabled, bring register into working set.
514 setPhysRegState(PhysReg
, regFree
);
518 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
519 /// similar to defineVirtReg except the physreg is reserved instead of
521 void RegAllocFast::definePhysReg(MachineBasicBlock::iterator MI
,
522 MCPhysReg PhysReg
, RegState NewState
) {
523 markRegUsedInInstr(PhysReg
);
524 switch (unsigned VirtReg
= PhysRegState
[PhysReg
]) {
528 spillVirtReg(MI
, VirtReg
);
532 setPhysRegState(PhysReg
, NewState
);
536 // This is a disabled register, disable all aliases.
537 setPhysRegState(PhysReg
, NewState
);
538 for (MCRegAliasIterator
AI(PhysReg
, TRI
, false); AI
.isValid(); ++AI
) {
539 MCPhysReg Alias
= *AI
;
540 switch (unsigned VirtReg
= PhysRegState
[Alias
]) {
544 spillVirtReg(MI
, VirtReg
);
548 setPhysRegState(Alias
, regDisabled
);
549 if (TRI
->isSuperRegister(PhysReg
, Alias
))
556 /// Return the cost of spilling clearing out PhysReg and aliases so it is free
557 /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
558 /// disabled - it can be allocated directly.
559 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
560 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg
) const {
561 if (isRegUsedInInstr(PhysReg
)) {
562 LLVM_DEBUG(dbgs() << printReg(PhysReg
, TRI
)
563 << " is already used in instr.\n");
564 return spillImpossible
;
566 switch (unsigned VirtReg
= PhysRegState
[PhysReg
]) {
572 LLVM_DEBUG(dbgs() << printReg(VirtReg
, TRI
) << " corresponding "
573 << printReg(PhysReg
, TRI
) << " is reserved already.\n");
574 return spillImpossible
;
576 LiveRegMap::const_iterator LRI
= findLiveVirtReg(VirtReg
);
577 assert(LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
&&
578 "Missing VirtReg entry");
579 return LRI
->Dirty
? spillDirty
: spillClean
;
583 // This is a disabled register, add up cost of aliases.
584 LLVM_DEBUG(dbgs() << printReg(PhysReg
, TRI
) << " is disabled.\n");
586 for (MCRegAliasIterator
AI(PhysReg
, TRI
, false); AI
.isValid(); ++AI
) {
587 MCPhysReg Alias
= *AI
;
588 switch (unsigned VirtReg
= PhysRegState
[Alias
]) {
595 return spillImpossible
;
597 LiveRegMap::const_iterator LRI
= findLiveVirtReg(VirtReg
);
598 assert(LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
&&
599 "Missing VirtReg entry");
600 Cost
+= LRI
->Dirty
? spillDirty
: spillClean
;
608 /// This method updates local state so that we know that PhysReg is the
609 /// proper container for VirtReg now. The physical register must not be used
610 /// for anything else when this is called.
611 void RegAllocFast::assignVirtToPhysReg(LiveReg
&LR
, MCPhysReg PhysReg
) {
612 unsigned VirtReg
= LR
.VirtReg
;
613 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg
, TRI
) << " to "
614 << printReg(PhysReg
, TRI
) << '\n');
615 assert(LR
.PhysReg
== 0 && "Already assigned a physreg");
616 assert(PhysReg
!= 0 && "Trying to assign no register");
617 LR
.PhysReg
= PhysReg
;
618 setPhysRegState(PhysReg
, VirtReg
);
621 static bool isCoalescable(const MachineInstr
&MI
) {
622 return MI
.isFullCopy();
625 unsigned RegAllocFast::traceCopyChain(unsigned Reg
) const {
626 static const unsigned ChainLengthLimit
= 3;
629 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
631 assert(TargetRegisterInfo::isVirtualRegister(Reg
));
633 MachineInstr
*VRegDef
= MRI
->getUniqueVRegDef(Reg
);
634 if (!VRegDef
|| !isCoalescable(*VRegDef
))
636 Reg
= VRegDef
->getOperand(1).getReg();
637 } while (++C
<= ChainLengthLimit
);
641 /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
642 /// chain of copies to check whether we reach a physical register we can
644 unsigned RegAllocFast::traceCopies(unsigned VirtReg
) const {
645 static const unsigned DefLimit
= 3;
647 for (const MachineInstr
&MI
: MRI
->def_instructions(VirtReg
)) {
648 if (isCoalescable(MI
)) {
649 unsigned Reg
= MI
.getOperand(1).getReg();
650 Reg
= traceCopyChain(Reg
);
661 /// Allocates a physical register for VirtReg.
662 void RegAllocFast::allocVirtReg(MachineInstr
&MI
, LiveReg
&LR
, unsigned Hint0
) {
663 const unsigned VirtReg
= LR
.VirtReg
;
665 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) &&
666 "Can only allocate virtual registers");
668 const TargetRegisterClass
&RC
= *MRI
->getRegClass(VirtReg
);
669 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg
)
670 << " in class " << TRI
->getRegClassName(&RC
)
671 << " with hint " << printReg(Hint0
, TRI
) << '\n');
673 // Take hint when possible.
674 if (TargetRegisterInfo::isPhysicalRegister(Hint0
) &&
675 MRI
->isAllocatable(Hint0
) && RC
.contains(Hint0
)) {
676 // Ignore the hint if we would have to spill a dirty register.
677 unsigned Cost
= calcSpillCost(Hint0
);
678 if (Cost
< spillDirty
) {
679 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0
, TRI
)
682 definePhysReg(MI
, Hint0
, regFree
);
683 assignVirtToPhysReg(LR
, Hint0
);
686 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0
, TRI
)
694 unsigned Hint1
= traceCopies(VirtReg
);
695 if (TargetRegisterInfo::isPhysicalRegister(Hint1
) &&
696 MRI
->isAllocatable(Hint1
) && RC
.contains(Hint1
) &&
697 !isRegUsedInInstr(Hint1
)) {
698 // Ignore the hint if we would have to spill a dirty register.
699 unsigned Cost
= calcSpillCost(Hint1
);
700 if (Cost
< spillDirty
) {
701 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1
, TRI
)
704 definePhysReg(MI
, Hint1
, regFree
);
705 assignVirtToPhysReg(LR
, Hint1
);
708 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1
, TRI
)
715 MCPhysReg BestReg
= 0;
716 unsigned BestCost
= spillImpossible
;
717 ArrayRef
<MCPhysReg
> AllocationOrder
= RegClassInfo
.getOrder(&RC
);
718 for (MCPhysReg PhysReg
: AllocationOrder
) {
719 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg
, TRI
) << ' ');
720 unsigned Cost
= calcSpillCost(PhysReg
);
721 LLVM_DEBUG(dbgs() << "Cost: " << Cost
<< " BestCost: " << BestCost
<< '\n');
722 // Immediate take a register with cost 0.
724 assignVirtToPhysReg(LR
, PhysReg
);
728 if (PhysReg
== Hint1
|| PhysReg
== Hint0
)
729 Cost
-= spillPrefBonus
;
731 if (Cost
< BestCost
) {
738 // Nothing we can do: Report an error and keep going with an invalid
740 if (MI
.isInlineAsm())
741 MI
.emitError("inline assembly requires more registers than available");
743 MI
.emitError("ran out of registers during register allocation");
744 definePhysReg(MI
, *AllocationOrder
.begin(), regFree
);
745 assignVirtToPhysReg(LR
, *AllocationOrder
.begin());
749 definePhysReg(MI
, BestReg
, regFree
);
750 assignVirtToPhysReg(LR
, BestReg
);
753 void RegAllocFast::allocVirtRegUndef(MachineOperand
&MO
) {
754 assert(MO
.isUndef() && "expected undef use");
755 unsigned VirtReg
= MO
.getReg();
756 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) && "Expected virtreg");
758 LiveRegMap::const_iterator LRI
= findLiveVirtReg(VirtReg
);
760 if (LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
) {
761 PhysReg
= LRI
->PhysReg
;
763 const TargetRegisterClass
&RC
= *MRI
->getRegClass(VirtReg
);
764 ArrayRef
<MCPhysReg
> AllocationOrder
= RegClassInfo
.getOrder(&RC
);
765 assert(!AllocationOrder
.empty() && "Allocation order must not be empty");
766 PhysReg
= AllocationOrder
[0];
769 unsigned SubRegIdx
= MO
.getSubReg();
770 if (SubRegIdx
!= 0) {
771 PhysReg
= TRI
->getSubReg(PhysReg
, SubRegIdx
);
775 MO
.setIsRenamable(true);
778 /// Allocates a register for VirtReg and mark it as dirty.
779 MCPhysReg
RegAllocFast::defineVirtReg(MachineInstr
&MI
, unsigned OpNum
,
780 unsigned VirtReg
, unsigned Hint
) {
781 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) &&
782 "Not a virtual register");
783 LiveRegMap::iterator LRI
;
785 std::tie(LRI
, New
) = LiveVirtRegs
.insert(LiveReg(VirtReg
));
787 // If there is no hint, peek at the only use of this register.
788 if ((!Hint
|| !TargetRegisterInfo::isPhysicalRegister(Hint
)) &&
789 MRI
->hasOneNonDBGUse(VirtReg
)) {
790 const MachineInstr
&UseMI
= *MRI
->use_instr_nodbg_begin(VirtReg
);
791 // It's a copy, use the destination register as a hint.
792 if (UseMI
.isCopyLike())
793 Hint
= UseMI
.getOperand(0).getReg();
795 allocVirtReg(MI
, *LRI
, Hint
);
796 } else if (LRI
->LastUse
) {
797 // Redefining a live register - kill at the last use, unless it is this
798 // instruction defining VirtReg multiple times.
799 if (LRI
->LastUse
!= &MI
|| LRI
->LastUse
->getOperand(LRI
->LastOpNum
).isUse())
802 assert(LRI
->PhysReg
&& "Register not assigned");
804 LRI
->LastOpNum
= OpNum
;
806 markRegUsedInInstr(LRI
->PhysReg
);
810 /// Make sure VirtReg is available in a physreg and return it.
811 RegAllocFast::LiveReg
&RegAllocFast::reloadVirtReg(MachineInstr
&MI
,
815 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) &&
816 "Not a virtual register");
817 LiveRegMap::iterator LRI
;
819 std::tie(LRI
, New
) = LiveVirtRegs
.insert(LiveReg(VirtReg
));
820 MachineOperand
&MO
= MI
.getOperand(OpNum
);
822 allocVirtReg(MI
, *LRI
, Hint
);
823 reload(MI
, VirtReg
, LRI
->PhysReg
);
824 } else if (LRI
->Dirty
) {
825 if (isLastUseOfLocalReg(MO
)) {
826 LLVM_DEBUG(dbgs() << "Killing last use: " << MO
<< '\n');
831 } else if (MO
.isKill()) {
832 LLVM_DEBUG(dbgs() << "Clearing dubious kill: " << MO
<< '\n');
834 } else if (MO
.isDead()) {
835 LLVM_DEBUG(dbgs() << "Clearing dubious dead: " << MO
<< '\n');
838 } else if (MO
.isKill()) {
839 // We must remove kill flags from uses of reloaded registers because the
840 // register would be killed immediately, and there might be a second use:
841 // %foo = OR killed %x, %x
842 // This would cause a second reload of %x into a different register.
843 LLVM_DEBUG(dbgs() << "Clearing clean kill: " << MO
<< '\n');
845 } else if (MO
.isDead()) {
846 LLVM_DEBUG(dbgs() << "Clearing clean dead: " << MO
<< '\n');
849 assert(LRI
->PhysReg
&& "Register not assigned");
851 LRI
->LastOpNum
= OpNum
;
852 markRegUsedInInstr(LRI
->PhysReg
);
856 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
857 /// may invalidate any operand pointers. Return true if the operand kills its
859 bool RegAllocFast::setPhysReg(MachineInstr
&MI
, MachineOperand
&MO
,
861 bool Dead
= MO
.isDead();
862 if (!MO
.getSubReg()) {
864 MO
.setIsRenamable(true);
865 return MO
.isKill() || Dead
;
868 // Handle subregister index.
869 MO
.setReg(PhysReg
? TRI
->getSubReg(PhysReg
, MO
.getSubReg()) : 0);
870 MO
.setIsRenamable(true);
873 // A kill flag implies killing the full register. Add corresponding super
876 MI
.addRegisterKilled(PhysReg
, TRI
, true);
880 // A <def,read-undef> of a sub-register requires an implicit def of the full
882 if (MO
.isDef() && MO
.isUndef())
883 MI
.addRegisterDefined(PhysReg
, TRI
);
888 // Handles special instruction operand like early clobbers and tied ops when
889 // there are additional physreg defines.
890 void RegAllocFast::handleThroughOperands(MachineInstr
&MI
,
891 SmallVectorImpl
<unsigned> &VirtDead
) {
892 LLVM_DEBUG(dbgs() << "Scanning for through registers:");
893 SmallSet
<unsigned, 8> ThroughRegs
;
894 for (const MachineOperand
&MO
: MI
.operands()) {
895 if (!MO
.isReg()) continue;
896 unsigned Reg
= MO
.getReg();
897 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
899 if (MO
.isEarlyClobber() || (MO
.isUse() && MO
.isTied()) ||
900 (MO
.getSubReg() && MI
.readsVirtualRegister(Reg
))) {
901 if (ThroughRegs
.insert(Reg
).second
)
902 LLVM_DEBUG(dbgs() << ' ' << printReg(Reg
));
906 // If any physreg defines collide with preallocated through registers,
907 // we must spill and reallocate.
908 LLVM_DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
909 for (const MachineOperand
&MO
: MI
.operands()) {
910 if (!MO
.isReg() || !MO
.isDef()) continue;
911 unsigned Reg
= MO
.getReg();
912 if (!Reg
|| !TargetRegisterInfo::isPhysicalRegister(Reg
)) continue;
913 markRegUsedInInstr(Reg
);
914 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
915 if (ThroughRegs
.count(PhysRegState
[*AI
]))
916 definePhysReg(MI
, *AI
, regFree
);
920 SmallVector
<unsigned, 8> PartialDefs
;
921 LLVM_DEBUG(dbgs() << "Allocating tied uses.\n");
922 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
923 MachineOperand
&MO
= MI
.getOperand(I
);
924 if (!MO
.isReg()) continue;
925 unsigned Reg
= MO
.getReg();
926 if (!TargetRegisterInfo::isVirtualRegister(Reg
)) continue;
928 if (!MO
.isTied()) continue;
929 LLVM_DEBUG(dbgs() << "Operand " << I
<< "(" << MO
930 << ") is tied to operand " << MI
.findTiedOperandIdx(I
)
932 LiveReg
&LR
= reloadVirtReg(MI
, I
, Reg
, 0);
933 MCPhysReg PhysReg
= LR
.PhysReg
;
934 setPhysReg(MI
, MO
, PhysReg
);
935 // Note: we don't update the def operand yet. That would cause the normal
936 // def-scan to attempt spilling.
937 } else if (MO
.getSubReg() && MI
.readsVirtualRegister(Reg
)) {
938 LLVM_DEBUG(dbgs() << "Partial redefine: " << MO
<< '\n');
939 // Reload the register, but don't assign to the operand just yet.
940 // That would confuse the later phys-def processing pass.
941 LiveReg
&LR
= reloadVirtReg(MI
, I
, Reg
, 0);
942 PartialDefs
.push_back(LR
.PhysReg
);
946 LLVM_DEBUG(dbgs() << "Allocating early clobbers.\n");
947 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
948 const MachineOperand
&MO
= MI
.getOperand(I
);
949 if (!MO
.isReg()) continue;
950 unsigned Reg
= MO
.getReg();
951 if (!TargetRegisterInfo::isVirtualRegister(Reg
)) continue;
952 if (!MO
.isEarlyClobber())
954 // Note: defineVirtReg may invalidate MO.
955 MCPhysReg PhysReg
= defineVirtReg(MI
, I
, Reg
, 0);
956 if (setPhysReg(MI
, MI
.getOperand(I
), PhysReg
))
957 VirtDead
.push_back(Reg
);
960 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
962 for (const MachineOperand
&MO
: MI
.operands()) {
963 if (!MO
.isReg() || (MO
.isDef() && !MO
.isEarlyClobber())) continue;
964 unsigned Reg
= MO
.getReg();
965 if (!Reg
|| !TargetRegisterInfo::isPhysicalRegister(Reg
)) continue;
966 LLVM_DEBUG(dbgs() << "\tSetting " << printReg(Reg
, TRI
)
967 << " as used in instr\n");
968 markRegUsedInInstr(Reg
);
971 // Also mark PartialDefs as used to avoid reallocation.
972 for (unsigned PartialDef
: PartialDefs
)
973 markRegUsedInInstr(PartialDef
);
977 void RegAllocFast::dumpState() {
978 for (unsigned Reg
= 1, E
= TRI
->getNumRegs(); Reg
!= E
; ++Reg
) {
979 if (PhysRegState
[Reg
] == regDisabled
) continue;
980 dbgs() << " " << printReg(Reg
, TRI
);
981 switch(PhysRegState
[Reg
]) {
988 dbgs() << '=' << printReg(PhysRegState
[Reg
]);
989 LiveRegMap::iterator LRI
= findLiveVirtReg(PhysRegState
[Reg
]);
990 assert(LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
&&
991 "Missing VirtReg entry");
994 assert(LRI
->PhysReg
== Reg
&& "Bad inverse map");
1000 // Check that LiveVirtRegs is the inverse.
1001 for (LiveRegMap::iterator i
= LiveVirtRegs
.begin(),
1002 e
= LiveVirtRegs
.end(); i
!= e
; ++i
) {
1005 assert(TargetRegisterInfo::isVirtualRegister(i
->VirtReg
) &&
1007 assert(TargetRegisterInfo::isPhysicalRegister(i
->PhysReg
) &&
1009 assert(PhysRegState
[i
->PhysReg
] == i
->VirtReg
&& "Bad inverse map");
1014 void RegAllocFast::allocateInstruction(MachineInstr
&MI
) {
1015 const MCInstrDesc
&MCID
= MI
.getDesc();
1017 // If this is a copy, we may be able to coalesce.
1018 unsigned CopySrcReg
= 0;
1019 unsigned CopyDstReg
= 0;
1020 unsigned CopySrcSub
= 0;
1021 unsigned CopyDstSub
= 0;
1023 CopyDstReg
= MI
.getOperand(0).getReg();
1024 CopySrcReg
= MI
.getOperand(1).getReg();
1025 CopyDstSub
= MI
.getOperand(0).getSubReg();
1026 CopySrcSub
= MI
.getOperand(1).getSubReg();
1029 // Track registers used by instruction.
1030 UsedInInstr
.clear();
1033 // Mark physreg uses and early clobbers as used.
1034 // Find the end of the virtreg operands
1035 unsigned VirtOpEnd
= 0;
1036 bool hasTiedOps
= false;
1037 bool hasEarlyClobbers
= false;
1038 bool hasPartialRedefs
= false;
1039 bool hasPhysDefs
= false;
1040 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
1041 MachineOperand
&MO
= MI
.getOperand(i
);
1042 // Make sure MRI knows about registers clobbered by regmasks.
1043 if (MO
.isRegMask()) {
1044 MRI
->addPhysRegsUsedFromRegMask(MO
.getRegMask());
1047 if (!MO
.isReg()) continue;
1048 unsigned Reg
= MO
.getReg();
1050 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1053 hasTiedOps
= hasTiedOps
||
1054 MCID
.getOperandConstraint(i
, MCOI::TIED_TO
) != -1;
1056 if (MO
.isEarlyClobber())
1057 hasEarlyClobbers
= true;
1058 if (MO
.getSubReg() && MI
.readsVirtualRegister(Reg
))
1059 hasPartialRedefs
= true;
1063 if (!MRI
->isAllocatable(Reg
)) continue;
1066 } else if (MO
.isEarlyClobber()) {
1067 definePhysReg(MI
, Reg
,
1068 (MO
.isImplicit() || MO
.isDead()) ? regFree
: regReserved
);
1069 hasEarlyClobbers
= true;
1074 // The instruction may have virtual register operands that must be allocated
1075 // the same register at use-time and def-time: early clobbers and tied
1076 // operands. If there are also physical defs, these registers must avoid
1077 // both physical defs and uses, making them more constrained than normal
1079 // Similarly, if there are multiple defs and tied operands, we must make
1080 // sure the same register is allocated to uses and defs.
1081 // We didn't detect inline asm tied operands above, so just make this extra
1082 // pass for all inline asm.
1083 if (MI
.isInlineAsm() || hasEarlyClobbers
|| hasPartialRedefs
||
1084 (hasTiedOps
&& (hasPhysDefs
|| MCID
.getNumDefs() > 1))) {
1085 handleThroughOperands(MI
, VirtDead
);
1086 // Don't attempt coalescing when we have funny stuff going on.
1088 // Pretend we have early clobbers so the use operands get marked below.
1089 // This is not necessary for the common case of a single tied use.
1090 hasEarlyClobbers
= true;
1094 // Allocate virtreg uses.
1095 bool HasUndefUse
= false;
1096 for (unsigned I
= 0; I
!= VirtOpEnd
; ++I
) {
1097 MachineOperand
&MO
= MI
.getOperand(I
);
1098 if (!MO
.isReg()) continue;
1099 unsigned Reg
= MO
.getReg();
1100 if (!TargetRegisterInfo::isVirtualRegister(Reg
)) continue;
1104 // There is no need to allocate a register for an undef use.
1108 // Populate MayLiveAcrossBlocks in case the use block is allocated before
1109 // the def block (removing the vreg uses).
1112 LiveReg
&LR
= reloadVirtReg(MI
, I
, Reg
, CopyDstReg
);
1113 MCPhysReg PhysReg
= LR
.PhysReg
;
1114 CopySrcReg
= (CopySrcReg
== Reg
|| CopySrcReg
== PhysReg
) ? PhysReg
: 0;
1115 if (setPhysReg(MI
, MO
, PhysReg
))
1120 // Allocate undef operands. This is a separate step because in a situation
1121 // like ` = OP undef %X, %X` both operands need the same register assign
1122 // so we should perform the normal assignment first.
1124 for (MachineOperand
&MO
: MI
.uses()) {
1125 if (!MO
.isReg() || !MO
.isUse())
1127 unsigned Reg
= MO
.getReg();
1128 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
1131 assert(MO
.isUndef() && "Should only have undef virtreg uses left");
1132 allocVirtRegUndef(MO
);
1136 // Track registers defined by instruction - early clobbers and tied uses at
1138 UsedInInstr
.clear();
1139 if (hasEarlyClobbers
) {
1140 for (const MachineOperand
&MO
: MI
.operands()) {
1141 if (!MO
.isReg()) continue;
1142 unsigned Reg
= MO
.getReg();
1143 if (!Reg
|| !TargetRegisterInfo::isPhysicalRegister(Reg
)) continue;
1144 // Look for physreg defs and tied uses.
1145 if (!MO
.isDef() && !MO
.isTied()) continue;
1146 markRegUsedInInstr(Reg
);
1150 unsigned DefOpEnd
= MI
.getNumOperands();
1152 // Spill all virtregs before a call. This serves one purpose: If an
1153 // exception is thrown, the landing pad is going to expect to find
1154 // registers in their spill slots.
1155 // Note: although this is appealing to just consider all definitions
1156 // as call-clobbered, this is not correct because some of those
1157 // definitions may be used later on and we do not want to reuse
1158 // those for virtual registers in between.
1159 LLVM_DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1160 spillAll(MI
, /*OnlyLiveOut*/ false);
1164 // Mark all physreg defs as used before allocating virtreg defs.
1165 for (unsigned I
= 0; I
!= DefOpEnd
; ++I
) {
1166 const MachineOperand
&MO
= MI
.getOperand(I
);
1167 if (!MO
.isReg() || !MO
.isDef() || !MO
.getReg() || MO
.isEarlyClobber())
1169 unsigned Reg
= MO
.getReg();
1171 if (!Reg
|| !TargetRegisterInfo::isPhysicalRegister(Reg
) ||
1172 !MRI
->isAllocatable(Reg
))
1174 definePhysReg(MI
, Reg
, MO
.isDead() ? regFree
: regReserved
);
1178 // Allocate defs and collect dead defs.
1179 for (unsigned I
= 0; I
!= DefOpEnd
; ++I
) {
1180 const MachineOperand
&MO
= MI
.getOperand(I
);
1181 if (!MO
.isReg() || !MO
.isDef() || !MO
.getReg() || MO
.isEarlyClobber())
1183 unsigned Reg
= MO
.getReg();
1185 // We have already dealt with phys regs in the previous scan.
1186 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
1188 MCPhysReg PhysReg
= defineVirtReg(MI
, I
, Reg
, CopySrcReg
);
1189 if (setPhysReg(MI
, MI
.getOperand(I
), PhysReg
)) {
1190 VirtDead
.push_back(Reg
);
1191 CopyDstReg
= 0; // cancel coalescing;
1193 CopyDstReg
= (CopyDstReg
== Reg
|| CopyDstReg
== PhysReg
) ? PhysReg
: 0;
1196 // Kill dead defs after the scan to ensure that multiple defs of the same
1197 // register are allocated identically. We didn't need to do this for uses
1198 // because we are crerating our own kill flags, and they are always at the
1200 for (unsigned VirtReg
: VirtDead
)
1201 killVirtReg(VirtReg
);
1204 LLVM_DEBUG(dbgs() << "<< " << MI
);
1205 if (CopyDstReg
&& CopyDstReg
== CopySrcReg
&& CopyDstSub
== CopySrcSub
) {
1206 LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1207 Coalesced
.push_back(&MI
);
1211 void RegAllocFast::handleDebugValue(MachineInstr
&MI
) {
1212 MachineOperand
&MO
= MI
.getOperand(0);
1214 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1215 // mostly constants and frame indices.
1218 unsigned Reg
= MO
.getReg();
1219 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
1222 // See if this virtual register has already been allocated to a physical
1223 // register or spilled to a stack slot.
1224 LiveRegMap::iterator LRI
= findLiveVirtReg(Reg
);
1225 if (LRI
!= LiveVirtRegs
.end() && LRI
->PhysReg
) {
1226 setPhysReg(MI
, MO
, LRI
->PhysReg
);
1228 int SS
= StackSlotForVirtReg
[Reg
];
1230 // Modify DBG_VALUE now that the value is in a spill slot.
1231 updateDbgValueForSpill(MI
, SS
);
1232 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << MI
);
1236 // We can't allocate a physreg for a DebugValue, sorry!
1237 LLVM_DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
1241 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1242 // that future spills of Reg will have DBG_VALUEs.
1243 LiveDbgValueMap
[Reg
].push_back(&MI
);
1246 void RegAllocFast::allocateBasicBlock(MachineBasicBlock
&MBB
) {
1248 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB
);
1250 PhysRegState
.assign(TRI
->getNumRegs(), regDisabled
);
1251 assert(LiveVirtRegs
.empty() && "Mapping not cleared from last block?");
1253 MachineBasicBlock::iterator MII
= MBB
.begin();
1255 // Add live-in registers as live.
1256 for (const MachineBasicBlock::RegisterMaskPair LI
: MBB
.liveins())
1257 if (MRI
->isAllocatable(LI
.PhysReg
))
1258 definePhysReg(MII
, LI
.PhysReg
, regReserved
);
1263 // Otherwise, sequentially allocate each instruction in the MBB.
1264 for (MachineInstr
&MI
: MBB
) {
1266 dbgs() << "\n>> " << MI
<< "Regs:";
1270 // Special handling for debug values. Note that they are not allowed to
1271 // affect codegen of the other instructions in any way.
1272 if (MI
.isDebugValue()) {
1273 handleDebugValue(MI
);
1277 allocateInstruction(MI
);
1280 // Spill all physical registers holding virtual registers now.
1281 LLVM_DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1282 spillAll(MBB
.getFirstTerminator(), /*OnlyLiveOut*/ true);
1284 // Erase all the coalesced copies. We are delaying it until now because
1285 // LiveVirtRegs might refer to the instrs.
1286 for (MachineInstr
*MI
: Coalesced
)
1288 NumCoalesced
+= Coalesced
.size();
1290 LLVM_DEBUG(MBB
.dump());
1293 bool RegAllocFast::runOnMachineFunction(MachineFunction
&MF
) {
1294 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1295 << "********** Function: " << MF
.getName() << '\n');
1296 MRI
= &MF
.getRegInfo();
1297 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
1298 TRI
= STI
.getRegisterInfo();
1299 TII
= STI
.getInstrInfo();
1300 MFI
= &MF
.getFrameInfo();
1301 MRI
->freezeReservedRegs(MF
);
1302 RegClassInfo
.runOnMachineFunction(MF
);
1303 UsedInInstr
.clear();
1304 UsedInInstr
.setUniverse(TRI
->getNumRegUnits());
1306 // initialize the virtual->physical register map to have a 'null'
1307 // mapping for all virtual registers
1308 unsigned NumVirtRegs
= MRI
->getNumVirtRegs();
1309 StackSlotForVirtReg
.resize(NumVirtRegs
);
1310 LiveVirtRegs
.setUniverse(NumVirtRegs
);
1311 MayLiveAcrossBlocks
.clear();
1312 MayLiveAcrossBlocks
.resize(NumVirtRegs
);
1314 // Loop over all of the basic blocks, eliminating virtual register references
1315 for (MachineBasicBlock
&MBB
: MF
)
1316 allocateBasicBlock(MBB
);
1318 // All machine operands and other references to virtual registers have been
1319 // replaced. Remove the virtual registers.
1320 MRI
->clearVirtRegs();
1322 StackSlotForVirtReg
.clear();
1323 LiveDbgValueMap
.clear();
1327 FunctionPass
*llvm::createFastRegisterAllocator() {
1328 return new RegAllocFast();