LLVM 24.0.0git
RegAllocFast.cpp
Go to the documentation of this file.
1//===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file A block-local register allocator. No virtual register stays in a
10/// register across a block boundary. A value live across one gets a stack slot:
11/// spilled after its def and reloaded above its uses in each block, at the top
12/// of the block or just after an intervening instruction that evicts it.
13/// There is no dataflow liveness analysis, only a bounded scan of def and use
14/// lists, and no live range splitting, interference graph or coalescer, only a
15/// copy hint plus removal of COPYs that end up identity or dead.
16///
17/// Each block is walked backwards: a use is the first reference reached and
18/// acquires a register, a def is the last and releases one.
19//
20//===----------------------------------------------------------------------===//
21
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IndexedMap.h"
26#include "llvm/ADT/MapVector.h"
27#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SparseSet.h"
30#include "llvm/ADT/Statistic.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/Debug.h"
52#include <cassert>
53#include <tuple>
54#include <vector>
55
56using namespace llvm;
57
58#define DEBUG_TYPE "regalloc"
59
60STATISTIC(NumStores, "Number of stores added");
61STATISTIC(NumLoads, "Number of loads added");
62STATISTIC(NumCoalesced, "Number of copies coalesced");
63
64// FIXME: Remove this switch when all testcases are fixed!
65static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
67
68static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
70
71namespace {
72
73/// Assign ascending index for instructions in machine basic block. The index
74/// can be used to determine dominance between instructions in same MBB.
75class InstrPosIndexes {
76public:
77 void unsetInitialized() { IsInitialized = false; }
78
79 void init(const MachineBasicBlock &MBB) {
80 CurMBB = &MBB;
81 Instr2PosIndex.clear();
82 uint64_t LastIndex = 0;
83 for (const MachineInstr &MI : MBB) {
84 LastIndex += InstrDist;
85 Instr2PosIndex[&MI] = LastIndex;
86 }
87 }
88
89 /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
90 /// index without affecting existing instruction's index. Return true if all
91 /// instructions index has been reassigned.
92 bool getIndex(const MachineInstr &MI, uint64_t &Index) {
93 if (!IsInitialized) {
94 init(*MI.getParent());
95 IsInitialized = true;
96 Index = Instr2PosIndex.at(&MI);
97 return true;
98 }
99
100 assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
101 auto It = Instr2PosIndex.find(&MI);
102 if (It != Instr2PosIndex.end()) {
103 Index = It->second;
104 return false;
105 }
106
107 // Distance is the number of consecutive unassigned instructions including
108 // MI. Start is the first instruction of them. End is the next of last
109 // instruction of them.
110 // e.g.
111 // |Instruction| A | B | C | MI | D | E |
112 // | Index | 1024 | | | | | 2048 |
113 //
114 // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
115 // is E.
116 unsigned Distance = 1;
118 End = std::next(Start);
119 while (Start != CurMBB->begin() &&
120 !Instr2PosIndex.count(&*std::prev(Start))) {
121 --Start;
122 ++Distance;
123 }
124 while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
125 ++End;
126 ++Distance;
127 }
128
129 // LastIndex is initialized to last used index prior to MI or zero.
130 // In previous example, LastIndex is 1024, EndIndex is 2048;
131 uint64_t LastIndex =
132 Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
133 uint64_t Step;
134 if (End == CurMBB->end())
135 Step = static_cast<uint64_t>(InstrDist);
136 else {
137 // No instruction uses index zero.
138 uint64_t EndIndex = Instr2PosIndex.at(&*End);
139 assert(EndIndex > LastIndex && "Index must be ascending order");
140 unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
141 // We want index gap between two adjacent MI is as same as possible. Given
142 // total A available indexes, D is number of consecutive unassigned
143 // instructions, S is the step.
144 // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
145 // There're S-1 available indexes between unassigned instruction and its
146 // predecessor. There're A-S*D available indexes between the last
147 // unassigned instruction and its successor.
148 // Ideally, we want
149 // S-1 = A-S*D
150 // then
151 // S = (A+1)/(D+1)
152 // An valid S must be integer greater than zero, so
153 // S <= (A+1)/(D+1)
154 // =>
155 // A-S*D >= 0
156 // That means we can safely use (A+1)/(D+1) as step.
157 // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
158 // 1636, 1840.
159 Step = (NumAvailableIndexes + 1) / (Distance + 1);
160 }
161
162 // Reassign index for all instructions if number of new inserted
163 // instructions exceed slot or all instructions are new.
164 if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
165 init(*CurMBB);
166 Index = Instr2PosIndex.at(&MI);
167 return true;
168 }
169
170 for (auto I = Start; I != End; ++I) {
171 LastIndex += Step;
172 Instr2PosIndex[&*I] = LastIndex;
173 }
174 Index = Instr2PosIndex.at(&MI);
175 return false;
176 }
177
178private:
179 bool IsInitialized = false;
180 enum { InstrDist = 1024 };
181 const MachineBasicBlock *CurMBB = nullptr;
182 DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
183};
184
185class RegAllocFastImpl {
186public:
187 RegAllocFastImpl(const RegAllocFilterFunc F = nullptr,
188 bool ClearVirtRegs_ = true)
189 : ShouldAllocateRegisterImpl(F), StackSlotForVirtReg(-1),
190 ClearVirtRegs(ClearVirtRegs_) {}
191
192private:
193 MachineFrameInfo *MFI = nullptr;
194 MachineRegisterInfo *MRI = nullptr;
195 const TargetRegisterInfo *TRI = nullptr;
196 const TargetInstrInfo *TII = nullptr;
197 RegisterClassInfo RegClassInfo;
198 const RegAllocFilterFunc ShouldAllocateRegisterImpl;
199
200 /// Basic block currently being allocated.
201 MachineBasicBlock *MBB = nullptr;
202
203 /// Maps virtual regs to the frame index where these values are spilled.
204 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
205
206 /// A virtual register live at the current point of the backward walk.
207 /// Created at its last reference, cleared only when the block is done.
208 struct LiveReg {
209 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
210 Register VirtReg; ///< Virtual register number.
211 MCRegister PhysReg; ///< Currently held here, 0 if none.
212 bool LiveOut = false; ///< May be live out; the def spills.
213 bool Reloaded = false; ///< Reloaded below; the def spills.
214 bool Error = false; ///< Could not allocate.
215
216 explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
217 explicit LiveReg() = default;
218
219 unsigned getSparseSetIndex() const { return VirtReg.virtRegIndex(); }
220 };
221
222 using LiveRegMap = SparseSet<LiveReg, unsigned, identity, uint16_t>;
223 /// This map contains entries for each virtual register that is currently
224 /// available in a physical register.
225 LiveRegMap LiveVirtRegs;
226
227 /// Stores assigned virtual registers present in the bundle MI.
228 DenseMap<Register, LiveReg> BundleVirtRegsMap;
229
230 DenseMap<Register, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
231 /// List of DBG_VALUE that we encountered without the vreg being assigned
232 /// because they were placed after the last use of the vreg.
233 DenseMap<Register, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
234
235 /// Has a bit set for every virtual register for which it was determined
236 /// that it is alive across blocks.
237 BitVector MayLiveAcrossBlocks;
238
239 /// What occupies a register unit. Registers interfere exactly when their
240 /// unit sets intersect, so overlap needs no alias walk.
241 enum RegUnitState {
242 /// Not in use; a register is allocatable iff all of its units are free.
243 regFree,
244
245 /// Not available to the allocator and not a virtual register: a physreg
246 /// operand or a block live-out. Cannot be spilled.
247 regPreAssigned,
248
249 /// Scratch marker: reloadAtBegin() stamps MBB.liveins() over the finished
250 /// map, and a virtual register left in a live-in register is not reloaded.
251 regLiveIn,
252
253 /// Any other value is a virtual register number (>= VirtualRegFlag);
254 /// LiveVirtRegs holds the inverse mapping.
255 };
256
257 /// State of each register unit, indexed by MCRegUnit.
258 std::vector<unsigned> RegUnitStates;
259
261
262 /// Track register units that are used in the current instruction, and so
263 /// cannot be allocated.
264 ///
265 /// In the first phase (tied defs/early clobber), we consider also physical
266 /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
267 /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
268 /// avoid resetting the entire vector after every instruction, we track the
269 /// instruction "generation" in the remaining 31 bits -- this means, that if
270 /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
271 /// never zero and always incremented by two.
272 ///
273 /// Don't allocate inline storage: the number of register units is typically
274 /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
275 uint32_t InstrGen;
276 SmallVector<unsigned, 0> UsedInInstr;
277
278 SmallVector<unsigned, 8> DefOperandIndexes;
279 // Register masks attached to the current instruction.
281
282 // Assign index for each instruction to quickly determine dominance.
283 InstrPosIndexes PosIndexes;
284
285 void setRegUnitState(MCRegUnit Unit, unsigned NewState);
286 unsigned getRegUnitState(MCRegUnit Unit) const;
287
288 void setPhysRegState(MCRegister PhysReg, unsigned NewState);
289 bool isPhysRegFree(MCRegister PhysReg) const;
290
291 /// Mark a physreg as used in this instruction.
292 void markRegUsedInInstr(MCRegister PhysReg) {
293 for (MCRegUnit Unit : TRI->regunits(PhysReg))
294 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen | 1;
295 }
296
297 // Check if physreg is clobbered by instruction's regmask(s).
298 bool isClobberedByRegMasks(MCRegister PhysReg) const {
299 return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
300 return MachineOperand::clobbersPhysReg(Mask, PhysReg);
301 });
302 }
303
304 /// Check if a physreg or any of its aliases are used in this instruction.
305 bool isRegUsedInInstr(MCRegister PhysReg, bool LookAtPhysRegUses) const {
306 if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
307 return true;
308 for (MCRegUnit Unit : TRI->regunits(PhysReg))
309 if (UsedInInstr[static_cast<unsigned>(Unit)] >=
310 (InstrGen | !LookAtPhysRegUses))
311 return true;
312 return false;
313 }
314
315 /// Mark physical register as being used in a register use operand.
316 /// This is only used by the special livethrough handling code.
317 void markPhysRegUsedInInstr(MCRegister PhysReg) {
318 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
319 assert(UsedInInstr[static_cast<unsigned>(Unit)] <= InstrGen &&
320 "non-phys use before phys use?");
321 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen;
322 }
323 }
324
325 /// Remove mark of physical register being used in the instruction.
326 void unmarkRegUsedInInstr(MCRegister PhysReg) {
327 for (MCRegUnit Unit : TRI->regunits(PhysReg))
328 UsedInInstr[static_cast<unsigned>(Unit)] = 0;
329 }
330
331 enum : unsigned {
332 spillClean = 50,
333 spillDirty = 100,
334 spillPrefBonus = 20,
335 spillImpossible = ~0u
336 };
337
338public:
339 bool ClearVirtRegs;
340
341 bool runOnMachineFunction(MachineFunction &MF);
342
343private:
344 void allocateBasicBlock(MachineBasicBlock &MBB);
345
346 void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
347 Register Reg) const;
348
349 void findAndSortDefOperandIndexes(const MachineInstr &MI);
350
351 void allocateInstruction(MachineInstr &MI);
352 void handleDebugValue(MachineInstr &MI);
353 void handleBundle(MachineInstr &MI);
354
355 bool usePhysReg(MachineInstr &MI, MCRegister PhysReg);
356 bool definePhysReg(MachineInstr &MI, MCRegister PhysReg);
357 bool displacePhysReg(MachineInstr &MI, MCRegister PhysReg);
358 void freePhysReg(MCRegister PhysReg);
359
360 unsigned calcSpillCost(MCPhysReg PhysReg) const;
361
362 LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
363 return LiveVirtRegs.find(VirtReg.virtRegIndex());
364 }
365
366 LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
367 return LiveVirtRegs.find(VirtReg.virtRegIndex());
368 }
369
370 void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCRegister PhysReg);
371 void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
372 bool LookAtPhysRegUses = false);
373 void allocVirtRegUndef(MachineOperand &MO);
374 void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
375 MCRegister Reg);
376 bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
377 Register VirtReg);
378 bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
379 bool LookAtPhysRegUses = false);
380 bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
381
382 MCPhysReg getErrorAssignment(const LiveReg &LR, MachineInstr &MI,
383 const TargetRegisterClass &RC);
384
386 getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
387 SmallSet<Register, 2> &PrologLiveIns) const;
388
389 void reloadAtBegin(MachineBasicBlock &MBB);
390 bool setPhysReg(MachineInstr &MI, MachineOperand &MO,
391 const LiveReg &Assignment);
392
393 Register traceCopies(Register VirtReg) const;
394 Register traceCopyChain(Register Reg) const;
395
396 bool shouldAllocateRegister(const Register Reg) const;
397 int getStackSpaceFor(Register VirtReg);
398 void spill(MachineBasicBlock::iterator Before, Register VirtReg,
399 MCRegister AssignedReg, bool Kill, bool LiveOut);
400 void reload(MachineBasicBlock::iterator Before, Register VirtReg,
401 MCRegister PhysReg);
402
403 bool mayLiveOut(Register VirtReg);
404 bool mayLiveIn(Register VirtReg);
405
406 bool mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const;
407
408 void dumpState() const;
409};
410
411class RegAllocFast : public MachineFunctionPass {
412 RegAllocFastImpl Impl;
413
414public:
415 static char ID;
416
417 RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
418 : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
419
420 bool runOnMachineFunction(MachineFunction &MF) override {
421 return Impl.runOnMachineFunction(MF);
422 }
423
424 StringRef getPassName() const override { return "Fast Register Allocator"; }
425
426 void getAnalysisUsage(AnalysisUsage &AU) const override {
427 AU.setPreservesCFG();
429 }
430
431 MachineFunctionProperties getRequiredProperties() const override {
432 return MachineFunctionProperties().setNoPHIs();
433 }
434
435 MachineFunctionProperties getSetProperties() const override {
436 if (Impl.ClearVirtRegs) {
437 return MachineFunctionProperties().setNoVRegs();
438 }
439
440 return MachineFunctionProperties();
441 }
442
443 MachineFunctionProperties getClearedProperties() const override {
444 return MachineFunctionProperties().setIsSSA();
445 }
446};
447
448} // end anonymous namespace
449
450char RegAllocFast::ID = 0;
451
452INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
453 false)
454
455bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
456 assert(Reg.isVirtual());
457 if (!ShouldAllocateRegisterImpl)
458 return true;
459
460 return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
461}
462
463void RegAllocFastImpl::setRegUnitState(MCRegUnit Unit, unsigned NewState) {
464 RegUnitStates[static_cast<unsigned>(Unit)] = NewState;
465}
466
467unsigned RegAllocFastImpl::getRegUnitState(MCRegUnit Unit) const {
468 return RegUnitStates[static_cast<unsigned>(Unit)];
469}
470
471void RegAllocFastImpl::setPhysRegState(MCRegister PhysReg, unsigned NewState) {
472 for (MCRegUnit Unit : TRI->regunits(PhysReg))
473 setRegUnitState(Unit, NewState);
474}
475
476bool RegAllocFastImpl::isPhysRegFree(MCRegister PhysReg) const {
477 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
478 if (getRegUnitState(Unit) != regFree)
479 return false;
480 }
481 return true;
482}
483
484/// This allocates space for the specified virtual register to be held on the
485/// stack.
486int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
487 // Find the location Reg would belong...
488 int SS = StackSlotForVirtReg[VirtReg];
489 // Already has space allocated?
490 if (SS != -1)
491 return SS;
492
493 // Allocate a new stack object for this spill location...
494 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
495 unsigned Size = TRI->getSpillSize(RC);
496 Align Alignment = TRI->getSpillAlign(RC);
497
498 const MachineFunction &MF = MRI->getMF();
499 auto &ST = MF.getSubtarget();
500 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
501 if (Alignment > CurrentAlign && !TRI->canRealignStack(MF))
502 Alignment = CurrentAlign;
503
504 int FrameIdx =
505 MFI->CreateSpillStackObject(Size, Alignment, TRI->getSpillStackID(RC));
506
507 // Assign the slot.
508 StackSlotForVirtReg[VirtReg] = FrameIdx;
509 return FrameIdx;
510}
511
512static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
513 const MachineInstr &B) {
514 uint64_t IndexA, IndexB;
515 PosIndexes.getIndex(A, IndexA);
516 // getIndex() returns true when it renumbered the block, invalidating IndexA.
517 if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
518 PosIndexes.getIndex(A, IndexA);
519 return IndexA < IndexB;
520}
521
522/// Returns true if \p MI is a spill of a live-in physical register in a block
523/// targeted by an INLINEASM_BR. Such spills must precede reloads of live-in
524/// virtual registers, so that we do not reload from an uninitialized stack
525/// slot.
526bool RegAllocFastImpl::mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const {
527 int FI;
528 auto *MBB = MI.getParent();
530 MFI->isSpillSlotObjectIndex(FI))
531 for (const auto &Op : MI.operands())
532 if (Op.isReg() && Op.getReg().isValid() && MBB->isLiveIn(Op.getReg()))
533 return true;
534 return false;
535}
536
537/// Returns false if \p VirtReg is known to not live out of the current block.
538bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
539 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex())) {
540 // Cannot be live-out if there are no successors.
541 return !MBB->succ_empty();
542 }
543
544 const MachineInstr *SelfLoopDef = nullptr;
545
546 // If this block loops back to itself, it is necessary to check whether the
547 // use comes after the def.
548 if (MBB->isSuccessor(MBB)) {
549 // Find the first def in the self loop MBB.
550 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
551 if (DefInst.getParent() != MBB) {
552 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
553 return true;
554 } else {
555 if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
556 SelfLoopDef = &DefInst;
557 }
558 }
559 if (!SelfLoopDef) {
560 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
561 return true;
562 }
563 }
564
565 // See if the first \p Limit uses of the register are all in the current
566 // block.
567 static const unsigned Limit = 8;
568 unsigned C = 0;
569 for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
570 if (UseInst.getParent() != MBB || ++C >= Limit) {
571 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
572 // Cannot be live-out if there are no successors.
573 return !MBB->succ_empty();
574 }
575
576 if (SelfLoopDef) {
577 // Try to handle some simple cases to avoid spilling and reloading every
578 // value inside a self looping block.
579 if (SelfLoopDef == &UseInst ||
580 !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
581 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
582 return true;
583 }
584 }
585 }
586
587 return false;
588}
589
590/// Returns false if \p VirtReg is known to not be live into the current block.
591bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
592 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex()))
593 return !MBB->pred_empty();
594
595 // See if the first \p Limit def of the register are all in the current block.
596 static const unsigned Limit = 8;
597 unsigned C = 0;
598 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
599 if (DefInst.getParent() != MBB || ++C >= Limit) {
600 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
601 return !MBB->pred_empty();
602 }
603 }
604
605 return false;
606}
607
608/// Insert spill instruction for \p AssignedReg before \p Before. Update
609/// DBG_VALUEs with \p VirtReg operands with the stack slot.
610void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
611 Register VirtReg, MCRegister AssignedReg,
612 bool Kill, bool LiveOut) {
613 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
614 << printReg(AssignedReg, TRI));
615 int FI = getStackSpaceFor(VirtReg);
616 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
617
618 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
619 TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, VirtReg);
620 ++NumStores;
621
623
624 // When we spill a virtual register, we will have spill instructions behind
625 // every definition of it, meaning we can switch all the DBG_VALUEs over
626 // to just reference the stack slot.
627 SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
628 SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
629 SpilledOperandsMap;
630 for (MachineOperand *MO : LRIDbgOperands)
631 SpilledOperandsMap[MO->getParent()].push_back(MO);
632 for (const auto &MISpilledOperands : SpilledOperandsMap) {
633 MachineInstr &DBG = *MISpilledOperands.first;
634 // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
635 if (DBG.isDebugValueList())
636 continue;
637 MachineInstr *NewDV = buildDbgValueForSpill(
638 *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
639 assert(NewDV->getParent() == MBB && "dangling parent pointer");
640 (void)NewDV;
641 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
642
643 if (LiveOut) {
644 // We need to insert a DBG_VALUE at the end of the block if the spill slot
645 // is live out, but there is another use of the value after the
646 // spill. This will allow LiveDebugValues to see the correct live out
647 // value to propagate to the successors.
648 MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
649 MBB->insert(FirstTerm, ClonedDV);
650 LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
651 }
652
653 // Rewrite unassigned dbg_values to use the stack slot.
654 // TODO We can potentially do this for list debug values as well if we know
655 // how the dbg_values are getting unassigned.
656 if (DBG.isNonListDebugValue()) {
657 MachineOperand &MO = DBG.getDebugOperand(0);
658 if (MO.isReg() && !MO.getReg()) {
660 }
661 }
662 }
663 // Now this register is spilled there is should not be any DBG_VALUE
664 // pointing to this register because they are all pointing to spilled value
665 // now.
666 LRIDbgOperands.clear();
667}
668
669/// Insert reload instruction for \p PhysReg before \p Before.
670void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
671 Register VirtReg, MCRegister PhysReg) {
672 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
673 << printReg(PhysReg, TRI) << '\n');
674 int FI = getStackSpaceFor(VirtReg);
675 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
676 TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, VirtReg);
677 ++NumLoads;
678}
679
680/// Get basic block begin insertion point.
681/// This is not just MBB.begin() because surprisingly we have EH_LABEL
682/// instructions marking the begin of a basic block. This means we must insert
683/// new instructions after such labels...
684MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
685 MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
687 while (I != MBB.end()) {
688 if (I->isLabel()) {
689 ++I;
690 continue;
691 }
692
693 // Skip prologues and inlineasm_br spills to place reloads afterwards.
694 if (!TII->isBasicBlockPrologue(*I) && !mayBeSpillFromInlineAsmBr(*I))
695 break;
696
697 // However if a prolog instruction reads a register that needs to be
698 // reloaded, the reload should be inserted before the prolog.
699 for (MachineOperand &MO : I->operands()) {
700 if (MO.isReg())
701 PrologLiveIns.insert(MO.getReg());
702 }
703
704 ++I;
705 }
706
707 return I;
708}
709
710/// Reload all currently assigned virtual registers.
711void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
712 if (LiveVirtRegs.empty())
713 return;
714
715 // Mark live-in registers so the loop below skips reloads into them. The
716 // virtual register mappings this overwrites are not needed anymore.
717 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins())
718 setPhysRegState(P.PhysReg, regLiveIn);
719
720 SmallSet<Register, 2> PrologLiveIns;
721
722 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
723 // of spilling here is deterministic, if arbitrary.
724 MachineBasicBlock::iterator InsertBefore =
725 getMBBBeginInsertionPoint(MBB, PrologLiveIns);
726 for (const LiveReg &LR : LiveVirtRegs) {
727 MCRegister PhysReg = LR.PhysReg;
728 if (!PhysReg || LR.Error)
729 continue;
730
731 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
732 if (getRegUnitState(FirstUnit) == regLiveIn)
733 continue;
734
736 "no reload in start block. Missing vreg def?");
737
738 if (PrologLiveIns.count(PhysReg)) {
739 // FIXME: Theoretically this should use an insert point skipping labels
740 // but I'm not sure how labels should interact with prolog instruction
741 // that need reloads.
742 reload(MBB.begin(), LR.VirtReg, PhysReg);
743 } else
744 reload(InsertBefore, LR.VirtReg, PhysReg);
745 }
746 LiveVirtRegs.clear();
747}
748
749/// Handle the direct use of a physical register. Displace whatever occupies it
750/// and mark it pre-assigned: backwards, a use means live from here upward.
751/// Returns false if nothing was displaced, so the use is a kill. This may add
752/// implicit kills to MO->getParent() and invalidate MO.
753bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCRegister Reg) {
754 assert(Reg.isPhysical() && "expected physreg");
755 bool displacedAny = displacePhysReg(MI, Reg);
756 setPhysRegState(Reg, regPreAssigned);
757 markRegUsedInInstr(Reg);
758 return displacedAny;
759}
760
761/// Displace whatever holds \p Reg and reserve it, so a virtual register def
762/// cannot land on a register this instruction already writes. Released in the
763/// free-def-operands step, or after the uses for an early clobber; if the
764/// instruction also reads \p Reg it ends up reserved for the code above.
765bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCRegister Reg) {
766 bool displacedAny = displacePhysReg(MI, Reg);
767 setPhysRegState(Reg, regPreAssigned);
768 return displacedAny;
769}
770
771/// Mark PhysReg as reserved or free after spilling any virtregs. This is very
772/// similar to defineVirtReg except the physreg is reserved instead of
773/// allocated.
774bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCRegister PhysReg) {
775 bool displacedAny = false;
776
777 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
778 switch (unsigned VirtReg = getRegUnitState(Unit)) {
779 default: {
780 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
781 assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
782 MachineBasicBlock::iterator ReloadBefore =
783 std::next((MachineBasicBlock::iterator)MI.getIterator());
784 while (mayBeSpillFromInlineAsmBr(*ReloadBefore))
785 ++ReloadBefore;
786 reload(ReloadBefore, VirtReg, LRI->PhysReg);
787
788 setPhysRegState(LRI->PhysReg, regFree);
789 LRI->PhysReg = MCRegister();
790 LRI->Reloaded = true;
791 displacedAny = true;
792 break;
793 }
794 case regPreAssigned:
795 setRegUnitState(Unit, regFree);
796 displacedAny = true;
797 break;
798 case regFree:
799 break;
800 }
801 }
802 return displacedAny;
803}
804
805void RegAllocFastImpl::freePhysReg(MCRegister PhysReg) {
806 LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
807
808 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
809 switch (unsigned VirtReg = getRegUnitState(FirstUnit)) {
810 case regFree:
811 LLVM_DEBUG(dbgs() << '\n');
812 return;
813 case regPreAssigned:
814 LLVM_DEBUG(dbgs() << '\n');
815 setPhysRegState(PhysReg, regFree);
816 return;
817 default: {
818 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
819 assert(LRI != LiveVirtRegs.end());
820 LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
821 setPhysRegState(LRI->PhysReg, regFree);
822 LRI->PhysReg = MCRegister();
823 }
824 return;
825 }
826}
827
828/// Return the cost of spilling clearing out PhysReg and aliases so it is free
829/// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
830/// disabled - it can be allocated directly.
831/// \returns spillImpossible when PhysReg or an alias can't be spilled.
832unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
833 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
834 switch (unsigned VirtReg = getRegUnitState(Unit)) {
835 case regFree:
836 break;
837 case regPreAssigned:
838 LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
839 << printReg(PhysReg, TRI) << '\n');
840 return spillImpossible;
841 default: {
842 bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
843 findLiveVirtReg(VirtReg)->LiveOut;
844 return SureSpill ? spillClean : spillDirty;
845 }
846 }
847 }
848 return 0;
849}
850
851void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
852 Register VirtReg,
853 MCRegister Reg) {
854 auto UDBGValIter = DanglingDbgValues.find(VirtReg);
855 if (UDBGValIter == DanglingDbgValues.end())
856 return;
857
858 SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
859 for (MachineInstr *DbgValue : Dangling) {
860 assert(DbgValue->isDebugValue());
861 if (!DbgValue->hasDebugOperandForReg(VirtReg))
862 continue;
863
864 // Test whether the physreg survives from the definition to the DBG_VALUE.
865 MCRegister SetToReg = Reg;
866 unsigned Limit = 20;
867 for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
868 E = DbgValue->getIterator();
869 I != E; ++I) {
870 if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
871 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
872 << '\n');
873 SetToReg = MCRegister();
874 break;
875 }
876 }
877 for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
878 MO.setReg(SetToReg);
879 if (SetToReg)
880 MO.setIsRenamable();
881 }
882 }
883 Dangling.clear();
884}
885
886/// This method updates local state so that we know that PhysReg is the
887/// proper container for VirtReg now. The physical register must not be used
888/// for anything else when this is called.
889void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
890 MCRegister PhysReg) {
891 Register VirtReg = LR.VirtReg;
892 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
893 << printReg(PhysReg, TRI) << '\n');
894 assert(!LR.PhysReg && "Already assigned a physreg");
895 assert(PhysReg && "Trying to assign no register");
896 LR.PhysReg = PhysReg;
897 setPhysRegState(PhysReg, VirtReg.id());
898
899 assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
900}
901
902static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
903
904Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
905 static const unsigned ChainLengthLimit = 3;
906 for (unsigned C = 0; C <= ChainLengthLimit; ++C) {
907 if (Reg.isPhysical())
908 return Reg;
910
911 const MachineOperand *DefMO = MRI->getOneDef(Reg);
912 if (!DefMO)
913 return Register();
914 const MachineInstr *Def = DefMO->getParent();
915 if (!isCoalescable(*Def))
916 return Register();
917 Reg = Def->getOperand(1).getReg();
918 }
919 return Register();
920}
921
922/// Check if any of \p VirtReg's definitions is a copy. If it is follow the
923/// chain of copies to check whether we reach a physical register we can
924/// coalesce with.
925Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
926 static const unsigned DefLimit = 3;
927 unsigned C = 0;
928 for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
929 if (isCoalescable(MI)) {
930 Register Reg = MI.getOperand(1).getReg();
931 Reg = traceCopyChain(Reg);
932 if (Reg.isValid())
933 return Reg;
934 }
935
936 if (++C >= DefLimit)
937 break;
938 }
939 return Register();
940}
941
942/// Allocates a physical register for VirtReg.
943void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
944 Register Hint0, bool LookAtPhysRegUses) {
945 const Register VirtReg = LR.VirtReg;
946 assert(!LR.PhysReg);
947
948 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
949 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
950 << " in class " << TRI->getRegClassName(&RC)
951 << " with hint " << printReg(Hint0, TRI) << '\n');
952
953 // Take hint when possible.
954 if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
955 !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
956 // Take hint if the register is currently free.
957 if (isPhysRegFree(Hint0)) {
958 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
959 << '\n');
960 assignVirtToPhysReg(MI, LR, Hint0);
961 return;
962 } else {
963 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
964 << " occupied\n");
965 }
966 } else {
967 Hint0 = Register();
968 }
969
970 // Try other hint.
971 Register Hint1 = traceCopies(VirtReg);
972 if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
973 !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
974 // Take hint if the register is currently free.
975 if (isPhysRegFree(Hint1)) {
976 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
977 << '\n');
978 assignVirtToPhysReg(MI, LR, Hint1);
979 return;
980 } else {
981 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
982 << " occupied\n");
983 }
984 } else {
985 Hint1 = Register();
986 }
987
988 MCPhysReg BestReg = 0;
989 unsigned BestCost = spillImpossible;
990 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
991 for (MCPhysReg PhysReg : AllocationOrder) {
992 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
993 if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
994 LLVM_DEBUG(dbgs() << "already used in instr.\n");
995 continue;
996 }
997
998 unsigned Cost = calcSpillCost(PhysReg);
999 LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
1000 // Immediate take a register with cost 0.
1001 if (Cost == 0) {
1002 assignVirtToPhysReg(MI, LR, PhysReg);
1003 return;
1004 }
1005
1006 if (PhysReg == Hint0 || PhysReg == Hint1)
1007 Cost -= spillPrefBonus;
1008
1009 if (Cost < BestCost) {
1010 BestReg = PhysReg;
1011 BestCost = Cost;
1012 }
1013 }
1014
1015 if (!BestReg) {
1016 // Nothing we can do: Report an error and keep going with an invalid
1017 // allocation.
1018 LR.PhysReg = getErrorAssignment(LR, MI, RC);
1019 LR.Error = true;
1020 return;
1021 }
1022
1023 displacePhysReg(MI, BestReg);
1024 assignVirtToPhysReg(MI, LR, BestReg);
1025}
1026
1027void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1028 assert(MO.isUndef() && "expected undef use");
1029 Register VirtReg = MO.getReg();
1030 assert(VirtReg.isVirtual() && "Expected virtreg");
1031 if (!shouldAllocateRegister(VirtReg))
1032 return;
1033
1034 // If there are multiple undef uses, give them the same register. The def is
1035 // already freed, so take the register from the tie, not the lookup below.
1036 MachineInstr &MI = *MO.getParent();
1037 for (const MachineOperand &Tied : MI.all_uses()) {
1038 if (!Tied.isTied() || Tied.getReg() != VirtReg)
1039 continue;
1040 MCRegister DefReg =
1041 MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&Tied)))
1042 .getReg()
1043 .asMCReg();
1044 for (MachineOperand &O : MI.all_uses()) {
1045 if (O.getReg() != VirtReg)
1046 continue;
1047 // The def is already narrowed, so a tie takes its register whole.
1048 unsigned SubIdx = O.isTied() ? 0 : O.getSubReg();
1049 O.setReg(SubIdx ? TRI->getSubReg(DefReg, SubIdx) : DefReg);
1050 O.setSubReg(0);
1051 O.setIsRenamable(!MRI->isReserved(O.getReg()));
1052 }
1053 return;
1054 }
1055
1056 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1057 MCRegister PhysReg;
1058 bool IsRenamable = true;
1059 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1060 PhysReg = LRI->PhysReg;
1061 } else {
1062 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1063 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1064 if (AllocationOrder.empty()) {
1065 // All registers in the class were reserved.
1066 //
1067 // It might be OK to take any entry from the class as this is an undef
1068 // use, but accepting this would give different behavior than greedy and
1069 // basic.
1070 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1071 LRI->Error = true;
1072 IsRenamable = false;
1073 } else
1074 PhysReg = AllocationOrder.front();
1075 }
1076
1077 unsigned SubRegIdx = MO.getSubReg();
1078 if (SubRegIdx != 0) {
1079 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1080 MO.setSubReg(0);
1081 }
1082 MO.setReg(PhysReg);
1083 MO.setIsRenamable(IsRenamable);
1084}
1085
1086/// Variation of defineVirtReg() with special handling for livethrough regs
1087/// (tied or earlyclobber) that may interfere with preassigned uses.
1088/// \return true if MI's MachineOperands were re-arranged/invalidated.
1089bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1090 unsigned OpNum,
1091 Register VirtReg) {
1092 if (!shouldAllocateRegister(VirtReg))
1093 return false;
1094 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1095 if (LRI != LiveVirtRegs.end()) {
1096 MCRegister PrevReg = LRI->PhysReg;
1097 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1098 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1099 << " (tied/earlyclobber resolution)\n");
1100 freePhysReg(PrevReg);
1101 LRI->PhysReg = MCRegister();
1102 allocVirtReg(MI, *LRI, Register(), true);
1103 MachineBasicBlock::iterator InsertBefore =
1104 std::next((MachineBasicBlock::iterator)MI.getIterator());
1105 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1106 << printReg(PrevReg, TRI) << '\n');
1107 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1108 TII->get(TargetOpcode::COPY), PrevReg)
1109 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1110 }
1111 MachineOperand &MO = MI.getOperand(OpNum);
1112 if (MO.getSubReg() && !MO.isUndef()) {
1113 LRI->LastUse = &MI;
1114 }
1115 }
1116 return defineVirtReg(MI, OpNum, VirtReg, true);
1117}
1118
1119/// Allocates a register for VirtReg definition. Typically the register is
1120/// already assigned from a use of the virtreg, however we still need to
1121/// perform an allocation if:
1122/// - It is a dead definition without any uses.
1123/// - The value is live out and all uses are in different basic blocks.
1124///
1125/// \return true if MI's MachineOperands were re-arranged/invalidated.
1126bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1127 Register VirtReg, bool LookAtPhysRegUses) {
1128 assert(VirtReg.isVirtual() && "Not a virtual register");
1129 if (!shouldAllocateRegister(VirtReg))
1130 return false;
1131 MachineOperand &MO = MI.getOperand(OpNum);
1132 LiveRegMap::iterator LRI;
1133 bool New;
1134 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1135 if (New) {
1136 if (!MO.isDead()) {
1137 if (mayLiveOut(VirtReg)) {
1138 LRI->LiveOut = true;
1139 } else {
1140 // It is a dead def without the dead flag; add the flag now.
1141 MO.setIsDead(true);
1142 }
1143 }
1144 }
1145 if (!LRI->PhysReg) {
1146 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1147 } else {
1148 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1149 "TODO: preassign mismatch");
1150 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1151 << " use existing assignment to "
1152 << printReg(LRI->PhysReg, TRI) << '\n');
1153 }
1154
1155 MCRegister PhysReg = LRI->PhysReg;
1156 // Either flag means a reader below depends on the slot.
1157 if (LRI->Reloaded || LRI->LiveOut) {
1158 if (!MI.isImplicitDef()) {
1159 MachineBasicBlock::iterator SpillBefore =
1160 std::next((MachineBasicBlock::iterator)MI.getIterator());
1161 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1162 << " RL: " << LRI->Reloaded << '\n');
1163 bool Kill = LRI->LastUse == nullptr;
1164 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1165
1166 // We need to place additional spills for each indirect destination of an
1167 // INLINEASM_BR.
1168 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1169 int FI = StackSlotForVirtReg[VirtReg];
1170 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1171 for (MachineOperand &MO : MI.operands()) {
1172 if (MO.isMBB()) {
1173 MachineBasicBlock *Succ = MO.getMBB();
1174 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1175 &RC, VirtReg);
1176 ++NumStores;
1177 Succ->addLiveIn(PhysReg);
1178 }
1179 }
1180 }
1181
1182 LRI->LastUse = nullptr;
1183 } else if (!LRI->LastUse) {
1184 // No spill was inserted, so nothing below reads this def.
1185 MO.setIsDead(true);
1186 }
1187 // A def above spills only if a displacement above reloads again.
1188 LRI->LiveOut = false;
1189 LRI->Reloaded = false;
1190 }
1191 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1192 BundleVirtRegsMap[VirtReg] = *LRI;
1193 }
1194 markRegUsedInInstr(PhysReg);
1195 return setPhysReg(MI, MO, *LRI);
1196}
1197
1198/// Allocates a register for a VirtReg use.
1199/// \return true if MI's MachineOperands were re-arranged/invalidated.
1200bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1201 Register VirtReg) {
1202 assert(VirtReg.isVirtual() && "Not a virtual register");
1203 if (!shouldAllocateRegister(VirtReg))
1204 return false;
1205 LiveRegMap::iterator LRI;
1206 bool New;
1207 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1208 if (New) {
1209 if (!MO.isKill()) {
1210 if (mayLiveOut(VirtReg)) {
1211 LRI->LiveOut = true;
1212 } else {
1213 // It is a last (killing) use without the kill flag; add the flag now.
1214 MO.setIsKill(true);
1215 }
1216 }
1217 } else {
1218 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1219 }
1220
1221 // If necessary allocate a register.
1222 if (!LRI->PhysReg) {
1223 assert(!MO.isTied() && "tied op should be allocated");
1224 Register Hint;
1225 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1226 Hint = MI.getOperand(0).getReg();
1227 if (Hint.isVirtual()) {
1228 assert(!shouldAllocateRegister(Hint));
1229 Hint = Register();
1230 } else {
1231 assert(Hint.isPhysical() &&
1232 "Copy destination should already be assigned");
1233 }
1234 }
1235 allocVirtReg(MI, *LRI, Hint, false);
1236 }
1237
1238 LRI->LastUse = &MI;
1239
1240 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1241 BundleVirtRegsMap[VirtReg] = *LRI;
1242 }
1243 markRegUsedInInstr(LRI->PhysReg);
1244 return setPhysReg(MI, MO, *LRI);
1245}
1246
1247/// Query a physical register to use as a filler in contexts where the
1248/// allocation has failed. This will raise an error, but not abort the
1249/// compilation.
1250MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1251 MachineInstr &MI,
1252 const TargetRegisterClass &RC) {
1253 MachineFunction &MF = *MI.getMF();
1254
1255 // Avoid repeating the error every time a register is used.
1256 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1257 if (EmitError)
1258 MF.getProperties().setFailedRegAlloc();
1259
1260 // If the allocation order was empty, all registers in the class were
1261 // probably reserved. Fall back to taking the first register in the class,
1262 // even if it's reserved.
1263 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1264 if (AllocationOrder.empty()) {
1265 const Function &Fn = MF.getFunction();
1266 if (EmitError) {
1267 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1268 "no registers from class available to allocate", Fn,
1269 MI.getDebugLoc()));
1270 }
1271
1272 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1273 assert(!RawRegs.empty() && "register classes cannot have no registers");
1274 return RawRegs.front();
1275 }
1276
1277 if (!LR.Error && EmitError) {
1278 // Nothing we can do: Report an error and keep going with an invalid
1279 // allocation.
1280 if (MI.isInlineAsm()) {
1281 MI.emitInlineAsmError(
1282 "inline assembly requires more registers than available");
1283 } else {
1284 const Function &Fn = MBB->getParent()->getFunction();
1285 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1286 "ran out of registers during register allocation", Fn,
1287 MI.getDebugLoc()));
1288 }
1289 }
1290
1291 return AllocationOrder.front();
1292}
1293
1294/// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1295/// \return true if MI's MachineOperands were re-arranged/invalidated.
1296bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1297 const LiveReg &Assignment) {
1298 MCRegister PhysReg = Assignment.PhysReg;
1299 assert(PhysReg && "assignments should always be to a valid physreg");
1300
1301 if (LLVM_UNLIKELY(Assignment.Error)) {
1302 // Make sure we don't set renamable in error scenarios, as we may have
1303 // assigned to a reserved register.
1304 if (MO.isUse())
1305 MO.setIsUndef(true);
1306 }
1307
1308 if (!MO.getSubReg()) {
1309 MO.setReg(PhysReg);
1310 MO.setIsRenamable(!Assignment.Error);
1311 return false;
1312 }
1313
1314 // Handle subregister index.
1315 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1316 MO.setIsRenamable(!Assignment.Error);
1317
1318 // Note: We leave the subreg number around a little longer in case of defs.
1319 // This is so that the register freeing logic in allocateInstruction can still
1320 // recognize this as subregister defs. The code there will clear the number.
1321 if (!MO.isDef())
1322 MO.setSubReg(0);
1323
1324 // A kill flag implies killing the full register. Add corresponding super
1325 // register kill.
1326 if (MO.isKill()) {
1327 MI.addRegisterKilled(PhysReg, TRI, true);
1328 // Conservatively assume implicit MOs were re-arranged
1329 return true;
1330 }
1331
1332 // A <def,read-undef> of a sub-register requires an implicit def of the full
1333 // register.
1334 if (MO.isDef() && MO.isUndef()) {
1335 if (MO.isDead())
1336 MI.addRegisterDead(PhysReg, TRI, true);
1337 else
1338 MI.addRegisterDefined(PhysReg, TRI);
1339 // Conservatively assume implicit MOs were re-arranged
1340 return true;
1341 }
1342 return false;
1343}
1344
1345#ifndef NDEBUG
1346
1347void RegAllocFastImpl::dumpState() const {
1348 for (MCRegUnit Unit : TRI->regunits()) {
1349 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1350 case regFree:
1351 break;
1352 case regPreAssigned:
1353 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1354 break;
1355 case regLiveIn:
1356 llvm_unreachable("Should not have regLiveIn in map");
1357 default: {
1358 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1359 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1360 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1361 if (I->LiveOut || I->Reloaded) {
1362 dbgs() << '[';
1363 if (I->LiveOut)
1364 dbgs() << 'O';
1365 if (I->Reloaded)
1366 dbgs() << 'R';
1367 dbgs() << ']';
1368 }
1369 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1370 break;
1371 }
1372 }
1373 }
1374 dbgs() << '\n';
1375 // Check that LiveVirtRegs is the inverse.
1376 for (const LiveReg &LR : LiveVirtRegs) {
1377 Register VirtReg = LR.VirtReg;
1378 assert(VirtReg.isVirtual() && "Bad map key");
1379 MCRegister PhysReg = LR.PhysReg;
1380 if (PhysReg) {
1381 assert(PhysReg.isPhysical() && "mapped to physreg");
1382 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1383 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1384 }
1385 }
1386 }
1387}
1388#endif
1389
1390/// Count number of defs consumed from each register class by \p Reg
1391void RegAllocFastImpl::addRegClassDefCounts(
1392 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1393 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1394
1395 if (Reg.isVirtual()) {
1396 if (!shouldAllocateRegister(Reg))
1397 return;
1398 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1399 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1400 RCIdx != RCIdxEnd; ++RCIdx) {
1401 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1402 // FIXME: Consider aliasing sub/super registers.
1403 if (OpRC->hasSubClassEq(IdxRC))
1404 ++RegClassDefCounts[RCIdx];
1405 }
1406
1407 return;
1408 }
1409
1410 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1411 RCIdx != RCIdxEnd; ++RCIdx) {
1412 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1413 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1414 if (IdxRC->contains(*Alias)) {
1415 ++RegClassDefCounts[RCIdx];
1416 break;
1417 }
1418 }
1419 }
1420}
1421
1422/// Early clobber, partial def, or tied to a use that carries a value: the
1423/// register is occupied while the uses are read.
1424static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO) {
1425 assert(MO.isDef() && "expected def operand");
1426 if (MO.isEarlyClobber() || MO.readsReg())
1427 return true;
1428 return MO.isTied() &&
1429 !MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO))).isUndef();
1430}
1431
1432/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1433/// that are to be allocated. Those are ordered in a way that small classes,
1434/// early clobbers and livethroughs are allocated first.
1435void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1436 DefOperandIndexes.clear();
1437
1438 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1439 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1440 const MachineOperand &MO = MI.getOperand(I);
1441 if (!MO.isReg())
1442 continue;
1443 Register Reg = MO.getReg();
1444 if (MO.readsReg()) {
1445 if (Reg.isPhysical()) {
1446 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1447 markPhysRegUsedInInstr(Reg);
1448 }
1449 }
1450
1451 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1452 DefOperandIndexes.push_back(I);
1453 }
1454
1455 // Most instructions only have one virtual def, so there's no point in
1456 // computing the possible number of defs for every register class.
1457 if (DefOperandIndexes.size() <= 1)
1458 return;
1459
1460 // Track number of defs which may consume a register from the class. This is
1461 // used to assign registers for possibly-too-small classes first. Example:
1462 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1463 // registers first so that the gr32 don't use the gr32_abcd registers before
1464 // we assign these.
1465 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1466
1467 for (const MachineOperand &MO : MI.all_defs())
1468 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1469
1470 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1471 const MachineOperand &MO0 = MI.getOperand(I0);
1472 const MachineOperand &MO1 = MI.getOperand(I1);
1473 Register Reg0 = MO0.getReg();
1474 Register Reg1 = MO1.getReg();
1475 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1476 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1477
1478 // Identify regclass that are easy to use up completely just in this
1479 // instruction.
1480 unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1481 unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1482
1483 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1484 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1485 if (SmallClass0 > SmallClass1)
1486 return true;
1487 if (SmallClass0 < SmallClass1)
1488 return false;
1489
1490 // Allocate early clobbers and livethrough operands first.
1491 bool Livethrough0 = isLiveThroughDef(MI, MO0);
1492 bool Livethrough1 = isLiveThroughDef(MI, MO1);
1493 if (Livethrough0 > Livethrough1)
1494 return true;
1495 if (Livethrough0 < Livethrough1)
1496 return false;
1497
1498 // Tie-break rule: operand index.
1499 return I0 < I1;
1500 });
1501}
1502
1503void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1504 // Backwards, a def frees a register and a use occupies it. The phases:
1505 // * pre-assigned physreg defs
1506 // * virtual register defs
1507 // * free the def operands' registers
1508 // * displace registers clobbered by regmasks
1509 // * pre-assigned physreg uses
1510 // * virtual register uses, inserting reloads
1511 // * undef uses
1512 // * free early-clobber defs
1513 //
1514 // Freeing follows the def allocation so a def is not handed a register this
1515 // instruction also writes, and precedes the uses so a use may take one. It
1516 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1517 // freed last so that no use lands on them.
1518
1519 InstrGen += 2;
1520 // In the event we ever get more than 2**31 instructions...
1521 if (LLVM_UNLIKELY(InstrGen == 0)) {
1522 UsedInInstr.assign(UsedInInstr.size(), 0);
1523 InstrGen = 2;
1524 }
1525 RegMasks.clear();
1526 BundleVirtRegsMap.clear();
1527
1528 // Scan for special cases; Apply pre-assigned register defs to state.
1529 bool HasPhysRegUse = false;
1530 bool HasRegMask = false;
1531 bool HasVRegDef = false;
1532 bool HasDef = false;
1533 bool HasEarlyClobber = false;
1534 bool NeedToAssignLiveThroughs = false;
1535 for (MachineOperand &MO : MI.operands()) {
1536 if (MO.isReg()) {
1537 Register Reg = MO.getReg();
1538 if (Reg.isVirtual()) {
1539 if (!shouldAllocateRegister(Reg))
1540 continue;
1541 if (MO.isDef()) {
1542 HasDef = true;
1543 HasVRegDef = true;
1544 if (MO.isEarlyClobber())
1545 HasEarlyClobber = true;
1546 if (isLiveThroughDef(MI, MO))
1547 NeedToAssignLiveThroughs = true;
1548 }
1549 } else if (Reg.isPhysical()) {
1550 if (!MRI->isReserved(Reg)) {
1551 if (MO.isDef()) {
1552 HasDef = true;
1553 bool displacedAny = definePhysReg(MI, Reg);
1554 if (MO.isEarlyClobber())
1555 HasEarlyClobber = true;
1556 if (!displacedAny)
1557 MO.setIsDead(true);
1558 }
1559 if (MO.readsReg())
1560 HasPhysRegUse = true;
1561 }
1562 }
1563 } else if (MO.isRegMask()) {
1564 HasRegMask = true;
1565 RegMasks.push_back(MO.getRegMask());
1566 }
1567 }
1568
1569 // Allocate virtreg defs.
1570 if (HasDef) {
1571 if (HasVRegDef) {
1572 // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1573 // multiple times to ensure no operand is missed.
1574 bool ReArrangedImplicitOps = true;
1575
1576 // Special handling for early clobbers, tied operands or subregister defs:
1577 // Compared to "normal" defs these:
1578 // - Must not use a register that is pre-assigned for a use operand.
1579 // - In order to solve tricky inline assembly constraints we change the
1580 // heuristic to figure out a good operand order before doing
1581 // assignments.
1582 if (NeedToAssignLiveThroughs) {
1583 while (ReArrangedImplicitOps) {
1584 ReArrangedImplicitOps = false;
1585 findAndSortDefOperandIndexes(MI);
1586 for (unsigned OpIdx : DefOperandIndexes) {
1587 MachineOperand &MO = MI.getOperand(OpIdx);
1588 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1589 Register Reg = MO.getReg();
1590 if (isLiveThroughDef(MI, MO)) {
1591 ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1592 } else {
1593 ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1594 }
1595 // Implicit operands of MI were re-arranged,
1596 // re-compute DefOperandIndexes.
1597 if (ReArrangedImplicitOps)
1598 break;
1599 }
1600 }
1601 } else {
1602 // Assign virtual register defs.
1603 while (ReArrangedImplicitOps) {
1604 ReArrangedImplicitOps = false;
1605 for (MachineOperand &MO : MI.all_defs()) {
1606 Register Reg = MO.getReg();
1607 if (Reg.isVirtual()) {
1608 ReArrangedImplicitOps =
1609 defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1610 if (ReArrangedImplicitOps)
1611 break;
1612 }
1613 }
1614 }
1615 }
1616 }
1617
1618 // Free registers occupied by defs.
1619 // Iterate operands in reverse order, so we see the implicit super register
1620 // defs first (we added them earlier in case of <def,read-undef>).
1621 for (MachineOperand &MO : reverse(MI.all_defs())) {
1622 Register Reg = MO.getReg();
1623
1624 // subreg defs don't free the full register. We left the subreg number
1625 // around as a marker in setPhysReg() to recognize this case here.
1626 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1627 MO.setSubReg(0);
1628 continue;
1629 }
1630
1631 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1632 "tied def assigned to clobbered register");
1633
1634 // Do not free live-through defs.
1635 if (isLiveThroughDef(MI, MO))
1636 continue;
1637 if (!Reg)
1638 continue;
1639 if (Reg.isVirtual()) {
1640 assert(!shouldAllocateRegister(Reg));
1641 continue;
1642 }
1644 if (MRI->isReserved(Reg))
1645 continue;
1646 freePhysReg(Reg);
1647 unmarkRegUsedInInstr(Reg);
1648 }
1649 }
1650
1651 // A regmask is a def of every clobbered register: reload what lives in one
1652 // below MI. Nothing is reserved, so the uses may still take those registers.
1653 if (HasRegMask) {
1654 assert(!RegMasks.empty() && "expected RegMask");
1655 // MRI bookkeeping.
1656 for (const auto *RM : RegMasks)
1658
1659 for (const LiveReg &LR : LiveVirtRegs) {
1660 MCRegister PhysReg = LR.PhysReg;
1661 if (PhysReg && isClobberedByRegMasks(PhysReg))
1662 displacePhysReg(MI, PhysReg);
1663 }
1664 }
1665
1666 // Apply pre-assigned register uses to state.
1667 if (HasPhysRegUse) {
1668 for (MachineOperand &MO : MI.operands()) {
1669 if (!MO.isReg() || !MO.readsReg())
1670 continue;
1671 Register Reg = MO.getReg();
1672 if (!Reg.isPhysical())
1673 continue;
1674 if (MRI->isReserved(Reg))
1675 continue;
1676 if (!usePhysReg(MI, Reg))
1677 MO.setIsKill(true);
1678 }
1679 }
1680
1681 // Allocate virtreg uses and insert reloads as necessary.
1682 // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1683 // times to ensure no operand is missed.
1684 bool HasUndefUse = false;
1685 bool ReArrangedImplicitMOs = true;
1686 while (ReArrangedImplicitMOs) {
1687 ReArrangedImplicitMOs = false;
1688 for (MachineOperand &MO : MI.operands()) {
1689 if (!MO.isReg() || !MO.isUse())
1690 continue;
1691 Register Reg = MO.getReg();
1692 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1693 continue;
1694
1695 if (MO.isUndef()) {
1696 HasUndefUse = true;
1697 continue;
1698 }
1699
1700 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1701 // to physregs, so a def block allocated later can no longer see them.
1702 mayLiveIn(Reg);
1703
1704 assert(!MO.isInternalRead() && "Bundles not supported");
1705 assert(MO.readsReg() && "reading use");
1706 ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1707 if (ReArrangedImplicitMOs)
1708 break;
1709 }
1710 }
1711
1712 // Allocate undef operands. This is a separate step because in a situation
1713 // like ` = OP undef %X, %X` both operands need the same register assign
1714 // so we should perform the normal assignment first.
1715 if (HasUndefUse) {
1716 for (MachineOperand &MO : MI.all_uses()) {
1717 Register Reg = MO.getReg();
1718 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1719 continue;
1720
1721 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1722 allocVirtRegUndef(MO);
1723 }
1724 }
1725
1726 // Free early clobbers. Last, because they must not share a register with any
1727 // use.
1728 if (HasEarlyClobber) {
1729 for (MachineOperand &MO : reverse(MI.all_defs())) {
1730 if (!MO.isEarlyClobber())
1731 continue;
1732 assert(!MO.getSubReg() && "should be already handled in def processing");
1733
1734 Register Reg = MO.getReg();
1735 if (!Reg)
1736 continue;
1737 if (Reg.isVirtual()) {
1738 assert(!shouldAllocateRegister(Reg));
1739 continue;
1740 }
1741 assert(Reg.isPhysical() && "should have register assigned");
1742
1743 // We sometimes get odd situations like:
1744 // early-clobber %x0 = INSTRUCTION %x0
1745 // which is semantically questionable as the early-clobber should
1746 // apply before the use. But in practice we consider the use to
1747 // happen before the early clobber now. Don't free the early clobber
1748 // register in this case.
1749 if (MI.readsRegister(Reg, TRI))
1750 continue;
1751
1752 freePhysReg(Reg);
1753 }
1754 }
1755
1756 LLVM_DEBUG(dbgs() << "<< " << MI);
1757 if (MI.isCopy() &&
1758 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1759 MI.getOperand(0).isDead()) &&
1760 MI.getNumOperands() == 2) {
1761 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1762 Coalesced.push_back(&MI);
1763 }
1764}
1765
1766void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1767 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1768 // mostly constants and frame indices.
1769 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1770 for (const auto &MO : MI.debug_operands()) {
1771 if (!MO.isReg())
1772 continue;
1773 Register Reg = MO.getReg();
1774 if (!Reg.isVirtual())
1775 continue;
1776 if (!shouldAllocateRegister(Reg))
1777 continue;
1778
1779 // Already spilled to a stackslot?
1780 int SS = StackSlotForVirtReg[Reg];
1781 if (SS != -1) {
1782 // Modify DBG_VALUE now that the value is in a spill slot.
1784 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1785 continue;
1786 }
1787
1788 // See if this virtual register has already been allocated to a physical
1789 // register or spilled to a stack slot.
1790 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1792 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1793
1794 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1795 // Update every use of Reg within MI.
1796 for (auto &RegMO : DbgOps)
1797 setPhysReg(MI, *RegMO, *LRI);
1798 } else {
1799 DanglingDbgValues[Reg].push_back(&MI);
1800 }
1801
1802 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1803 // that future spills of Reg will have DBG_VALUEs.
1804 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1805 }
1806}
1807
1808void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1809 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1810 ++BundledMI;
1811 while (BundledMI->isBundledWithPred()) {
1812 for (MachineOperand &MO : BundledMI->operands()) {
1813 if (!MO.isReg())
1814 continue;
1815
1816 Register Reg = MO.getReg();
1817 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1818 continue;
1819
1820 auto DI = BundleVirtRegsMap.find(Reg);
1821 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1822
1823 setPhysReg(MI, MO, DI->second);
1824 }
1825
1826 ++BundledMI;
1827 }
1828}
1829
1830void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1831 this->MBB = &MBB;
1832 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1833
1834 PosIndexes.unsetInitialized();
1835 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1836 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1837
1838 for (const auto &LiveReg : MBB.liveouts())
1839 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1840
1841 Coalesced.clear();
1842
1843 // Traverse block in reverse order allocating instructions one by one.
1844 for (MachineInstr &MI : reverse(MBB)) {
1845 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1846
1847 // Special handling for debug values. Note that they are not allowed to
1848 // affect codegen of the other instructions in any way.
1849 if (MI.isDebugValue()) {
1850 handleDebugValue(MI);
1851 continue;
1852 }
1853
1854 allocateInstruction(MI);
1855
1856 // Once BUNDLE header is assigned registers, same assignments need to be
1857 // done for bundled MIs.
1858 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1859 handleBundle(MI);
1860 }
1861 }
1862
1863 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1864
1865 // Spill all physical registers holding virtual registers now.
1866 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1867 reloadAtBegin(MBB);
1868
1869 // Erase all the coalesced copies. We are delaying it until now because
1870 // LiveVirtRegs might refer to the instrs.
1871 for (MachineInstr *MI : Coalesced)
1872 MBB.erase(MI);
1873 NumCoalesced += Coalesced.size();
1874
1875 for (auto &UDBGPair : DanglingDbgValues) {
1876 for (MachineInstr *DbgValue : UDBGPair.second) {
1877 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1878 // Nothing to do if the vreg was spilled in the meantime.
1879 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1880 continue;
1881 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1882 << '\n');
1883 DbgValue->setDebugValueUndef();
1884 }
1885 }
1886 DanglingDbgValues.clear();
1887
1888 LLVM_DEBUG(MBB.dump());
1889}
1890
1891bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
1892 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1893 << "********** Function: " << MF.getName() << '\n');
1894 MRI = &MF.getRegInfo();
1895 const TargetSubtargetInfo &STI = MF.getSubtarget();
1896 TRI = STI.getRegisterInfo();
1897 TII = STI.getInstrInfo();
1898 MFI = &MF.getFrameInfo();
1899 MRI->freezeReservedRegs();
1900 RegClassInfo.runOnMachineFunction(MF);
1901 unsigned NumRegUnits = TRI->getNumRegUnits();
1902 InstrGen = 0;
1903 UsedInInstr.assign(NumRegUnits, 0);
1904
1905 // initialize the virtual->physical register map to have a 'null'
1906 // mapping for all virtual registers
1907 unsigned NumVirtRegs = MRI->getNumVirtRegs();
1908 StackSlotForVirtReg.resize(NumVirtRegs);
1909 LiveVirtRegs.setUniverse(NumVirtRegs);
1910 MayLiveAcrossBlocks.clear();
1911 MayLiveAcrossBlocks.resize(NumVirtRegs);
1912
1913 // Loop over all of the basic blocks, eliminating virtual register references
1914 for (MachineBasicBlock &MBB : MF)
1915 allocateBasicBlock(MBB);
1916
1917 if (ClearVirtRegs) {
1918 // All machine operands and other references to virtual registers have been
1919 // replaced. Remove the virtual registers.
1920 MRI->clearVirtRegs();
1921 }
1922
1923 StackSlotForVirtReg.clear();
1924 LiveDbgValueMap.clear();
1925 return true;
1926}
1927
1930 MFPropsModifier _(*this, MF);
1931 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1932 bool Changed = Impl.runOnMachineFunction(MF);
1933 if (!Changed)
1934 return PreservedAnalyses::all();
1936 PA.preserveSet<CFGAnalyses>();
1937 return PA;
1938}
1939
1941 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1942 bool PrintFilterName = Opts.FilterName != "all";
1943 bool PrintNoClearVRegs = !Opts.ClearVRegs;
1944 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1945
1946 OS << "regallocfast";
1947 if (PrintFilterName || PrintNoClearVRegs) {
1948 OS << '<';
1949 if (PrintFilterName)
1950 OS << "filter=" << Opts.FilterName;
1951 if (PrintSemicolon)
1952 OS << ';';
1953 if (PrintNoClearVRegs)
1954 OS << "no-clear-vregs";
1955 OS << '>';
1956 }
1957}
1958
1959FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1960
1962 bool ClearVirtRegs) {
1963 return new RegAllocFast(Ftor, ClearVirtRegs);
1964}
#define DBG(...)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
MachineBasicBlock & MBB
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:352
This file defines the DenseMap class.
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
This file implements an indexed map.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isCoalescable(const MachineInstr &MI)
static cl::opt< bool > IgnoreMissingDefs("rafast-ignore-missing-defs", cl::Hidden)
static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO)
Early clobber, partial def, or tied to a use that carries a value: the register is occupied while the...
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
iterator end()
Definition DenseMap.h:702
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Store the specified register of the given register class to the specified stack frame index.
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Load the specified register of the given register class from the specified stack frame index.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
void resize(typename StorageT::size_type S)
Definition IndexedMap.h:67
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
unsigned getID() const
getID() - Return the register class ID number.
ArrayRef< MCPhysReg > getRegisters() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
iterator_range< liveout_iterator > liveouts() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void dump() const
Instructions::iterator instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
void setDebugValueUndef()
Sets all register debug operands in this debug value instruction to be undef.
const MachineBasicBlock * getParent() const
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
MachineOperand * getOneDef(Register Reg) const
Returns the defining operand if there is exactly one operand defining the specified register,...
LLVM_ABI void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
const MachineFunction & getMF() const
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
Definition Register.h:87
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void assign(size_type NumElts, ValueParamT Elt)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
@ Kill
The last use of a register.
LLVM_ABI void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg)
Update a DBG_VALUE whose value has been spilled to FrameIndex.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI MachineInstr * buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I, const MachineInstr &Orig, int FrameIndex, Register SpillReg)
Clone a DBG_VALUE whose value has been spilled to FrameIndex.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58