xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/RegAllocFast.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file This register allocator allocates registers to a basic block at a
100b57cec5SDimitry Andric /// time, attempting to keep values in registers and reusing registers as
110b57cec5SDimitry Andric /// appropriate.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
15*0fca6ea1SDimitry Andric #include "llvm/CodeGen/RegAllocFast.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/IndexedMap.h"
19349cc55cSDimitry Andric #include "llvm/ADT/MapVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SparseSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
32fe6060f1SDimitry Andric #include "llvm/CodeGen/RegAllocCommon.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/RegAllocRegistry.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
39480093f4SDimitry Andric #include "llvm/InitializePasses.h"
400b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
410b57cec5SDimitry Andric #include "llvm/Pass.h"
420b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
430b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
440b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
450b57cec5SDimitry Andric #include <cassert>
460b57cec5SDimitry Andric #include <tuple>
470b57cec5SDimitry Andric #include <vector>
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric using namespace llvm;
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric #define DEBUG_TYPE "regalloc"
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric STATISTIC(NumStores, "Number of stores added");
540b57cec5SDimitry Andric STATISTIC(NumLoads, "Number of loads added");
550b57cec5SDimitry Andric STATISTIC(NumCoalesced, "Number of copies coalesced");
560b57cec5SDimitry Andric 
57e8d8bef9SDimitry Andric // FIXME: Remove this switch when all testcases are fixed!
58e8d8bef9SDimitry Andric static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
59e8d8bef9SDimitry Andric                                        cl::Hidden);
60e8d8bef9SDimitry Andric 
615f757f3fSDimitry Andric static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
625f757f3fSDimitry Andric                                      createFastRegisterAllocator);
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric namespace {
650b57cec5SDimitry Andric 
66cb14a3feSDimitry Andric /// Assign ascending index for instructions in machine basic block. The index
67cb14a3feSDimitry Andric /// can be used to determine dominance between instructions in same MBB.
68cb14a3feSDimitry Andric class InstrPosIndexes {
69cb14a3feSDimitry Andric public:
70cb14a3feSDimitry Andric   void unsetInitialized() { IsInitialized = false; }
71cb14a3feSDimitry Andric 
72cb14a3feSDimitry Andric   void init(const MachineBasicBlock &MBB) {
73cb14a3feSDimitry Andric     CurMBB = &MBB;
74cb14a3feSDimitry Andric     Instr2PosIndex.clear();
75cb14a3feSDimitry Andric     uint64_t LastIndex = 0;
76cb14a3feSDimitry Andric     for (const MachineInstr &MI : MBB) {
77cb14a3feSDimitry Andric       LastIndex += InstrDist;
78cb14a3feSDimitry Andric       Instr2PosIndex[&MI] = LastIndex;
79cb14a3feSDimitry Andric     }
80cb14a3feSDimitry Andric   }
81cb14a3feSDimitry Andric 
82cb14a3feSDimitry Andric   /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
83cb14a3feSDimitry Andric   /// index without affecting existing instruction's index. Return true if all
84cb14a3feSDimitry Andric   /// instructions index has been reassigned.
85cb14a3feSDimitry Andric   bool getIndex(const MachineInstr &MI, uint64_t &Index) {
86cb14a3feSDimitry Andric     if (!IsInitialized) {
87cb14a3feSDimitry Andric       init(*MI.getParent());
88cb14a3feSDimitry Andric       IsInitialized = true;
89cb14a3feSDimitry Andric       Index = Instr2PosIndex.at(&MI);
90cb14a3feSDimitry Andric       return true;
91cb14a3feSDimitry Andric     }
92cb14a3feSDimitry Andric 
93cb14a3feSDimitry Andric     assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
94cb14a3feSDimitry Andric     auto It = Instr2PosIndex.find(&MI);
95cb14a3feSDimitry Andric     if (It != Instr2PosIndex.end()) {
96cb14a3feSDimitry Andric       Index = It->second;
97cb14a3feSDimitry Andric       return false;
98cb14a3feSDimitry Andric     }
99cb14a3feSDimitry Andric 
100cb14a3feSDimitry Andric     // Distance is the number of consecutive unassigned instructions including
101cb14a3feSDimitry Andric     // MI. Start is the first instruction of them. End is the next of last
102cb14a3feSDimitry Andric     // instruction of them.
103cb14a3feSDimitry Andric     // e.g.
104cb14a3feSDimitry Andric     // |Instruction|  A   |  B   |  C   |  MI  |  D   |  E   |
105cb14a3feSDimitry Andric     // |   Index   | 1024 |      |      |      |      | 2048 |
106cb14a3feSDimitry Andric     //
107cb14a3feSDimitry Andric     // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
108cb14a3feSDimitry Andric     // is E.
109cb14a3feSDimitry Andric     unsigned Distance = 1;
110cb14a3feSDimitry Andric     MachineBasicBlock::const_iterator Start = MI.getIterator(),
111cb14a3feSDimitry Andric                                       End = std::next(Start);
112cb14a3feSDimitry Andric     while (Start != CurMBB->begin() &&
113cb14a3feSDimitry Andric            !Instr2PosIndex.count(&*std::prev(Start))) {
114cb14a3feSDimitry Andric       --Start;
115cb14a3feSDimitry Andric       ++Distance;
116cb14a3feSDimitry Andric     }
117cb14a3feSDimitry Andric     while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
118cb14a3feSDimitry Andric       ++End;
119cb14a3feSDimitry Andric       ++Distance;
120cb14a3feSDimitry Andric     }
121cb14a3feSDimitry Andric 
122cb14a3feSDimitry Andric     // LastIndex is initialized to last used index prior to MI or zero.
123cb14a3feSDimitry Andric     // In previous example, LastIndex is 1024, EndIndex is 2048;
124cb14a3feSDimitry Andric     uint64_t LastIndex =
125cb14a3feSDimitry Andric         Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
126cb14a3feSDimitry Andric     uint64_t Step;
127cb14a3feSDimitry Andric     if (End == CurMBB->end())
128cb14a3feSDimitry Andric       Step = static_cast<uint64_t>(InstrDist);
129cb14a3feSDimitry Andric     else {
130cb14a3feSDimitry Andric       // No instruction uses index zero.
131cb14a3feSDimitry Andric       uint64_t EndIndex = Instr2PosIndex.at(&*End);
132cb14a3feSDimitry Andric       assert(EndIndex > LastIndex && "Index must be ascending order");
133cb14a3feSDimitry Andric       unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
134cb14a3feSDimitry Andric       // We want index gap between two adjacent MI is as same as possible. Given
135cb14a3feSDimitry Andric       // total A available indexes, D is number of consecutive unassigned
136cb14a3feSDimitry Andric       // instructions, S is the step.
137cb14a3feSDimitry Andric       // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
138cb14a3feSDimitry Andric       // There're S-1 available indexes between unassigned instruction and its
139cb14a3feSDimitry Andric       // predecessor. There're A-S*D available indexes between the last
140cb14a3feSDimitry Andric       // unassigned instruction and its successor.
141cb14a3feSDimitry Andric       // Ideally, we want
142cb14a3feSDimitry Andric       //    S-1 = A-S*D
143cb14a3feSDimitry Andric       // then
144cb14a3feSDimitry Andric       //    S = (A+1)/(D+1)
145cb14a3feSDimitry Andric       // An valid S must be integer greater than zero, so
146cb14a3feSDimitry Andric       //    S <= (A+1)/(D+1)
147cb14a3feSDimitry Andric       // =>
148cb14a3feSDimitry Andric       //    A-S*D >= 0
149cb14a3feSDimitry Andric       // That means we can safely use (A+1)/(D+1) as step.
150cb14a3feSDimitry Andric       // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
151cb14a3feSDimitry Andric       // 1636, 1840.
152cb14a3feSDimitry Andric       Step = (NumAvailableIndexes + 1) / (Distance + 1);
153cb14a3feSDimitry Andric     }
154cb14a3feSDimitry Andric 
155cb14a3feSDimitry Andric     // Reassign index for all instructions if number of new inserted
156cb14a3feSDimitry Andric     // instructions exceed slot or all instructions are new.
157cb14a3feSDimitry Andric     if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
158cb14a3feSDimitry Andric       init(*CurMBB);
159cb14a3feSDimitry Andric       Index = Instr2PosIndex.at(&MI);
160cb14a3feSDimitry Andric       return true;
161cb14a3feSDimitry Andric     }
162cb14a3feSDimitry Andric 
163cb14a3feSDimitry Andric     for (auto I = Start; I != End; ++I) {
164cb14a3feSDimitry Andric       LastIndex += Step;
165cb14a3feSDimitry Andric       Instr2PosIndex[&*I] = LastIndex;
166cb14a3feSDimitry Andric     }
167cb14a3feSDimitry Andric     Index = Instr2PosIndex.at(&MI);
168cb14a3feSDimitry Andric     return false;
169cb14a3feSDimitry Andric   }
170cb14a3feSDimitry Andric 
171cb14a3feSDimitry Andric private:
172cb14a3feSDimitry Andric   bool IsInitialized = false;
173cb14a3feSDimitry Andric   enum { InstrDist = 1024 };
174cb14a3feSDimitry Andric   const MachineBasicBlock *CurMBB = nullptr;
175cb14a3feSDimitry Andric   DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
176cb14a3feSDimitry Andric };
177cb14a3feSDimitry Andric 
178*0fca6ea1SDimitry Andric class RegAllocFastImpl {
1790b57cec5SDimitry Andric public:
180*0fca6ea1SDimitry Andric   RegAllocFastImpl(const RegAllocFilterFunc F = nullptr,
1815f757f3fSDimitry Andric                    bool ClearVirtRegs_ = true)
182*0fca6ea1SDimitry Andric       : ShouldAllocateRegisterImpl(F), StackSlotForVirtReg(-1),
183*0fca6ea1SDimitry Andric         ClearVirtRegs(ClearVirtRegs_) {}
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric private:
18606c3fb27SDimitry Andric   MachineFrameInfo *MFI = nullptr;
18706c3fb27SDimitry Andric   MachineRegisterInfo *MRI = nullptr;
18806c3fb27SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
18906c3fb27SDimitry Andric   const TargetInstrInfo *TII = nullptr;
1900b57cec5SDimitry Andric   RegisterClassInfo RegClassInfo;
191*0fca6ea1SDimitry Andric   const RegAllocFilterFunc ShouldAllocateRegisterImpl;
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   /// Basic block currently being allocated.
19406c3fb27SDimitry Andric   MachineBasicBlock *MBB = nullptr;
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   /// Maps virtual regs to the frame index where these values are spilled.
1970b57cec5SDimitry Andric   IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   /// Everything we know about a live virtual register.
2000b57cec5SDimitry Andric   struct LiveReg {
2010b57cec5SDimitry Andric     MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
202480093f4SDimitry Andric     Register VirtReg;                ///< Virtual register number.
2030b57cec5SDimitry Andric     MCPhysReg PhysReg = 0;           ///< Currently held here.
204e8d8bef9SDimitry Andric     bool LiveOut = false;            ///< Register is possibly live out.
205e8d8bef9SDimitry Andric     bool Reloaded = false;           ///< Register was reloaded.
206e8d8bef9SDimitry Andric     bool Error = false;              ///< Could not allocate.
2070b57cec5SDimitry Andric 
208480093f4SDimitry Andric     explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric     unsigned getSparseSetIndex() const {
2118bcb0991SDimitry Andric       return Register::virtReg2Index(VirtReg);
2120b57cec5SDimitry Andric     }
2130b57cec5SDimitry Andric   };
2140b57cec5SDimitry Andric 
21506c3fb27SDimitry Andric   using LiveRegMap = SparseSet<LiveReg, identity<unsigned>, uint16_t>;
2160b57cec5SDimitry Andric   /// This map contains entries for each virtual register that is currently
2170b57cec5SDimitry Andric   /// available in a physical register.
2180b57cec5SDimitry Andric   LiveRegMap LiveVirtRegs;
2190b57cec5SDimitry Andric 
220e8d8bef9SDimitry Andric   /// Stores assigned virtual registers present in the bundle MI.
221e8d8bef9SDimitry Andric   DenseMap<Register, MCPhysReg> BundleVirtRegsMap;
222e8d8bef9SDimitry Andric 
223fe6060f1SDimitry Andric   DenseMap<unsigned, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
224e8d8bef9SDimitry Andric   /// List of DBG_VALUE that we encountered without the vreg being assigned
225e8d8bef9SDimitry Andric   /// because they were placed after the last use of the vreg.
226e8d8bef9SDimitry Andric   DenseMap<unsigned, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   /// Has a bit set for every virtual register for which it was determined
2290b57cec5SDimitry Andric   /// that it is alive across blocks.
2300b57cec5SDimitry Andric   BitVector MayLiveAcrossBlocks;
2310b57cec5SDimitry Andric 
232e8d8bef9SDimitry Andric   /// State of a register unit.
233e8d8bef9SDimitry Andric   enum RegUnitState {
2340b57cec5SDimitry Andric     /// A free register is not currently in use and can be allocated
2350b57cec5SDimitry Andric     /// immediately without checking aliases.
2360b57cec5SDimitry Andric     regFree,
2370b57cec5SDimitry Andric 
238e8d8bef9SDimitry Andric     /// A pre-assigned register has been assigned before register allocation
239e8d8bef9SDimitry Andric     /// (e.g., setting up a call parameter).
240e8d8bef9SDimitry Andric     regPreAssigned,
241e8d8bef9SDimitry Andric 
242e8d8bef9SDimitry Andric     /// Used temporarily in reloadAtBegin() to mark register units that are
243e8d8bef9SDimitry Andric     /// live-in to the basic block.
244e8d8bef9SDimitry Andric     regLiveIn,
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     /// A register state may also be a virtual register number, indication
2470b57cec5SDimitry Andric     /// that the physical register is currently allocated to a virtual
2480b57cec5SDimitry Andric     /// register. In that case, LiveVirtRegs contains the inverse mapping.
2490b57cec5SDimitry Andric   };
2500b57cec5SDimitry Andric 
251e8d8bef9SDimitry Andric   /// Maps each physical register to a RegUnitState enum or virtual register.
252e8d8bef9SDimitry Andric   std::vector<unsigned> RegUnitStates;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   SmallVector<MachineInstr *, 32> Coalesced;
2550b57cec5SDimitry Andric 
256*0fca6ea1SDimitry Andric   /// Track register units that are used in the current instruction, and so
2570b57cec5SDimitry Andric   /// cannot be allocated.
258*0fca6ea1SDimitry Andric   ///
259*0fca6ea1SDimitry Andric   /// In the first phase (tied defs/early clobber), we consider also physical
260*0fca6ea1SDimitry Andric   /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
261*0fca6ea1SDimitry Andric   /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
262*0fca6ea1SDimitry Andric   /// avoid resetting the entire vector after every instruction, we track the
263*0fca6ea1SDimitry Andric   /// instruction "generation" in the remaining 31 bits -- this means, that if
264*0fca6ea1SDimitry Andric   /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
265*0fca6ea1SDimitry Andric   /// never zero and always incremented by two.
266*0fca6ea1SDimitry Andric   ///
267*0fca6ea1SDimitry Andric   /// Don't allocate inline storage: the number of register units is typically
268*0fca6ea1SDimitry Andric   /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
269*0fca6ea1SDimitry Andric   uint32_t InstrGen;
270*0fca6ea1SDimitry Andric   SmallVector<unsigned, 0> UsedInInstr;
271*0fca6ea1SDimitry Andric 
272*0fca6ea1SDimitry Andric   SmallVector<unsigned, 8> DefOperandIndexes;
273fe6060f1SDimitry Andric   // Register masks attached to the current instruction.
274fe6060f1SDimitry Andric   SmallVector<const uint32_t *> RegMasks;
2750b57cec5SDimitry Andric 
276cb14a3feSDimitry Andric   // Assign index for each instruction to quickly determine dominance.
277cb14a3feSDimitry Andric   InstrPosIndexes PosIndexes;
278cb14a3feSDimitry Andric 
2790b57cec5SDimitry Andric   void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
280e8d8bef9SDimitry Andric   bool isPhysRegFree(MCPhysReg PhysReg) const;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   /// Mark a physreg as used in this instruction.
2830b57cec5SDimitry Andric   void markRegUsedInInstr(MCPhysReg PhysReg) {
28406c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
285*0fca6ea1SDimitry Andric       UsedInInstr[Unit] = InstrGen | 1;
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
288fe6060f1SDimitry Andric   // Check if physreg is clobbered by instruction's regmask(s).
289fe6060f1SDimitry Andric   bool isClobberedByRegMasks(MCPhysReg PhysReg) const {
290fe6060f1SDimitry Andric     return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
291fe6060f1SDimitry Andric       return MachineOperand::clobbersPhysReg(Mask, PhysReg);
292fe6060f1SDimitry Andric     });
293fe6060f1SDimitry Andric   }
294fe6060f1SDimitry Andric 
2950b57cec5SDimitry Andric   /// Check if a physreg or any of its aliases are used in this instruction.
296e8d8bef9SDimitry Andric   bool isRegUsedInInstr(MCPhysReg PhysReg, bool LookAtPhysRegUses) const {
297fe6060f1SDimitry Andric     if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
298fe6060f1SDimitry Andric       return true;
299*0fca6ea1SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
300*0fca6ea1SDimitry Andric       if (UsedInInstr[Unit] >= (InstrGen | !LookAtPhysRegUses))
3010b57cec5SDimitry Andric         return true;
3020b57cec5SDimitry Andric     return false;
3030b57cec5SDimitry Andric   }
3040b57cec5SDimitry Andric 
305e8d8bef9SDimitry Andric   /// Mark physical register as being used in a register use operand.
306e8d8bef9SDimitry Andric   /// This is only used by the special livethrough handling code.
307e8d8bef9SDimitry Andric   void markPhysRegUsedInInstr(MCPhysReg PhysReg) {
308*0fca6ea1SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
309*0fca6ea1SDimitry Andric       assert(UsedInInstr[Unit] <= InstrGen && "non-phys use before phys use?");
310*0fca6ea1SDimitry Andric       UsedInInstr[Unit] = InstrGen;
311*0fca6ea1SDimitry Andric     }
312e8d8bef9SDimitry Andric   }
313e8d8bef9SDimitry Andric 
314e8d8bef9SDimitry Andric   /// Remove mark of physical register being used in the instruction.
315e8d8bef9SDimitry Andric   void unmarkRegUsedInInstr(MCPhysReg PhysReg) {
31606c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(PhysReg))
317*0fca6ea1SDimitry Andric       UsedInInstr[Unit] = 0;
318e8d8bef9SDimitry Andric   }
319e8d8bef9SDimitry Andric 
3200b57cec5SDimitry Andric   enum : unsigned {
3210b57cec5SDimitry Andric     spillClean = 50,
3220b57cec5SDimitry Andric     spillDirty = 100,
3230b57cec5SDimitry Andric     spillPrefBonus = 20,
3240b57cec5SDimitry Andric     spillImpossible = ~0u
3250b57cec5SDimitry Andric   };
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric public:
328*0fca6ea1SDimitry Andric   bool ClearVirtRegs;
3290b57cec5SDimitry Andric 
330*0fca6ea1SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF);
331e8d8bef9SDimitry Andric 
3320b57cec5SDimitry Andric private:
3330b57cec5SDimitry Andric   void allocateBasicBlock(MachineBasicBlock &MBB);
334e8d8bef9SDimitry Andric 
335*0fca6ea1SDimitry Andric   void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
336e8d8bef9SDimitry Andric                             Register Reg) const;
337e8d8bef9SDimitry Andric 
33806c3fb27SDimitry Andric   void findAndSortDefOperandIndexes(const MachineInstr &MI);
33906c3fb27SDimitry Andric 
3400b57cec5SDimitry Andric   void allocateInstruction(MachineInstr &MI);
3410b57cec5SDimitry Andric   void handleDebugValue(MachineInstr &MI);
342e8d8bef9SDimitry Andric   void handleBundle(MachineInstr &MI);
3430b57cec5SDimitry Andric 
344e8d8bef9SDimitry Andric   bool usePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
345e8d8bef9SDimitry Andric   bool definePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
346e8d8bef9SDimitry Andric   bool displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg);
347e8d8bef9SDimitry Andric   void freePhysReg(MCPhysReg PhysReg);
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   unsigned calcSpillCost(MCPhysReg PhysReg) const;
3500b57cec5SDimitry Andric 
351480093f4SDimitry Andric   LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
3528bcb0991SDimitry Andric     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric 
355480093f4SDimitry Andric   LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
3568bcb0991SDimitry Andric     return LiveVirtRegs.find(Register::virtReg2Index(VirtReg));
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric 
359e8d8bef9SDimitry Andric   void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCPhysReg PhysReg);
360e8d8bef9SDimitry Andric   void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
361e8d8bef9SDimitry Andric                     bool LookAtPhysRegUses = false);
3620b57cec5SDimitry Andric   void allocVirtRegUndef(MachineOperand &MO);
363e8d8bef9SDimitry Andric   void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
364e8d8bef9SDimitry Andric                                  MCPhysReg Reg);
36506c3fb27SDimitry Andric   bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
366e8d8bef9SDimitry Andric                                 Register VirtReg);
36706c3fb27SDimitry Andric   bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
368e8d8bef9SDimitry Andric                      bool LookAtPhysRegUses = false);
3695f757f3fSDimitry Andric   bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
370e8d8bef9SDimitry Andric 
371e8d8bef9SDimitry Andric   MachineBasicBlock::iterator
372e8d8bef9SDimitry Andric   getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
373e8d8bef9SDimitry Andric                             SmallSet<Register, 2> &PrologLiveIns) const;
374e8d8bef9SDimitry Andric 
375e8d8bef9SDimitry Andric   void reloadAtBegin(MachineBasicBlock &MBB);
37606c3fb27SDimitry Andric   bool setPhysReg(MachineInstr &MI, MachineOperand &MO, MCPhysReg PhysReg);
3770b57cec5SDimitry Andric 
378480093f4SDimitry Andric   Register traceCopies(Register VirtReg) const;
379480093f4SDimitry Andric   Register traceCopyChain(Register Reg) const;
3800b57cec5SDimitry Andric 
381bdd1243dSDimitry Andric   bool shouldAllocateRegister(const Register Reg) const;
382480093f4SDimitry Andric   int getStackSpaceFor(Register VirtReg);
383480093f4SDimitry Andric   void spill(MachineBasicBlock::iterator Before, Register VirtReg,
384e8d8bef9SDimitry Andric              MCPhysReg AssignedReg, bool Kill, bool LiveOut);
385480093f4SDimitry Andric   void reload(MachineBasicBlock::iterator Before, Register VirtReg,
3860b57cec5SDimitry Andric               MCPhysReg PhysReg);
3870b57cec5SDimitry Andric 
388480093f4SDimitry Andric   bool mayLiveOut(Register VirtReg);
389480093f4SDimitry Andric   bool mayLiveIn(Register VirtReg);
3900b57cec5SDimitry Andric 
391e8d8bef9SDimitry Andric   void dumpState() const;
3920b57cec5SDimitry Andric };
3930b57cec5SDimitry Andric 
394*0fca6ea1SDimitry Andric class RegAllocFast : public MachineFunctionPass {
395*0fca6ea1SDimitry Andric   RegAllocFastImpl Impl;
396*0fca6ea1SDimitry Andric 
397*0fca6ea1SDimitry Andric public:
398*0fca6ea1SDimitry Andric   static char ID;
399*0fca6ea1SDimitry Andric 
400*0fca6ea1SDimitry Andric   RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
401*0fca6ea1SDimitry Andric       : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
402*0fca6ea1SDimitry Andric 
403*0fca6ea1SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override {
404*0fca6ea1SDimitry Andric     return Impl.runOnMachineFunction(MF);
405*0fca6ea1SDimitry Andric   }
406*0fca6ea1SDimitry Andric 
407*0fca6ea1SDimitry Andric   StringRef getPassName() const override { return "Fast Register Allocator"; }
408*0fca6ea1SDimitry Andric 
409*0fca6ea1SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
410*0fca6ea1SDimitry Andric     AU.setPreservesCFG();
411*0fca6ea1SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
412*0fca6ea1SDimitry Andric   }
413*0fca6ea1SDimitry Andric 
414*0fca6ea1SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
415*0fca6ea1SDimitry Andric     return MachineFunctionProperties().set(
416*0fca6ea1SDimitry Andric         MachineFunctionProperties::Property::NoPHIs);
417*0fca6ea1SDimitry Andric   }
418*0fca6ea1SDimitry Andric 
419*0fca6ea1SDimitry Andric   MachineFunctionProperties getSetProperties() const override {
420*0fca6ea1SDimitry Andric     if (Impl.ClearVirtRegs) {
421*0fca6ea1SDimitry Andric       return MachineFunctionProperties().set(
422*0fca6ea1SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
423*0fca6ea1SDimitry Andric     }
424*0fca6ea1SDimitry Andric 
425*0fca6ea1SDimitry Andric     return MachineFunctionProperties();
426*0fca6ea1SDimitry Andric   }
427*0fca6ea1SDimitry Andric 
428*0fca6ea1SDimitry Andric   MachineFunctionProperties getClearedProperties() const override {
429*0fca6ea1SDimitry Andric     return MachineFunctionProperties().set(
430*0fca6ea1SDimitry Andric         MachineFunctionProperties::Property::IsSSA);
431*0fca6ea1SDimitry Andric   }
432*0fca6ea1SDimitry Andric };
433*0fca6ea1SDimitry Andric 
4340b57cec5SDimitry Andric } // end anonymous namespace
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric char RegAllocFast::ID = 0;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
4390b57cec5SDimitry Andric                 false)
4400b57cec5SDimitry Andric 
441*0fca6ea1SDimitry Andric bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
442bdd1243dSDimitry Andric   assert(Reg.isVirtual());
443*0fca6ea1SDimitry Andric   if (!ShouldAllocateRegisterImpl)
444*0fca6ea1SDimitry Andric     return true;
445*0fca6ea1SDimitry Andric 
446*0fca6ea1SDimitry Andric   return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
447bdd1243dSDimitry Andric }
448bdd1243dSDimitry Andric 
449*0fca6ea1SDimitry Andric void RegAllocFastImpl::setPhysRegState(MCPhysReg PhysReg, unsigned NewState) {
45006c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg))
45106c3fb27SDimitry Andric     RegUnitStates[Unit] = NewState;
452e8d8bef9SDimitry Andric }
453e8d8bef9SDimitry Andric 
454*0fca6ea1SDimitry Andric bool RegAllocFastImpl::isPhysRegFree(MCPhysReg PhysReg) const {
45506c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
45606c3fb27SDimitry Andric     if (RegUnitStates[Unit] != regFree)
457e8d8bef9SDimitry Andric       return false;
458e8d8bef9SDimitry Andric   }
459e8d8bef9SDimitry Andric   return true;
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric /// This allocates space for the specified virtual register to be held on the
4630b57cec5SDimitry Andric /// stack.
464*0fca6ea1SDimitry Andric int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
4650b57cec5SDimitry Andric   // Find the location Reg would belong...
4660b57cec5SDimitry Andric   int SS = StackSlotForVirtReg[VirtReg];
4670b57cec5SDimitry Andric   // Already has space allocated?
4680b57cec5SDimitry Andric   if (SS != -1)
4690b57cec5SDimitry Andric     return SS;
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   // Allocate a new stack object for this spill location...
4720b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
4730b57cec5SDimitry Andric   unsigned Size = TRI->getSpillSize(RC);
4745ffd83dbSDimitry Andric   Align Alignment = TRI->getSpillAlign(RC);
4755ffd83dbSDimitry Andric   int FrameIdx = MFI->CreateSpillStackObject(Size, Alignment);
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // Assign the slot.
4780b57cec5SDimitry Andric   StackSlotForVirtReg[VirtReg] = FrameIdx;
4790b57cec5SDimitry Andric   return FrameIdx;
4800b57cec5SDimitry Andric }
4810b57cec5SDimitry Andric 
482cb14a3feSDimitry Andric static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
483cb14a3feSDimitry Andric                       const MachineInstr &B) {
484cb14a3feSDimitry Andric   uint64_t IndexA, IndexB;
485cb14a3feSDimitry Andric   PosIndexes.getIndex(A, IndexA);
486cb14a3feSDimitry Andric   if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
487cb14a3feSDimitry Andric     PosIndexes.getIndex(A, IndexA);
488cb14a3feSDimitry Andric   return IndexA < IndexB;
489e8d8bef9SDimitry Andric }
490e8d8bef9SDimitry Andric 
4910b57cec5SDimitry Andric /// Returns false if \p VirtReg is known to not live out of the current block.
492*0fca6ea1SDimitry Andric bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
4938bcb0991SDimitry Andric   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg))) {
4940b57cec5SDimitry Andric     // Cannot be live-out if there are no successors.
4950b57cec5SDimitry Andric     return !MBB->succ_empty();
4960b57cec5SDimitry Andric   }
4970b57cec5SDimitry Andric 
498e8d8bef9SDimitry Andric   const MachineInstr *SelfLoopDef = nullptr;
499e8d8bef9SDimitry Andric 
500e8d8bef9SDimitry Andric   // If this block loops back to itself, it is necessary to check whether the
501e8d8bef9SDimitry Andric   // use comes after the def.
5020b57cec5SDimitry Andric   if (MBB->isSuccessor(MBB)) {
50381ad6265SDimitry Andric     // Find the first def in the self loop MBB.
50481ad6265SDimitry Andric     for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
50581ad6265SDimitry Andric       if (DefInst.getParent() != MBB) {
50681ad6265SDimitry Andric         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
50781ad6265SDimitry Andric         return true;
50881ad6265SDimitry Andric       } else {
509cb14a3feSDimitry Andric         if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
51081ad6265SDimitry Andric           SelfLoopDef = &DefInst;
51181ad6265SDimitry Andric       }
51281ad6265SDimitry Andric     }
513e8d8bef9SDimitry Andric     if (!SelfLoopDef) {
5148bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
5150b57cec5SDimitry Andric       return true;
5160b57cec5SDimitry Andric     }
517e8d8bef9SDimitry Andric   }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // See if the first \p Limit uses of the register are all in the current
5200b57cec5SDimitry Andric   // block.
5210b57cec5SDimitry Andric   static const unsigned Limit = 8;
5220b57cec5SDimitry Andric   unsigned C = 0;
523e8d8bef9SDimitry Andric   for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
5240b57cec5SDimitry Andric     if (UseInst.getParent() != MBB || ++C >= Limit) {
5258bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
5260b57cec5SDimitry Andric       // Cannot be live-out if there are no successors.
5270b57cec5SDimitry Andric       return !MBB->succ_empty();
5280b57cec5SDimitry Andric     }
529e8d8bef9SDimitry Andric 
530e8d8bef9SDimitry Andric     if (SelfLoopDef) {
531e8d8bef9SDimitry Andric       // Try to handle some simple cases to avoid spilling and reloading every
532e8d8bef9SDimitry Andric       // value inside a self looping block.
533e8d8bef9SDimitry Andric       if (SelfLoopDef == &UseInst ||
534cb14a3feSDimitry Andric           !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
535e8d8bef9SDimitry Andric         MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
536e8d8bef9SDimitry Andric         return true;
537e8d8bef9SDimitry Andric       }
538e8d8bef9SDimitry Andric     }
5390b57cec5SDimitry Andric   }
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   return false;
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric /// Returns false if \p VirtReg is known to not be live into the current block.
545*0fca6ea1SDimitry Andric bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
5468bcb0991SDimitry Andric   if (MayLiveAcrossBlocks.test(Register::virtReg2Index(VirtReg)))
5470b57cec5SDimitry Andric     return !MBB->pred_empty();
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   // See if the first \p Limit def of the register are all in the current block.
5500b57cec5SDimitry Andric   static const unsigned Limit = 8;
5510b57cec5SDimitry Andric   unsigned C = 0;
5520b57cec5SDimitry Andric   for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
5530b57cec5SDimitry Andric     if (DefInst.getParent() != MBB || ++C >= Limit) {
5548bcb0991SDimitry Andric       MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
5550b57cec5SDimitry Andric       return !MBB->pred_empty();
5560b57cec5SDimitry Andric     }
5570b57cec5SDimitry Andric   }
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric   return false;
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric /// Insert spill instruction for \p AssignedReg before \p Before. Update
5630b57cec5SDimitry Andric /// DBG_VALUEs with \p VirtReg operands with the stack slot.
564*0fca6ea1SDimitry Andric void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
565*0fca6ea1SDimitry Andric                              Register VirtReg, MCPhysReg AssignedReg, bool Kill,
566*0fca6ea1SDimitry Andric                              bool LiveOut) {
5675f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
5685f757f3fSDimitry Andric                     << printReg(AssignedReg, TRI));
5690b57cec5SDimitry Andric   int FI = getStackSpaceFor(VirtReg);
5700b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
573bdd1243dSDimitry Andric   TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, TRI,
574bdd1243dSDimitry Andric                            VirtReg);
5750b57cec5SDimitry Andric   ++NumStores;
5760b57cec5SDimitry Andric 
577e8d8bef9SDimitry Andric   MachineBasicBlock::iterator FirstTerm = MBB->getFirstTerminator();
578e8d8bef9SDimitry Andric 
579e8d8bef9SDimitry Andric   // When we spill a virtual register, we will have spill instructions behind
580e8d8bef9SDimitry Andric   // every definition of it, meaning we can switch all the DBG_VALUEs over
581e8d8bef9SDimitry Andric   // to just reference the stack slot.
582fe6060f1SDimitry Andric   SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
583349cc55cSDimitry Andric   SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
584fe6060f1SDimitry Andric       SpilledOperandsMap;
585fe6060f1SDimitry Andric   for (MachineOperand *MO : LRIDbgOperands)
586fe6060f1SDimitry Andric     SpilledOperandsMap[MO->getParent()].push_back(MO);
587fe6060f1SDimitry Andric   for (auto MISpilledOperands : SpilledOperandsMap) {
588fe6060f1SDimitry Andric     MachineInstr &DBG = *MISpilledOperands.first;
58950d7464cSDimitry Andric     // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
59050d7464cSDimitry Andric     if (DBG.isDebugValueList())
59150d7464cSDimitry Andric       continue;
592fe6060f1SDimitry Andric     MachineInstr *NewDV = buildDbgValueForSpill(
593fe6060f1SDimitry Andric         *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
5940b57cec5SDimitry Andric     assert(NewDV->getParent() == MBB && "dangling parent pointer");
5950b57cec5SDimitry Andric     (void)NewDV;
5960b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
597e8d8bef9SDimitry Andric 
598e8d8bef9SDimitry Andric     if (LiveOut) {
599e8d8bef9SDimitry Andric       // We need to insert a DBG_VALUE at the end of the block if the spill slot
600e8d8bef9SDimitry Andric       // is live out, but there is another use of the value after the
601e8d8bef9SDimitry Andric       // spill. This will allow LiveDebugValues to see the correct live out
602e8d8bef9SDimitry Andric       // value to propagate to the successors.
603e8d8bef9SDimitry Andric       MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
604e8d8bef9SDimitry Andric       MBB->insert(FirstTerm, ClonedDV);
605e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
606e8d8bef9SDimitry Andric     }
607e8d8bef9SDimitry Andric 
608e8d8bef9SDimitry Andric     // Rewrite unassigned dbg_values to use the stack slot.
609fe6060f1SDimitry Andric     // TODO We can potentially do this for list debug values as well if we know
610fe6060f1SDimitry Andric     // how the dbg_values are getting unassigned.
611fe6060f1SDimitry Andric     if (DBG.isNonListDebugValue()) {
612fe6060f1SDimitry Andric       MachineOperand &MO = DBG.getDebugOperand(0);
613fe6060f1SDimitry Andric       if (MO.isReg() && MO.getReg() == 0) {
614fe6060f1SDimitry Andric         updateDbgValueForSpill(DBG, FI, 0);
615fe6060f1SDimitry Andric       }
616fe6060f1SDimitry Andric     }
6170b57cec5SDimitry Andric   }
6180b57cec5SDimitry Andric   // Now this register is spilled there is should not be any DBG_VALUE
6190b57cec5SDimitry Andric   // pointing to this register because they are all pointing to spilled value
6200b57cec5SDimitry Andric   // now.
621fe6060f1SDimitry Andric   LRIDbgOperands.clear();
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric /// Insert reload instruction for \p PhysReg before \p Before.
625*0fca6ea1SDimitry Andric void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
626*0fca6ea1SDimitry Andric                               Register VirtReg, MCPhysReg PhysReg) {
6270b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
6280b57cec5SDimitry Andric                     << printReg(PhysReg, TRI) << '\n');
6290b57cec5SDimitry Andric   int FI = getStackSpaceFor(VirtReg);
6300b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
631bdd1243dSDimitry Andric   TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, TRI, VirtReg);
6320b57cec5SDimitry Andric   ++NumLoads;
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric 
635e8d8bef9SDimitry Andric /// Get basic block begin insertion point.
636e8d8bef9SDimitry Andric /// This is not just MBB.begin() because surprisingly we have EH_LABEL
637e8d8bef9SDimitry Andric /// instructions marking the begin of a basic block. This means we must insert
638e8d8bef9SDimitry Andric /// new instructions after such labels...
639*0fca6ea1SDimitry Andric MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
640e8d8bef9SDimitry Andric     MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
641e8d8bef9SDimitry Andric   MachineBasicBlock::iterator I = MBB.begin();
642e8d8bef9SDimitry Andric   while (I != MBB.end()) {
643e8d8bef9SDimitry Andric     if (I->isLabel()) {
644e8d8bef9SDimitry Andric       ++I;
645e8d8bef9SDimitry Andric       continue;
6460b57cec5SDimitry Andric     }
6470b57cec5SDimitry Andric 
648e8d8bef9SDimitry Andric     // Most reloads should be inserted after prolog instructions.
649e8d8bef9SDimitry Andric     if (!TII->isBasicBlockPrologue(*I))
650e8d8bef9SDimitry Andric       break;
651e8d8bef9SDimitry Andric 
652e8d8bef9SDimitry Andric     // However if a prolog instruction reads a register that needs to be
653e8d8bef9SDimitry Andric     // reloaded, the reload should be inserted before the prolog.
654e8d8bef9SDimitry Andric     for (MachineOperand &MO : I->operands()) {
655e8d8bef9SDimitry Andric       if (MO.isReg())
656e8d8bef9SDimitry Andric         PrologLiveIns.insert(MO.getReg());
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric 
659e8d8bef9SDimitry Andric     ++I;
6600b57cec5SDimitry Andric   }
6610b57cec5SDimitry Andric 
662e8d8bef9SDimitry Andric   return I;
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
665e8d8bef9SDimitry Andric /// Reload all currently assigned virtual registers.
666*0fca6ea1SDimitry Andric void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
6670b57cec5SDimitry Andric   if (LiveVirtRegs.empty())
6680b57cec5SDimitry Andric     return;
669e8d8bef9SDimitry Andric 
670e8d8bef9SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
671e8d8bef9SDimitry Andric     MCPhysReg Reg = P.PhysReg;
672e8d8bef9SDimitry Andric     // Set state to live-in. This possibly overrides mappings to virtual
673e8d8bef9SDimitry Andric     // registers but we don't care anymore at this point.
674e8d8bef9SDimitry Andric     setPhysRegState(Reg, regLiveIn);
675e8d8bef9SDimitry Andric   }
676e8d8bef9SDimitry Andric 
677e8d8bef9SDimitry Andric   SmallSet<Register, 2> PrologLiveIns;
678e8d8bef9SDimitry Andric 
6790b57cec5SDimitry Andric   // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
6800b57cec5SDimitry Andric   // of spilling here is deterministic, if arbitrary.
6815f757f3fSDimitry Andric   MachineBasicBlock::iterator InsertBefore =
6825f757f3fSDimitry Andric       getMBBBeginInsertionPoint(MBB, PrologLiveIns);
683e8d8bef9SDimitry Andric   for (const LiveReg &LR : LiveVirtRegs) {
684e8d8bef9SDimitry Andric     MCPhysReg PhysReg = LR.PhysReg;
685e8d8bef9SDimitry Andric     if (PhysReg == 0)
6860b57cec5SDimitry Andric       continue;
687e8d8bef9SDimitry Andric 
68806c3fb27SDimitry Andric     MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
689e8d8bef9SDimitry Andric     if (RegUnitStates[FirstUnit] == regLiveIn)
6900b57cec5SDimitry Andric       continue;
691e8d8bef9SDimitry Andric 
692e8d8bef9SDimitry Andric     assert((&MBB != &MBB.getParent()->front() || IgnoreMissingDefs) &&
693e8d8bef9SDimitry Andric            "no reload in start block. Missing vreg def?");
694e8d8bef9SDimitry Andric 
695e8d8bef9SDimitry Andric     if (PrologLiveIns.count(PhysReg)) {
696e8d8bef9SDimitry Andric       // FIXME: Theoretically this should use an insert point skipping labels
697e8d8bef9SDimitry Andric       // but I'm not sure how labels should interact with prolog instruction
698e8d8bef9SDimitry Andric       // that need reloads.
699e8d8bef9SDimitry Andric       reload(MBB.begin(), LR.VirtReg, PhysReg);
700e8d8bef9SDimitry Andric     } else
701e8d8bef9SDimitry Andric       reload(InsertBefore, LR.VirtReg, PhysReg);
7020b57cec5SDimitry Andric   }
7030b57cec5SDimitry Andric   LiveVirtRegs.clear();
7040b57cec5SDimitry Andric }
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric /// Handle the direct use of a physical register.  Check that the register is
7070b57cec5SDimitry Andric /// not used by a virtreg. Kill the physreg, marking it free. This may add
7080b57cec5SDimitry Andric /// implicit kills to MO->getParent() and invalidate MO.
709*0fca6ea1SDimitry Andric bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCPhysReg Reg) {
710e8d8bef9SDimitry Andric   assert(Register::isPhysicalRegister(Reg) && "expected physreg");
711e8d8bef9SDimitry Andric   bool displacedAny = displacePhysReg(MI, Reg);
712e8d8bef9SDimitry Andric   setPhysRegState(Reg, regPreAssigned);
713e8d8bef9SDimitry Andric   markRegUsedInInstr(Reg);
714e8d8bef9SDimitry Andric   return displacedAny;
71516d6b3b3SDimitry Andric }
71616d6b3b3SDimitry Andric 
717*0fca6ea1SDimitry Andric bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCPhysReg Reg) {
718e8d8bef9SDimitry Andric   bool displacedAny = displacePhysReg(MI, Reg);
719e8d8bef9SDimitry Andric   setPhysRegState(Reg, regPreAssigned);
720e8d8bef9SDimitry Andric   return displacedAny;
7210b57cec5SDimitry Andric }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
7240b57cec5SDimitry Andric /// similar to defineVirtReg except the physreg is reserved instead of
7250b57cec5SDimitry Andric /// allocated.
726*0fca6ea1SDimitry Andric bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCPhysReg PhysReg) {
727e8d8bef9SDimitry Andric   bool displacedAny = false;
728e8d8bef9SDimitry Andric 
72906c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
730e8d8bef9SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
731e8d8bef9SDimitry Andric     default: {
732e8d8bef9SDimitry Andric       LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
733e8d8bef9SDimitry Andric       assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
734e8d8bef9SDimitry Andric       MachineBasicBlock::iterator ReloadBefore =
735e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
736e8d8bef9SDimitry Andric       reload(ReloadBefore, VirtReg, LRI->PhysReg);
737e8d8bef9SDimitry Andric 
738e8d8bef9SDimitry Andric       setPhysRegState(LRI->PhysReg, regFree);
739e8d8bef9SDimitry Andric       LRI->PhysReg = 0;
740e8d8bef9SDimitry Andric       LRI->Reloaded = true;
741e8d8bef9SDimitry Andric       displacedAny = true;
74216d6b3b3SDimitry Andric       break;
743e8d8bef9SDimitry Andric     }
744e8d8bef9SDimitry Andric     case regPreAssigned:
745e8d8bef9SDimitry Andric       RegUnitStates[Unit] = regFree;
746e8d8bef9SDimitry Andric       displacedAny = true;
747e8d8bef9SDimitry Andric       break;
7480b57cec5SDimitry Andric     case regFree:
749e8d8bef9SDimitry Andric       break;
750e8d8bef9SDimitry Andric     }
751e8d8bef9SDimitry Andric   }
752e8d8bef9SDimitry Andric   return displacedAny;
75316d6b3b3SDimitry Andric }
75416d6b3b3SDimitry Andric 
755*0fca6ea1SDimitry Andric void RegAllocFastImpl::freePhysReg(MCPhysReg PhysReg) {
756e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
757e8d8bef9SDimitry Andric 
75806c3fb27SDimitry Andric   MCRegister FirstUnit = *TRI->regunits(PhysReg).begin();
759e8d8bef9SDimitry Andric   switch (unsigned VirtReg = RegUnitStates[FirstUnit]) {
76016d6b3b3SDimitry Andric   case regFree:
761e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
76216d6b3b3SDimitry Andric     return;
763e8d8bef9SDimitry Andric   case regPreAssigned:
764e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
765e8d8bef9SDimitry Andric     setPhysRegState(PhysReg, regFree);
766e8d8bef9SDimitry Andric     return;
767e8d8bef9SDimitry Andric   default: {
768e8d8bef9SDimitry Andric     LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
769e8d8bef9SDimitry Andric     assert(LRI != LiveVirtRegs.end());
770e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
771e8d8bef9SDimitry Andric     setPhysRegState(LRI->PhysReg, regFree);
772e8d8bef9SDimitry Andric     LRI->PhysReg = 0;
7735ffd83dbSDimitry Andric   }
774e8d8bef9SDimitry Andric     return;
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric }
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric /// Return the cost of spilling clearing out PhysReg and aliases so it is free
7790b57cec5SDimitry Andric /// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
7800b57cec5SDimitry Andric /// disabled - it can be allocated directly.
7810b57cec5SDimitry Andric /// \returns spillImpossible when PhysReg or an alias can't be spilled.
782*0fca6ea1SDimitry Andric unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
78306c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
78406c3fb27SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
78516d6b3b3SDimitry Andric     case regFree:
786e8d8bef9SDimitry Andric       break;
787e8d8bef9SDimitry Andric     case regPreAssigned:
788e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
789e8d8bef9SDimitry Andric                         << printReg(PhysReg, TRI) << '\n');
7900b57cec5SDimitry Andric       return spillImpossible;
7910b57cec5SDimitry Andric     default: {
792e8d8bef9SDimitry Andric       bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
793e8d8bef9SDimitry Andric                        findLiveVirtReg(VirtReg)->LiveOut;
794e8d8bef9SDimitry Andric       return SureSpill ? spillClean : spillDirty;
7950b57cec5SDimitry Andric     }
7960b57cec5SDimitry Andric     }
797e8d8bef9SDimitry Andric   }
798e8d8bef9SDimitry Andric   return 0;
799e8d8bef9SDimitry Andric }
80016d6b3b3SDimitry Andric 
801*0fca6ea1SDimitry Andric void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
802*0fca6ea1SDimitry Andric                                                  Register VirtReg,
803*0fca6ea1SDimitry Andric                                                  MCPhysReg Reg) {
804e8d8bef9SDimitry Andric   auto UDBGValIter = DanglingDbgValues.find(VirtReg);
805e8d8bef9SDimitry Andric   if (UDBGValIter == DanglingDbgValues.end())
806e8d8bef9SDimitry Andric     return;
807e8d8bef9SDimitry Andric 
808e8d8bef9SDimitry Andric   SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
809e8d8bef9SDimitry Andric   for (MachineInstr *DbgValue : Dangling) {
810e8d8bef9SDimitry Andric     assert(DbgValue->isDebugValue());
811fe6060f1SDimitry Andric     if (!DbgValue->hasDebugOperandForReg(VirtReg))
812e8d8bef9SDimitry Andric       continue;
813e8d8bef9SDimitry Andric 
814e8d8bef9SDimitry Andric     // Test whether the physreg survives from the definition to the DBG_VALUE.
815e8d8bef9SDimitry Andric     MCPhysReg SetToReg = Reg;
816e8d8bef9SDimitry Andric     unsigned Limit = 20;
817e8d8bef9SDimitry Andric     for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
8185f757f3fSDimitry Andric                                      E = DbgValue->getIterator();
8195f757f3fSDimitry Andric          I != E; ++I) {
820e8d8bef9SDimitry Andric       if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
821e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
822e8d8bef9SDimitry Andric                           << '\n');
823e8d8bef9SDimitry Andric         SetToReg = 0;
82416d6b3b3SDimitry Andric         break;
8250b57cec5SDimitry Andric       }
82616d6b3b3SDimitry Andric     }
827fe6060f1SDimitry Andric     for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
828e8d8bef9SDimitry Andric       MO.setReg(SetToReg);
829e8d8bef9SDimitry Andric       if (SetToReg != 0)
830e8d8bef9SDimitry Andric         MO.setIsRenamable();
83116d6b3b3SDimitry Andric     }
832fe6060f1SDimitry Andric   }
833e8d8bef9SDimitry Andric   Dangling.clear();
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric /// This method updates local state so that we know that PhysReg is the
8370b57cec5SDimitry Andric /// proper container for VirtReg now.  The physical register must not be used
8380b57cec5SDimitry Andric /// for anything else when this is called.
839*0fca6ea1SDimitry Andric void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
840e8d8bef9SDimitry Andric                                            MCPhysReg PhysReg) {
841480093f4SDimitry Andric   Register VirtReg = LR.VirtReg;
8420b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
8430b57cec5SDimitry Andric                     << printReg(PhysReg, TRI) << '\n');
8440b57cec5SDimitry Andric   assert(LR.PhysReg == 0 && "Already assigned a physreg");
8450b57cec5SDimitry Andric   assert(PhysReg != 0 && "Trying to assign no register");
8460b57cec5SDimitry Andric   LR.PhysReg = PhysReg;
8470b57cec5SDimitry Andric   setPhysRegState(PhysReg, VirtReg);
848e8d8bef9SDimitry Andric 
849e8d8bef9SDimitry Andric   assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
8525f757f3fSDimitry Andric static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
8530b57cec5SDimitry Andric 
854*0fca6ea1SDimitry Andric Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
8550b57cec5SDimitry Andric   static const unsigned ChainLengthLimit = 3;
8560b57cec5SDimitry Andric   unsigned C = 0;
8570b57cec5SDimitry Andric   do {
858480093f4SDimitry Andric     if (Reg.isPhysical())
8590b57cec5SDimitry Andric       return Reg;
860480093f4SDimitry Andric     assert(Reg.isVirtual());
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric     MachineInstr *VRegDef = MRI->getUniqueVRegDef(Reg);
8630b57cec5SDimitry Andric     if (!VRegDef || !isCoalescable(*VRegDef))
8640b57cec5SDimitry Andric       return 0;
8650b57cec5SDimitry Andric     Reg = VRegDef->getOperand(1).getReg();
8660b57cec5SDimitry Andric   } while (++C <= ChainLengthLimit);
8670b57cec5SDimitry Andric   return 0;
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric /// Check if any of \p VirtReg's definitions is a copy. If it is follow the
8710b57cec5SDimitry Andric /// chain of copies to check whether we reach a physical register we can
8720b57cec5SDimitry Andric /// coalesce with.
873*0fca6ea1SDimitry Andric Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
8740b57cec5SDimitry Andric   static const unsigned DefLimit = 3;
8750b57cec5SDimitry Andric   unsigned C = 0;
8760b57cec5SDimitry Andric   for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
8770b57cec5SDimitry Andric     if (isCoalescable(MI)) {
8788bcb0991SDimitry Andric       Register Reg = MI.getOperand(1).getReg();
8790b57cec5SDimitry Andric       Reg = traceCopyChain(Reg);
880480093f4SDimitry Andric       if (Reg.isValid())
8810b57cec5SDimitry Andric         return Reg;
8820b57cec5SDimitry Andric     }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric     if (++C >= DefLimit)
8850b57cec5SDimitry Andric       break;
8860b57cec5SDimitry Andric   }
887480093f4SDimitry Andric   return Register();
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric /// Allocates a physical register for VirtReg.
891*0fca6ea1SDimitry Andric void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
892*0fca6ea1SDimitry Andric                                     Register Hint0, bool LookAtPhysRegUses) {
893480093f4SDimitry Andric   const Register VirtReg = LR.VirtReg;
894e8d8bef9SDimitry Andric   assert(LR.PhysReg == 0);
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
8970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
8980b57cec5SDimitry Andric                     << " in class " << TRI->getRegClassName(&RC)
8990b57cec5SDimitry Andric                     << " with hint " << printReg(Hint0, TRI) << '\n');
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric   // Take hint when possible.
902e8d8bef9SDimitry Andric   if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
903e8d8bef9SDimitry Andric       !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
904e8d8bef9SDimitry Andric     // Take hint if the register is currently free.
905e8d8bef9SDimitry Andric     if (isPhysRegFree(Hint0)) {
9060b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
9070b57cec5SDimitry Andric                         << '\n');
908e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, Hint0);
9090b57cec5SDimitry Andric       return;
9100b57cec5SDimitry Andric     } else {
911e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
9120b57cec5SDimitry Andric                         << " occupied\n");
9130b57cec5SDimitry Andric     }
9140b57cec5SDimitry Andric   } else {
915480093f4SDimitry Andric     Hint0 = Register();
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   // Try other hint.
919480093f4SDimitry Andric   Register Hint1 = traceCopies(VirtReg);
920e8d8bef9SDimitry Andric   if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
921e8d8bef9SDimitry Andric       !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
922e8d8bef9SDimitry Andric     // Take hint if the register is currently free.
923e8d8bef9SDimitry Andric     if (isPhysRegFree(Hint1)) {
9240b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
9250b57cec5SDimitry Andric                         << '\n');
926e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, Hint1);
9270b57cec5SDimitry Andric       return;
9280b57cec5SDimitry Andric     } else {
929e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
9300b57cec5SDimitry Andric                         << " occupied\n");
9310b57cec5SDimitry Andric     }
9320b57cec5SDimitry Andric   } else {
933480093f4SDimitry Andric     Hint1 = Register();
9340b57cec5SDimitry Andric   }
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric   MCPhysReg BestReg = 0;
9370b57cec5SDimitry Andric   unsigned BestCost = spillImpossible;
9380b57cec5SDimitry Andric   ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
9390b57cec5SDimitry Andric   for (MCPhysReg PhysReg : AllocationOrder) {
9400b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
941e8d8bef9SDimitry Andric     if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
942e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "already used in instr.\n");
943e8d8bef9SDimitry Andric       continue;
944e8d8bef9SDimitry Andric     }
945e8d8bef9SDimitry Andric 
9460b57cec5SDimitry Andric     unsigned Cost = calcSpillCost(PhysReg);
9470b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
9480b57cec5SDimitry Andric     // Immediate take a register with cost 0.
9490b57cec5SDimitry Andric     if (Cost == 0) {
950e8d8bef9SDimitry Andric       assignVirtToPhysReg(MI, LR, PhysReg);
9510b57cec5SDimitry Andric       return;
9520b57cec5SDimitry Andric     }
9530b57cec5SDimitry Andric 
954e8d8bef9SDimitry Andric     if (PhysReg == Hint0 || PhysReg == Hint1)
9550b57cec5SDimitry Andric       Cost -= spillPrefBonus;
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric     if (Cost < BestCost) {
9580b57cec5SDimitry Andric       BestReg = PhysReg;
9590b57cec5SDimitry Andric       BestCost = Cost;
9600b57cec5SDimitry Andric     }
9610b57cec5SDimitry Andric   }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   if (!BestReg) {
9640b57cec5SDimitry Andric     // Nothing we can do: Report an error and keep going with an invalid
9650b57cec5SDimitry Andric     // allocation.
9660b57cec5SDimitry Andric     if (MI.isInlineAsm())
9670b57cec5SDimitry Andric       MI.emitError("inline assembly requires more registers than available");
9680b57cec5SDimitry Andric     else
9690b57cec5SDimitry Andric       MI.emitError("ran out of registers during register allocation");
970e8d8bef9SDimitry Andric 
971e8d8bef9SDimitry Andric     LR.Error = true;
972e8d8bef9SDimitry Andric     LR.PhysReg = 0;
9730b57cec5SDimitry Andric     return;
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
976e8d8bef9SDimitry Andric   displacePhysReg(MI, BestReg);
977e8d8bef9SDimitry Andric   assignVirtToPhysReg(MI, LR, BestReg);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
980*0fca6ea1SDimitry Andric void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
9810b57cec5SDimitry Andric   assert(MO.isUndef() && "expected undef use");
9828bcb0991SDimitry Andric   Register VirtReg = MO.getReg();
983bdd1243dSDimitry Andric   assert(VirtReg.isVirtual() && "Expected virtreg");
984bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
985bdd1243dSDimitry Andric     return;
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   LiveRegMap::const_iterator LRI = findLiveVirtReg(VirtReg);
9880b57cec5SDimitry Andric   MCPhysReg PhysReg;
9890b57cec5SDimitry Andric   if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
9900b57cec5SDimitry Andric     PhysReg = LRI->PhysReg;
9910b57cec5SDimitry Andric   } else {
9920b57cec5SDimitry Andric     const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
9930b57cec5SDimitry Andric     ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
9940b57cec5SDimitry Andric     assert(!AllocationOrder.empty() && "Allocation order must not be empty");
9950b57cec5SDimitry Andric     PhysReg = AllocationOrder[0];
9960b57cec5SDimitry Andric   }
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric   unsigned SubRegIdx = MO.getSubReg();
9990b57cec5SDimitry Andric   if (SubRegIdx != 0) {
10000b57cec5SDimitry Andric     PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
10010b57cec5SDimitry Andric     MO.setSubReg(0);
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric   MO.setReg(PhysReg);
10040b57cec5SDimitry Andric   MO.setIsRenamable(true);
10050b57cec5SDimitry Andric }
10060b57cec5SDimitry Andric 
1007e8d8bef9SDimitry Andric /// Variation of defineVirtReg() with special handling for livethrough regs
1008e8d8bef9SDimitry Andric /// (tied or earlyclobber) that may interfere with preassigned uses.
100906c3fb27SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
1010*0fca6ea1SDimitry Andric bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1011*0fca6ea1SDimitry Andric                                                 unsigned OpNum,
1012e8d8bef9SDimitry Andric                                                 Register VirtReg) {
1013bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
101406c3fb27SDimitry Andric     return false;
1015e8d8bef9SDimitry Andric   LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1016e8d8bef9SDimitry Andric   if (LRI != LiveVirtRegs.end()) {
1017e8d8bef9SDimitry Andric     MCPhysReg PrevReg = LRI->PhysReg;
1018e8d8bef9SDimitry Andric     if (PrevReg != 0 && isRegUsedInInstr(PrevReg, true)) {
1019e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1020e8d8bef9SDimitry Andric                         << " (tied/earlyclobber resolution)\n");
1021e8d8bef9SDimitry Andric       freePhysReg(PrevReg);
1022e8d8bef9SDimitry Andric       LRI->PhysReg = 0;
1023e8d8bef9SDimitry Andric       allocVirtReg(MI, *LRI, 0, true);
1024e8d8bef9SDimitry Andric       MachineBasicBlock::iterator InsertBefore =
1025e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
1026e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1027e8d8bef9SDimitry Andric                         << printReg(PrevReg, TRI) << '\n');
1028e8d8bef9SDimitry Andric       BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1029e8d8bef9SDimitry Andric               TII->get(TargetOpcode::COPY), PrevReg)
1030e8d8bef9SDimitry Andric           .addReg(LRI->PhysReg, llvm::RegState::Kill);
10310b57cec5SDimitry Andric     }
1032e8d8bef9SDimitry Andric     MachineOperand &MO = MI.getOperand(OpNum);
1033e8d8bef9SDimitry Andric     if (MO.getSubReg() && !MO.isUndef()) {
10340b57cec5SDimitry Andric       LRI->LastUse = &MI;
1035e8d8bef9SDimitry Andric     }
1036e8d8bef9SDimitry Andric   }
1037e8d8bef9SDimitry Andric   return defineVirtReg(MI, OpNum, VirtReg, true);
10380b57cec5SDimitry Andric }
10390b57cec5SDimitry Andric 
1040e8d8bef9SDimitry Andric /// Allocates a register for VirtReg definition. Typically the register is
1041e8d8bef9SDimitry Andric /// already assigned from a use of the virtreg, however we still need to
1042e8d8bef9SDimitry Andric /// perform an allocation if:
1043e8d8bef9SDimitry Andric /// - It is a dead definition without any uses.
1044e8d8bef9SDimitry Andric /// - The value is live out and all uses are in different basic blocks.
104506c3fb27SDimitry Andric ///
104606c3fb27SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
1047*0fca6ea1SDimitry Andric bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1048e8d8bef9SDimitry Andric                                      Register VirtReg, bool LookAtPhysRegUses) {
1049e8d8bef9SDimitry Andric   assert(VirtReg.isVirtual() && "Not a virtual register");
1050bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
105106c3fb27SDimitry Andric     return false;
1052e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpNum);
10530b57cec5SDimitry Andric   LiveRegMap::iterator LRI;
10540b57cec5SDimitry Andric   bool New;
10550b57cec5SDimitry Andric   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1056e8d8bef9SDimitry Andric   if (New) {
1057e8d8bef9SDimitry Andric     if (!MO.isDead()) {
1058e8d8bef9SDimitry Andric       if (mayLiveOut(VirtReg)) {
1059e8d8bef9SDimitry Andric         LRI->LiveOut = true;
1060e8d8bef9SDimitry Andric       } else {
1061e8d8bef9SDimitry Andric         // It is a dead def without the dead flag; add the flag now.
1062e8d8bef9SDimitry Andric         MO.setIsDead(true);
1063e8d8bef9SDimitry Andric       }
1064e8d8bef9SDimitry Andric     }
1065e8d8bef9SDimitry Andric   }
10665f757f3fSDimitry Andric   if (LRI->PhysReg == 0) {
1067e8d8bef9SDimitry Andric     allocVirtReg(MI, *LRI, 0, LookAtPhysRegUses);
10685f757f3fSDimitry Andric     // If no physical register is available for LRI, we assign one at random
10695f757f3fSDimitry Andric     // and bail out of this function immediately.
10705f757f3fSDimitry Andric     if (LRI->Error) {
10715f757f3fSDimitry Andric       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
10725f757f3fSDimitry Andric       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
10735f757f3fSDimitry Andric       if (AllocationOrder.empty())
10745f757f3fSDimitry Andric         return setPhysReg(MI, MO, MCRegister::NoRegister);
10755f757f3fSDimitry Andric       return setPhysReg(MI, MO, *AllocationOrder.begin());
10765f757f3fSDimitry Andric     }
10775f757f3fSDimitry Andric   } else {
1078e8d8bef9SDimitry Andric     assert(!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) &&
1079e8d8bef9SDimitry Andric            "TODO: preassign mismatch");
1080e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1081e8d8bef9SDimitry Andric                       << " use existing assignment to "
1082e8d8bef9SDimitry Andric                       << printReg(LRI->PhysReg, TRI) << '\n');
1083e8d8bef9SDimitry Andric   }
1084e8d8bef9SDimitry Andric 
1085e8d8bef9SDimitry Andric   MCPhysReg PhysReg = LRI->PhysReg;
1086e8d8bef9SDimitry Andric   if (LRI->Reloaded || LRI->LiveOut) {
1087e8d8bef9SDimitry Andric     if (!MI.isImplicitDef()) {
1088e8d8bef9SDimitry Andric       MachineBasicBlock::iterator SpillBefore =
1089e8d8bef9SDimitry Andric           std::next((MachineBasicBlock::iterator)MI.getIterator());
10905f757f3fSDimitry Andric       LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
10915f757f3fSDimitry Andric                         << " RL: " << LRI->Reloaded << '\n');
1092e8d8bef9SDimitry Andric       bool Kill = LRI->LastUse == nullptr;
1093e8d8bef9SDimitry Andric       spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
109406c3fb27SDimitry Andric 
109506c3fb27SDimitry Andric       // We need to place additional spills for each indirect destination of an
109606c3fb27SDimitry Andric       // INLINEASM_BR.
109706c3fb27SDimitry Andric       if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
109806c3fb27SDimitry Andric         int FI = StackSlotForVirtReg[VirtReg];
109906c3fb27SDimitry Andric         const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
110006c3fb27SDimitry Andric         for (MachineOperand &MO : MI.operands()) {
110106c3fb27SDimitry Andric           if (MO.isMBB()) {
110206c3fb27SDimitry Andric             MachineBasicBlock *Succ = MO.getMBB();
11035f757f3fSDimitry Andric             TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
11045f757f3fSDimitry Andric                                      &RC, TRI, VirtReg);
110506c3fb27SDimitry Andric             ++NumStores;
110606c3fb27SDimitry Andric             Succ->addLiveIn(PhysReg);
110706c3fb27SDimitry Andric           }
110806c3fb27SDimitry Andric         }
110906c3fb27SDimitry Andric       }
111006c3fb27SDimitry Andric 
1111e8d8bef9SDimitry Andric       LRI->LastUse = nullptr;
1112e8d8bef9SDimitry Andric     }
1113e8d8bef9SDimitry Andric     LRI->LiveOut = false;
1114e8d8bef9SDimitry Andric     LRI->Reloaded = false;
1115e8d8bef9SDimitry Andric   }
1116e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1117e8d8bef9SDimitry Andric     BundleVirtRegsMap[VirtReg] = PhysReg;
1118e8d8bef9SDimitry Andric   }
1119e8d8bef9SDimitry Andric   markRegUsedInInstr(PhysReg);
112006c3fb27SDimitry Andric   return setPhysReg(MI, MO, PhysReg);
1121e8d8bef9SDimitry Andric }
1122e8d8bef9SDimitry Andric 
1123e8d8bef9SDimitry Andric /// Allocates a register for a VirtReg use.
112406c3fb27SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
1125*0fca6ea1SDimitry Andric bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1126e8d8bef9SDimitry Andric                                   Register VirtReg) {
1127e8d8bef9SDimitry Andric   assert(VirtReg.isVirtual() && "Not a virtual register");
1128bdd1243dSDimitry Andric   if (!shouldAllocateRegister(VirtReg))
112906c3fb27SDimitry Andric     return false;
1130e8d8bef9SDimitry Andric   LiveRegMap::iterator LRI;
1131e8d8bef9SDimitry Andric   bool New;
1132e8d8bef9SDimitry Andric   std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1133e8d8bef9SDimitry Andric   if (New) {
1134e8d8bef9SDimitry Andric     if (!MO.isKill()) {
1135e8d8bef9SDimitry Andric       if (mayLiveOut(VirtReg)) {
1136e8d8bef9SDimitry Andric         LRI->LiveOut = true;
1137e8d8bef9SDimitry Andric       } else {
1138e8d8bef9SDimitry Andric         // It is a last (killing) use without the kill flag; add the flag now.
1139e8d8bef9SDimitry Andric         MO.setIsKill(true);
11400b57cec5SDimitry Andric       }
11410b57cec5SDimitry Andric     }
1142e8d8bef9SDimitry Andric   } else {
1143e8d8bef9SDimitry Andric     assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1144e8d8bef9SDimitry Andric   }
1145e8d8bef9SDimitry Andric 
1146e8d8bef9SDimitry Andric   // If necessary allocate a register.
1147e8d8bef9SDimitry Andric   if (LRI->PhysReg == 0) {
1148e8d8bef9SDimitry Andric     assert(!MO.isTied() && "tied op should be allocated");
1149e8d8bef9SDimitry Andric     Register Hint;
1150e8d8bef9SDimitry Andric     if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1151e8d8bef9SDimitry Andric       Hint = MI.getOperand(0).getReg();
1152bdd1243dSDimitry Andric       if (Hint.isVirtual()) {
1153bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Hint));
1154bdd1243dSDimitry Andric         Hint = Register();
1155bdd1243dSDimitry Andric       } else {
1156e8d8bef9SDimitry Andric         assert(Hint.isPhysical() &&
1157e8d8bef9SDimitry Andric                "Copy destination should already be assigned");
1158e8d8bef9SDimitry Andric       }
1159bdd1243dSDimitry Andric     }
1160e8d8bef9SDimitry Andric     allocVirtReg(MI, *LRI, Hint, false);
1161e8d8bef9SDimitry Andric     if (LRI->Error) {
1162e8d8bef9SDimitry Andric       const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1163e8d8bef9SDimitry Andric       ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
11645f757f3fSDimitry Andric       if (AllocationOrder.empty())
11655f757f3fSDimitry Andric         return setPhysReg(MI, MO, MCRegister::NoRegister);
116606c3fb27SDimitry Andric       return setPhysReg(MI, MO, *AllocationOrder.begin());
1167e8d8bef9SDimitry Andric     }
1168e8d8bef9SDimitry Andric   }
1169e8d8bef9SDimitry Andric 
11700b57cec5SDimitry Andric   LRI->LastUse = &MI;
1171e8d8bef9SDimitry Andric 
1172e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1173e8d8bef9SDimitry Andric     BundleVirtRegsMap[VirtReg] = LRI->PhysReg;
1174e8d8bef9SDimitry Andric   }
11750b57cec5SDimitry Andric   markRegUsedInInstr(LRI->PhysReg);
117606c3fb27SDimitry Andric   return setPhysReg(MI, MO, LRI->PhysReg);
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
117906c3fb27SDimitry Andric /// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
118006c3fb27SDimitry Andric /// \return true if MI's MachineOperands were re-arranged/invalidated.
1181*0fca6ea1SDimitry Andric bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
11820b57cec5SDimitry Andric                                   MCPhysReg PhysReg) {
11830b57cec5SDimitry Andric   if (!MO.getSubReg()) {
11840b57cec5SDimitry Andric     MO.setReg(PhysReg);
11850b57cec5SDimitry Andric     MO.setIsRenamable(true);
118606c3fb27SDimitry Andric     return false;
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // Handle subregister index.
1190e8d8bef9SDimitry Andric   MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : MCRegister());
11910b57cec5SDimitry Andric   MO.setIsRenamable(true);
1192e8d8bef9SDimitry Andric   // Note: We leave the subreg number around a little longer in case of defs.
1193e8d8bef9SDimitry Andric   // This is so that the register freeing logic in allocateInstruction can still
1194e8d8bef9SDimitry Andric   // recognize this as subregister defs. The code there will clear the number.
1195e8d8bef9SDimitry Andric   if (!MO.isDef())
11960b57cec5SDimitry Andric     MO.setSubReg(0);
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   // A kill flag implies killing the full register. Add corresponding super
11990b57cec5SDimitry Andric   // register kill.
12000b57cec5SDimitry Andric   if (MO.isKill()) {
12010b57cec5SDimitry Andric     MI.addRegisterKilled(PhysReg, TRI, true);
120206c3fb27SDimitry Andric     // Conservatively assume implicit MOs were re-arranged
120306c3fb27SDimitry Andric     return true;
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric   // A <def,read-undef> of a sub-register requires an implicit def of the full
12070b57cec5SDimitry Andric   // register.
1208e8d8bef9SDimitry Andric   if (MO.isDef() && MO.isUndef()) {
1209e8d8bef9SDimitry Andric     if (MO.isDead())
1210e8d8bef9SDimitry Andric       MI.addRegisterDead(PhysReg, TRI, true);
1211e8d8bef9SDimitry Andric     else
12120b57cec5SDimitry Andric       MI.addRegisterDefined(PhysReg, TRI);
121306c3fb27SDimitry Andric     // Conservatively assume implicit MOs were re-arranged
121406c3fb27SDimitry Andric     return true;
12150b57cec5SDimitry Andric   }
121606c3fb27SDimitry Andric   return false;
12170b57cec5SDimitry Andric }
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric #ifndef NDEBUG
1220e8d8bef9SDimitry Andric 
1221*0fca6ea1SDimitry Andric void RegAllocFastImpl::dumpState() const {
1222e8d8bef9SDimitry Andric   for (unsigned Unit = 1, UnitE = TRI->getNumRegUnits(); Unit != UnitE;
1223e8d8bef9SDimitry Andric        ++Unit) {
1224e8d8bef9SDimitry Andric     switch (unsigned VirtReg = RegUnitStates[Unit]) {
12250b57cec5SDimitry Andric     case regFree:
12260b57cec5SDimitry Andric       break;
1227e8d8bef9SDimitry Andric     case regPreAssigned:
1228e8d8bef9SDimitry Andric       dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
12290b57cec5SDimitry Andric       break;
1230e8d8bef9SDimitry Andric     case regLiveIn:
1231e8d8bef9SDimitry Andric       llvm_unreachable("Should not have regLiveIn in map");
12320b57cec5SDimitry Andric     default: {
1233e8d8bef9SDimitry Andric       dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1234e8d8bef9SDimitry Andric       LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1235e8d8bef9SDimitry Andric       assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1236e8d8bef9SDimitry Andric       if (I->LiveOut || I->Reloaded) {
1237e8d8bef9SDimitry Andric         dbgs() << '[';
12385f757f3fSDimitry Andric         if (I->LiveOut)
12395f757f3fSDimitry Andric           dbgs() << 'O';
12405f757f3fSDimitry Andric         if (I->Reloaded)
12415f757f3fSDimitry Andric           dbgs() << 'R';
1242e8d8bef9SDimitry Andric         dbgs() << ']';
1243e8d8bef9SDimitry Andric       }
1244e8d8bef9SDimitry Andric       assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
12450b57cec5SDimitry Andric       break;
12460b57cec5SDimitry Andric     }
12470b57cec5SDimitry Andric     }
12480b57cec5SDimitry Andric   }
12490b57cec5SDimitry Andric   dbgs() << '\n';
12500b57cec5SDimitry Andric   // Check that LiveVirtRegs is the inverse.
1251e8d8bef9SDimitry Andric   for (const LiveReg &LR : LiveVirtRegs) {
1252e8d8bef9SDimitry Andric     Register VirtReg = LR.VirtReg;
1253e8d8bef9SDimitry Andric     assert(VirtReg.isVirtual() && "Bad map key");
1254e8d8bef9SDimitry Andric     MCPhysReg PhysReg = LR.PhysReg;
1255e8d8bef9SDimitry Andric     if (PhysReg != 0) {
12565f757f3fSDimitry Andric       assert(Register::isPhysicalRegister(PhysReg) && "mapped to physreg");
125706c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
125806c3fb27SDimitry Andric         assert(RegUnitStates[Unit] == VirtReg && "inverse map valid");
1259e8d8bef9SDimitry Andric       }
1260e8d8bef9SDimitry Andric     }
12610b57cec5SDimitry Andric   }
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric #endif
12640b57cec5SDimitry Andric 
1265e8d8bef9SDimitry Andric /// Count number of defs consumed from each register class by \p Reg
1266*0fca6ea1SDimitry Andric void RegAllocFastImpl::addRegClassDefCounts(
1267*0fca6ea1SDimitry Andric     MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1268e8d8bef9SDimitry Andric   assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1269e8d8bef9SDimitry Andric 
1270e8d8bef9SDimitry Andric   if (Reg.isVirtual()) {
1271bdd1243dSDimitry Andric     if (!shouldAllocateRegister(Reg))
1272bdd1243dSDimitry Andric       return;
1273e8d8bef9SDimitry Andric     const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1274e8d8bef9SDimitry Andric     for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1275e8d8bef9SDimitry Andric          RCIdx != RCIdxEnd; ++RCIdx) {
1276e8d8bef9SDimitry Andric       const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1277e8d8bef9SDimitry Andric       // FIXME: Consider aliasing sub/super registers.
1278e8d8bef9SDimitry Andric       if (OpRC->hasSubClassEq(IdxRC))
1279e8d8bef9SDimitry Andric         ++RegClassDefCounts[RCIdx];
1280e8d8bef9SDimitry Andric     }
1281e8d8bef9SDimitry Andric 
1282e8d8bef9SDimitry Andric     return;
1283e8d8bef9SDimitry Andric   }
1284e8d8bef9SDimitry Andric 
1285e8d8bef9SDimitry Andric   for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1286e8d8bef9SDimitry Andric        RCIdx != RCIdxEnd; ++RCIdx) {
1287e8d8bef9SDimitry Andric     const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1288e8d8bef9SDimitry Andric     for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1289e8d8bef9SDimitry Andric       if (IdxRC->contains(*Alias)) {
1290e8d8bef9SDimitry Andric         ++RegClassDefCounts[RCIdx];
1291e8d8bef9SDimitry Andric         break;
1292e8d8bef9SDimitry Andric       }
1293e8d8bef9SDimitry Andric     }
1294e8d8bef9SDimitry Andric   }
1295e8d8bef9SDimitry Andric }
1296e8d8bef9SDimitry Andric 
129706c3fb27SDimitry Andric /// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
129806c3fb27SDimitry Andric /// that are to be allocated. Those are ordered in a way that small classes,
129906c3fb27SDimitry Andric /// early clobbers and livethroughs are allocated first.
1300*0fca6ea1SDimitry Andric void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
130106c3fb27SDimitry Andric   DefOperandIndexes.clear();
130206c3fb27SDimitry Andric 
130306c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
130406c3fb27SDimitry Andric   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
130506c3fb27SDimitry Andric     const MachineOperand &MO = MI.getOperand(I);
130606c3fb27SDimitry Andric     if (!MO.isReg())
130706c3fb27SDimitry Andric       continue;
130806c3fb27SDimitry Andric     Register Reg = MO.getReg();
130906c3fb27SDimitry Andric     if (MO.readsReg()) {
131006c3fb27SDimitry Andric       if (Reg.isPhysical()) {
131106c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
131206c3fb27SDimitry Andric         markPhysRegUsedInInstr(Reg);
131306c3fb27SDimitry Andric       }
131406c3fb27SDimitry Andric     }
131506c3fb27SDimitry Andric 
1316*0fca6ea1SDimitry Andric     if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
131706c3fb27SDimitry Andric       DefOperandIndexes.push_back(I);
131806c3fb27SDimitry Andric   }
131906c3fb27SDimitry Andric 
1320*0fca6ea1SDimitry Andric   // Most instructions only have one virtual def, so there's no point in
1321*0fca6ea1SDimitry Andric   // computing the possible number of defs for every register class.
1322*0fca6ea1SDimitry Andric   if (DefOperandIndexes.size() <= 1)
1323*0fca6ea1SDimitry Andric     return;
1324*0fca6ea1SDimitry Andric 
1325*0fca6ea1SDimitry Andric   // Track number of defs which may consume a register from the class. This is
1326*0fca6ea1SDimitry Andric   // used to assign registers for possibly-too-small classes first. Example:
1327*0fca6ea1SDimitry Andric   // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1328*0fca6ea1SDimitry Andric   // registers first so that the gr32 don't use the gr32_abcd registers before
1329*0fca6ea1SDimitry Andric   // we assign these.
1330*0fca6ea1SDimitry Andric   SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1331*0fca6ea1SDimitry Andric 
1332*0fca6ea1SDimitry Andric   for (const MachineOperand &MO : MI.operands())
1333*0fca6ea1SDimitry Andric     if (MO.isReg() && MO.isDef())
1334*0fca6ea1SDimitry Andric       addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1335*0fca6ea1SDimitry Andric 
1336*0fca6ea1SDimitry Andric   llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
133706c3fb27SDimitry Andric     const MachineOperand &MO0 = MI.getOperand(I0);
133806c3fb27SDimitry Andric     const MachineOperand &MO1 = MI.getOperand(I1);
133906c3fb27SDimitry Andric     Register Reg0 = MO0.getReg();
134006c3fb27SDimitry Andric     Register Reg1 = MO1.getReg();
134106c3fb27SDimitry Andric     const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
134206c3fb27SDimitry Andric     const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
134306c3fb27SDimitry Andric 
134406c3fb27SDimitry Andric     // Identify regclass that are easy to use up completely just in this
134506c3fb27SDimitry Andric     // instruction.
134606c3fb27SDimitry Andric     unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
134706c3fb27SDimitry Andric     unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
134806c3fb27SDimitry Andric 
134906c3fb27SDimitry Andric     bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
135006c3fb27SDimitry Andric     bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
135106c3fb27SDimitry Andric     if (SmallClass0 > SmallClass1)
135206c3fb27SDimitry Andric       return true;
135306c3fb27SDimitry Andric     if (SmallClass0 < SmallClass1)
135406c3fb27SDimitry Andric       return false;
135506c3fb27SDimitry Andric 
135606c3fb27SDimitry Andric     // Allocate early clobbers and livethrough operands first.
135706c3fb27SDimitry Andric     bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
135806c3fb27SDimitry Andric                         (MO0.getSubReg() == 0 && !MO0.isUndef());
135906c3fb27SDimitry Andric     bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
136006c3fb27SDimitry Andric                         (MO1.getSubReg() == 0 && !MO1.isUndef());
136106c3fb27SDimitry Andric     if (Livethrough0 > Livethrough1)
136206c3fb27SDimitry Andric       return true;
136306c3fb27SDimitry Andric     if (Livethrough0 < Livethrough1)
136406c3fb27SDimitry Andric       return false;
136506c3fb27SDimitry Andric 
136606c3fb27SDimitry Andric     // Tie-break rule: operand index.
136706c3fb27SDimitry Andric     return I0 < I1;
136806c3fb27SDimitry Andric   });
136906c3fb27SDimitry Andric }
137006c3fb27SDimitry Andric 
13715f757f3fSDimitry Andric // Returns true if MO is tied and the operand it's tied to is not Undef (not
13725f757f3fSDimitry Andric // Undef is not the same thing as Def).
13735f757f3fSDimitry Andric static bool isTiedToNotUndef(const MachineOperand &MO) {
13745f757f3fSDimitry Andric   if (!MO.isTied())
13755f757f3fSDimitry Andric     return false;
13765f757f3fSDimitry Andric   const MachineInstr &MI = *MO.getParent();
13775f757f3fSDimitry Andric   unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
13785f757f3fSDimitry Andric   const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
13795f757f3fSDimitry Andric   return !TiedMO.isUndef();
13805f757f3fSDimitry Andric }
13815f757f3fSDimitry Andric 
1382*0fca6ea1SDimitry Andric void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1383e8d8bef9SDimitry Andric   // The basic algorithm here is:
1384e8d8bef9SDimitry Andric   // 1. Mark registers of def operands as free
1385e8d8bef9SDimitry Andric   // 2. Allocate registers to use operands and place reload instructions for
1386e8d8bef9SDimitry Andric   //    registers displaced by the allocation.
1387e8d8bef9SDimitry Andric   //
1388e8d8bef9SDimitry Andric   // However we need to handle some corner cases:
1389e8d8bef9SDimitry Andric   // - pre-assigned defs and uses need to be handled before the other def/use
1390e8d8bef9SDimitry Andric   //   operands are processed to avoid the allocation heuristics clashing with
1391e8d8bef9SDimitry Andric   //   the pre-assignment.
1392e8d8bef9SDimitry Andric   // - The "free def operands" step has to come last instead of first for tied
1393e8d8bef9SDimitry Andric   //   operands and early-clobbers.
13940b57cec5SDimitry Andric 
1395*0fca6ea1SDimitry Andric   InstrGen += 2;
1396*0fca6ea1SDimitry Andric   // In the event we ever get more than 2**31 instructions...
1397*0fca6ea1SDimitry Andric   if (LLVM_UNLIKELY(InstrGen == 0)) {
1398*0fca6ea1SDimitry Andric     UsedInInstr.assign(UsedInInstr.size(), 0);
1399*0fca6ea1SDimitry Andric     InstrGen = 2;
1400*0fca6ea1SDimitry Andric   }
1401fe6060f1SDimitry Andric   RegMasks.clear();
1402e8d8bef9SDimitry Andric   BundleVirtRegsMap.clear();
14030b57cec5SDimitry Andric 
1404e8d8bef9SDimitry Andric   // Scan for special cases; Apply pre-assigned register defs to state.
1405e8d8bef9SDimitry Andric   bool HasPhysRegUse = false;
1406e8d8bef9SDimitry Andric   bool HasRegMask = false;
1407e8d8bef9SDimitry Andric   bool HasVRegDef = false;
1408e8d8bef9SDimitry Andric   bool HasDef = false;
1409e8d8bef9SDimitry Andric   bool HasEarlyClobber = false;
1410e8d8bef9SDimitry Andric   bool NeedToAssignLiveThroughs = false;
14115f757f3fSDimitry Andric   for (MachineOperand &MO : MI.operands()) {
1412e8d8bef9SDimitry Andric     if (MO.isReg()) {
14138bcb0991SDimitry Andric       Register Reg = MO.getReg();
1414e8d8bef9SDimitry Andric       if (Reg.isVirtual()) {
1415bdd1243dSDimitry Andric         if (!shouldAllocateRegister(Reg))
1416bdd1243dSDimitry Andric           continue;
1417e8d8bef9SDimitry Andric         if (MO.isDef()) {
1418e8d8bef9SDimitry Andric           HasDef = true;
1419e8d8bef9SDimitry Andric           HasVRegDef = true;
1420e8d8bef9SDimitry Andric           if (MO.isEarlyClobber()) {
1421e8d8bef9SDimitry Andric             HasEarlyClobber = true;
1422e8d8bef9SDimitry Andric             NeedToAssignLiveThroughs = true;
14230b57cec5SDimitry Andric           }
14245f757f3fSDimitry Andric           if (isTiedToNotUndef(MO) || (MO.getSubReg() != 0 && !MO.isUndef()))
1425e8d8bef9SDimitry Andric             NeedToAssignLiveThroughs = true;
1426e8d8bef9SDimitry Andric         }
1427e8d8bef9SDimitry Andric       } else if (Reg.isPhysical()) {
1428e8d8bef9SDimitry Andric         if (!MRI->isReserved(Reg)) {
1429e8d8bef9SDimitry Andric           if (MO.isDef()) {
1430e8d8bef9SDimitry Andric             HasDef = true;
1431e8d8bef9SDimitry Andric             bool displacedAny = definePhysReg(MI, Reg);
1432e8d8bef9SDimitry Andric             if (MO.isEarlyClobber())
1433e8d8bef9SDimitry Andric               HasEarlyClobber = true;
1434e8d8bef9SDimitry Andric             if (!displacedAny)
1435e8d8bef9SDimitry Andric               MO.setIsDead(true);
1436e8d8bef9SDimitry Andric           }
1437e8d8bef9SDimitry Andric           if (MO.readsReg())
1438e8d8bef9SDimitry Andric             HasPhysRegUse = true;
1439e8d8bef9SDimitry Andric         }
1440e8d8bef9SDimitry Andric       }
1441e8d8bef9SDimitry Andric     } else if (MO.isRegMask()) {
1442e8d8bef9SDimitry Andric       HasRegMask = true;
1443fe6060f1SDimitry Andric       RegMasks.push_back(MO.getRegMask());
1444e8d8bef9SDimitry Andric     }
1445e8d8bef9SDimitry Andric   }
1446e8d8bef9SDimitry Andric 
1447e8d8bef9SDimitry Andric   // Allocate virtreg defs.
1448e8d8bef9SDimitry Andric   if (HasDef) {
1449e8d8bef9SDimitry Andric     if (HasVRegDef) {
145006c3fb27SDimitry Andric       // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
145106c3fb27SDimitry Andric       // multiple times to ensure no operand is missed.
145206c3fb27SDimitry Andric       bool ReArrangedImplicitOps = true;
145306c3fb27SDimitry Andric 
1454e8d8bef9SDimitry Andric       // Special handling for early clobbers, tied operands or subregister defs:
1455e8d8bef9SDimitry Andric       // Compared to "normal" defs these:
1456e8d8bef9SDimitry Andric       // - Must not use a register that is pre-assigned for a use operand.
1457e8d8bef9SDimitry Andric       // - In order to solve tricky inline assembly constraints we change the
1458e8d8bef9SDimitry Andric       //   heuristic to figure out a good operand order before doing
1459e8d8bef9SDimitry Andric       //   assignments.
1460e8d8bef9SDimitry Andric       if (NeedToAssignLiveThroughs) {
146106c3fb27SDimitry Andric         while (ReArrangedImplicitOps) {
146206c3fb27SDimitry Andric           ReArrangedImplicitOps = false;
146306c3fb27SDimitry Andric           findAndSortDefOperandIndexes(MI);
1464*0fca6ea1SDimitry Andric           for (unsigned OpIdx : DefOperandIndexes) {
1465e8d8bef9SDimitry Andric             MachineOperand &MO = MI.getOperand(OpIdx);
1466e8d8bef9SDimitry Andric             LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
14675f757f3fSDimitry Andric             Register Reg = MO.getReg();
14685f757f3fSDimitry Andric             if (MO.isEarlyClobber() || isTiedToNotUndef(MO) ||
1469e8d8bef9SDimitry Andric                 (MO.getSubReg() && !MO.isUndef())) {
147006c3fb27SDimitry Andric               ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1471e8d8bef9SDimitry Andric             } else {
147206c3fb27SDimitry Andric               ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
147306c3fb27SDimitry Andric             }
147406c3fb27SDimitry Andric             // Implicit operands of MI were re-arranged,
147506c3fb27SDimitry Andric             // re-compute DefOperandIndexes.
14765f757f3fSDimitry Andric             if (ReArrangedImplicitOps)
147706c3fb27SDimitry Andric               break;
147806c3fb27SDimitry Andric           }
1479e8d8bef9SDimitry Andric         }
1480e8d8bef9SDimitry Andric       } else {
1481e8d8bef9SDimitry Andric         // Assign virtual register defs.
148206c3fb27SDimitry Andric         while (ReArrangedImplicitOps) {
148306c3fb27SDimitry Andric           ReArrangedImplicitOps = false;
14845f757f3fSDimitry Andric           for (MachineOperand &MO : MI.operands()) {
1485e8d8bef9SDimitry Andric             if (!MO.isReg() || !MO.isDef())
1486e8d8bef9SDimitry Andric               continue;
1487e8d8bef9SDimitry Andric             Register Reg = MO.getReg();
148806c3fb27SDimitry Andric             if (Reg.isVirtual()) {
14895f757f3fSDimitry Andric               ReArrangedImplicitOps =
14905f757f3fSDimitry Andric                   defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
14915f757f3fSDimitry Andric               if (ReArrangedImplicitOps)
149206c3fb27SDimitry Andric                 break;
149306c3fb27SDimitry Andric             }
149406c3fb27SDimitry Andric           }
149506c3fb27SDimitry Andric         }
1496e8d8bef9SDimitry Andric       }
1497e8d8bef9SDimitry Andric     }
1498e8d8bef9SDimitry Andric 
1499e8d8bef9SDimitry Andric     // Free registers occupied by defs.
1500e8d8bef9SDimitry Andric     // Iterate operands in reverse order, so we see the implicit super register
1501e8d8bef9SDimitry Andric     // defs first (we added them earlier in case of <def,read-undef>).
15025f757f3fSDimitry Andric     for (MachineOperand &MO : reverse(MI.operands())) {
1503e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.isDef())
1504e8d8bef9SDimitry Andric         continue;
1505e8d8bef9SDimitry Andric 
150606c3fb27SDimitry Andric       Register Reg = MO.getReg();
150706c3fb27SDimitry Andric 
1508e8d8bef9SDimitry Andric       // subreg defs don't free the full register. We left the subreg number
1509e8d8bef9SDimitry Andric       // around as a marker in setPhysReg() to recognize this case here.
151006c3fb27SDimitry Andric       if (Reg.isPhysical() && MO.getSubReg() != 0) {
1511e8d8bef9SDimitry Andric         MO.setSubReg(0);
15120b57cec5SDimitry Andric         continue;
15130b57cec5SDimitry Andric       }
1514e8d8bef9SDimitry Andric 
1515fe6060f1SDimitry Andric       assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1516fe6060f1SDimitry Andric              "tied def assigned to clobbered register");
1517fe6060f1SDimitry Andric 
1518e8d8bef9SDimitry Andric       // Do not free tied operands and early clobbers.
15195f757f3fSDimitry Andric       if (isTiedToNotUndef(MO) || MO.isEarlyClobber())
1520e8d8bef9SDimitry Andric         continue;
1521e8d8bef9SDimitry Andric       if (!Reg)
1522e8d8bef9SDimitry Andric         continue;
1523bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
1524bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Reg));
1525bdd1243dSDimitry Andric         continue;
1526bdd1243dSDimitry Andric       }
1527e8d8bef9SDimitry Andric       assert(Reg.isPhysical());
1528e8d8bef9SDimitry Andric       if (MRI->isReserved(Reg))
1529e8d8bef9SDimitry Andric         continue;
1530e8d8bef9SDimitry Andric       freePhysReg(Reg);
1531e8d8bef9SDimitry Andric       unmarkRegUsedInInstr(Reg);
1532e8d8bef9SDimitry Andric     }
15330b57cec5SDimitry Andric   }
15340b57cec5SDimitry Andric 
1535e8d8bef9SDimitry Andric   // Displace clobbered registers.
1536e8d8bef9SDimitry Andric   if (HasRegMask) {
1537fe6060f1SDimitry Andric     assert(!RegMasks.empty() && "expected RegMask");
1538e8d8bef9SDimitry Andric     // MRI bookkeeping.
1539fe6060f1SDimitry Andric     for (const auto *RM : RegMasks)
1540fe6060f1SDimitry Andric       MRI->addPhysRegsUsedFromRegMask(RM);
1541e8d8bef9SDimitry Andric 
1542e8d8bef9SDimitry Andric     // Displace clobbered registers.
1543fe6060f1SDimitry Andric     for (const LiveReg &LR : LiveVirtRegs) {
1544fe6060f1SDimitry Andric       MCPhysReg PhysReg = LR.PhysReg;
1545fe6060f1SDimitry Andric       if (PhysReg != 0 && isClobberedByRegMasks(PhysReg))
1546e8d8bef9SDimitry Andric         displacePhysReg(MI, PhysReg);
1547e8d8bef9SDimitry Andric     }
1548e8d8bef9SDimitry Andric   }
15490b57cec5SDimitry Andric 
1550e8d8bef9SDimitry Andric   // Apply pre-assigned register uses to state.
1551e8d8bef9SDimitry Andric   if (HasPhysRegUse) {
1552e8d8bef9SDimitry Andric     for (MachineOperand &MO : MI.operands()) {
1553e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.readsReg())
1554e8d8bef9SDimitry Andric         continue;
1555e8d8bef9SDimitry Andric       Register Reg = MO.getReg();
1556e8d8bef9SDimitry Andric       if (!Reg.isPhysical())
1557e8d8bef9SDimitry Andric         continue;
1558e8d8bef9SDimitry Andric       if (MRI->isReserved(Reg))
1559e8d8bef9SDimitry Andric         continue;
15605f757f3fSDimitry Andric       if (!usePhysReg(MI, Reg))
1561e8d8bef9SDimitry Andric         MO.setIsKill(true);
1562e8d8bef9SDimitry Andric     }
1563e8d8bef9SDimitry Andric   }
1564e8d8bef9SDimitry Andric 
1565e8d8bef9SDimitry Andric   // Allocate virtreg uses and insert reloads as necessary.
156606c3fb27SDimitry Andric   // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
156706c3fb27SDimitry Andric   // times to ensure no operand is missed.
15680b57cec5SDimitry Andric   bool HasUndefUse = false;
156906c3fb27SDimitry Andric   bool ReArrangedImplicitMOs = true;
157006c3fb27SDimitry Andric   while (ReArrangedImplicitMOs) {
157106c3fb27SDimitry Andric     ReArrangedImplicitMOs = false;
15725f757f3fSDimitry Andric     for (MachineOperand &MO : MI.operands()) {
1573e8d8bef9SDimitry Andric       if (!MO.isReg() || !MO.isUse())
1574e8d8bef9SDimitry Andric         continue;
15758bcb0991SDimitry Andric       Register Reg = MO.getReg();
1576bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
15778bcb0991SDimitry Andric         continue;
1578e8d8bef9SDimitry Andric 
15790b57cec5SDimitry Andric       if (MO.isUndef()) {
15800b57cec5SDimitry Andric         HasUndefUse = true;
15810b57cec5SDimitry Andric         continue;
15820b57cec5SDimitry Andric       }
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric       // Populate MayLiveAcrossBlocks in case the use block is allocated before
15850b57cec5SDimitry Andric       // the def block (removing the vreg uses).
15860b57cec5SDimitry Andric       mayLiveIn(Reg);
15870b57cec5SDimitry Andric 
1588e8d8bef9SDimitry Andric       assert(!MO.isInternalRead() && "Bundles not supported");
1589e8d8bef9SDimitry Andric       assert(MO.readsReg() && "reading use");
15905f757f3fSDimitry Andric       ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
159106c3fb27SDimitry Andric       if (ReArrangedImplicitMOs)
159206c3fb27SDimitry Andric         break;
159306c3fb27SDimitry Andric     }
15940b57cec5SDimitry Andric   }
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // Allocate undef operands. This is a separate step because in a situation
15970b57cec5SDimitry Andric   // like  ` = OP undef %X, %X`    both operands need the same register assign
15980b57cec5SDimitry Andric   // so we should perform the normal assignment first.
15990b57cec5SDimitry Andric   if (HasUndefUse) {
160006c3fb27SDimitry Andric     for (MachineOperand &MO : MI.all_uses()) {
16018bcb0991SDimitry Andric       Register Reg = MO.getReg();
1602bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
16030b57cec5SDimitry Andric         continue;
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric       assert(MO.isUndef() && "Should only have undef virtreg uses left");
16060b57cec5SDimitry Andric       allocVirtRegUndef(MO);
16070b57cec5SDimitry Andric     }
16080b57cec5SDimitry Andric   }
16090b57cec5SDimitry Andric 
1610e8d8bef9SDimitry Andric   // Free early clobbers.
1611e8d8bef9SDimitry Andric   if (HasEarlyClobber) {
16125f757f3fSDimitry Andric     for (MachineOperand &MO : reverse(MI.all_defs())) {
161306c3fb27SDimitry Andric       if (!MO.isEarlyClobber())
1614e8d8bef9SDimitry Andric         continue;
1615bdd1243dSDimitry Andric       assert(!MO.getSubReg() && "should be already handled in def processing");
1616e8d8bef9SDimitry Andric 
16178bcb0991SDimitry Andric       Register Reg = MO.getReg();
1618e8d8bef9SDimitry Andric       if (!Reg)
16198bcb0991SDimitry Andric         continue;
1620bdd1243dSDimitry Andric       if (Reg.isVirtual()) {
1621bdd1243dSDimitry Andric         assert(!shouldAllocateRegister(Reg));
1622bdd1243dSDimitry Andric         continue;
1623bdd1243dSDimitry Andric       }
1624e8d8bef9SDimitry Andric       assert(Reg.isPhysical() && "should have register assigned");
1625e8d8bef9SDimitry Andric 
1626e8d8bef9SDimitry Andric       // We sometimes get odd situations like:
1627e8d8bef9SDimitry Andric       //    early-clobber %x0 = INSTRUCTION %x0
1628e8d8bef9SDimitry Andric       // which is semantically questionable as the early-clobber should
1629e8d8bef9SDimitry Andric       // apply before the use. But in practice we consider the use to
1630e8d8bef9SDimitry Andric       // happen before the early clobber now. Don't free the early clobber
1631e8d8bef9SDimitry Andric       // register in this case.
1632e8d8bef9SDimitry Andric       if (MI.readsRegister(Reg, TRI))
1633e8d8bef9SDimitry Andric         continue;
1634e8d8bef9SDimitry Andric 
1635e8d8bef9SDimitry Andric       freePhysReg(Reg);
16360b57cec5SDimitry Andric     }
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "<< " << MI);
1640e8d8bef9SDimitry Andric   if (MI.isCopy() && MI.getOperand(0).getReg() == MI.getOperand(1).getReg() &&
1641e8d8bef9SDimitry Andric       MI.getNumOperands() == 2) {
16420b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Mark identity copy for removal\n");
16430b57cec5SDimitry Andric     Coalesced.push_back(&MI);
16440b57cec5SDimitry Andric   }
16450b57cec5SDimitry Andric }
16460b57cec5SDimitry Andric 
1647*0fca6ea1SDimitry Andric void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
16480b57cec5SDimitry Andric   // Ignore DBG_VALUEs that aren't based on virtual registers. These are
16490b57cec5SDimitry Andric   // mostly constants and frame indices.
16505f757f3fSDimitry Andric   assert(MI.isDebugValue() && "not a DBG_VALUE*");
16515f757f3fSDimitry Andric   for (const auto &MO : MI.debug_operands()) {
16525f757f3fSDimitry Andric     if (!MO.isReg())
16535f757f3fSDimitry Andric       continue;
16545f757f3fSDimitry Andric     Register Reg = MO.getReg();
1655bdd1243dSDimitry Andric     if (!Reg.isVirtual())
1656bdd1243dSDimitry Andric       continue;
1657bdd1243dSDimitry Andric     if (!shouldAllocateRegister(Reg))
1658fe6060f1SDimitry Andric       continue;
16590b57cec5SDimitry Andric 
1660e8d8bef9SDimitry Andric     // Already spilled to a stackslot?
1661e8d8bef9SDimitry Andric     int SS = StackSlotForVirtReg[Reg];
1662e8d8bef9SDimitry Andric     if (SS != -1) {
1663e8d8bef9SDimitry Andric       // Modify DBG_VALUE now that the value is in a spill slot.
1664fe6060f1SDimitry Andric       updateDbgValueForSpill(MI, SS, Reg);
1665e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1666fe6060f1SDimitry Andric       continue;
1667e8d8bef9SDimitry Andric     }
1668e8d8bef9SDimitry Andric 
16690b57cec5SDimitry Andric     // See if this virtual register has already been allocated to a physical
16700b57cec5SDimitry Andric     // register or spilled to a stack slot.
16710b57cec5SDimitry Andric     LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1672fe6060f1SDimitry Andric     SmallVector<MachineOperand *> DbgOps;
1673fe6060f1SDimitry Andric     for (MachineOperand &Op : MI.getDebugOperandsForReg(Reg))
1674fe6060f1SDimitry Andric       DbgOps.push_back(&Op);
1675fe6060f1SDimitry Andric 
16760b57cec5SDimitry Andric     if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1677fe6060f1SDimitry Andric       // Update every use of Reg within MI.
1678fe6060f1SDimitry Andric       for (auto &RegMO : DbgOps)
1679fe6060f1SDimitry Andric         setPhysReg(MI, *RegMO, LRI->PhysReg);
16800b57cec5SDimitry Andric     } else {
1681e8d8bef9SDimitry Andric       DanglingDbgValues[Reg].push_back(&MI);
16820b57cec5SDimitry Andric     }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric     // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
16850b57cec5SDimitry Andric     // that future spills of Reg will have DBG_VALUEs.
1686fe6060f1SDimitry Andric     LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1687fe6060f1SDimitry Andric   }
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric 
1690*0fca6ea1SDimitry Andric void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1691e8d8bef9SDimitry Andric   MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1692e8d8bef9SDimitry Andric   ++BundledMI;
1693e8d8bef9SDimitry Andric   while (BundledMI->isBundledWithPred()) {
16944824e7fdSDimitry Andric     for (MachineOperand &MO : BundledMI->operands()) {
1695e8d8bef9SDimitry Andric       if (!MO.isReg())
1696e8d8bef9SDimitry Andric         continue;
1697e8d8bef9SDimitry Andric 
1698e8d8bef9SDimitry Andric       Register Reg = MO.getReg();
1699bdd1243dSDimitry Andric       if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1700e8d8bef9SDimitry Andric         continue;
1701e8d8bef9SDimitry Andric 
1702e8d8bef9SDimitry Andric       DenseMap<Register, MCPhysReg>::iterator DI;
1703e8d8bef9SDimitry Andric       DI = BundleVirtRegsMap.find(Reg);
1704e8d8bef9SDimitry Andric       assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1705e8d8bef9SDimitry Andric 
1706e8d8bef9SDimitry Andric       setPhysReg(MI, MO, DI->second);
1707e8d8bef9SDimitry Andric     }
1708e8d8bef9SDimitry Andric 
1709e8d8bef9SDimitry Andric     ++BundledMI;
1710e8d8bef9SDimitry Andric   }
1711e8d8bef9SDimitry Andric }
1712e8d8bef9SDimitry Andric 
1713*0fca6ea1SDimitry Andric void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
17140b57cec5SDimitry Andric   this->MBB = &MBB;
17150b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
17160b57cec5SDimitry Andric 
1717cb14a3feSDimitry Andric   PosIndexes.unsetInitialized();
1718e8d8bef9SDimitry Andric   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
17190b57cec5SDimitry Andric   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
17200b57cec5SDimitry Andric 
1721fcaf7f86SDimitry Andric   for (const auto &LiveReg : MBB.liveouts())
1722fe6060f1SDimitry Andric     setPhysRegState(LiveReg.PhysReg, regPreAssigned);
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   Coalesced.clear();
17250b57cec5SDimitry Andric 
1726e8d8bef9SDimitry Andric   // Traverse block in reverse order allocating instructions one by one.
1727e8d8bef9SDimitry Andric   for (MachineInstr &MI : reverse(MBB)) {
17285f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric     // Special handling for debug values. Note that they are not allowed to
17310b57cec5SDimitry Andric     // affect codegen of the other instructions in any way.
17320b57cec5SDimitry Andric     if (MI.isDebugValue()) {
17330b57cec5SDimitry Andric       handleDebugValue(MI);
17340b57cec5SDimitry Andric       continue;
17350b57cec5SDimitry Andric     }
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric     allocateInstruction(MI);
1738e8d8bef9SDimitry Andric 
1739e8d8bef9SDimitry Andric     // Once BUNDLE header is assigned registers, same assignments need to be
1740e8d8bef9SDimitry Andric     // done for bundled MIs.
1741e8d8bef9SDimitry Andric     if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1742e8d8bef9SDimitry Andric       handleBundle(MI);
1743e8d8bef9SDimitry Andric     }
17440b57cec5SDimitry Andric   }
17450b57cec5SDimitry Andric 
17465f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1747e8d8bef9SDimitry Andric 
17480b57cec5SDimitry Andric   // Spill all physical registers holding virtual registers now.
1749e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1750e8d8bef9SDimitry Andric   reloadAtBegin(MBB);
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   // Erase all the coalesced copies. We are delaying it until now because
17530b57cec5SDimitry Andric   // LiveVirtRegs might refer to the instrs.
17540b57cec5SDimitry Andric   for (MachineInstr *MI : Coalesced)
17550b57cec5SDimitry Andric     MBB.erase(MI);
17560b57cec5SDimitry Andric   NumCoalesced += Coalesced.size();
17570b57cec5SDimitry Andric 
1758e8d8bef9SDimitry Andric   for (auto &UDBGPair : DanglingDbgValues) {
1759e8d8bef9SDimitry Andric     for (MachineInstr *DbgValue : UDBGPair.second) {
1760e8d8bef9SDimitry Andric       assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1761e8d8bef9SDimitry Andric       // Nothing to do if the vreg was spilled in the meantime.
1762fe6060f1SDimitry Andric       if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1763e8d8bef9SDimitry Andric         continue;
1764e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1765e8d8bef9SDimitry Andric                         << '\n');
1766fe6060f1SDimitry Andric       DbgValue->setDebugValueUndef();
1767e8d8bef9SDimitry Andric     }
1768e8d8bef9SDimitry Andric   }
1769e8d8bef9SDimitry Andric   DanglingDbgValues.clear();
1770e8d8bef9SDimitry Andric 
17710b57cec5SDimitry Andric   LLVM_DEBUG(MBB.dump());
17720b57cec5SDimitry Andric }
17730b57cec5SDimitry Andric 
1774*0fca6ea1SDimitry Andric bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
17750b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
17760b57cec5SDimitry Andric                     << "********** Function: " << MF.getName() << '\n');
17770b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
17780b57cec5SDimitry Andric   const TargetSubtargetInfo &STI = MF.getSubtarget();
17790b57cec5SDimitry Andric   TRI = STI.getRegisterInfo();
17800b57cec5SDimitry Andric   TII = STI.getInstrInfo();
17810b57cec5SDimitry Andric   MFI = &MF.getFrameInfo();
1782*0fca6ea1SDimitry Andric   MRI->freezeReservedRegs();
17830b57cec5SDimitry Andric   RegClassInfo.runOnMachineFunction(MF);
1784e8d8bef9SDimitry Andric   unsigned NumRegUnits = TRI->getNumRegUnits();
1785*0fca6ea1SDimitry Andric   InstrGen = 0;
1786*0fca6ea1SDimitry Andric   UsedInInstr.assign(NumRegUnits, 0);
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   // initialize the virtual->physical register map to have a 'null'
17890b57cec5SDimitry Andric   // mapping for all virtual registers
17900b57cec5SDimitry Andric   unsigned NumVirtRegs = MRI->getNumVirtRegs();
17910b57cec5SDimitry Andric   StackSlotForVirtReg.resize(NumVirtRegs);
17920b57cec5SDimitry Andric   LiveVirtRegs.setUniverse(NumVirtRegs);
17930b57cec5SDimitry Andric   MayLiveAcrossBlocks.clear();
17940b57cec5SDimitry Andric   MayLiveAcrossBlocks.resize(NumVirtRegs);
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   // Loop over all of the basic blocks, eliminating virtual register references
17970b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF)
17980b57cec5SDimitry Andric     allocateBasicBlock(MBB);
17990b57cec5SDimitry Andric 
1800fe6060f1SDimitry Andric   if (ClearVirtRegs) {
18010b57cec5SDimitry Andric     // All machine operands and other references to virtual registers have been
18020b57cec5SDimitry Andric     // replaced. Remove the virtual registers.
18030b57cec5SDimitry Andric     MRI->clearVirtRegs();
1804fe6060f1SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   StackSlotForVirtReg.clear();
18070b57cec5SDimitry Andric   LiveDbgValueMap.clear();
18080b57cec5SDimitry Andric   return true;
18090b57cec5SDimitry Andric }
18100b57cec5SDimitry Andric 
1811*0fca6ea1SDimitry Andric PreservedAnalyses RegAllocFastPass::run(MachineFunction &MF,
1812*0fca6ea1SDimitry Andric                                         MachineFunctionAnalysisManager &) {
1813*0fca6ea1SDimitry Andric   MFPropsModifier _(*this, MF);
1814*0fca6ea1SDimitry Andric   RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1815*0fca6ea1SDimitry Andric   bool Changed = Impl.runOnMachineFunction(MF);
1816*0fca6ea1SDimitry Andric   if (!Changed)
1817*0fca6ea1SDimitry Andric     return PreservedAnalyses::all();
1818*0fca6ea1SDimitry Andric   auto PA = getMachineFunctionPassPreservedAnalyses();
1819*0fca6ea1SDimitry Andric   PA.preserveSet<CFGAnalyses>();
1820*0fca6ea1SDimitry Andric   return PA;
1821*0fca6ea1SDimitry Andric }
1822*0fca6ea1SDimitry Andric 
1823*0fca6ea1SDimitry Andric void RegAllocFastPass::printPipeline(
1824*0fca6ea1SDimitry Andric     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1825*0fca6ea1SDimitry Andric   bool PrintFilterName = Opts.FilterName != "all";
1826*0fca6ea1SDimitry Andric   bool PrintNoClearVRegs = !Opts.ClearVRegs;
1827*0fca6ea1SDimitry Andric   bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1828*0fca6ea1SDimitry Andric 
1829*0fca6ea1SDimitry Andric   OS << "regallocfast";
1830*0fca6ea1SDimitry Andric   if (PrintFilterName || PrintNoClearVRegs) {
1831*0fca6ea1SDimitry Andric     OS << '<';
1832*0fca6ea1SDimitry Andric     if (PrintFilterName)
1833*0fca6ea1SDimitry Andric       OS << "filter=" << Opts.FilterName;
1834*0fca6ea1SDimitry Andric     if (PrintSemicolon)
1835*0fca6ea1SDimitry Andric       OS << ';';
1836*0fca6ea1SDimitry Andric     if (PrintNoClearVRegs)
1837*0fca6ea1SDimitry Andric       OS << "no-clear-vregs";
1838*0fca6ea1SDimitry Andric     OS << '>';
1839*0fca6ea1SDimitry Andric   }
1840*0fca6ea1SDimitry Andric }
1841*0fca6ea1SDimitry Andric 
18425f757f3fSDimitry Andric FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1843fe6060f1SDimitry Andric 
1844*0fca6ea1SDimitry Andric FunctionPass *llvm::createFastRegisterAllocator(RegAllocFilterFunc Ftor,
1845fcaf7f86SDimitry Andric                                                 bool ClearVirtRegs) {
1846fe6060f1SDimitry Andric   return new RegAllocFast(Ftor, ClearVirtRegs);
1847fe6060f1SDimitry Andric }
1848