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