1044eb2f6SDimitry Andric //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
2d7f7719eSRoman Divacky //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d7f7719eSRoman Divacky //
7d7f7719eSRoman Divacky //===----------------------------------------------------------------------===//
8d7f7719eSRoman Divacky //
9044eb2f6SDimitry Andric /// \file This register allocator allocates registers to a basic block at a
10044eb2f6SDimitry Andric /// time, attempting to keep values in registers and reusing registers as
11044eb2f6SDimitry Andric /// appropriate.
12d7f7719eSRoman Divacky //
13d7f7719eSRoman Divacky //===----------------------------------------------------------------------===//
14d7f7719eSRoman Divacky
15ac9a064cSDimitry Andric #include "llvm/CodeGen/RegAllocFast.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
17d7f7719eSRoman Divacky #include "llvm/ADT/DenseMap.h"
18d7f7719eSRoman Divacky #include "llvm/ADT/IndexedMap.h"
19c0981da4SDimitry Andric #include "llvm/ADT/MapVector.h"
20d7f7719eSRoman Divacky #include "llvm/ADT/SmallSet.h"
21d7f7719eSRoman Divacky #include "llvm/ADT/SmallVector.h"
2263faed5bSDimitry Andric #include "llvm/ADT/SparseSet.h"
23d7f7719eSRoman Divacky #include "llvm/ADT/Statistic.h"
24044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
254a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
274a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
284a16efa3SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
294a16efa3SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
30044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
314a16efa3SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
32344a3780SDimitry Andric #include "llvm/CodeGen/RegAllocCommon.h"
334a16efa3SDimitry Andric #include "llvm/CodeGen/RegAllocRegistry.h"
344a16efa3SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
35044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
36044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
37044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
39706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
40044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
41044eb2f6SDimitry Andric #include "llvm/Pass.h"
424a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
434a16efa3SDimitry Andric #include "llvm/Support/ErrorHandling.h"
44044eb2f6SDimitry Andric #include "llvm/Support/raw_ostream.h"
45044eb2f6SDimitry Andric #include <cassert>
46044eb2f6SDimitry Andric #include <tuple>
47044eb2f6SDimitry Andric #include <vector>
48044eb2f6SDimitry Andric
49d7f7719eSRoman Divacky using namespace llvm;
50d7f7719eSRoman Divacky
515ca98fd9SDimitry Andric #define DEBUG_TYPE "regalloc"
525ca98fd9SDimitry Andric
53d7f7719eSRoman Divacky STATISTIC(NumStores, "Number of stores added");
54d7f7719eSRoman Divacky STATISTIC(NumLoads, "Number of loads added");
55d8e91e46SDimitry Andric STATISTIC(NumCoalesced, "Number of copies coalesced");
56d7f7719eSRoman Divacky
57b60736ecSDimitry Andric // FIXME: Remove this switch when all testcases are fixed!
58b60736ecSDimitry Andric static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
59b60736ecSDimitry Andric cl::Hidden);
60b60736ecSDimitry Andric
61b1c73532SDimitry Andric static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
62b1c73532SDimitry Andric createFastRegisterAllocator);
63d7f7719eSRoman Divacky
64d7f7719eSRoman Divacky namespace {
65044eb2f6SDimitry Andric
6699aabd70SDimitry Andric /// Assign ascending index for instructions in machine basic block. The index
6799aabd70SDimitry Andric /// can be used to determine dominance between instructions in same MBB.
6899aabd70SDimitry Andric class InstrPosIndexes {
6999aabd70SDimitry Andric public:
unsetInitialized()7099aabd70SDimitry Andric void unsetInitialized() { IsInitialized = false; }
7199aabd70SDimitry Andric
init(const MachineBasicBlock & MBB)7299aabd70SDimitry Andric void init(const MachineBasicBlock &MBB) {
7399aabd70SDimitry Andric CurMBB = &MBB;
7499aabd70SDimitry Andric Instr2PosIndex.clear();
7599aabd70SDimitry Andric uint64_t LastIndex = 0;
7699aabd70SDimitry Andric for (const MachineInstr &MI : MBB) {
7799aabd70SDimitry Andric LastIndex += InstrDist;
7899aabd70SDimitry Andric Instr2PosIndex[&MI] = LastIndex;
7999aabd70SDimitry Andric }
8099aabd70SDimitry Andric }
8199aabd70SDimitry Andric
8299aabd70SDimitry Andric /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
8399aabd70SDimitry Andric /// index without affecting existing instruction's index. Return true if all
8499aabd70SDimitry Andric /// instructions index has been reassigned.
getIndex(const MachineInstr & MI,uint64_t & Index)8599aabd70SDimitry Andric bool getIndex(const MachineInstr &MI, uint64_t &Index) {
8699aabd70SDimitry Andric if (!IsInitialized) {
8799aabd70SDimitry Andric init(*MI.getParent());
8899aabd70SDimitry Andric IsInitialized = true;
8999aabd70SDimitry Andric Index = Instr2PosIndex.at(&MI);
9099aabd70SDimitry Andric return true;
9199aabd70SDimitry Andric }
9299aabd70SDimitry Andric
9399aabd70SDimitry Andric assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
9499aabd70SDimitry Andric auto It = Instr2PosIndex.find(&MI);
9599aabd70SDimitry Andric if (It != Instr2PosIndex.end()) {
9699aabd70SDimitry Andric Index = It->second;
9799aabd70SDimitry Andric return false;
9899aabd70SDimitry Andric }
9999aabd70SDimitry Andric
10099aabd70SDimitry Andric // Distance is the number of consecutive unassigned instructions including
10199aabd70SDimitry Andric // MI. Start is the first instruction of them. End is the next of last
10299aabd70SDimitry Andric // instruction of them.
10399aabd70SDimitry Andric // e.g.
10499aabd70SDimitry Andric // |Instruction| A | B | C | MI | D | E |
10599aabd70SDimitry Andric // | Index | 1024 | | | | | 2048 |
10699aabd70SDimitry Andric //
10799aabd70SDimitry Andric // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
10899aabd70SDimitry Andric // is E.
10999aabd70SDimitry Andric unsigned Distance = 1;
11099aabd70SDimitry Andric MachineBasicBlock::const_iterator Start = MI.getIterator(),
11199aabd70SDimitry Andric End = std::next(Start);
11299aabd70SDimitry Andric while (Start != CurMBB->begin() &&
11399aabd70SDimitry Andric !Instr2PosIndex.count(&*std::prev(Start))) {
11499aabd70SDimitry Andric --Start;
11599aabd70SDimitry Andric ++Distance;
11699aabd70SDimitry Andric }
11799aabd70SDimitry Andric while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
11899aabd70SDimitry Andric ++End;
11999aabd70SDimitry Andric ++Distance;
12099aabd70SDimitry Andric }
12199aabd70SDimitry Andric
12299aabd70SDimitry Andric // LastIndex is initialized to last used index prior to MI or zero.
12399aabd70SDimitry Andric // In previous example, LastIndex is 1024, EndIndex is 2048;
12499aabd70SDimitry Andric uint64_t LastIndex =
12599aabd70SDimitry Andric Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
12699aabd70SDimitry Andric uint64_t Step;
12799aabd70SDimitry Andric if (End == CurMBB->end())
12899aabd70SDimitry Andric Step = static_cast<uint64_t>(InstrDist);
12999aabd70SDimitry Andric else {
13099aabd70SDimitry Andric // No instruction uses index zero.
13199aabd70SDimitry Andric uint64_t EndIndex = Instr2PosIndex.at(&*End);
13299aabd70SDimitry Andric assert(EndIndex > LastIndex && "Index must be ascending order");
13399aabd70SDimitry Andric unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
13499aabd70SDimitry Andric // We want index gap between two adjacent MI is as same as possible. Given
13599aabd70SDimitry Andric // total A available indexes, D is number of consecutive unassigned
13699aabd70SDimitry Andric // instructions, S is the step.
13799aabd70SDimitry Andric // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
13899aabd70SDimitry Andric // There're S-1 available indexes between unassigned instruction and its
13999aabd70SDimitry Andric // predecessor. There're A-S*D available indexes between the last
14099aabd70SDimitry Andric // unassigned instruction and its successor.
14199aabd70SDimitry Andric // Ideally, we want
14299aabd70SDimitry Andric // S-1 = A-S*D
14399aabd70SDimitry Andric // then
14499aabd70SDimitry Andric // S = (A+1)/(D+1)
14599aabd70SDimitry Andric // An valid S must be integer greater than zero, so
14699aabd70SDimitry Andric // S <= (A+1)/(D+1)
14799aabd70SDimitry Andric // =>
14899aabd70SDimitry Andric // A-S*D >= 0
14999aabd70SDimitry Andric // That means we can safely use (A+1)/(D+1) as step.
15099aabd70SDimitry Andric // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
15199aabd70SDimitry Andric // 1636, 1840.
15299aabd70SDimitry Andric Step = (NumAvailableIndexes + 1) / (Distance + 1);
15399aabd70SDimitry Andric }
15499aabd70SDimitry Andric
15599aabd70SDimitry Andric // Reassign index for all instructions if number of new inserted
15699aabd70SDimitry Andric // instructions exceed slot or all instructions are new.
15799aabd70SDimitry Andric if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
15899aabd70SDimitry Andric init(*CurMBB);
15999aabd70SDimitry Andric Index = Instr2PosIndex.at(&MI);
16099aabd70SDimitry Andric return true;
16199aabd70SDimitry Andric }
16299aabd70SDimitry Andric
16399aabd70SDimitry Andric for (auto I = Start; I != End; ++I) {
16499aabd70SDimitry Andric LastIndex += Step;
16599aabd70SDimitry Andric Instr2PosIndex[&*I] = LastIndex;
16699aabd70SDimitry Andric }
16799aabd70SDimitry Andric Index = Instr2PosIndex.at(&MI);
16899aabd70SDimitry Andric return false;
16999aabd70SDimitry Andric }
17099aabd70SDimitry Andric
17199aabd70SDimitry Andric private:
17299aabd70SDimitry Andric bool IsInitialized = false;
17399aabd70SDimitry Andric enum { InstrDist = 1024 };
17499aabd70SDimitry Andric const MachineBasicBlock *CurMBB = nullptr;
17599aabd70SDimitry Andric DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
17699aabd70SDimitry Andric };
17799aabd70SDimitry Andric
178ac9a064cSDimitry Andric class RegAllocFastImpl {
179d7f7719eSRoman Divacky public:
RegAllocFastImpl(const RegAllocFilterFunc F=nullptr,bool ClearVirtRegs_=true)180ac9a064cSDimitry Andric RegAllocFastImpl(const RegAllocFilterFunc F = nullptr,
181b1c73532SDimitry Andric bool ClearVirtRegs_ = true)
182ac9a064cSDimitry Andric : ShouldAllocateRegisterImpl(F), StackSlotForVirtReg(-1),
183ac9a064cSDimitry Andric ClearVirtRegs(ClearVirtRegs_) {}
18401095a5dSDimitry Andric
185d7f7719eSRoman Divacky private:
1867fa27ce4SDimitry Andric MachineFrameInfo *MFI = nullptr;
1877fa27ce4SDimitry Andric MachineRegisterInfo *MRI = nullptr;
1887fa27ce4SDimitry Andric const TargetRegisterInfo *TRI = nullptr;
1897fa27ce4SDimitry Andric const TargetInstrInfo *TII = nullptr;
19056fe8f14SDimitry Andric RegisterClassInfo RegClassInfo;
191ac9a064cSDimitry Andric const RegAllocFilterFunc ShouldAllocateRegisterImpl;
192d7f7719eSRoman Divacky
193044eb2f6SDimitry Andric /// Basic block currently being allocated.
1947fa27ce4SDimitry Andric MachineBasicBlock *MBB = nullptr;
195abdf259dSRoman Divacky
196044eb2f6SDimitry Andric /// Maps virtual regs to the frame index where these values are spilled.
197d7f7719eSRoman Divacky IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
198d7f7719eSRoman Divacky
199044eb2f6SDimitry Andric /// Everything we know about a live virtual register.
200abdf259dSRoman Divacky struct LiveReg {
201044eb2f6SDimitry Andric MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
202706b4fc4SDimitry Andric Register VirtReg; ///< Virtual register number.
203044eb2f6SDimitry Andric MCPhysReg PhysReg = 0; ///< Currently held here.
204b60736ecSDimitry Andric bool LiveOut = false; ///< Register is possibly live out.
205b60736ecSDimitry Andric bool Reloaded = false; ///< Register was reloaded.
206b60736ecSDimitry Andric bool Error = false; ///< Could not allocate.
207abdf259dSRoman Divacky
LiveReg__anonaa58e9000111::RegAllocFastImpl::LiveReg208706b4fc4SDimitry Andric explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
20963faed5bSDimitry Andric
getSparseSetIndex__anonaa58e9000111::RegAllocFastImpl::LiveReg21058b69754SDimitry Andric unsigned getSparseSetIndex() const {
2111d5ae102SDimitry Andric return Register::virtReg2Index(VirtReg);
21263faed5bSDimitry Andric }
213abdf259dSRoman Divacky };
214abdf259dSRoman Divacky
2157fa27ce4SDimitry Andric using LiveRegMap = SparseSet<LiveReg, identity<unsigned>, uint16_t>;
216044eb2f6SDimitry Andric /// This map contains entries for each virtual register that is currently
217044eb2f6SDimitry Andric /// available in a physical register.
218abdf259dSRoman Divacky LiveRegMap LiveVirtRegs;
219d7f7719eSRoman Divacky
220b60736ecSDimitry Andric /// Stores assigned virtual registers present in the bundle MI.
221b60736ecSDimitry Andric DenseMap<Register, MCPhysReg> BundleVirtRegsMap;
222b60736ecSDimitry Andric
223344a3780SDimitry Andric DenseMap<unsigned, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
224b60736ecSDimitry Andric /// List of DBG_VALUE that we encountered without the vreg being assigned
225b60736ecSDimitry Andric /// because they were placed after the last use of the vreg.
226b60736ecSDimitry Andric DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
227d39c594dSDimitry Andric
228e6d15924SDimitry Andric /// Has a bit set for every virtual register for which it was determined
229e6d15924SDimitry Andric /// that it is alive across blocks.
230e6d15924SDimitry Andric BitVector MayLiveAcrossBlocks;
231e6d15924SDimitry Andric
232cfca06d7SDimitry Andric /// State of a register unit.
233cfca06d7SDimitry Andric enum RegUnitState {
234044eb2f6SDimitry Andric /// A free register is not currently in use and can be allocated
235044eb2f6SDimitry Andric /// immediately without checking aliases.
236abdf259dSRoman Divacky regFree,
237abdf259dSRoman Divacky
238b60736ecSDimitry Andric /// A pre-assigned register has been assigned before register allocation
239b60736ecSDimitry Andric /// (e.g., setting up a call parameter).
240b60736ecSDimitry Andric regPreAssigned,
241b60736ecSDimitry Andric
242b60736ecSDimitry Andric /// Used temporarily in reloadAtBegin() to mark register units that are
243b60736ecSDimitry Andric /// live-in to the basic block.
244b60736ecSDimitry Andric regLiveIn,
245abdf259dSRoman Divacky
246044eb2f6SDimitry Andric /// A register state may also be a virtual register number, indication
247044eb2f6SDimitry Andric /// that the physical register is currently allocated to a virtual
248044eb2f6SDimitry Andric /// register. In that case, LiveVirtRegs contains the inverse mapping.
249abdf259dSRoman Divacky };
250abdf259dSRoman Divacky
251cfca06d7SDimitry Andric /// Maps each physical register to a RegUnitState enum or virtual register.
252cfca06d7SDimitry Andric std::vector<unsigned> RegUnitStates;
253d7f7719eSRoman Divacky
254044eb2f6SDimitry Andric SmallVector<MachineInstr *, 32> Coalesced;
255522600a2SDimitry Andric
256ac9a064cSDimitry Andric /// Track register units that are used in the current instruction, and so
257044eb2f6SDimitry Andric /// cannot be allocated.
258ac9a064cSDimitry Andric ///
259ac9a064cSDimitry Andric /// In the first phase (tied defs/early clobber), we consider also physical
260ac9a064cSDimitry Andric /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
261ac9a064cSDimitry Andric /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
262ac9a064cSDimitry Andric /// avoid resetting the entire vector after every instruction, we track the
263ac9a064cSDimitry Andric /// instruction "generation" in the remaining 31 bits -- this means, that if
264ac9a064cSDimitry Andric /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
265ac9a064cSDimitry Andric /// never zero and always incremented by two.
266ac9a064cSDimitry Andric ///
267ac9a064cSDimitry Andric /// Don't allocate inline storage: the number of register units is typically
268ac9a064cSDimitry Andric /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
269ac9a064cSDimitry Andric uint32_t InstrGen;
270ac9a064cSDimitry Andric SmallVector<unsigned, 0> UsedInInstr;
271ac9a064cSDimitry Andric
272ac9a064cSDimitry Andric SmallVector<unsigned, 8> DefOperandIndexes;
273344a3780SDimitry Andric // Register masks attached to the current instruction.
274344a3780SDimitry Andric SmallVector<const uint32_t *> RegMasks;
275d8e91e46SDimitry Andric
27699aabd70SDimitry Andric // Assign index for each instruction to quickly determine dominance.
27799aabd70SDimitry Andric InstrPosIndexes PosIndexes;
27899aabd70SDimitry Andric
279d8e91e46SDimitry Andric void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
280b60736ecSDimitry Andric bool isPhysRegFree(MCPhysReg PhysReg) const;
281d7f7719eSRoman Divacky
282044eb2f6SDimitry Andric /// Mark a physreg as used in this instruction.
markRegUsedInInstr(MCPhysReg PhysReg)283044eb2f6SDimitry Andric void markRegUsedInInstr(MCPhysReg PhysReg) {
2847fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg))
285ac9a064cSDimitry Andric UsedInInstr[Unit] = InstrGen | 1;
2864a16efa3SDimitry Andric }
2874a16efa3SDimitry Andric
288344a3780SDimitry Andric // Check if physreg is clobbered by instruction's regmask(s).
isClobberedByRegMasks(MCPhysReg PhysReg) const289344a3780SDimitry Andric bool isClobberedByRegMasks(MCPhysReg PhysReg) const {
290344a3780SDimitry Andric return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
291344a3780SDimitry Andric return MachineOperand::clobbersPhysReg(Mask, PhysReg);
292344a3780SDimitry Andric });
293344a3780SDimitry Andric }
294344a3780SDimitry Andric
295044eb2f6SDimitry Andric /// Check if a physreg or any of its aliases are used in this instruction.
isRegUsedInInstr(MCPhysReg PhysReg,bool LookAtPhysRegUses) const296b60736ecSDimitry Andric bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
297344a3780SDimitry Andric if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
298344a3780SDimitry Andric return true;
299ac9a064cSDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg))
300ac9a064cSDimitry Andric if (UsedInInstr[Unit] >= (InstrGen | !LookAtPhysRegUses))
3014a16efa3SDimitry Andric return true;
3024a16efa3SDimitry Andric return false;
3034a16efa3SDimitry Andric }
3044a16efa3SDimitry Andric
305b60736ecSDimitry Andric /// Mark physical register as being used in a register use operand.
306b60736ecSDimitry Andric /// This is only used by the special livethrough handling code.
markPhysRegUsedInInstr(MCPhysReg PhysReg)307b60736ecSDimitry Andric void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
308ac9a064cSDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
309ac9a064cSDimitry Andric assert(UsedInInstr[Unit] <= InstrGen && "non-phys use before phys use?");
310ac9a064cSDimitry Andric UsedInInstr[Unit] = InstrGen;
311ac9a064cSDimitry Andric }
312b60736ecSDimitry Andric }
313b60736ecSDimitry Andric
314b60736ecSDimitry Andric /// Remove mark of physical register being used in the instruction.
unmarkRegUsedInInstr(MCPhysReg PhysReg)315b60736ecSDimitry Andric void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
3167fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg))
317ac9a064cSDimitry Andric UsedInInstr[Unit] = 0;
318b60736ecSDimitry Andric }
319b60736ecSDimitry Andric
3205ca98fd9SDimitry Andric enum : unsigned {
321d8e91e46SDimitry Andric spillClean = 50,
322abdf259dSRoman Divacky spillDirty = 100,
323e6d15924SDimitry Andric spillPrefBonus = 20,
324abdf259dSRoman Divacky spillImpossible = ~0u
325abdf259dSRoman Divacky };
326044eb2f6SDimitry Andric
327d7f7719eSRoman Divacky public:
328ac9a064cSDimitry Andric bool ClearVirtRegs;
329d7f7719eSRoman Divacky
330ac9a064cSDimitry Andric bool runOnMachineFunction(MachineFunction &MF);
331b60736ecSDimitry Andric
332d7f7719eSRoman Divacky private:
333044eb2f6SDimitry Andric void allocateBasicBlock(MachineBasicBlock &MBB);
334b60736ecSDimitry Andric
335ac9a064cSDimitry Andric void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
336b60736ecSDimitry Andric Register Reg) const;
337b60736ecSDimitry Andric
3387fa27ce4SDimitry Andric void findAndSortDefOperandIndexes(const MachineInstr &MI);
3397fa27ce4SDimitry Andric
340d8e91e46SDimitry Andric void allocateInstruction(MachineInstr &MI);
341d8e91e46SDimitry Andric void handleDebugValue(MachineInstr &MI);
342b60736ecSDimitry Andric void handleBundle(MachineInstr &MI);
343d7f7719eSRoman Divacky
344b60736ecSDimitry Andric bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
345b60736ecSDimitry Andric bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
346b60736ecSDimitry Andric bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
347b60736ecSDimitry Andric void freePhysReg(MCPhysReg PhysReg);
348cfca06d7SDimitry Andric
349044eb2f6SDimitry Andric unsigned calcSpillCost(MCPhysReg PhysReg) const;
350044eb2f6SDimitry Andric
findLiveVirtReg(Register VirtReg)351706b4fc4SDimitry Andric LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
3521d5ae102SDimitry Andric return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
35363faed5bSDimitry Andric }
354044eb2f6SDimitry Andric
findLiveVirtReg(Register VirtReg) const355706b4fc4SDimitry Andric LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
3561d5ae102SDimitry Andric return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
35763faed5bSDimitry Andric }
358044eb2f6SDimitry Andric
359b60736ecSDimitry Andric void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
360b60736ecSDimitry Andric void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
361b60736ecSDimitry Andric bool LookAtPhysRegUses = false);
362e6d15924SDimitry Andric void allocVirtRegUndef(MachineOperand &MO);
363b60736ecSDimitry Andric void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
364b60736ecSDimitry Andric MCPhysReg Reg);
3657fa27ce4SDimitry Andric bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
366b60736ecSDimitry Andric Register VirtReg);
3677fa27ce4SDimitry Andric bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
368b60736ecSDimitry Andric bool LookAtPhysRegUses = false);
369312c0ed1SDimitry Andric bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
370b60736ecSDimitry Andric
371b60736ecSDimitry Andric MachineBasicBlock::iterator
372b60736ecSDimitry Andric getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
373b60736ecSDimitry Andric SmallSet<Register, 2> &PrologLiveIns) const;
374b60736ecSDimitry Andric
375b60736ecSDimitry Andric void reloadAtBegin(MachineBasicBlock &MBB);
3767fa27ce4SDimitry Andric bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
377d8e91e46SDimitry Andric
378706b4fc4SDimitry Andric Register traceCopies(Register VirtReg) const;
379706b4fc4SDimitry Andric Register traceCopyChain(Register Reg) const;
380e6d15924SDimitry Andric
381e3b55780SDimitry Andric bool shouldAllocateRegister(const Register Reg) const;
382706b4fc4SDimitry Andric int getStackSpaceFor(Register VirtReg);
383706b4fc4SDimitry Andric void spill(MachineBasicBlock::iterator Before, Register VirtReg,
384b60736ecSDimitry Andric MCPhysReg AssignedReg, bool Kill, bool LiveOut);
385706b4fc4SDimitry Andric void reload(MachineBasicBlock::iterator Before, Register VirtReg,
386d8e91e46SDimitry Andric MCPhysReg PhysReg);
387044eb2f6SDimitry Andric
388706b4fc4SDimitry Andric bool mayLiveOut(Register VirtReg);
389706b4fc4SDimitry Andric bool mayLiveIn(Register VirtReg);
390e6d15924SDimitry Andric
391cfca06d7SDimitry Andric void dumpState() const;
392d7f7719eSRoman Divacky };
393d7f7719eSRoman Divacky
394ac9a064cSDimitry Andric class RegAllocFast : public MachineFunctionPass {
395ac9a064cSDimitry Andric RegAllocFastImpl Impl;
396ac9a064cSDimitry Andric
397ac9a064cSDimitry Andric public:
398ac9a064cSDimitry Andric static char ID;
399ac9a064cSDimitry Andric
RegAllocFast(const RegAllocFilterFunc F=nullptr,bool ClearVirtRegs_=true)400ac9a064cSDimitry Andric RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
401ac9a064cSDimitry Andric : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
402ac9a064cSDimitry Andric
runOnMachineFunction(MachineFunction & MF)403ac9a064cSDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override {
404ac9a064cSDimitry Andric return Impl.runOnMachineFunction(MF);
405ac9a064cSDimitry Andric }
406ac9a064cSDimitry Andric
getPassName() const407ac9a064cSDimitry Andric StringRef getPassName() const override { return "Fast Register Allocator"; }
408ac9a064cSDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const409ac9a064cSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
410ac9a064cSDimitry Andric AU.setPreservesCFG();
411ac9a064cSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
412ac9a064cSDimitry Andric }
413ac9a064cSDimitry Andric
getRequiredProperties() const414ac9a064cSDimitry Andric MachineFunctionProperties getRequiredProperties() const override {
415ac9a064cSDimitry Andric return MachineFunctionProperties().set(
416ac9a064cSDimitry Andric MachineFunctionProperties::Property::NoPHIs);
417ac9a064cSDimitry Andric }
418ac9a064cSDimitry Andric
getSetProperties() const419ac9a064cSDimitry Andric MachineFunctionProperties getSetProperties() const override {
420ac9a064cSDimitry Andric if (Impl.ClearVirtRegs) {
421ac9a064cSDimitry Andric return MachineFunctionProperties().set(
422ac9a064cSDimitry Andric MachineFunctionProperties::Property::NoVRegs);
423ac9a064cSDimitry Andric }
424ac9a064cSDimitry Andric
425ac9a064cSDimitry Andric return MachineFunctionProperties();
426ac9a064cSDimitry Andric }
427ac9a064cSDimitry Andric
getClearedProperties() const428ac9a064cSDimitry Andric MachineFunctionProperties getClearedProperties() const override {
429ac9a064cSDimitry Andric return MachineFunctionProperties().set(
430ac9a064cSDimitry Andric MachineFunctionProperties::Property::IsSSA);
431ac9a064cSDimitry Andric }
432ac9a064cSDimitry Andric };
433ac9a064cSDimitry Andric
434044eb2f6SDimitry Andric } // end anonymous namespace
435ca089b24SDimitry Andric
436044eb2f6SDimitry Andric char RegAllocFast::ID = 0;
437044eb2f6SDimitry Andric
438044eb2f6SDimitry Andric INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
439044eb2f6SDimitry Andric false)
440044eb2f6SDimitry Andric
shouldAllocateRegister(const Register Reg) const441ac9a064cSDimitry Andric bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
442e3b55780SDimitry Andric assert(Reg.isVirtual());
443ac9a064cSDimitry Andric if (!ShouldAllocateRegisterImpl)
444ac9a064cSDimitry Andric return true;
445ac9a064cSDimitry Andric
446ac9a064cSDimitry Andric return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
447e3b55780SDimitry Andric }
448e3b55780SDimitry Andric
setPhysRegState(MCPhysReg PhysReg,unsigned NewState)449ac9a064cSDimitry Andric void RegAllocFastImpl::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
4507fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg))
4517fa27ce4SDimitry Andric RegUnitStates[Unit] = NewState;
452d8e91e46SDimitry Andric }
453d8e91e46SDimitry Andric
isPhysRegFree(MCPhysReg PhysReg) const454ac9a064cSDimitry Andric bool RegAllocFastImpl::isPhysRegFree(MCPhysReg PhysReg) const {
4557fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
4567fa27ce4SDimitry Andric if (RegUnitStates[Unit] != regFree)
457b60736ecSDimitry Andric return false;
458b60736ecSDimitry Andric }
459b60736ecSDimitry Andric return true;
460b60736ecSDimitry Andric }
461b60736ecSDimitry Andric
462044eb2f6SDimitry Andric /// This allocates space for the specified virtual register to be held on the
463044eb2f6SDimitry Andric /// stack.
getStackSpaceFor(Register VirtReg)464ac9a064cSDimitry Andric int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
465d7f7719eSRoman Divacky // Find the location Reg would belong...
466d7f7719eSRoman Divacky int SS = StackSlotForVirtReg[VirtReg];
467044eb2f6SDimitry Andric // Already has space allocated?
468d7f7719eSRoman Divacky if (SS != -1)
469044eb2f6SDimitry Andric return SS;
470d7f7719eSRoman Divacky
471d7f7719eSRoman Divacky // Allocate a new stack object for this spill location...
472d8e91e46SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
473044eb2f6SDimitry Andric unsigned Size = TRI->getSpillSize(RC);
474cfca06d7SDimitry Andric Align Alignment = TRI->getSpillAlign(RC);
475cfca06d7SDimitry Andric int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
476d7f7719eSRoman Divacky
477d7f7719eSRoman Divacky // Assign the slot.
478d7f7719eSRoman Divacky StackSlotForVirtReg[VirtReg] = FrameIdx;
479d7f7719eSRoman Divacky return FrameIdx;
480d7f7719eSRoman Divacky }
481d7f7719eSRoman Divacky
dominates(InstrPosIndexes & PosIndexes,const MachineInstr & A,const MachineInstr & B)48299aabd70SDimitry Andric static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
48399aabd70SDimitry Andric const MachineInstr &B) {
48499aabd70SDimitry Andric uint64_t IndexA, IndexB;
48599aabd70SDimitry Andric PosIndexes.getIndex(A, IndexA);
48699aabd70SDimitry Andric if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
48799aabd70SDimitry Andric PosIndexes.getIndex(A, IndexA);
48899aabd70SDimitry Andric return IndexA < IndexB;
489b60736ecSDimitry Andric }
490b60736ecSDimitry Andric
491e6d15924SDimitry Andric /// Returns false if \p VirtReg is known to not live out of the current block.
mayLiveOut(Register VirtReg)492ac9a064cSDimitry Andric bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
4931d5ae102SDimitry Andric if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
494e6d15924SDimitry Andric // Cannot be live-out if there are no successors.
495e6d15924SDimitry Andric return !MBB->succ_empty();
496e6d15924SDimitry Andric }
497e6d15924SDimitry Andric
498b60736ecSDimitry Andric const MachineInstr *SelfLoopDef = nullptr;
499b60736ecSDimitry Andric
500b60736ecSDimitry Andric // If this block loops back to itself, it is necessary to check whether the
501b60736ecSDimitry Andric // use comes after the def.
502e6d15924SDimitry Andric if (MBB->isSuccessor(MBB)) {
503145449b1SDimitry Andric // Find the first def in the self loop MBB.
504145449b1SDimitry Andric for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
505145449b1SDimitry Andric if (DefInst.getParent() != MBB) {
506145449b1SDimitry Andric MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
507145449b1SDimitry Andric return true;
508145449b1SDimitry Andric } else {
50999aabd70SDimitry Andric if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
510145449b1SDimitry Andric SelfLoopDef = &DefInst;
511145449b1SDimitry Andric }
512145449b1SDimitry Andric }
513b60736ecSDimitry Andric if (!SelfLoopDef) {
5141d5ae102SDimitry Andric MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
515e6d15924SDimitry Andric return true;
516e6d15924SDimitry Andric }
517b60736ecSDimitry Andric }
518e6d15924SDimitry Andric
519e6d15924SDimitry Andric // See if the first \p Limit uses of the register are all in the current
520e6d15924SDimitry Andric // block.
521e6d15924SDimitry Andric static const unsigned Limit = 8;
522e6d15924SDimitry Andric unsigned C = 0;
523b60736ecSDimitry Andric for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
524e6d15924SDimitry Andric if (UseInst.getParent() != MBB || ++C >= Limit) {
5251d5ae102SDimitry Andric MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
526e6d15924SDimitry Andric // Cannot be live-out if there are no successors.
527e6d15924SDimitry Andric return !MBB->succ_empty();
528e6d15924SDimitry Andric }
529b60736ecSDimitry Andric
530b60736ecSDimitry Andric if (SelfLoopDef) {
531b60736ecSDimitry Andric // Try to handle some simple cases to avoid spilling and reloading every
532b60736ecSDimitry Andric // value inside a self looping block.
533b60736ecSDimitry Andric if (SelfLoopDef == &UseInst ||
53499aabd70SDimitry Andric !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
535b60736ecSDimitry Andric MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
536b60736ecSDimitry Andric return true;
537b60736ecSDimitry Andric }
538b60736ecSDimitry Andric }
539e6d15924SDimitry Andric }
540e6d15924SDimitry Andric
541e6d15924SDimitry Andric return false;
542e6d15924SDimitry Andric }
543e6d15924SDimitry Andric
544e6d15924SDimitry Andric /// Returns false if \p VirtReg is known to not be live into the current block.
mayLiveIn(Register VirtReg)545ac9a064cSDimitry Andric bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
5461d5ae102SDimitry Andric if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
547e6d15924SDimitry Andric return !MBB->pred_empty();
548e6d15924SDimitry Andric
549e6d15924SDimitry Andric // See if the first \p Limit def of the register are all in the current block.
550e6d15924SDimitry Andric static const unsigned Limit = 8;
551e6d15924SDimitry Andric unsigned C = 0;
552e6d15924SDimitry Andric for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
553e6d15924SDimitry Andric if (DefInst.getParent() != MBB || ++C >= Limit) {
5541d5ae102SDimitry Andric MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
555e6d15924SDimitry Andric return !MBB->pred_empty();
556e6d15924SDimitry Andric }
557e6d15924SDimitry Andric }
558e6d15924SDimitry Andric
559e6d15924SDimitry Andric return false;
560e6d15924SDimitry Andric }
561e6d15924SDimitry Andric
562d8e91e46SDimitry Andric /// Insert spill instruction for \p AssignedReg before \p Before. Update
563d8e91e46SDimitry Andric /// DBG_VALUEs with \p VirtReg operands with the stack slot.
spill(MachineBasicBlock::iterator Before,Register VirtReg,MCPhysReg AssignedReg,bool Kill,bool LiveOut)564ac9a064cSDimitry Andric void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
565ac9a064cSDimitry Andric Register VirtReg, MCPhysReg AssignedReg, bool Kill,
566ac9a064cSDimitry Andric bool LiveOut) {
567b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
568b1c73532SDimitry Andric << printReg(AssignedReg, TRI));
569d8e91e46SDimitry Andric int FI = getStackSpaceFor(VirtReg);
570d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
571d8e91e46SDimitry Andric
572d8e91e46SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
573e3b55780SDimitry Andric TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI,
574e3b55780SDimitry Andric VirtReg);
575d8e91e46SDimitry Andric ++NumStores;
576d8e91e46SDimitry Andric
577b60736ecSDimitry Andric MachineBasicBlock::iterator FirstTerm = MBB->getFirstTerminator();
578b60736ecSDimitry Andric
579b60736ecSDimitry Andric // When we spill a virtual register, we will have spill instructions behind
580b60736ecSDimitry Andric // every definition of it, meaning we can switch all the DBG_VALUEs over
581b60736ecSDimitry Andric // to just reference the stack slot.
582344a3780SDimitry Andric SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
583c0981da4SDimitry Andric SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
584344a3780SDimitry Andric SpilledOperandsMap;
585344a3780SDimitry Andric for (MachineOperand *MO : LRIDbgOperands)
586344a3780SDimitry Andric SpilledOperandsMap[MO->getParent()].push_back(MO);
587344a3780SDimitry Andric for (auto MISpilledOperands : SpilledOperandsMap) {
588344a3780SDimitry Andric MachineInstr &DBG = *MISpilledOperands.first;
589e3b55780SDimitry Andric // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
590e3b55780SDimitry Andric if (DBG.isDebugValueList())
591e3b55780SDimitry Andric continue;
592344a3780SDimitry Andric MachineInstr *NewDV = buildDbgValueForSpill(
593344a3780SDimitry Andric *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
594d8e91e46SDimitry Andric assert(NewDV->getParent() == MBB && "dangling parent pointer");
595d8e91e46SDimitry Andric (void)NewDV;
596d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
597b60736ecSDimitry Andric
598b60736ecSDimitry Andric if (LiveOut) {
599b60736ecSDimitry Andric // We need to insert a DBG_VALUE at the end of the block if the spill slot
600b60736ecSDimitry Andric // is live out, but there is another use of the value after the
601b60736ecSDimitry Andric // spill. This will allow LiveDebugValues to see the correct live out
602b60736ecSDimitry Andric // value to propagate to the successors.
603b60736ecSDimitry Andric MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
604b60736ecSDimitry Andric MBB->insert(FirstTerm, ClonedDV);
605b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
606b60736ecSDimitry Andric }
607b60736ecSDimitry Andric
608b60736ecSDimitry Andric // Rewrite unassigned dbg_values to use the stack slot.
609344a3780SDimitry Andric // TODO We can potentially do this for list debug values as well if we know
610344a3780SDimitry Andric // how the dbg_values are getting unassigned.
611344a3780SDimitry Andric if (DBG.isNonListDebugValue()) {
612344a3780SDimitry Andric MachineOperand &MO = DBG.getDebugOperand(0);
613344a3780SDimitry Andric if (MO.isReg() && MO.getReg() == 0) {
614344a3780SDimitry Andric updateDbgValueForSpill(DBG, FI, 0);
615344a3780SDimitry Andric }
616344a3780SDimitry Andric }
617d8e91e46SDimitry Andric }
618d8e91e46SDimitry Andric // Now this register is spilled there is should not be any DBG_VALUE
619d8e91e46SDimitry Andric // pointing to this register because they are all pointing to spilled value
620d8e91e46SDimitry Andric // now.
621344a3780SDimitry Andric LRIDbgOperands.clear();
622d8e91e46SDimitry Andric }
623d8e91e46SDimitry Andric
624d8e91e46SDimitry Andric /// Insert reload instruction for \p PhysReg before \p Before.
reload(MachineBasicBlock::iterator Before,Register VirtReg,MCPhysReg PhysReg)625ac9a064cSDimitry Andric void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
626ac9a064cSDimitry Andric Register VirtReg, MCPhysReg PhysReg) {
627d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
628d8e91e46SDimitry Andric << printReg(PhysReg, TRI) << '\n');
629d8e91e46SDimitry Andric int FI = getStackSpaceFor(VirtReg);
630d8e91e46SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
631e3b55780SDimitry Andric TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI, VirtReg);
632d8e91e46SDimitry Andric ++NumLoads;
633d8e91e46SDimitry Andric }
634d8e91e46SDimitry Andric
635b60736ecSDimitry Andric /// Get basic block begin insertion point.
636b60736ecSDimitry Andric /// This is not just MBB.begin() because surprisingly we have EH_LABEL
637b60736ecSDimitry Andric /// instructions marking the begin of a basic block. This means we must insert
638b60736ecSDimitry Andric /// new instructions after such labels...
getMBBBeginInsertionPoint(MachineBasicBlock & MBB,SmallSet<Register,2> & PrologLiveIns) const639ac9a064cSDimitry Andric MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
640b60736ecSDimitry Andric MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
641b60736ecSDimitry Andric MachineBasicBlock::iterator I = MBB.begin();
642b60736ecSDimitry Andric while (I != MBB.end()) {
643b60736ecSDimitry Andric if (I->isLabel()) {
644b60736ecSDimitry Andric ++I;
645b60736ecSDimitry Andric continue;
646d7f7719eSRoman Divacky }
647d7f7719eSRoman Divacky
648b60736ecSDimitry Andric // Most reloads should be inserted after prolog instructions.
649b60736ecSDimitry Andric if (!TII->isBasicBlockPrologue(*I))
650b60736ecSDimitry Andric break;
651b60736ecSDimitry Andric
652b60736ecSDimitry Andric // However if a prolog instruction reads a register that needs to be
653b60736ecSDimitry Andric // reloaded, the reload should be inserted before the prolog.
654b60736ecSDimitry Andric for (MachineOperand &MO : I->operands()) {
655b60736ecSDimitry Andric if (MO.isReg())
656b60736ecSDimitry Andric PrologLiveIns.insert(MO.getReg());
657abdf259dSRoman Divacky }
658d7f7719eSRoman Divacky
659b60736ecSDimitry Andric ++I;
660cfca06d7SDimitry Andric }
661cfca06d7SDimitry Andric
662b60736ecSDimitry Andric return I;
663abdf259dSRoman Divacky }
664d7f7719eSRoman Divacky
665b60736ecSDimitry Andric /// Reload all currently assigned virtual registers.
reloadAtBegin(MachineBasicBlock & MBB)666ac9a064cSDimitry Andric void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
667d8e91e46SDimitry Andric if (LiveVirtRegs.empty())
668d8e91e46SDimitry Andric return;
669b60736ecSDimitry Andric
670b60736ecSDimitry Andric for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
671b60736ecSDimitry Andric MCPhysReg Reg = P.PhysReg;
672b60736ecSDimitry Andric // Set state to live-in. This possibly overrides mappings to virtual
673b60736ecSDimitry Andric // registers but we don't care anymore at this point.
674b60736ecSDimitry Andric setPhysRegState(Reg, regLiveIn);
675b60736ecSDimitry Andric }
676b60736ecSDimitry Andric
677b60736ecSDimitry Andric SmallSet<Register, 2> PrologLiveIns;
678b60736ecSDimitry Andric
679abdf259dSRoman Divacky // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
680abdf259dSRoman Divacky // of spilling here is deterministic, if arbitrary.
681b1c73532SDimitry Andric MachineBasicBlock::iterator InsertBefore =
682b1c73532SDimitry Andric getMBBBeginInsertionPoint(MBB, PrologLiveIns);
683b60736ecSDimitry Andric for (const LiveReg &LR : LiveVirtRegs) {
684b60736ecSDimitry Andric MCPhysReg PhysReg = LR.PhysReg;
685b60736ecSDimitry Andric if (PhysReg == 0)
686d8e91e46SDimitry Andric continue;
687b60736ecSDimitry Andric
6887fa27ce4SDimitry Andric MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
689b60736ecSDimitry Andric if (RegUnitStates[FirstUnit] == regLiveIn)
690e6d15924SDimitry Andric continue;
691b60736ecSDimitry Andric
692b60736ecSDimitry Andric assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
693b60736ecSDimitry Andric "no reload in start block. Missing vreg def?");
694b60736ecSDimitry Andric
695b60736ecSDimitry Andric if (PrologLiveIns.count(PhysReg)) {
696b60736ecSDimitry Andric // FIXME: Theoretically this should use an insert point skipping labels
697b60736ecSDimitry Andric // but I'm not sure how labels should interact with prolog instruction
698b60736ecSDimitry Andric // that need reloads.
699b60736ecSDimitry Andric reload(MBB.begin(), LR.VirtReg, PhysReg);
700b60736ecSDimitry Andric } else
701b60736ecSDimitry Andric reload(InsertBefore, LR.VirtReg, PhysReg);
702d8e91e46SDimitry Andric }
703abdf259dSRoman Divacky LiveVirtRegs.clear();
704d7f7719eSRoman Divacky }
705d7f7719eSRoman Divacky
706044eb2f6SDimitry Andric /// Handle the direct use of a physical register. Check that the register is
707044eb2f6SDimitry Andric /// not used by a virtreg. Kill the physreg, marking it free. This may add
708044eb2f6SDimitry Andric /// implicit kills to MO->getParent() and invalidate MO.
usePhysReg(MachineInstr & MI,MCPhysReg Reg)709ac9a064cSDimitry Andric bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
710b60736ecSDimitry Andric assert(Register::isPhysicalRegister(Reg) && "expected physreg");
711b60736ecSDimitry Andric bool displacedAny = displacePhysReg(MI, Reg);
712b60736ecSDimitry Andric setPhysRegState(Reg, regPreAssigned);
713b60736ecSDimitry Andric markRegUsedInInstr(Reg);
714b60736ecSDimitry Andric return displacedAny;
715abdf259dSRoman Divacky }
716abdf259dSRoman Divacky
definePhysReg(MachineInstr & MI,MCPhysReg Reg)717ac9a064cSDimitry Andric bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
718b60736ecSDimitry Andric bool displacedAny = displacePhysReg(MI, Reg);
719b60736ecSDimitry Andric setPhysRegState(Reg, regPreAssigned);
720b60736ecSDimitry Andric return displacedAny;
721abdf259dSRoman Divacky }
722abdf259dSRoman Divacky
723044eb2f6SDimitry Andric /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
724044eb2f6SDimitry Andric /// similar to defineVirtReg except the physreg is reserved instead of
725044eb2f6SDimitry Andric /// allocated.
displacePhysReg(MachineInstr & MI,MCPhysReg PhysReg)726ac9a064cSDimitry Andric bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
727b60736ecSDimitry Andric bool displacedAny = false;
728b60736ecSDimitry Andric
7297fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
730b60736ecSDimitry Andric switch (unsigned VirtReg = RegUnitStates[Unit]) {
731b60736ecSDimitry Andric default: {
732b60736ecSDimitry Andric LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
733b60736ecSDimitry Andric assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
734b60736ecSDimitry Andric MachineBasicBlock::iterator ReloadBefore =
735b60736ecSDimitry Andric std::next((MachineBasicBlock::iterator)MI.getIterator());
736b60736ecSDimitry Andric reload(ReloadBefore, VirtReg, LRI->PhysReg);
737b60736ecSDimitry Andric
738b60736ecSDimitry Andric setPhysRegState(LRI->PhysReg, regFree);
739b60736ecSDimitry Andric LRI->PhysReg = 0;
740b60736ecSDimitry Andric LRI->Reloaded = true;
741b60736ecSDimitry Andric displacedAny = true;
742b60736ecSDimitry Andric break;
743b60736ecSDimitry Andric }
744b60736ecSDimitry Andric case regPreAssigned:
745b60736ecSDimitry Andric RegUnitStates[Unit] = regFree;
746b60736ecSDimitry Andric displacedAny = true;
747cfca06d7SDimitry Andric break;
748abdf259dSRoman Divacky case regFree:
749cfca06d7SDimitry Andric break;
750cfca06d7SDimitry Andric }
751d7f7719eSRoman Divacky }
752b60736ecSDimitry Andric return displacedAny;
753b60736ecSDimitry Andric }
754d7f7719eSRoman Divacky
freePhysReg(MCPhysReg PhysReg)755ac9a064cSDimitry Andric void RegAllocFastImpl::freePhysReg(MCPhysReg PhysReg) {
756b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
757b60736ecSDimitry Andric
7587fa27ce4SDimitry Andric MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
759b60736ecSDimitry Andric switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
760b60736ecSDimitry Andric case regFree:
761b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << '\n');
762b60736ecSDimitry Andric return;
763b60736ecSDimitry Andric case regPreAssigned:
764b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << '\n');
765b60736ecSDimitry Andric setPhysRegState(PhysReg, regFree);
766b60736ecSDimitry Andric return;
767b60736ecSDimitry Andric default: {
768b60736ecSDimitry Andric LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
769b60736ecSDimitry Andric assert(LRI != LiveVirtRegs.end());
770b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
771b60736ecSDimitry Andric setPhysRegState(LRI->PhysReg, regFree);
772b60736ecSDimitry Andric LRI->PhysReg = 0;
773b60736ecSDimitry Andric }
774b60736ecSDimitry Andric return;
775b60736ecSDimitry Andric }
776abdf259dSRoman Divacky }
777abdf259dSRoman Divacky
778d8e91e46SDimitry Andric /// Return the cost of spilling clearing out PhysReg and aliases so it is free
779d8e91e46SDimitry Andric /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
780d8e91e46SDimitry Andric /// disabled - it can be allocated directly.
781044eb2f6SDimitry Andric /// \returns spillImpossible when PhysReg or an alias can't be spilled.
calcSpillCost(MCPhysReg PhysReg) const782ac9a064cSDimitry Andric unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
7837fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
7847fa27ce4SDimitry Andric switch (unsigned VirtReg = RegUnitStates[Unit]) {
785abdf259dSRoman Divacky case regFree:
786cfca06d7SDimitry Andric break;
787b60736ecSDimitry Andric case regPreAssigned:
788b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
789b60736ecSDimitry Andric << printReg(PhysReg, TRI) << '\n');
790abdf259dSRoman Divacky return spillImpossible;
79163faed5bSDimitry Andric default: {
792b60736ecSDimitry Andric bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
793b60736ecSDimitry Andric findLiveVirtReg(VirtReg)->LiveOut;
794b60736ecSDimitry Andric return SureSpill ? spillClean : spillDirty;
79563faed5bSDimitry Andric }
796abdf259dSRoman Divacky }
797abdf259dSRoman Divacky }
798cfca06d7SDimitry Andric return 0;
799abdf259dSRoman Divacky }
800d7f7719eSRoman Divacky
assignDanglingDebugValues(MachineInstr & Definition,Register VirtReg,MCPhysReg Reg)801ac9a064cSDimitry Andric void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
802ac9a064cSDimitry Andric Register VirtReg,
803ac9a064cSDimitry Andric MCPhysReg Reg) {
804b60736ecSDimitry Andric auto UDBGValIter = DanglingDbgValues.find(VirtReg);
805b60736ecSDimitry Andric if (UDBGValIter == DanglingDbgValues.end())
806b60736ecSDimitry Andric return;
807b60736ecSDimitry Andric
808b60736ecSDimitry Andric SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
809b60736ecSDimitry Andric for (MachineInstr *DbgValue : Dangling) {
810b60736ecSDimitry Andric assert(DbgValue->isDebugValue());
811344a3780SDimitry Andric if (!DbgValue->hasDebugOperandForReg(VirtReg))
812b60736ecSDimitry Andric continue;
813b60736ecSDimitry Andric
814b60736ecSDimitry Andric // Test whether the physreg survives from the definition to the DBG_VALUE.
815b60736ecSDimitry Andric MCPhysReg SetToReg = Reg;
816b60736ecSDimitry Andric unsigned Limit = 20;
817b60736ecSDimitry Andric for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
818b1c73532SDimitry Andric E = DbgValue->getIterator();
819b1c73532SDimitry Andric I != E; ++I) {
820b60736ecSDimitry Andric if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
821b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
822b60736ecSDimitry Andric << '\n');
823b60736ecSDimitry Andric SetToReg = 0;
824b60736ecSDimitry Andric break;
825b60736ecSDimitry Andric }
826b60736ecSDimitry Andric }
827344a3780SDimitry Andric for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
828b60736ecSDimitry Andric MO.setReg(SetToReg);
829b60736ecSDimitry Andric if (SetToReg != 0)
830b60736ecSDimitry Andric MO.setIsRenamable();
831b60736ecSDimitry Andric }
832344a3780SDimitry Andric }
833b60736ecSDimitry Andric Dangling.clear();
834b60736ecSDimitry Andric }
835b60736ecSDimitry Andric
836eb11fae6SDimitry Andric /// This method updates local state so that we know that PhysReg is the
837044eb2f6SDimitry Andric /// proper container for VirtReg now. The physical register must not be used
838044eb2f6SDimitry Andric /// for anything else when this is called.
assignVirtToPhysReg(MachineInstr & AtMI,LiveReg & LR,MCPhysReg PhysReg)839ac9a064cSDimitry Andric void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
840b60736ecSDimitry Andric MCPhysReg PhysReg) {
841706b4fc4SDimitry Andric Register VirtReg = LR.VirtReg;
842d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
843d8e91e46SDimitry Andric << printReg(PhysReg, TRI) << '\n');
844d8e91e46SDimitry Andric assert(LR.PhysReg == 0 && "Already assigned a physreg");
845d8e91e46SDimitry Andric assert(PhysReg != 0 && "Trying to assign no register");
84663faed5bSDimitry Andric LR.PhysReg = PhysReg;
847d8e91e46SDimitry Andric setPhysRegState(PhysReg, VirtReg);
848b60736ecSDimitry Andric
849b60736ecSDimitry Andric assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
850d7f7719eSRoman Divacky }
851d7f7719eSRoman Divacky
isCoalescable(const MachineInstr & MI)852b1c73532SDimitry Andric static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
853e6d15924SDimitry Andric
traceCopyChain(Register Reg) const854ac9a064cSDimitry Andric Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
855e6d15924SDimitry Andric static const unsigned ChainLengthLimit = 3;
856e6d15924SDimitry Andric unsigned C = 0;
857e6d15924SDimitry Andric do {
858706b4fc4SDimitry Andric if (Reg.isPhysical())
859e6d15924SDimitry Andric return Reg;
860706b4fc4SDimitry Andric assert(Reg.isVirtual());
861e6d15924SDimitry Andric
862e6d15924SDimitry Andric MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
863e6d15924SDimitry Andric if (!VRegDef || !isCoalescable(*VRegDef))
864e6d15924SDimitry Andric return 0;
865e6d15924SDimitry Andric Reg = VRegDef->getOperand(1).getReg();
866e6d15924SDimitry Andric } while (++C <= ChainLengthLimit);
867e6d15924SDimitry Andric return 0;
868e6d15924SDimitry Andric }
869e6d15924SDimitry Andric
870e6d15924SDimitry Andric /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
871e6d15924SDimitry Andric /// chain of copies to check whether we reach a physical register we can
872e6d15924SDimitry Andric /// coalesce with.
traceCopies(Register VirtReg) const873ac9a064cSDimitry Andric Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
874e6d15924SDimitry Andric static const unsigned DefLimit = 3;
875e6d15924SDimitry Andric unsigned C = 0;
876e6d15924SDimitry Andric for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
877e6d15924SDimitry Andric if (isCoalescable(MI)) {
8781d5ae102SDimitry Andric Register Reg = MI.getOperand(1).getReg();
879e6d15924SDimitry Andric Reg = traceCopyChain(Reg);
880706b4fc4SDimitry Andric if (Reg.isValid())
881e6d15924SDimitry Andric return Reg;
882e6d15924SDimitry Andric }
883e6d15924SDimitry Andric
884e6d15924SDimitry Andric if (++C >= DefLimit)
885e6d15924SDimitry Andric break;
886e6d15924SDimitry Andric }
887706b4fc4SDimitry Andric return Register();
888e6d15924SDimitry Andric }
889e6d15924SDimitry Andric
890044eb2f6SDimitry Andric /// Allocates a physical register for VirtReg.
allocVirtReg(MachineInstr & MI,LiveReg & LR,Register Hint0,bool LookAtPhysRegUses)891ac9a064cSDimitry Andric void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
892ac9a064cSDimitry Andric Register Hint0, bool LookAtPhysRegUses) {
893706b4fc4SDimitry Andric const Register VirtReg = LR.VirtReg;
894b60736ecSDimitry Andric assert(LR.PhysReg == 0);
895d7f7719eSRoman Divacky
896044eb2f6SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
897d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
898e6d15924SDimitry Andric << " in class " << TRI->getRegClassName(&RC)
899e6d15924SDimitry Andric << " with hint " << printReg(Hint0, TRI) << '\n');
900d8e91e46SDimitry Andric
901d8e91e46SDimitry Andric // Take hint when possible.
902b60736ecSDimitry Andric if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
903b60736ecSDimitry Andric !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
904b60736ecSDimitry Andric // Take hint if the register is currently free.
905b60736ecSDimitry Andric if (isPhysRegFree(Hint0)) {
906e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
907e6d15924SDimitry Andric << '\n');
908b60736ecSDimitry Andric assignVirtToPhysReg(MI, LR, Hint0);
909d8e91e46SDimitry Andric return;
910e6d15924SDimitry Andric } else {
911b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
912e6d15924SDimitry Andric << " occupied\n");
913d7f7719eSRoman Divacky }
914e6d15924SDimitry Andric } else {
915706b4fc4SDimitry Andric Hint0 = Register();
916d7f7719eSRoman Divacky }
917d7f7719eSRoman Divacky
918e6d15924SDimitry Andric // Try other hint.
919706b4fc4SDimitry Andric Register Hint1 = traceCopies(VirtReg);
920b60736ecSDimitry Andric if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
921b60736ecSDimitry Andric !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
922b60736ecSDimitry Andric // Take hint if the register is currently free.
923b60736ecSDimitry Andric if (isPhysRegFree(Hint1)) {
924e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
925e6d15924SDimitry Andric << '\n');
926b60736ecSDimitry Andric assignVirtToPhysReg(MI, LR, Hint1);
927d8e91e46SDimitry Andric return;
928e6d15924SDimitry Andric } else {
929b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
930e6d15924SDimitry Andric << " occupied\n");
93163faed5bSDimitry Andric }
932e6d15924SDimitry Andric } else {
933706b4fc4SDimitry Andric Hint1 = Register();
934d7f7719eSRoman Divacky }
935d7f7719eSRoman Divacky
936d8e91e46SDimitry Andric MCPhysReg BestReg = 0;
937044eb2f6SDimitry Andric unsigned BestCost = spillImpossible;
938e6d15924SDimitry Andric ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
939d8e91e46SDimitry Andric for (MCPhysReg PhysReg : AllocationOrder) {
940d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
941b60736ecSDimitry Andric if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
942b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "already used in instr.\n");
943b60736ecSDimitry Andric continue;
944b60736ecSDimitry Andric }
945b60736ecSDimitry Andric
946044eb2f6SDimitry Andric unsigned Cost = calcSpillCost(PhysReg);
947d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
948d8e91e46SDimitry Andric // Immediate take a register with cost 0.
94963faed5bSDimitry Andric if (Cost == 0) {
950b60736ecSDimitry Andric assignVirtToPhysReg(MI, LR, PhysReg);
951d8e91e46SDimitry Andric return;
95263faed5bSDimitry Andric }
953e6d15924SDimitry Andric
954b60736ecSDimitry Andric if (PhysReg == Hint0 || PhysReg == Hint1)
955e6d15924SDimitry Andric Cost -= spillPrefBonus;
956e6d15924SDimitry Andric
957d8e91e46SDimitry Andric if (Cost < BestCost) {
958d8e91e46SDimitry Andric BestReg = PhysReg;
959d8e91e46SDimitry Andric BestCost = Cost;
960d8e91e46SDimitry Andric }
961abdf259dSRoman Divacky }
962abdf259dSRoman Divacky
963d8e91e46SDimitry Andric if (!BestReg) {
964d8e91e46SDimitry Andric // Nothing we can do: Report an error and keep going with an invalid
965d8e91e46SDimitry Andric // allocation.
96601095a5dSDimitry Andric if (MI.isInlineAsm())
96701095a5dSDimitry Andric MI.emitError("inline assembly requires more registers than available");
968f8af5cf6SDimitry Andric else
96901095a5dSDimitry Andric MI.emitError("ran out of registers during register allocation");
970b60736ecSDimitry Andric
971b60736ecSDimitry Andric LR.Error = true;
972b60736ecSDimitry Andric LR.PhysReg = 0;
973d8e91e46SDimitry Andric return;
974d8e91e46SDimitry Andric }
975d8e91e46SDimitry Andric
976b60736ecSDimitry Andric displacePhysReg(MI, BestReg);
977b60736ecSDimitry Andric assignVirtToPhysReg(MI, LR, BestReg);
978abdf259dSRoman Divacky }
979abdf259dSRoman Divacky
allocVirtRegUndef(MachineOperand & MO)980ac9a064cSDimitry Andric void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
981e6d15924SDimitry Andric assert(MO.isUndef() && "expected undef use");
9821d5ae102SDimitry Andric Register VirtReg = MO.getReg();
983e3b55780SDimitry Andric assert(VirtReg.isVirtual() && "Expected virtreg");
984e3b55780SDimitry Andric if (!shouldAllocateRegister(VirtReg))
985e3b55780SDimitry Andric return;
986e6d15924SDimitry Andric
987e6d15924SDimitry Andric LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
988e6d15924SDimitry Andric MCPhysReg PhysReg;
989e6d15924SDimitry Andric if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
990e6d15924SDimitry Andric PhysReg = LRI->PhysReg;
991e6d15924SDimitry Andric } else {
992e6d15924SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
993e6d15924SDimitry Andric ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
994e6d15924SDimitry Andric assert(!AllocationOrder.empty() && "Allocation order must not be empty");
995e6d15924SDimitry Andric PhysReg = AllocationOrder[0];
996e6d15924SDimitry Andric }
997e6d15924SDimitry Andric
998e6d15924SDimitry Andric unsigned SubRegIdx = MO.getSubReg();
999e6d15924SDimitry Andric if (SubRegIdx != 0) {
1000e6d15924SDimitry Andric PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1001e6d15924SDimitry Andric MO.setSubReg(0);
1002e6d15924SDimitry Andric }
1003e6d15924SDimitry Andric MO.setReg(PhysReg);
1004e6d15924SDimitry Andric MO.setIsRenamable(true);
1005e6d15924SDimitry Andric }
1006e6d15924SDimitry Andric
1007b60736ecSDimitry Andric /// Variation of defineVirtReg() with special handling for livethrough regs
1008b60736ecSDimitry Andric /// (tied or earlyclobber) that may interfere with preassigned uses.
10097fa27ce4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
defineLiveThroughVirtReg(MachineInstr & MI,unsigned OpNum,Register VirtReg)1010ac9a064cSDimitry Andric bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1011ac9a064cSDimitry Andric unsigned OpNum,
1012b60736ecSDimitry Andric Register VirtReg) {
1013e3b55780SDimitry Andric if (!shouldAllocateRegister(VirtReg))
10147fa27ce4SDimitry Andric return false;
1015b60736ecSDimitry Andric LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1016b60736ecSDimitry Andric if (LRI != LiveVirtRegs.end()) {
1017b60736ecSDimitry Andric MCPhysReg PrevReg = LRI->PhysReg;
1018b60736ecSDimitry Andric if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
1019b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1020b60736ecSDimitry Andric << " (tied/earlyclobber resolution)\n");
1021b60736ecSDimitry Andric freePhysReg(PrevReg);
1022b60736ecSDimitry Andric LRI->PhysReg = 0;
1023b60736ecSDimitry Andric allocVirtReg(MI, *LRI, 0, true);
1024b60736ecSDimitry Andric MachineBasicBlock::iterator InsertBefore =
1025b60736ecSDimitry Andric std::next((MachineBasicBlock::iterator)MI.getIterator());
1026b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1027b60736ecSDimitry Andric << printReg(PrevReg, TRI) << '\n');
1028b60736ecSDimitry Andric BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1029b60736ecSDimitry Andric TII->get(TargetOpcode::COPY), PrevReg)
1030b60736ecSDimitry Andric .addReg(LRI->PhysReg, llvm::RegState::Kill);
1031abdf259dSRoman Divacky }
1032b60736ecSDimitry Andric MachineOperand &MO = MI.getOperand(OpNum);
1033b60736ecSDimitry Andric if (MO.getSubReg() && !MO.isUndef()) {
103401095a5dSDimitry Andric LRI->LastUse = &MI;
1035b60736ecSDimitry Andric }
1036b60736ecSDimitry Andric }
1037b60736ecSDimitry Andric return defineVirtReg(MI, OpNum, VirtReg, true);
1038abdf259dSRoman Divacky }
1039abdf259dSRoman Divacky
1040b60736ecSDimitry Andric /// Allocates a register for VirtReg definition. Typically the register is
1041b60736ecSDimitry Andric /// already assigned from a use of the virtreg, however we still need to
1042b60736ecSDimitry Andric /// perform an allocation if:
1043b60736ecSDimitry Andric /// - It is a dead definition without any uses.
1044b60736ecSDimitry Andric /// - The value is live out and all uses are in different basic blocks.
10457fa27ce4SDimitry Andric ///
10467fa27ce4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
defineVirtReg(MachineInstr & MI,unsigned OpNum,Register VirtReg,bool LookAtPhysRegUses)1047ac9a064cSDimitry Andric bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1048b60736ecSDimitry Andric Register VirtReg, bool LookAtPhysRegUses) {
1049b60736ecSDimitry Andric assert(VirtReg.isVirtual() && "Not a virtual register");
1050e3b55780SDimitry Andric if (!shouldAllocateRegister(VirtReg))
10517fa27ce4SDimitry Andric return false;
1052b60736ecSDimitry Andric MachineOperand &MO = MI.getOperand(OpNum);
1053abdf259dSRoman Divacky LiveRegMap::iterator LRI;
1054abdf259dSRoman Divacky bool New;
10555ca98fd9SDimitry Andric std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1056b60736ecSDimitry Andric if (New) {
1057b60736ecSDimitry Andric if (!MO.isDead()) {
1058b60736ecSDimitry Andric if (mayLiveOut(VirtReg)) {
1059b60736ecSDimitry Andric LRI->LiveOut = true;
1060b60736ecSDimitry Andric } else {
1061b60736ecSDimitry Andric // It is a dead def without the dead flag; add the flag now.
1062b60736ecSDimitry Andric MO.setIsDead(true);
1063b60736ecSDimitry Andric }
1064b60736ecSDimitry Andric }
1065b60736ecSDimitry Andric }
1066b1c73532SDimitry Andric if (LRI->PhysReg == 0) {
1067b60736ecSDimitry Andric allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
1068b1c73532SDimitry Andric // If no physical register is available for LRI, we assign one at random
1069b1c73532SDimitry Andric // and bail out of this function immediately.
1070b1c73532SDimitry Andric if (LRI->Error) {
1071b1c73532SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1072b1c73532SDimitry Andric ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1073b1c73532SDimitry Andric if (AllocationOrder.empty())
1074b1c73532SDimitry Andric return setPhysReg(MI, MO, MCRegister::NoRegister);
1075b1c73532SDimitry Andric return setPhysReg(MI, MO, *AllocationOrder.begin());
1076b1c73532SDimitry Andric }
1077b1c73532SDimitry Andric } else {
1078b60736ecSDimitry Andric assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
1079b60736ecSDimitry Andric "TODO: preassign mismatch");
1080b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1081b60736ecSDimitry Andric << " use existing assignment to "
1082b60736ecSDimitry Andric << printReg(LRI->PhysReg, TRI) << '\n');
1083b60736ecSDimitry Andric }
1084b60736ecSDimitry Andric
1085b60736ecSDimitry Andric MCPhysReg PhysReg = LRI->PhysReg;
1086b60736ecSDimitry Andric if (LRI->Reloaded || LRI->LiveOut) {
1087b60736ecSDimitry Andric if (!MI.isImplicitDef()) {
1088b60736ecSDimitry Andric MachineBasicBlock::iterator SpillBefore =
1089b60736ecSDimitry Andric std::next((MachineBasicBlock::iterator)MI.getIterator());
1090b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1091b1c73532SDimitry Andric << " RL: " << LRI->Reloaded << '\n');
1092b60736ecSDimitry Andric bool Kill = LRI->LastUse == nullptr;
1093b60736ecSDimitry Andric spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
10947fa27ce4SDimitry Andric
10957fa27ce4SDimitry Andric // We need to place additional spills for each indirect destination of an
10967fa27ce4SDimitry Andric // INLINEASM_BR.
10977fa27ce4SDimitry Andric if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
10987fa27ce4SDimitry Andric int FI = StackSlotForVirtReg[VirtReg];
10997fa27ce4SDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
11007fa27ce4SDimitry Andric for (MachineOperand &MO : MI.operands()) {
11017fa27ce4SDimitry Andric if (MO.isMBB()) {
11027fa27ce4SDimitry Andric MachineBasicBlock *Succ = MO.getMBB();
1103b1c73532SDimitry Andric TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1104b1c73532SDimitry Andric &RC, TRI, VirtReg);
11057fa27ce4SDimitry Andric ++NumStores;
11067fa27ce4SDimitry Andric Succ->addLiveIn(PhysReg);
11077fa27ce4SDimitry Andric }
11087fa27ce4SDimitry Andric }
11097fa27ce4SDimitry Andric }
11107fa27ce4SDimitry Andric
1111b60736ecSDimitry Andric LRI->LastUse = nullptr;
1112b60736ecSDimitry Andric }
1113b60736ecSDimitry Andric LRI->LiveOut = false;
1114b60736ecSDimitry Andric LRI->Reloaded = false;
1115b60736ecSDimitry Andric }
1116b60736ecSDimitry Andric if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1117b60736ecSDimitry Andric BundleVirtRegsMap[VirtReg] = PhysReg;
1118b60736ecSDimitry Andric }
1119b60736ecSDimitry Andric markRegUsedInInstr(PhysReg);
11207fa27ce4SDimitry Andric return setPhysReg(MI, MO, PhysReg);
1121b60736ecSDimitry Andric }
1122b60736ecSDimitry Andric
1123b60736ecSDimitry Andric /// Allocates a register for a VirtReg use.
11247fa27ce4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
useVirtReg(MachineInstr & MI,MachineOperand & MO,Register VirtReg)1125ac9a064cSDimitry Andric bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1126b60736ecSDimitry Andric Register VirtReg) {
1127b60736ecSDimitry Andric assert(VirtReg.isVirtual() && "Not a virtual register");
1128e3b55780SDimitry Andric if (!shouldAllocateRegister(VirtReg))
11297fa27ce4SDimitry Andric return false;
1130b60736ecSDimitry Andric LiveRegMap::iterator LRI;
1131b60736ecSDimitry Andric bool New;
1132b60736ecSDimitry Andric std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1133b60736ecSDimitry Andric if (New) {
1134b60736ecSDimitry Andric if (!MO.isKill()) {
1135b60736ecSDimitry Andric if (mayLiveOut(VirtReg)) {
1136b60736ecSDimitry Andric LRI->LiveOut = true;
1137b60736ecSDimitry Andric } else {
1138b60736ecSDimitry Andric // It is a last (killing) use without the kill flag; add the flag now.
1139b60736ecSDimitry Andric MO.setIsKill(true);
1140d7f7719eSRoman Divacky }
1141d7f7719eSRoman Divacky }
1142b60736ecSDimitry Andric } else {
1143b60736ecSDimitry Andric assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1144b60736ecSDimitry Andric }
1145b60736ecSDimitry Andric
1146b60736ecSDimitry Andric // If necessary allocate a register.
1147b60736ecSDimitry Andric if (LRI->PhysReg == 0) {
1148b60736ecSDimitry Andric assert(!MO.isTied() && "tied op should be allocated");
1149b60736ecSDimitry Andric Register Hint;
1150b60736ecSDimitry Andric if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1151b60736ecSDimitry Andric Hint = MI.getOperand(0).getReg();
1152e3b55780SDimitry Andric if (Hint.isVirtual()) {
1153e3b55780SDimitry Andric assert(!shouldAllocateRegister(Hint));
1154e3b55780SDimitry Andric Hint = Register();
1155e3b55780SDimitry Andric } else {
1156b60736ecSDimitry Andric assert(Hint.isPhysical() &&
1157b60736ecSDimitry Andric "Copy destination should already be assigned");
1158b60736ecSDimitry Andric }
1159e3b55780SDimitry Andric }
1160b60736ecSDimitry Andric allocVirtReg(MI, *LRI, Hint, false);
1161b60736ecSDimitry Andric if (LRI->Error) {
1162b60736ecSDimitry Andric const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1163b60736ecSDimitry Andric ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1164b1c73532SDimitry Andric if (AllocationOrder.empty())
1165b1c73532SDimitry Andric return setPhysReg(MI, MO, MCRegister::NoRegister);
11667fa27ce4SDimitry Andric return setPhysReg(MI, MO, *AllocationOrder.begin());
1167b60736ecSDimitry Andric }
1168b60736ecSDimitry Andric }
1169b60736ecSDimitry Andric
117001095a5dSDimitry Andric LRI->LastUse = &MI;
1171b60736ecSDimitry Andric
1172b60736ecSDimitry Andric if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1173b60736ecSDimitry Andric BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
1174b60736ecSDimitry Andric }
11754a16efa3SDimitry Andric markRegUsedInInstr(LRI->PhysReg);
11767fa27ce4SDimitry Andric return setPhysReg(MI, MO, LRI->PhysReg);
1177d7f7719eSRoman Divacky }
1178d7f7719eSRoman Divacky
11797fa27ce4SDimitry Andric /// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
11807fa27ce4SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
setPhysReg(MachineInstr & MI,MachineOperand & MO,MCPhysReg PhysReg)1181ac9a064cSDimitry Andric bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1182044eb2f6SDimitry Andric MCPhysReg PhysReg) {
1183abdf259dSRoman Divacky if (!MO.getSubReg()) {
1184abdf259dSRoman Divacky MO.setReg(PhysReg);
1185eb11fae6SDimitry Andric MO.setIsRenamable(true);
11867fa27ce4SDimitry Andric return false;
1187d7f7719eSRoman Divacky }
1188d7f7719eSRoman Divacky
1189abdf259dSRoman Divacky // Handle subregister index.
1190b60736ecSDimitry Andric MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
1191eb11fae6SDimitry Andric MO.setIsRenamable(true);
1192b60736ecSDimitry Andric // Note: We leave the subreg number around a little longer in case of defs.
1193b60736ecSDimitry Andric // This is so that the register freeing logic in allocateInstruction can still
1194b60736ecSDimitry Andric // recognize this as subregister defs. The code there will clear the number.
1195b60736ecSDimitry Andric if (!MO.isDef())
1196abdf259dSRoman Divacky MO.setSubReg(0);
1197abdf259dSRoman Divacky
1198abdf259dSRoman Divacky // A kill flag implies killing the full register. Add corresponding super
1199abdf259dSRoman Divacky // register kill.
1200abdf259dSRoman Divacky if (MO.isKill()) {
1201044eb2f6SDimitry Andric MI.addRegisterKilled(PhysReg, TRI, true);
12027fa27ce4SDimitry Andric // Conservatively assume implicit MOs were re-arranged
12037fa27ce4SDimitry Andric return true;
1204d7f7719eSRoman Divacky }
120558b69754SDimitry Andric
120658b69754SDimitry Andric // A <def,read-undef> of a sub-register requires an implicit def of the full
120758b69754SDimitry Andric // register.
1208b60736ecSDimitry Andric if (MO.isDef() && MO.isUndef()) {
1209b60736ecSDimitry Andric if (MO.isDead())
1210b60736ecSDimitry Andric MI.addRegisterDead(PhysReg, TRI, true);
1211b60736ecSDimitry Andric else
1212044eb2f6SDimitry Andric MI.addRegisterDefined(PhysReg, TRI);
12137fa27ce4SDimitry Andric // Conservatively assume implicit MOs were re-arranged
12147fa27ce4SDimitry Andric return true;
1215d7f7719eSRoman Divacky }
12167fa27ce4SDimitry Andric return false;
121763faed5bSDimitry Andric }
121863faed5bSDimitry Andric
1219044eb2f6SDimitry Andric #ifndef NDEBUG
1220cfca06d7SDimitry Andric
dumpState() const1221ac9a064cSDimitry Andric void RegAllocFastImpl::dumpState() const {
1222cfca06d7SDimitry Andric for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
1223cfca06d7SDimitry Andric ++Unit) {
1224cfca06d7SDimitry Andric switch (unsigned VirtReg = RegUnitStates[Unit]) {
1225abdf259dSRoman Divacky case regFree:
1226abdf259dSRoman Divacky break;
1227b60736ecSDimitry Andric case regPreAssigned:
1228cfca06d7SDimitry Andric dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1229abdf259dSRoman Divacky break;
1230b60736ecSDimitry Andric case regLiveIn:
1231b60736ecSDimitry Andric llvm_unreachable("Should not have regLiveIn in map");
123263faed5bSDimitry Andric default: {
1233cfca06d7SDimitry Andric dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1234cfca06d7SDimitry Andric LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1235cfca06d7SDimitry Andric assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1236b60736ecSDimitry Andric if (I->LiveOut || I->Reloaded) {
1237b60736ecSDimitry Andric dbgs() << '[';
1238b1c73532SDimitry Andric if (I->LiveOut)
1239b1c73532SDimitry Andric dbgs() << 'O';
1240b1c73532SDimitry Andric if (I->Reloaded)
1241b1c73532SDimitry Andric dbgs() << 'R';
1242b60736ecSDimitry Andric dbgs() << ']';
1243b60736ecSDimitry Andric }
1244cfca06d7SDimitry Andric assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1245abdf259dSRoman Divacky break;
1246abdf259dSRoman Divacky }
1247abdf259dSRoman Divacky }
124863faed5bSDimitry Andric }
1249d7f7719eSRoman Divacky dbgs() << '\n';
1250abdf259dSRoman Divacky // Check that LiveVirtRegs is the inverse.
1251cfca06d7SDimitry Andric for (const LiveReg &LR : LiveVirtRegs) {
1252cfca06d7SDimitry Andric Register VirtReg = LR.VirtReg;
1253cfca06d7SDimitry Andric assert(VirtReg.isVirtual() && "Bad map key");
1254cfca06d7SDimitry Andric MCPhysReg PhysReg = LR.PhysReg;
1255cfca06d7SDimitry Andric if (PhysReg != 0) {
1256b1c73532SDimitry Andric assert(Register::isPhysicalRegister(PhysReg) && "mapped to physreg");
12577fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
12587fa27ce4SDimitry Andric assert(RegUnitStates[Unit] == VirtReg && "inverse map valid");
1259cfca06d7SDimitry Andric }
1260cfca06d7SDimitry Andric }
1261abdf259dSRoman Divacky }
1262044eb2f6SDimitry Andric }
1263044eb2f6SDimitry Andric #endif
1264044eb2f6SDimitry Andric
1265b60736ecSDimitry Andric /// Count number of defs consumed from each register class by \p Reg
addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,Register Reg) const1266ac9a064cSDimitry Andric void RegAllocFastImpl::addRegClassDefCounts(
1267ac9a064cSDimitry Andric MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1268b60736ecSDimitry Andric assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1269b60736ecSDimitry Andric
1270b60736ecSDimitry Andric if (Reg.isVirtual()) {
1271e3b55780SDimitry Andric if (!shouldAllocateRegister(Reg))
1272e3b55780SDimitry Andric return;
1273b60736ecSDimitry Andric const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1274b60736ecSDimitry Andric for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1275b60736ecSDimitry Andric RCIdx != RCIdxEnd; ++RCIdx) {
1276b60736ecSDimitry Andric const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1277b60736ecSDimitry Andric // FIXME: Consider aliasing sub/super registers.
1278b60736ecSDimitry Andric if (OpRC->hasSubClassEq(IdxRC))
1279b60736ecSDimitry Andric ++RegClassDefCounts[RCIdx];
1280b60736ecSDimitry Andric }
1281b60736ecSDimitry Andric
1282b60736ecSDimitry Andric return;
1283b60736ecSDimitry Andric }
1284b60736ecSDimitry Andric
1285b60736ecSDimitry Andric for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1286b60736ecSDimitry Andric RCIdx != RCIdxEnd; ++RCIdx) {
1287b60736ecSDimitry Andric const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1288b60736ecSDimitry Andric for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1289b60736ecSDimitry Andric if (IdxRC->contains(*Alias)) {
1290b60736ecSDimitry Andric ++RegClassDefCounts[RCIdx];
1291b60736ecSDimitry Andric break;
1292b60736ecSDimitry Andric }
1293b60736ecSDimitry Andric }
1294b60736ecSDimitry Andric }
1295b60736ecSDimitry Andric }
1296b60736ecSDimitry Andric
12977fa27ce4SDimitry Andric /// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
12987fa27ce4SDimitry Andric /// that are to be allocated. Those are ordered in a way that small classes,
12997fa27ce4SDimitry Andric /// early clobbers and livethroughs are allocated first.
findAndSortDefOperandIndexes(const MachineInstr & MI)1300ac9a064cSDimitry Andric void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
13017fa27ce4SDimitry Andric DefOperandIndexes.clear();
13027fa27ce4SDimitry Andric
13037fa27ce4SDimitry Andric LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
13047fa27ce4SDimitry Andric for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
13057fa27ce4SDimitry Andric const MachineOperand &MO = MI.getOperand(I);
13067fa27ce4SDimitry Andric if (!MO.isReg())
13077fa27ce4SDimitry Andric continue;
13087fa27ce4SDimitry Andric Register Reg = MO.getReg();
13097fa27ce4SDimitry Andric if (MO.readsReg()) {
13107fa27ce4SDimitry Andric if (Reg.isPhysical()) {
13117fa27ce4SDimitry Andric LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
13127fa27ce4SDimitry Andric markPhysRegUsedInInstr(Reg);
13137fa27ce4SDimitry Andric }
13147fa27ce4SDimitry Andric }
13157fa27ce4SDimitry Andric
1316ac9a064cSDimitry Andric if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
13177fa27ce4SDimitry Andric DefOperandIndexes.push_back(I);
13187fa27ce4SDimitry Andric }
13197fa27ce4SDimitry Andric
1320ac9a064cSDimitry Andric // Most instructions only have one virtual def, so there's no point in
1321ac9a064cSDimitry Andric // computing the possible number of defs for every register class.
1322ac9a064cSDimitry Andric if (DefOperandIndexes.size() <= 1)
1323ac9a064cSDimitry Andric return;
1324ac9a064cSDimitry Andric
1325ac9a064cSDimitry Andric // Track number of defs which may consume a register from the class. This is
1326ac9a064cSDimitry Andric // used to assign registers for possibly-too-small classes first. Example:
1327ac9a064cSDimitry Andric // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1328ac9a064cSDimitry Andric // registers first so that the gr32 don't use the gr32_abcd registers before
1329ac9a064cSDimitry Andric // we assign these.
1330ac9a064cSDimitry Andric SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1331ac9a064cSDimitry Andric
1332ac9a064cSDimitry Andric for (const MachineOperand &MO : MI.operands())
1333ac9a064cSDimitry Andric if (MO.isReg() && MO.isDef())
1334ac9a064cSDimitry Andric addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1335ac9a064cSDimitry Andric
1336ac9a064cSDimitry Andric llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
13377fa27ce4SDimitry Andric const MachineOperand &MO0 = MI.getOperand(I0);
13387fa27ce4SDimitry Andric const MachineOperand &MO1 = MI.getOperand(I1);
13397fa27ce4SDimitry Andric Register Reg0 = MO0.getReg();
13407fa27ce4SDimitry Andric Register Reg1 = MO1.getReg();
13417fa27ce4SDimitry Andric const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
13427fa27ce4SDimitry Andric const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
13437fa27ce4SDimitry Andric
13447fa27ce4SDimitry Andric // Identify regclass that are easy to use up completely just in this
13457fa27ce4SDimitry Andric // instruction.
13467fa27ce4SDimitry Andric unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
13477fa27ce4SDimitry Andric unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
13487fa27ce4SDimitry Andric
13497fa27ce4SDimitry Andric bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
13507fa27ce4SDimitry Andric bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
13517fa27ce4SDimitry Andric if (SmallClass0 > SmallClass1)
13527fa27ce4SDimitry Andric return true;
13537fa27ce4SDimitry Andric if (SmallClass0 < SmallClass1)
13547fa27ce4SDimitry Andric return false;
13557fa27ce4SDimitry Andric
13567fa27ce4SDimitry Andric // Allocate early clobbers and livethrough operands first.
13577fa27ce4SDimitry Andric bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
13587fa27ce4SDimitry Andric (MO0.getSubReg() == 0 && !MO0.isUndef());
13597fa27ce4SDimitry Andric bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
13607fa27ce4SDimitry Andric (MO1.getSubReg() == 0 && !MO1.isUndef());
13617fa27ce4SDimitry Andric if (Livethrough0 > Livethrough1)
13627fa27ce4SDimitry Andric return true;
13637fa27ce4SDimitry Andric if (Livethrough0 < Livethrough1)
13647fa27ce4SDimitry Andric return false;
13657fa27ce4SDimitry Andric
13667fa27ce4SDimitry Andric // Tie-break rule: operand index.
13677fa27ce4SDimitry Andric return I0 < I1;
13687fa27ce4SDimitry Andric });
13697fa27ce4SDimitry Andric }
13707fa27ce4SDimitry Andric
1371312c0ed1SDimitry Andric // Returns true if MO is tied and the operand it's tied to is not Undef (not
1372312c0ed1SDimitry Andric // Undef is not the same thing as Def).
isTiedToNotUndef(const MachineOperand & MO)1373312c0ed1SDimitry Andric static bool isTiedToNotUndef(const MachineOperand &MO) {
1374312c0ed1SDimitry Andric if (!MO.isTied())
1375312c0ed1SDimitry Andric return false;
1376312c0ed1SDimitry Andric const MachineInstr &MI = *MO.getParent();
1377312c0ed1SDimitry Andric unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
1378312c0ed1SDimitry Andric const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
1379312c0ed1SDimitry Andric return !TiedMO.isUndef();
1380312c0ed1SDimitry Andric }
1381312c0ed1SDimitry Andric
allocateInstruction(MachineInstr & MI)1382ac9a064cSDimitry Andric void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1383b60736ecSDimitry Andric // The basic algorithm here is:
1384b60736ecSDimitry Andric // 1. Mark registers of def operands as free
1385b60736ecSDimitry Andric // 2. Allocate registers to use operands and place reload instructions for
1386b60736ecSDimitry Andric // registers displaced by the allocation.
1387b60736ecSDimitry Andric //
1388b60736ecSDimitry Andric // However we need to handle some corner cases:
1389b60736ecSDimitry Andric // - pre-assigned defs and uses need to be handled before the other def/use
1390b60736ecSDimitry Andric // operands are processed to avoid the allocation heuristics clashing with
1391b60736ecSDimitry Andric // the pre-assignment.
1392b60736ecSDimitry Andric // - The "free def operands" step has to come last instead of first for tied
1393b60736ecSDimitry Andric // operands and early-clobbers.
1394eb11fae6SDimitry Andric
1395ac9a064cSDimitry Andric InstrGen += 2;
1396ac9a064cSDimitry Andric // In the event we ever get more than 2**31 instructions...
1397ac9a064cSDimitry Andric if (LLVM_UNLIKELY(InstrGen == 0)) {
1398ac9a064cSDimitry Andric UsedInInstr.assign(UsedInInstr.size(), 0);
1399ac9a064cSDimitry Andric InstrGen = 2;
1400ac9a064cSDimitry Andric }
1401344a3780SDimitry Andric RegMasks.clear();
1402b60736ecSDimitry Andric BundleVirtRegsMap.clear();
1403d7f7719eSRoman Divacky
1404b60736ecSDimitry Andric // Scan for special cases; Apply pre-assigned register defs to state.
1405b60736ecSDimitry Andric bool HasPhysRegUse = false;
1406b60736ecSDimitry Andric bool HasRegMask = false;
1407b60736ecSDimitry Andric bool HasVRegDef = false;
1408b60736ecSDimitry Andric bool HasDef = false;
1409b60736ecSDimitry Andric bool HasEarlyClobber = false;
1410b60736ecSDimitry Andric bool NeedToAssignLiveThroughs = false;
1411312c0ed1SDimitry Andric for (MachineOperand &MO : MI.operands()) {
1412b60736ecSDimitry Andric if (MO.isReg()) {
14131d5ae102SDimitry Andric Register Reg = MO.getReg();
1414b60736ecSDimitry Andric if (Reg.isVirtual()) {
1415e3b55780SDimitry Andric if (!shouldAllocateRegister(Reg))
1416e3b55780SDimitry Andric continue;
1417b60736ecSDimitry Andric if (MO.isDef()) {
1418b60736ecSDimitry Andric HasDef = true;
1419b60736ecSDimitry Andric HasVRegDef = true;
1420b60736ecSDimitry Andric if (MO.isEarlyClobber()) {
1421b60736ecSDimitry Andric HasEarlyClobber = true;
1422b60736ecSDimitry Andric NeedToAssignLiveThroughs = true;
142366e41e3cSRoman Divacky }
1424312c0ed1SDimitry Andric if (isTiedToNotUndef(MO) || (MO.getSubReg() != 0 && !MO.isUndef()))
1425b60736ecSDimitry Andric NeedToAssignLiveThroughs = true;
1426b60736ecSDimitry Andric }
1427b60736ecSDimitry Andric } else if (Reg.isPhysical()) {
1428b60736ecSDimitry Andric if (!MRI->isReserved(Reg)) {
1429b60736ecSDimitry Andric if (MO.isDef()) {
1430b60736ecSDimitry Andric HasDef = true;
1431b60736ecSDimitry Andric bool displacedAny = definePhysReg(MI, Reg);
1432b60736ecSDimitry Andric if (MO.isEarlyClobber())
1433b60736ecSDimitry Andric HasEarlyClobber = true;
1434b60736ecSDimitry Andric if (!displacedAny)
1435b60736ecSDimitry Andric MO.setIsDead(true);
1436b60736ecSDimitry Andric }
1437b60736ecSDimitry Andric if (MO.readsReg())
1438b60736ecSDimitry Andric HasPhysRegUse = true;
1439b60736ecSDimitry Andric }
1440b60736ecSDimitry Andric }
1441b60736ecSDimitry Andric } else if (MO.isRegMask()) {
1442b60736ecSDimitry Andric HasRegMask = true;
1443344a3780SDimitry Andric RegMasks.push_back(MO.getRegMask());
1444b60736ecSDimitry Andric }
1445b60736ecSDimitry Andric }
1446b60736ecSDimitry Andric
1447b60736ecSDimitry Andric // Allocate virtreg defs.
1448b60736ecSDimitry Andric if (HasDef) {
1449b60736ecSDimitry Andric if (HasVRegDef) {
14507fa27ce4SDimitry Andric // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
14517fa27ce4SDimitry Andric // multiple times to ensure no operand is missed.
14527fa27ce4SDimitry Andric bool ReArrangedImplicitOps = true;
14537fa27ce4SDimitry Andric
1454b60736ecSDimitry Andric // Special handling for early clobbers, tied operands or subregister defs:
1455b60736ecSDimitry Andric // Compared to "normal" defs these:
1456b60736ecSDimitry Andric // - Must not use a register that is pre-assigned for a use operand.
1457b60736ecSDimitry Andric // - In order to solve tricky inline assembly constraints we change the
1458b60736ecSDimitry Andric // heuristic to figure out a good operand order before doing
1459b60736ecSDimitry Andric // assignments.
1460b60736ecSDimitry Andric if (NeedToAssignLiveThroughs) {
14617fa27ce4SDimitry Andric while (ReArrangedImplicitOps) {
14627fa27ce4SDimitry Andric ReArrangedImplicitOps = false;
14637fa27ce4SDimitry Andric findAndSortDefOperandIndexes(MI);
1464ac9a064cSDimitry Andric for (unsigned OpIdx : DefOperandIndexes) {
1465b60736ecSDimitry Andric MachineOperand &MO = MI.getOperand(OpIdx);
1466b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1467312c0ed1SDimitry Andric Register Reg = MO.getReg();
1468312c0ed1SDimitry Andric if (MO.isEarlyClobber() || isTiedToNotUndef(MO) ||
1469b60736ecSDimitry Andric (MO.getSubReg() && !MO.isUndef())) {
14707fa27ce4SDimitry Andric ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1471b60736ecSDimitry Andric } else {
14727fa27ce4SDimitry Andric ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
14737fa27ce4SDimitry Andric }
14747fa27ce4SDimitry Andric // Implicit operands of MI were re-arranged,
14757fa27ce4SDimitry Andric // re-compute DefOperandIndexes.
1476312c0ed1SDimitry Andric if (ReArrangedImplicitOps)
14777fa27ce4SDimitry Andric break;
14787fa27ce4SDimitry Andric }
1479b60736ecSDimitry Andric }
1480b60736ecSDimitry Andric } else {
1481b60736ecSDimitry Andric // Assign virtual register defs.
14827fa27ce4SDimitry Andric while (ReArrangedImplicitOps) {
14837fa27ce4SDimitry Andric ReArrangedImplicitOps = false;
1484312c0ed1SDimitry Andric for (MachineOperand &MO : MI.operands()) {
1485b60736ecSDimitry Andric if (!MO.isReg() || !MO.isDef())
1486b60736ecSDimitry Andric continue;
1487b60736ecSDimitry Andric Register Reg = MO.getReg();
14887fa27ce4SDimitry Andric if (Reg.isVirtual()) {
1489312c0ed1SDimitry Andric ReArrangedImplicitOps =
1490312c0ed1SDimitry Andric defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1491312c0ed1SDimitry Andric if (ReArrangedImplicitOps)
14927fa27ce4SDimitry Andric break;
14937fa27ce4SDimitry Andric }
14947fa27ce4SDimitry Andric }
14957fa27ce4SDimitry Andric }
1496b60736ecSDimitry Andric }
1497b60736ecSDimitry Andric }
1498b60736ecSDimitry Andric
1499b60736ecSDimitry Andric // Free registers occupied by defs.
1500b60736ecSDimitry Andric // Iterate operands in reverse order, so we see the implicit super register
1501b60736ecSDimitry Andric // defs first (we added them earlier in case of <def,read-undef>).
1502312c0ed1SDimitry Andric for (MachineOperand &MO : reverse(MI.operands())) {
1503b60736ecSDimitry Andric if (!MO.isReg() || !MO.isDef())
1504b60736ecSDimitry Andric continue;
1505b60736ecSDimitry Andric
15067fa27ce4SDimitry Andric Register Reg = MO.getReg();
15077fa27ce4SDimitry Andric
1508b60736ecSDimitry Andric // subreg defs don't free the full register. We left the subreg number
1509b60736ecSDimitry Andric // around as a marker in setPhysReg() to recognize this case here.
15107fa27ce4SDimitry Andric if (Reg.isPhysical() && MO.getSubReg() != 0) {
1511b60736ecSDimitry Andric MO.setSubReg(0);
1512d7f7719eSRoman Divacky continue;
1513d7f7719eSRoman Divacky }
1514b60736ecSDimitry Andric
1515344a3780SDimitry Andric assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1516344a3780SDimitry Andric "tied def assigned to clobbered register");
1517344a3780SDimitry Andric
1518b60736ecSDimitry Andric // Do not free tied operands and early clobbers.
1519312c0ed1SDimitry Andric if (isTiedToNotUndef(MO) || MO.isEarlyClobber())
1520b60736ecSDimitry Andric continue;
1521b60736ecSDimitry Andric if (!Reg)
1522b60736ecSDimitry Andric continue;
1523e3b55780SDimitry Andric if (Reg.isVirtual()) {
1524e3b55780SDimitry Andric assert(!shouldAllocateRegister(Reg));
1525e3b55780SDimitry Andric continue;
1526e3b55780SDimitry Andric }
1527b60736ecSDimitry Andric assert(Reg.isPhysical());
1528b60736ecSDimitry Andric if (MRI->isReserved(Reg))
1529b60736ecSDimitry Andric continue;
1530b60736ecSDimitry Andric freePhysReg(Reg);
1531b60736ecSDimitry Andric unmarkRegUsedInInstr(Reg);
1532b60736ecSDimitry Andric }
1533d7f7719eSRoman Divacky }
153466e41e3cSRoman Divacky
1535b60736ecSDimitry Andric // Displace clobbered registers.
1536b60736ecSDimitry Andric if (HasRegMask) {
1537344a3780SDimitry Andric assert(!RegMasks.empty() && "expected RegMask");
1538b60736ecSDimitry Andric // MRI bookkeeping.
1539344a3780SDimitry Andric for (const auto *RM : RegMasks)
1540344a3780SDimitry Andric MRI->addPhysRegsUsedFromRegMask(RM);
1541b60736ecSDimitry Andric
1542b60736ecSDimitry Andric // Displace clobbered registers.
1543344a3780SDimitry Andric for (const LiveReg &LR : LiveVirtRegs) {
1544344a3780SDimitry Andric MCPhysReg PhysReg = LR.PhysReg;
1545344a3780SDimitry Andric if (PhysReg != 0 && isClobberedByRegMasks(PhysReg))
1546b60736ecSDimitry Andric displacePhysReg(MI, PhysReg);
1547b60736ecSDimitry Andric }
1548b60736ecSDimitry Andric }
1549d7f7719eSRoman Divacky
1550b60736ecSDimitry Andric // Apply pre-assigned register uses to state.
1551b60736ecSDimitry Andric if (HasPhysRegUse) {
1552b60736ecSDimitry Andric for (MachineOperand &MO : MI.operands()) {
1553b60736ecSDimitry Andric if (!MO.isReg() || !MO.readsReg())
1554b60736ecSDimitry Andric continue;
1555b60736ecSDimitry Andric Register Reg = MO.getReg();
1556b60736ecSDimitry Andric if (!Reg.isPhysical())
1557b60736ecSDimitry Andric continue;
1558b60736ecSDimitry Andric if (MRI->isReserved(Reg))
1559b60736ecSDimitry Andric continue;
1560312c0ed1SDimitry Andric if (!usePhysReg(MI, Reg))
1561b60736ecSDimitry Andric MO.setIsKill(true);
1562b60736ecSDimitry Andric }
1563b60736ecSDimitry Andric }
1564b60736ecSDimitry Andric
1565b60736ecSDimitry Andric // Allocate virtreg uses and insert reloads as necessary.
15667fa27ce4SDimitry Andric // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
15677fa27ce4SDimitry Andric // times to ensure no operand is missed.
1568e6d15924SDimitry Andric bool HasUndefUse = false;
15697fa27ce4SDimitry Andric bool ReArrangedImplicitMOs = true;
15707fa27ce4SDimitry Andric while (ReArrangedImplicitMOs) {
15717fa27ce4SDimitry Andric ReArrangedImplicitMOs = false;
1572312c0ed1SDimitry Andric for (MachineOperand &MO : MI.operands()) {
1573b60736ecSDimitry Andric if (!MO.isReg() || !MO.isUse())
1574b60736ecSDimitry Andric continue;
15751d5ae102SDimitry Andric Register Reg = MO.getReg();
1576e3b55780SDimitry Andric if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
15771d5ae102SDimitry Andric continue;
1578b60736ecSDimitry Andric
1579e6d15924SDimitry Andric if (MO.isUndef()) {
1580e6d15924SDimitry Andric HasUndefUse = true;
1581e6d15924SDimitry Andric continue;
1582e6d15924SDimitry Andric }
1583e6d15924SDimitry Andric
1584e6d15924SDimitry Andric // Populate MayLiveAcrossBlocks in case the use block is allocated before
1585e6d15924SDimitry Andric // the def block (removing the vreg uses).
1586e6d15924SDimitry Andric mayLiveIn(Reg);
1587e6d15924SDimitry Andric
1588b60736ecSDimitry Andric assert(!MO.isInternalRead() && "Bundles not supported");
1589b60736ecSDimitry Andric assert(MO.readsReg() && "reading use");
1590312c0ed1SDimitry Andric ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
15917fa27ce4SDimitry Andric if (ReArrangedImplicitMOs)
15927fa27ce4SDimitry Andric break;
15937fa27ce4SDimitry Andric }
1594abdf259dSRoman Divacky }
1595abdf259dSRoman Divacky
1596e6d15924SDimitry Andric // Allocate undef operands. This is a separate step because in a situation
1597e6d15924SDimitry Andric // like ` = OP undef %X, %X` both operands need the same register assign
1598e6d15924SDimitry Andric // so we should perform the normal assignment first.
1599e6d15924SDimitry Andric if (HasUndefUse) {
16007fa27ce4SDimitry Andric for (MachineOperand &MO : MI.all_uses()) {
16011d5ae102SDimitry Andric Register Reg = MO.getReg();
1602e3b55780SDimitry Andric if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1603e6d15924SDimitry Andric continue;
1604e6d15924SDimitry Andric
1605e6d15924SDimitry Andric assert(MO.isUndef() && "Should only have undef virtreg uses left");
1606e6d15924SDimitry Andric allocVirtRegUndef(MO);
1607e6d15924SDimitry Andric }
1608e6d15924SDimitry Andric }
1609e6d15924SDimitry Andric
1610b60736ecSDimitry Andric // Free early clobbers.
1611b60736ecSDimitry Andric if (HasEarlyClobber) {
1612312c0ed1SDimitry Andric for (MachineOperand &MO : reverse(MI.all_defs())) {
16137fa27ce4SDimitry Andric if (!MO.isEarlyClobber())
1614b60736ecSDimitry Andric continue;
1615e3b55780SDimitry Andric assert(!MO.getSubReg() && "should be already handled in def processing");
1616b60736ecSDimitry Andric
16171d5ae102SDimitry Andric Register Reg = MO.getReg();
1618b60736ecSDimitry Andric if (!Reg)
16191d5ae102SDimitry Andric continue;
1620e3b55780SDimitry Andric if (Reg.isVirtual()) {
1621e3b55780SDimitry Andric assert(!shouldAllocateRegister(Reg));
1622e3b55780SDimitry Andric continue;
1623e3b55780SDimitry Andric }
1624b60736ecSDimitry Andric assert(Reg.isPhysical() && "should have register assigned");
1625b60736ecSDimitry Andric
1626b60736ecSDimitry Andric // We sometimes get odd situations like:
1627b60736ecSDimitry Andric // early-clobber %x0 = INSTRUCTION %x0
1628b60736ecSDimitry Andric // which is semantically questionable as the early-clobber should
1629b60736ecSDimitry Andric // apply before the use. But in practice we consider the use to
1630b60736ecSDimitry Andric // happen before the early clobber now. Don't free the early clobber
1631b60736ecSDimitry Andric // register in this case.
1632b60736ecSDimitry Andric if (MI.readsRegister(Reg, TRI))
1633b60736ecSDimitry Andric continue;
1634b60736ecSDimitry Andric
1635b60736ecSDimitry Andric freePhysReg(Reg);
163666e41e3cSRoman Divacky }
1637abdf259dSRoman Divacky }
1638d7f7719eSRoman Divacky
1639eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "<< " << MI);
1640b60736ecSDimitry Andric if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1641b60736ecSDimitry Andric MI.getNumOperands() == 2) {
1642d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
1643d8e91e46SDimitry Andric Coalesced.push_back(&MI);
1644d7f7719eSRoman Divacky }
1645abdf259dSRoman Divacky }
1646d7f7719eSRoman Divacky
handleDebugValue(MachineInstr & MI)1647ac9a064cSDimitry Andric void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1648d8e91e46SDimitry Andric // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1649d8e91e46SDimitry Andric // mostly constants and frame indices.
1650b1c73532SDimitry Andric assert(MI.isDebugValue() && "not a DBG_VALUE*");
1651b1c73532SDimitry Andric for (const auto &MO : MI.debug_operands()) {
1652b1c73532SDimitry Andric if (!MO.isReg())
1653b1c73532SDimitry Andric continue;
1654b1c73532SDimitry Andric Register Reg = MO.getReg();
1655e3b55780SDimitry Andric if (!Reg.isVirtual())
1656e3b55780SDimitry Andric continue;
1657e3b55780SDimitry Andric if (!shouldAllocateRegister(Reg))
1658344a3780SDimitry Andric continue;
1659d8e91e46SDimitry Andric
1660b60736ecSDimitry Andric // Already spilled to a stackslot?
1661b60736ecSDimitry Andric int SS = StackSlotForVirtReg[Reg];
1662b60736ecSDimitry Andric if (SS != -1) {
1663b60736ecSDimitry Andric // Modify DBG_VALUE now that the value is in a spill slot.
1664344a3780SDimitry Andric updateDbgValueForSpill(MI, SS, Reg);
1665b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1666344a3780SDimitry Andric continue;
1667b60736ecSDimitry Andric }
1668b60736ecSDimitry Andric
1669d8e91e46SDimitry Andric // See if this virtual register has already been allocated to a physical
1670d8e91e46SDimitry Andric // register or spilled to a stack slot.
1671d8e91e46SDimitry Andric LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1672344a3780SDimitry Andric SmallVector<MachineOperand *> DbgOps;
1673344a3780SDimitry Andric for (MachineOperand &Op : MI.getDebugOperandsForReg(Reg))
1674344a3780SDimitry Andric DbgOps.push_back(&Op);
1675344a3780SDimitry Andric
1676d8e91e46SDimitry Andric if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1677344a3780SDimitry Andric // Update every use of Reg within MI.
1678344a3780SDimitry Andric for (auto &RegMO : DbgOps)
1679344a3780SDimitry Andric setPhysReg(MI, *RegMO, LRI->PhysReg);
1680d8e91e46SDimitry Andric } else {
1681b60736ecSDimitry Andric DanglingDbgValues[Reg].push_back(&MI);
1682d8e91e46SDimitry Andric }
1683d8e91e46SDimitry Andric
1684d8e91e46SDimitry Andric // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1685d8e91e46SDimitry Andric // that future spills of Reg will have DBG_VALUEs.
1686344a3780SDimitry Andric LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1687344a3780SDimitry Andric }
1688d8e91e46SDimitry Andric }
1689d8e91e46SDimitry Andric
handleBundle(MachineInstr & MI)1690ac9a064cSDimitry Andric void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1691b60736ecSDimitry Andric MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1692b60736ecSDimitry Andric ++BundledMI;
1693b60736ecSDimitry Andric while (BundledMI->isBundledWithPred()) {
1694f65dcba8SDimitry Andric for (MachineOperand &MO : BundledMI->operands()) {
1695b60736ecSDimitry Andric if (!MO.isReg())
1696b60736ecSDimitry Andric continue;
1697b60736ecSDimitry Andric
1698b60736ecSDimitry Andric Register Reg = MO.getReg();
1699e3b55780SDimitry Andric if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1700b60736ecSDimitry Andric continue;
1701b60736ecSDimitry Andric
1702b60736ecSDimitry Andric DenseMap<Register, MCPhysReg>::iterator DI;
1703b60736ecSDimitry Andric DI = BundleVirtRegsMap.find(Reg);
1704b60736ecSDimitry Andric assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1705b60736ecSDimitry Andric
1706b60736ecSDimitry Andric setPhysReg(MI, MO, DI->second);
1707b60736ecSDimitry Andric }
1708b60736ecSDimitry Andric
1709b60736ecSDimitry Andric ++BundledMI;
1710b60736ecSDimitry Andric }
1711b60736ecSDimitry Andric }
1712b60736ecSDimitry Andric
allocateBasicBlock(MachineBasicBlock & MBB)1713ac9a064cSDimitry Andric void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1714d8e91e46SDimitry Andric this->MBB = &MBB;
1715d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1716d8e91e46SDimitry Andric
171799aabd70SDimitry Andric PosIndexes.unsetInitialized();
1718cfca06d7SDimitry Andric RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1719d8e91e46SDimitry Andric assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1720d8e91e46SDimitry Andric
17214b4fe385SDimitry Andric for (const auto &LiveReg : MBB.liveouts())
1722344a3780SDimitry Andric setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1723d8e91e46SDimitry Andric
1724d8e91e46SDimitry Andric Coalesced.clear();
1725d8e91e46SDimitry Andric
1726b60736ecSDimitry Andric // Traverse block in reverse order allocating instructions one by one.
1727b60736ecSDimitry Andric for (MachineInstr &MI : reverse(MBB)) {
1728b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1729d8e91e46SDimitry Andric
1730d8e91e46SDimitry Andric // Special handling for debug values. Note that they are not allowed to
1731d8e91e46SDimitry Andric // affect codegen of the other instructions in any way.
1732d8e91e46SDimitry Andric if (MI.isDebugValue()) {
1733d8e91e46SDimitry Andric handleDebugValue(MI);
1734d8e91e46SDimitry Andric continue;
1735d8e91e46SDimitry Andric }
1736d8e91e46SDimitry Andric
1737d8e91e46SDimitry Andric allocateInstruction(MI);
1738b60736ecSDimitry Andric
1739b60736ecSDimitry Andric // Once BUNDLE header is assigned registers, same assignments need to be
1740b60736ecSDimitry Andric // done for bundled MIs.
1741b60736ecSDimitry Andric if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1742b60736ecSDimitry Andric handleBundle(MI);
1743b60736ecSDimitry Andric }
1744d8e91e46SDimitry Andric }
1745d8e91e46SDimitry Andric
1746b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1747b60736ecSDimitry Andric
1748d7f7719eSRoman Divacky // Spill all physical registers holding virtual registers now.
1749b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1750b60736ecSDimitry Andric reloadAtBegin(MBB);
1751abdf259dSRoman Divacky
1752abdf259dSRoman Divacky // Erase all the coalesced copies. We are delaying it until now because
1753abdf259dSRoman Divacky // LiveVirtRegs might refer to the instrs.
1754044eb2f6SDimitry Andric for (MachineInstr *MI : Coalesced)
1755044eb2f6SDimitry Andric MBB.erase(MI);
1756d8e91e46SDimitry Andric NumCoalesced += Coalesced.size();
1757abdf259dSRoman Divacky
1758b60736ecSDimitry Andric for (auto &UDBGPair : DanglingDbgValues) {
1759b60736ecSDimitry Andric for (MachineInstr *DbgValue : UDBGPair.second) {
1760b60736ecSDimitry Andric assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1761b60736ecSDimitry Andric // Nothing to do if the vreg was spilled in the meantime.
1762344a3780SDimitry Andric if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1763b60736ecSDimitry Andric continue;
1764b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1765b60736ecSDimitry Andric << '\n');
1766344a3780SDimitry Andric DbgValue->setDebugValueUndef();
1767b60736ecSDimitry Andric }
1768b60736ecSDimitry Andric }
1769b60736ecSDimitry Andric DanglingDbgValues.clear();
1770b60736ecSDimitry Andric
1771eb11fae6SDimitry Andric LLVM_DEBUG(MBB.dump());
1772d7f7719eSRoman Divacky }
1773d7f7719eSRoman Divacky
runOnMachineFunction(MachineFunction & MF)1774ac9a064cSDimitry Andric bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
1775eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1776044eb2f6SDimitry Andric << "********** Function: " << MF.getName() << '\n');
1777044eb2f6SDimitry Andric MRI = &MF.getRegInfo();
1778044eb2f6SDimitry Andric const TargetSubtargetInfo &STI = MF.getSubtarget();
1779044eb2f6SDimitry Andric TRI = STI.getRegisterInfo();
1780044eb2f6SDimitry Andric TII = STI.getInstrInfo();
1781044eb2f6SDimitry Andric MFI = &MF.getFrameInfo();
1782ac9a064cSDimitry Andric MRI->freezeReservedRegs();
1783044eb2f6SDimitry Andric RegClassInfo.runOnMachineFunction(MF);
1784b60736ecSDimitry Andric unsigned NumRegUnits = TRI->getNumRegUnits();
1785ac9a064cSDimitry Andric InstrGen = 0;
1786ac9a064cSDimitry Andric UsedInInstr.assign(NumRegUnits, 0);
1787d7f7719eSRoman Divacky
1788d7f7719eSRoman Divacky // initialize the virtual->physical register map to have a 'null'
1789d7f7719eSRoman Divacky // mapping for all virtual registers
1790044eb2f6SDimitry Andric unsigned NumVirtRegs = MRI->getNumVirtRegs();
1791044eb2f6SDimitry Andric StackSlotForVirtReg.resize(NumVirtRegs);
1792044eb2f6SDimitry Andric LiveVirtRegs.setUniverse(NumVirtRegs);
1793e6d15924SDimitry Andric MayLiveAcrossBlocks.clear();
1794e6d15924SDimitry Andric MayLiveAcrossBlocks.resize(NumVirtRegs);
1795d7f7719eSRoman Divacky
1796d7f7719eSRoman Divacky // Loop over all of the basic blocks, eliminating virtual register references
1797044eb2f6SDimitry Andric for (MachineBasicBlock &MBB : MF)
1798044eb2f6SDimitry Andric allocateBasicBlock(MBB);
1799abdf259dSRoman Divacky
1800344a3780SDimitry Andric if (ClearVirtRegs) {
180163faed5bSDimitry Andric // All machine operands and other references to virtual registers have been
180263faed5bSDimitry Andric // replaced. Remove the virtual registers.
180363faed5bSDimitry Andric MRI->clearVirtRegs();
1804344a3780SDimitry Andric }
180563faed5bSDimitry Andric
1806d7f7719eSRoman Divacky StackSlotForVirtReg.clear();
1807d39c594dSDimitry Andric LiveDbgValueMap.clear();
1808d7f7719eSRoman Divacky return true;
1809d7f7719eSRoman Divacky }
1810d7f7719eSRoman Divacky
run(MachineFunction & MF,MachineFunctionAnalysisManager &)1811ac9a064cSDimitry Andric PreservedAnalyses RegAllocFastPass::run(MachineFunction &MF,
1812ac9a064cSDimitry Andric MachineFunctionAnalysisManager &) {
1813ac9a064cSDimitry Andric MFPropsModifier _(*this, MF);
1814ac9a064cSDimitry Andric RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1815ac9a064cSDimitry Andric bool Changed = Impl.runOnMachineFunction(MF);
1816ac9a064cSDimitry Andric if (!Changed)
1817ac9a064cSDimitry Andric return PreservedAnalyses::all();
1818ac9a064cSDimitry Andric auto PA = getMachineFunctionPassPreservedAnalyses();
1819ac9a064cSDimitry Andric PA.preserveSet<CFGAnalyses>();
1820ac9a064cSDimitry Andric return PA;
1821ac9a064cSDimitry Andric }
1822ac9a064cSDimitry Andric
printPipeline(raw_ostream & OS,function_ref<StringRef (StringRef)> MapClassName2PassName)1823ac9a064cSDimitry Andric void RegAllocFastPass::printPipeline(
1824ac9a064cSDimitry Andric raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1825ac9a064cSDimitry Andric bool PrintFilterName = Opts.FilterName != "all";
1826ac9a064cSDimitry Andric bool PrintNoClearVRegs = !Opts.ClearVRegs;
1827ac9a064cSDimitry Andric bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1828ac9a064cSDimitry Andric
1829ac9a064cSDimitry Andric OS << "regallocfast";
1830ac9a064cSDimitry Andric if (PrintFilterName || PrintNoClearVRegs) {
1831ac9a064cSDimitry Andric OS << '<';
1832ac9a064cSDimitry Andric if (PrintFilterName)
1833ac9a064cSDimitry Andric OS << "filter=" << Opts.FilterName;
1834ac9a064cSDimitry Andric if (PrintSemicolon)
1835ac9a064cSDimitry Andric OS << ';';
1836ac9a064cSDimitry Andric if (PrintNoClearVRegs)
1837ac9a064cSDimitry Andric OS << "no-clear-vregs";
1838ac9a064cSDimitry Andric OS << '>';
1839ac9a064cSDimitry Andric }
1840ac9a064cSDimitry Andric }
1841ac9a064cSDimitry Andric
createFastRegisterAllocator()1842b1c73532SDimitry Andric FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1843344a3780SDimitry Andric
createFastRegisterAllocator(RegAllocFilterFunc Ftor,bool ClearVirtRegs)1844ac9a064cSDimitry Andric FunctionPass *llvm::createFastRegisterAllocator(RegAllocFilterFunc Ftor,
18454b4fe385SDimitry Andric bool ClearVirtRegs) {
1846344a3780SDimitry Andric return new RegAllocFast(Ftor, ClearVirtRegs);
1847344a3780SDimitry Andric }
1848