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/// Where the target enables it, TwoAddressInstructionPass is left out of the
21/// pipeline: this pass lowers tied operands and expands REG_SEQUENCE and
22/// INSERT_SUBREG itself.
23//
24//===----------------------------------------------------------------------===//
25
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/IndexedMap.h"
30#include "llvm/ADT/MapVector.h"
31#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SparseSet.h"
34#include "llvm/ADT/Statistic.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
56#include <cassert>
57#include <tuple>
58#include <vector>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "regalloc"
63
64STATISTIC(NumStores, "Number of stores added");
65STATISTIC(NumLoads, "Number of loads added");
66STATISTIC(NumCoalesced, "Number of copies coalesced");
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 = nullptr;
198 const RegAllocFilterFunc ShouldAllocateRegisterImpl;
199
200 /// Tied operands reach this pass unrewritten (TwoAddressInstructionPass was
201 /// left out of the pipeline): lower them here.
202 bool LowerTiedOps = false;
203
204 /// Basic block currently being allocated.
205 MachineBasicBlock *MBB = nullptr;
206
207 /// Maps virtual regs to the frame index where these values are spilled.
208 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
209
210 /// A virtual register live at the current point of the backward walk.
211 /// Created at its last reference, cleared only when the block is done.
212 struct LiveReg {
213 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
214 Register VirtReg; ///< Virtual register number.
215 MCRegister PhysReg; ///< Currently held here, 0 if none.
216 bool LiveOut = false; ///< May be live out; the def spills.
217 bool Reloaded = false; ///< Reloaded below; the def spills.
218 bool Error = false; ///< Could not allocate.
219
220 explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
221 explicit LiveReg() = default;
222
223 unsigned getSparseSetIndex() const { return VirtReg.virtRegIndex(); }
224 };
225
226 using LiveRegMap = SparseSet<LiveReg, unsigned, identity, uint16_t>;
227 /// This map contains entries for each virtual register that is currently
228 /// available in a physical register.
229 LiveRegMap LiveVirtRegs;
230
231 /// Stores assigned virtual registers present in the bundle MI.
232 DenseMap<Register, LiveReg> BundleVirtRegsMap;
233
234 DenseMap<Register, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
235 /// List of DBG_VALUE that we encountered without the vreg being assigned
236 /// because they were placed after the last use of the vreg.
237 DenseMap<Register, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
238
239 /// Has a bit set for every virtual register for which it was determined
240 /// that it is alive across blocks.
241 BitVector MayLiveAcrossBlocks;
242
243 /// What occupies a register unit. Registers interfere exactly when their
244 /// unit sets intersect, so overlap needs no alias walk.
245 enum RegUnitState {
246 /// Not in use; a register is allocatable iff all of its units are free.
247 regFree,
248
249 /// Not available to the allocator and not a virtual register: a physreg
250 /// operand or a block live-out. Cannot be spilled.
251 regPreAssigned,
252
253 /// Scratch marker: reloadAtBegin() stamps MBB.liveins() over the finished
254 /// map, and a virtual register left in a live-in register is not reloaded.
255 regLiveIn,
256
257 /// Any other value is a virtual register number (>= VirtualRegFlag);
258 /// LiveVirtRegs holds the inverse mapping.
259 };
260
261 /// State of each register unit, indexed by MCRegUnit.
262 std::vector<unsigned> RegUnitStates;
263
265
266 /// Track register units that are used in the current instruction, and so
267 /// cannot be allocated.
268 ///
269 /// In the first phase (tied defs/early clobber), we consider also physical
270 /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
271 /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
272 /// avoid resetting the entire vector after every instruction, we track the
273 /// instruction "generation" in the remaining 31 bits -- this means, that if
274 /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
275 /// never zero and always incremented by two.
276 ///
277 /// Don't allocate inline storage: the number of register units is typically
278 /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
279 uint32_t InstrGen;
280 SmallVector<unsigned, 0> UsedInInstr;
281
282 /// Physical registers with a non-dead def on the current instruction.
283 SmallVector<MCRegister, 4> LiveDefRegs;
284
285 SmallVector<unsigned, 8> DefOperandIndexes;
286
287 /// Set if an error assignment was used for a def in the current instruction.
288 bool HasErrorDef = false;
289
290 // Register masks attached to the current instruction.
292
293 // Assign index for each instruction to quickly determine dominance.
294 InstrPosIndexes PosIndexes;
295
296 void setRegUnitState(MCRegUnit Unit, unsigned NewState);
297 unsigned getRegUnitState(MCRegUnit Unit) const;
298
299 void setPhysRegState(MCRegister PhysReg, unsigned NewState);
300 bool isPhysRegFree(MCRegister PhysReg) const;
301
302 /// Mark a physreg as used in this instruction.
303 void markRegUsedInInstr(MCRegister PhysReg) {
304 for (MCRegUnit Unit : TRI->regunits(PhysReg))
305 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen | 1;
306 }
307
308 // Check if physreg is clobbered by instruction's regmask(s).
309 bool isClobberedByRegMasks(MCRegister PhysReg) const {
310 return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
311 return MachineOperand::clobbersPhysReg(Mask, PhysReg);
312 });
313 }
314
315 /// Check if a physreg or any of its aliases are used in this instruction.
316 bool isRegUsedInInstr(MCRegister PhysReg, bool LookAtPhysRegUses) const {
317 if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
318 return true;
319 for (MCRegUnit Unit : TRI->regunits(PhysReg))
320 if (UsedInInstr[static_cast<unsigned>(Unit)] >=
321 (InstrGen | !LookAtPhysRegUses))
322 return true;
323 return false;
324 }
325
326 /// Mark physical register as being used in a register use operand.
327 /// This is only used by the special livethrough handling code.
328 void markPhysRegUsedInInstr(MCRegister PhysReg) {
329 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
330 assert(UsedInInstr[static_cast<unsigned>(Unit)] <= InstrGen &&
331 "non-phys use before phys use?");
332 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen;
333 }
334 }
335
336 /// Remove mark of physical register being used in the instruction.
337 void unmarkRegUsedInInstr(MCRegister PhysReg) {
338 for (MCRegUnit Unit : TRI->regunits(PhysReg))
339 UsedInInstr[static_cast<unsigned>(Unit)] = 0;
340 }
341
342 /// Check if \p PhysReg or a super-register has a non-dead def on the current
343 /// instruction.
344 bool hasLiveDefOfSuperReg(MCRegister PhysReg) const {
345 return any_of(LiveDefRegs, [&](MCRegister LiveReg) {
346 return TRI->isSuperRegisterEq(PhysReg, LiveReg);
347 });
348 }
349
350 enum : unsigned {
351 spillClean = 50,
352 spillDirty = 100,
353 spillPrefBonus = 20,
354 spillImpossible = ~0u
355 };
356
357public:
358 bool ClearVirtRegs;
359
360 bool runOnMachineFunction(MachineFunction &MF, RegisterClassInfo &RCI);
361
362private:
363 void allocateBasicBlock(MachineBasicBlock &MBB);
364 void expandSubregPseudo(MachineInstr &MI);
365
366 void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
367 Register Reg) const;
368
369 void findAndSortDefOperandIndexes(const MachineInstr &MI);
370
371 void allocateInstruction(MachineInstr &MI);
372 void handleDebugValue(MachineInstr &MI);
373 void handleBundle(MachineInstr &MI);
374
375 bool usePhysReg(MachineInstr &MI, MCRegister PhysReg);
376 bool definePhysReg(MachineInstr &MI, MCRegister PhysReg);
377 bool displacePhysReg(MachineInstr &MI, MCRegister PhysReg);
378 void freePhysReg(MCRegister PhysReg);
379
380 unsigned calcSpillCost(MCPhysReg PhysReg) const;
381
382 LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
383 return LiveVirtRegs.find(VirtReg.virtRegIndex());
384 }
385
386 LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
387 return LiveVirtRegs.find(VirtReg.virtRegIndex());
388 }
389
390 void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCRegister PhysReg);
391 void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
392 bool LookAtPhysRegUses = false);
393 void allocVirtRegUndef(MachineOperand &MO);
394 void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
395 MCRegister Reg);
396 void defineLiveThroughVirtReg(MachineInstr &MI, MachineOperand &MO,
397 Register VirtReg);
398 void defineVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg,
399 bool LookAtPhysRegUses = false);
400 void useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
401 bool lowerTiedUse(MachineInstr &MI, MachineOperand &MO, LiveReg &LR);
402
403 MCPhysReg getErrorAssignment(const LiveReg &LR, MachineInstr &MI,
404 const TargetRegisterClass &RC);
405
407 getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
408 SmallSet<Register, 2> &PrologLiveIns) const;
409
410 void reloadAtBegin(MachineBasicBlock &MBB);
411 void setPhysReg(MachineOperand &MO, const LiveReg &Assignment);
412 void addImplicitOps(MachineInstr &MI);
413
414 /// Implicit full-register operands for subregister operands, added after
415 /// operand iteration because adding them can reorder implicit operands.
416 enum ImplicitOpKind { ImplicitKill, ImplicitDead, ImplicitDef };
418
419 Register traceCopies(Register VirtReg) const;
420 Register traceCopyChain(Register Reg) const;
421
422 bool shouldAllocateRegister(const Register Reg) const;
423 int getStackSpaceFor(Register VirtReg);
424 void spill(MachineBasicBlock::iterator Before, Register VirtReg,
425 MCRegister AssignedReg, bool Kill, bool LiveOut);
426 void reload(MachineBasicBlock::iterator Before, Register VirtReg,
427 MCRegister PhysReg);
428
429 bool mayLiveOut(Register VirtReg);
430 bool mayLiveIn(Register VirtReg);
431
432 bool mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const;
433
434 void dumpState() const;
435};
436
437class RegAllocFast : public MachineFunctionPass {
438 RegAllocFastImpl Impl;
439
440public:
441 static char ID;
442
443 RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
444 : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
445
446 bool runOnMachineFunction(MachineFunction &MF) override {
447 return Impl.runOnMachineFunction(
448 MF, getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI());
449 }
450
451 StringRef getPassName() const override { return "Fast Register Allocator"; }
452
453 void getAnalysisUsage(AnalysisUsage &AU) const override {
454 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
455 AU.setPreservesCFG();
457 }
458
459 MachineFunctionProperties getRequiredProperties() const override {
460 return MachineFunctionProperties().setNoPHIs();
461 }
462
463 MachineFunctionProperties getSetProperties() const override {
464 MachineFunctionProperties P;
465 if (Impl.ClearVirtRegs)
466 P.setNoVRegs().setTiedOpsRewritten();
467 return P;
468 }
469
470 MachineFunctionProperties getClearedProperties() const override {
471 return MachineFunctionProperties().setIsSSA();
472 }
473};
474
475} // end anonymous namespace
476
477char RegAllocFast::ID = 0;
478
479INITIALIZE_PASS_BEGIN(RegAllocFast, "regallocfast", "Fast Register Allocator",
480 false, false)
482INITIALIZE_PASS_END(RegAllocFast, "regallocfast", "Fast Register Allocator",
484
485bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
486 assert(Reg.isVirtual());
487 if (!ShouldAllocateRegisterImpl)
488 return true;
489
490 return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
491}
492
493void RegAllocFastImpl::setRegUnitState(MCRegUnit Unit, unsigned NewState) {
494 RegUnitStates[static_cast<unsigned>(Unit)] = NewState;
495}
496
497unsigned RegAllocFastImpl::getRegUnitState(MCRegUnit Unit) const {
498 return RegUnitStates[static_cast<unsigned>(Unit)];
499}
500
501void RegAllocFastImpl::setPhysRegState(MCRegister PhysReg, unsigned NewState) {
502 for (MCRegUnit Unit : TRI->regunits(PhysReg))
503 setRegUnitState(Unit, NewState);
504}
505
506bool RegAllocFastImpl::isPhysRegFree(MCRegister PhysReg) const {
507 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
508 if (getRegUnitState(Unit) != regFree)
509 return false;
510 }
511 return true;
512}
513
514/// This allocates space for the specified virtual register to be held on the
515/// stack.
516int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
517 // Find the location Reg would belong...
518 int SS = StackSlotForVirtReg[VirtReg];
519 // Already has space allocated?
520 if (SS != -1)
521 return SS;
522
523 // Allocate a new stack object for this spill location...
524 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
525 unsigned Size = TRI->getSpillSize(RC);
526 Align Alignment = TRI->getSpillAlign(RC);
527
528 const MachineFunction &MF = MRI->getMF();
529 auto &ST = MF.getSubtarget();
530 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
531 if (Alignment > CurrentAlign && !TRI->canRealignStack(MF))
532 Alignment = CurrentAlign;
533
534 int FrameIdx =
535 MFI->CreateSpillStackObject(Size, Alignment, TRI->getSpillStackID(RC));
536
537 // Assign the slot.
538 StackSlotForVirtReg[VirtReg] = FrameIdx;
539 return FrameIdx;
540}
541
542static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
543 const MachineInstr &B) {
544 uint64_t IndexA, IndexB;
545 PosIndexes.getIndex(A, IndexA);
546 // getIndex() returns true when it renumbered the block, invalidating IndexA.
547 if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
548 PosIndexes.getIndex(A, IndexA);
549 return IndexA < IndexB;
550}
551
552/// Returns true if \p MI is a spill of a live-in physical register in a block
553/// targeted by an INLINEASM_BR. Such spills must precede reloads of live-in
554/// virtual registers, so that we do not reload from an uninitialized stack
555/// slot.
556bool RegAllocFastImpl::mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const {
557 int FI;
558 auto *MBB = MI.getParent();
560 MFI->isSpillSlotObjectIndex(FI))
561 for (const auto &Op : MI.operands())
562 if (Op.isReg() && Op.getReg().isValid() && MBB->isLiveIn(Op.getReg()))
563 return true;
564 return false;
565}
566
567/// Returns false if \p VirtReg is known to not live out of the current block.
568bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
569 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex())) {
570 // Cannot be live-out if there are no successors.
571 return !MBB->succ_empty();
572 }
573
574 const MachineInstr *SelfLoopDef = nullptr;
575
576 // If this block loops back to itself, it is necessary to check whether the
577 // use comes after the def.
578 if (MBB->isSuccessor(MBB)) {
579 // Find the first def in the self loop MBB.
580 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
581 if (DefInst.getParent() != MBB) {
582 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
583 return true;
584 } else {
585 if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
586 SelfLoopDef = &DefInst;
587 }
588 }
589 if (!SelfLoopDef) {
590 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
591 return true;
592 }
593 }
594
595 // See if the first \p Limit uses of the register are all in the current
596 // block.
597 static const unsigned Limit = 8;
598 unsigned C = 0;
599 for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
600 if (UseInst.getParent() != MBB || ++C >= Limit) {
601 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
602 // Cannot be live-out if there are no successors.
603 return !MBB->succ_empty();
604 }
605
606 if (SelfLoopDef) {
607 // Try to handle some simple cases to avoid spilling and reloading every
608 // value inside a self looping block.
609 if (SelfLoopDef == &UseInst ||
610 !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
611 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
612 return true;
613 }
614 }
615 }
616
617 return false;
618}
619
620/// Returns false if \p VirtReg is known to not be live into the current block.
621bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
622 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex()))
623 return !MBB->pred_empty();
624
625 // See if the first \p Limit def of the register are all in the current block.
626 static const unsigned Limit = 8;
627 unsigned C = 0;
628 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
629 if (DefInst.getParent() != MBB || ++C >= Limit) {
630 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
631 return !MBB->pred_empty();
632 }
633 }
634
635 return false;
636}
637
638/// Insert spill instruction for \p AssignedReg before \p Before. Update
639/// DBG_VALUEs with \p VirtReg operands with the stack slot.
640void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
641 Register VirtReg, MCRegister AssignedReg,
642 bool Kill, bool LiveOut) {
643 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
644 << printReg(AssignedReg, TRI));
645 int FI = getStackSpaceFor(VirtReg);
646 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
647
648 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
649 TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, VirtReg);
650 ++NumStores;
651
653
654 // When we spill a virtual register, we will have spill instructions behind
655 // every definition of it, meaning we can switch all the DBG_VALUEs over
656 // to just reference the stack slot.
657 SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
658 SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
659 SpilledOperandsMap;
660 for (MachineOperand *MO : LRIDbgOperands)
661 SpilledOperandsMap[MO->getParent()].push_back(MO);
662 for (const auto &MISpilledOperands : SpilledOperandsMap) {
663 MachineInstr &DBG = *MISpilledOperands.first;
664 // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
665 if (DBG.isDebugValueList())
666 continue;
667 MachineInstr *NewDV = buildDbgValueForSpill(
668 *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
669 assert(NewDV->getParent() == MBB && "dangling parent pointer");
670 (void)NewDV;
671 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
672
673 if (LiveOut) {
674 // We need to insert a DBG_VALUE at the end of the block if the spill slot
675 // is live out, but there is another use of the value after the
676 // spill. This will allow LiveDebugValues to see the correct live out
677 // value to propagate to the successors.
678 MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
679 MBB->insert(FirstTerm, ClonedDV);
680 LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
681 }
682
683 // Rewrite the dbg_values to use the stack slot too, whether or not they
684 // were assigned a register. They all come after the spill, so the slot
685 // holds the value wherever they are, but the register can be clobbered
686 // before the end of the block. A dbg_value left on the register would
687 // also override the one inserted above, leaving a hole in the variable's
688 // location from the clobber until the clone before the terminator.
689 // TODO We can potentially do this for list debug values as well.
690 if (DBG.isNonListDebugValue()) {
691 MachineOperand &MO = DBG.getDebugOperand(0);
692 if (MO.isReg())
694 }
695 }
696 // Now this register is spilled there is should not be any DBG_VALUE
697 // pointing to this register because they are all pointing to spilled value
698 // now.
699 LRIDbgOperands.clear();
700}
701
702/// Insert reload instruction for \p PhysReg before \p Before.
703void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
704 Register VirtReg, MCRegister PhysReg) {
705 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
706 << printReg(PhysReg, TRI) << '\n');
707 int FI = getStackSpaceFor(VirtReg);
708 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
709 TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, VirtReg);
710 ++NumLoads;
711}
712
713/// Get basic block begin insertion point.
714/// This is not just MBB.begin() because surprisingly we have EH_LABEL
715/// instructions marking the begin of a basic block. This means we must insert
716/// new instructions after such labels...
717MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
718 MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
720 while (I != MBB.end()) {
721 if (I->isLabel()) {
722 ++I;
723 continue;
724 }
725
726 // Skip prologues and inlineasm_br spills to place reloads afterwards.
727 if (!TII->isBasicBlockPrologue(*I) && !mayBeSpillFromInlineAsmBr(*I))
728 break;
729
730 // However if a prolog instruction reads a register that needs to be
731 // reloaded, the reload should be inserted before the prolog.
732 for (MachineOperand &MO : I->operands()) {
733 if (MO.isReg())
734 PrologLiveIns.insert(MO.getReg());
735 }
736
737 ++I;
738 }
739
740 return I;
741}
742
743/// Reload all currently assigned virtual registers.
744void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
745 if (LiveVirtRegs.empty())
746 return;
747
748 // Mark live-in registers so the loop below skips reloads into them. The
749 // virtual register mappings this overwrites are not needed anymore.
750 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins())
751 setPhysRegState(P.PhysReg, regLiveIn);
752
753 SmallSet<Register, 2> PrologLiveIns;
754
755 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
756 // of spilling here is deterministic, if arbitrary.
757 MachineBasicBlock::iterator InsertBefore =
758 getMBBBeginInsertionPoint(MBB, PrologLiveIns);
759 for (const LiveReg &LR : LiveVirtRegs) {
760 MCRegister PhysReg = LR.PhysReg;
761 if (!PhysReg || LR.Error)
762 continue;
763
764 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
765 if (getRegUnitState(FirstUnit) == regLiveIn)
766 continue;
767
768 assert(&MBB != &MBB.getParent()->front() &&
769 "no reload in start block. Missing vreg def?");
770
771 if (PrologLiveIns.count(PhysReg)) {
772 // FIXME: Theoretically this should use an insert point skipping labels
773 // but I'm not sure how labels should interact with prolog instruction
774 // that need reloads.
775 reload(MBB.begin(), LR.VirtReg, PhysReg);
776 } else
777 reload(InsertBefore, LR.VirtReg, PhysReg);
778 }
779 LiveVirtRegs.clear();
780}
781
782/// Handle the direct use of a physical register. Displace whatever occupies it
783/// and mark it pre-assigned: backwards, a use means live from here upward.
784/// Returns false if nothing was displaced, so the use is a kill. This may add
785/// implicit kills to MO->getParent() and invalidate MO.
786bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCRegister Reg) {
787 assert(Reg.isPhysical() && "expected physreg");
788 bool displacedAny = displacePhysReg(MI, Reg);
789 setPhysRegState(Reg, regPreAssigned);
790 markRegUsedInInstr(Reg);
791 return displacedAny;
792}
793
794/// Displace whatever holds \p Reg and reserve it, so a virtual register def
795/// cannot land on a register this instruction already writes. Released in the
796/// free-def-operands step, after the uses for an early clobber, or by
797/// lowerTiedUse(); if the instruction also reads \p Reg it ends up reserved
798/// for the code above.
799bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCRegister Reg) {
800 bool displacedAny = displacePhysReg(MI, Reg);
801 setPhysRegState(Reg, regPreAssigned);
802 return displacedAny;
803}
804
805/// Mark PhysReg as reserved or free after spilling any virtregs. This is very
806/// similar to defineVirtReg except the physreg is reserved instead of
807/// allocated.
808bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCRegister PhysReg) {
809 bool displacedAny = false;
810
811 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
812 switch (unsigned VirtReg = getRegUnitState(Unit)) {
813 default: {
814 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
815 assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
816 MachineBasicBlock::iterator ReloadBefore =
817 std::next((MachineBasicBlock::iterator)MI.getIterator());
818 while (mayBeSpillFromInlineAsmBr(*ReloadBefore))
819 ++ReloadBefore;
820 reload(ReloadBefore, VirtReg, LRI->PhysReg);
821
822 setPhysRegState(LRI->PhysReg, regFree);
823 LRI->PhysReg = MCRegister();
824 LRI->Reloaded = true;
825 displacedAny = true;
826 break;
827 }
828 case regPreAssigned:
829 setRegUnitState(Unit, regFree);
830 displacedAny = true;
831 break;
832 case regFree:
833 break;
834 }
835 }
836 return displacedAny;
837}
838
839void RegAllocFastImpl::freePhysReg(MCRegister PhysReg) {
840 LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
841
842 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
843 switch (unsigned VirtReg = getRegUnitState(FirstUnit)) {
844 case regFree:
845 LLVM_DEBUG(dbgs() << '\n');
846 return;
847 case regPreAssigned:
848 LLVM_DEBUG(dbgs() << '\n');
849 setPhysRegState(PhysReg, regFree);
850 return;
851 default: {
852 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
853 assert(LRI != LiveVirtRegs.end());
854 LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
855 setPhysRegState(LRI->PhysReg, regFree);
856 LRI->PhysReg = MCRegister();
857 }
858 return;
859 }
860}
861
862/// Return the cost of spilling clearing out PhysReg and aliases so it is free
863/// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
864/// disabled - it can be allocated directly.
865/// \returns spillImpossible when PhysReg or an alias can't be spilled.
866unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
867 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
868 switch (unsigned VirtReg = getRegUnitState(Unit)) {
869 case regFree:
870 break;
871 case regPreAssigned:
872 LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
873 << printReg(PhysReg, TRI) << '\n');
874 return spillImpossible;
875 default: {
876 bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
877 findLiveVirtReg(VirtReg)->LiveOut;
878 return SureSpill ? spillClean : spillDirty;
879 }
880 }
881 }
882 return 0;
883}
884
885void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
886 Register VirtReg,
887 MCRegister Reg) {
888 auto UDBGValIter = DanglingDbgValues.find(VirtReg);
889 if (UDBGValIter == DanglingDbgValues.end())
890 return;
891
892 SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
893 for (MachineInstr *DbgValue : Dangling) {
894 assert(DbgValue->isDebugValue());
895 if (!DbgValue->hasDebugOperandForReg(VirtReg))
896 continue;
897
898 // Test whether the physreg survives from the definition to the DBG_VALUE.
899 // A tied use that took over its def's register is assigned at an
900 // instruction that overwrites it, so start the scan there.
901 MCRegister SetToReg = Reg;
902 unsigned Limit = 20;
903 MachineBasicBlock::iterator I = Definition.getIterator();
904 if (!Definition.definesRegister(Reg, TRI))
905 ++I;
906 for (MachineBasicBlock::iterator E = DbgValue->getIterator(); I != E; ++I) {
907 if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
908 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
909 << '\n');
910 SetToReg = MCRegister();
911 break;
912 }
913 }
914 for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
915 MO.setReg(SetToReg);
916 if (SetToReg)
917 MO.setIsRenamable();
918 }
919 }
920 Dangling.clear();
921}
922
923/// This method updates local state so that we know that PhysReg is the
924/// proper container for VirtReg now. The physical register must not be used
925/// for anything else when this is called.
926void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
927 MCRegister PhysReg) {
928 Register VirtReg = LR.VirtReg;
929 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
930 << printReg(PhysReg, TRI) << '\n');
931 assert(!LR.PhysReg && "Already assigned a physreg");
932 assert(PhysReg && "Trying to assign no register");
933 LR.PhysReg = PhysReg;
934 setPhysRegState(PhysReg, VirtReg.id());
935
936 assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
937}
938
939static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
940
941/// The operand \p MO is tied to.
943 const MachineOperand &MO) {
944 return MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO)));
945}
946
947/// The register \p DefMO's tied use reads, when the two end up in the same
948/// register: a subregister index on either side makes them differ.
950 const MachineOperand &DefMO) {
951 if (!DefMO.isTied() || DefMO.getSubReg())
952 return Register();
953 const MachineOperand &UseMO = getTiedOperand(MI, DefMO);
954 return UseMO.getSubReg() ? Register() : UseMO.getReg();
955}
956
957Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
958 static const unsigned ChainLengthLimit = 3;
959 for (unsigned C = 0; C <= ChainLengthLimit; ++C) {
960 if (Reg.isPhysical())
961 return Reg;
963
964 const MachineOperand *DefMO = MRI->getOneDef(Reg);
965 if (!DefMO)
966 return Register();
967 const MachineInstr *Def = DefMO->getParent();
968 if (isCoalescable(*Def)) {
969 Reg = Def->getOperand(1).getReg();
970 continue;
971 }
972 // A two-address instruction's def and tied use end up in the same
973 // register, so the tie continues the chain.
974 Reg = LowerTiedOps ? getTiedUseReg(*Def, *DefMO) : Register();
975 if (!Reg)
976 return Register();
977 }
978 return Register();
979}
980
981/// Check if any of \p VirtReg's definitions is a copy or a tied def. If it is
982/// follow the chain of copies to check whether we reach a physical register we
983/// can coalesce with.
984Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
985 static const unsigned DefLimit = 3;
986 unsigned C = 0;
987 for (const MachineOperand &DefMO : MRI->def_operands(VirtReg)) {
988 const MachineInstr &MI = *DefMO.getParent();
990 if (isCoalescable(MI))
991 Reg = MI.getOperand(1).getReg();
992 else if (LowerTiedOps)
993 Reg = getTiedUseReg(MI, DefMO);
994 if (Reg) {
995 Reg = traceCopyChain(Reg);
996 if (Reg.isValid())
997 return Reg;
998 }
999
1000 if (++C >= DefLimit)
1001 break;
1002 }
1003 return Register();
1004}
1005
1006/// Allocates a physical register for VirtReg.
1007void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
1008 Register Hint0, bool LookAtPhysRegUses) {
1009 const Register VirtReg = LR.VirtReg;
1010 assert(!LR.PhysReg);
1011
1012 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1013 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
1014 << " in class " << TRI->getRegClassName(&RC)
1015 << " with hint " << printReg(Hint0, TRI) << '\n');
1016
1017 // Take hint when possible.
1018 if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
1019 !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
1020 // Take hint if the register is currently free.
1021 if (isPhysRegFree(Hint0)) {
1022 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
1023 << '\n');
1024 assignVirtToPhysReg(MI, LR, Hint0);
1025 return;
1026 } else {
1027 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
1028 << " occupied\n");
1029 }
1030 } else {
1031 Hint0 = Register();
1032 }
1033
1034 // Try other hint.
1035 Register Hint1 = traceCopies(VirtReg);
1036 if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
1037 !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
1038 // Take hint if the register is currently free.
1039 if (isPhysRegFree(Hint1)) {
1040 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
1041 << '\n');
1042 assignVirtToPhysReg(MI, LR, Hint1);
1043 return;
1044 } else {
1045 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
1046 << " occupied\n");
1047 }
1048 } else {
1049 Hint1 = Register();
1050 }
1051
1052 MCPhysReg BestReg = 0;
1053 unsigned BestCost = spillImpossible;
1054 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1055 for (MCPhysReg PhysReg : AllocationOrder) {
1056 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
1057 if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
1058 LLVM_DEBUG(dbgs() << "already used in instr.\n");
1059 continue;
1060 }
1061
1062 unsigned Cost = calcSpillCost(PhysReg);
1063 LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
1064 // Immediate take a register with cost 0.
1065 if (Cost == 0) {
1066 assignVirtToPhysReg(MI, LR, PhysReg);
1067 return;
1068 }
1069
1070 if (PhysReg == Hint0 || PhysReg == Hint1)
1071 Cost -= spillPrefBonus;
1072
1073 if (Cost < BestCost) {
1074 BestReg = PhysReg;
1075 BestCost = Cost;
1076 }
1077 }
1078
1079 if (!BestReg) {
1080 // Nothing we can do: Report an error and keep going with an invalid
1081 // allocation.
1082 LR.PhysReg = getErrorAssignment(LR, MI, RC);
1083 LR.Error = true;
1084 return;
1085 }
1086
1087 displacePhysReg(MI, BestReg);
1088 assignVirtToPhysReg(MI, LR, BestReg);
1089}
1090
1091void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1092 assert(MO.isUndef() && "expected undef use");
1093 Register VirtReg = MO.getReg();
1094 assert(VirtReg.isVirtual() && "Expected virtreg");
1095 if (!shouldAllocateRegister(VirtReg))
1096 return;
1097
1098 // If there are multiple undef uses, give them the same register. The def is
1099 // already freed, so take the register from the tie, not the lookup below.
1100 MachineInstr &MI = *MO.getParent();
1101 for (const MachineOperand &Tied : MI.all_uses()) {
1102 if (!Tied.isTied() || Tied.getReg() != VirtReg)
1103 continue;
1104 MCRegister DefReg = getTiedOperand(MI, Tied).getReg().asMCReg();
1105 for (MachineOperand &O : MI.all_uses()) {
1106 if (O.getReg() != VirtReg)
1107 continue;
1108 // The def is already narrowed, so a tie takes its register whole.
1109 unsigned SubIdx = O.isTied() ? 0 : O.getSubReg();
1110 O.setReg(SubIdx ? TRI->getSubReg(DefReg, SubIdx) : DefReg);
1111 O.setSubReg(0);
1112 O.setIsRenamable(!MRI->isReserved(O.getReg()));
1113 }
1114 return;
1115 }
1116
1117 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1118 MCRegister PhysReg;
1119 bool IsRenamable = true;
1120 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1121 PhysReg = LRI->PhysReg;
1122 } else {
1123 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1124 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1125 if (AllocationOrder.empty()) {
1126 // All registers in the class were reserved.
1127 //
1128 // It might be OK to take any entry from the class as this is an undef
1129 // use, but accepting this would give different behavior than greedy and
1130 // basic.
1131 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1132 LRI->Error = true;
1133 IsRenamable = false;
1134 } else
1135 PhysReg = AllocationOrder.front();
1136 }
1137
1138 unsigned SubRegIdx = MO.getSubReg();
1139 if (SubRegIdx != 0) {
1140 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1141 MO.setSubReg(0);
1142 }
1143 MO.setReg(PhysReg);
1144 MO.setIsRenamable(IsRenamable);
1145}
1146
1147/// Variation of defineVirtReg() with special handling for livethrough regs
1148/// (tied or earlyclobber) that may interfere with preassigned uses.
1149void RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1150 MachineOperand &MO,
1151 Register VirtReg) {
1152 if (!shouldAllocateRegister(VirtReg))
1153 return;
1154 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1155 if (LRI != LiveVirtRegs.end()) {
1156 MCRegister PrevReg = LRI->PhysReg;
1157 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1158 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1159 << " (tied/earlyclobber resolution)\n");
1160 freePhysReg(PrevReg);
1161 LRI->PhysReg = MCRegister();
1162 allocVirtReg(MI, *LRI, Register(), true);
1163 MachineBasicBlock::iterator InsertBefore =
1164 std::next((MachineBasicBlock::iterator)MI.getIterator());
1165 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1166 << printReg(PrevReg, TRI) << '\n');
1167 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1168 TII->get(TargetOpcode::COPY), PrevReg)
1169 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1170 }
1171 if (MO.getSubReg() && !MO.isUndef()) {
1172 LRI->LastUse = &MI;
1173 }
1174 }
1175 defineVirtReg(MI, MO, VirtReg, true);
1176}
1177
1178/// Allocates a register for VirtReg definition. Typically the register is
1179/// already assigned from a use of the virtreg, however we still need to
1180/// perform an allocation if:
1181/// - It is a dead definition without any uses.
1182/// - The value is live out and all uses are in different basic blocks.
1183void RegAllocFastImpl::defineVirtReg(MachineInstr &MI, MachineOperand &MO,
1184 Register VirtReg, bool LookAtPhysRegUses) {
1185 assert(VirtReg.isVirtual() && "Not a virtual register");
1186 if (!shouldAllocateRegister(VirtReg))
1187 return;
1188 LiveRegMap::iterator LRI;
1189 bool New;
1190 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1191 if (New) {
1192 if (!MO.isDead()) {
1193 if (mayLiveOut(VirtReg)) {
1194 LRI->LiveOut = true;
1195 } else {
1196 // It is a dead def without the dead flag; add the flag now.
1197 MO.setIsDead(true);
1198 }
1199 }
1200 }
1201 if (!LRI->PhysReg) {
1202 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1203 } else {
1204 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1205 "TODO: preassign mismatch");
1206 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1207 << " use existing assignment to "
1208 << printReg(LRI->PhysReg, TRI) << '\n');
1209 }
1210
1211 MCRegister PhysReg = LRI->PhysReg;
1212 // Either flag means a reader below depends on the slot.
1213 if (LRI->Reloaded || LRI->LiveOut) {
1214 if (!MI.isImplicitDef()) {
1215 MachineBasicBlock::iterator SpillBefore =
1216 std::next((MachineBasicBlock::iterator)MI.getIterator());
1217 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1218 << " RL: " << LRI->Reloaded << '\n');
1219 bool Kill = LRI->LastUse == nullptr;
1220 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1221
1222 // We need to place additional spills for each indirect destination of an
1223 // INLINEASM_BR.
1224 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1225 int FI = StackSlotForVirtReg[VirtReg];
1226 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1227 for (MachineOperand &MO : MI.operands()) {
1228 if (MO.isMBB()) {
1229 MachineBasicBlock *Succ = MO.getMBB();
1230 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1231 &RC, VirtReg);
1232 ++NumStores;
1233 Succ->addLiveIn(PhysReg);
1234 }
1235 }
1236 }
1237
1238 LRI->LastUse = nullptr;
1239 } else if (!LRI->LastUse) {
1240 // No spill was inserted, so nothing below reads this def.
1241 MO.setIsDead(true);
1242 }
1243 // A def above spills only if a displacement above reloads again.
1244 LRI->LiveOut = false;
1245 LRI->Reloaded = false;
1246 }
1247 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1248 BundleVirtRegsMap[VirtReg] = *LRI;
1249 }
1250 markRegUsedInInstr(PhysReg);
1251 setPhysReg(MO, *LRI);
1252}
1253
1254/// Place MO's value in its tied def's register, by taking the register over or
1255/// copying into it. Return false if useVirtReg() should finish MO.
1256bool RegAllocFastImpl::lowerTiedUse(MachineInstr &MI, MachineOperand &MO,
1257 LiveReg &LR) {
1258 const MachineOperand &DefMO = getTiedOperand(MI, MO);
1259 assert(DefMO.getReg().isPhysical() && "tied def allocated before its use");
1260 MCRegister DefReg = DefMO.getReg().asMCReg();
1261 unsigned SubReg = MO.getSubReg();
1262 if (!LR.PhysReg) {
1263 // No register holds the value below MI, so it can live in DefReg, unless
1264 // MO reads a subregister, DefReg cannot hold the value, or an early-clobber
1265 // def would overwrite DefReg before another operand reads the value.
1266 bool MustCopy = SubReg || !MRI->isAllocatable(DefReg) ||
1267 !MRI->getRegClass(LR.VirtReg)->contains(DefReg) ||
1268 (DefMO.isEarlyClobber() &&
1269 any_of(MI.all_uses(), [&](const MachineOperand &O) {
1270 return &O != &MO && O.getReg() == LR.VirtReg;
1271 }));
1272 if (!MustCopy) {
1273 // The def is not live above MI, so the value can occupy DefReg there.
1274 freePhysReg(DefReg);
1275 assignVirtToPhysReg(MI, LR, DefReg);
1276 return false;
1277 }
1278 allocVirtReg(MI, LR, Register(), false);
1279 // The def phase marked DefReg used in MI, so allocVirtReg skips it.
1280 assert((LR.Error || !TRI->regsOverlap(LR.PhysReg, DefReg)) &&
1281 "copy source overlaps the tied def");
1282 }
1283
1284 MCRegister SrcReg = SubReg ? TRI->getSubReg(LR.PhysReg, SubReg) : LR.PhysReg;
1285 // Only an already rewritten tie (%x = OP %x) finds the value in DefReg.
1286 if (SrcReg == DefReg)
1287 return false;
1288
1289 // The copy reads SrcReg above MI, so no other operand may take it.
1290 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(TargetOpcode::COPY), DefReg)
1291 .addReg(SrcReg);
1292 LR.LastUse = &MI;
1293 markRegUsedInInstr(LR.PhysReg);
1294
1295 bool Renamable = !MRI->isReserved(DefReg);
1296 auto ReadDefReg = [&](MachineOperand &O) {
1297 O.setReg(DefReg);
1298 O.setSubReg(0);
1299 O.setIsRenamable(Renamable);
1300 };
1301 ReadDefReg(MO);
1302 // The other reads of the value follow it into DefReg, so SrcReg dies at the
1303 // copy. They cannot when an early-clobber def overwrites DefReg first, and a
1304 // read tied to another def owes that def's register.
1305 if (!DefMO.isEarlyClobber()) {
1306 for (MachineOperand &O : MI.all_uses()) {
1307 if (O.isTied() || O.getReg() != LR.VirtReg || O.getSubReg() != SubReg)
1308 continue;
1309 ReadDefReg(O);
1310 O.setIsKill(false);
1311 }
1312 }
1313
1314 // The free-defs step skips tied defs, so DefReg still holds the def.
1315 freePhysReg(DefReg);
1316 return true;
1317}
1318
1319/// Allocates a register for a VirtReg use.
1320void RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1321 Register VirtReg) {
1322 assert(VirtReg.isVirtual() && "Not a virtual register");
1323 if (!shouldAllocateRegister(VirtReg))
1324 return;
1325 LiveRegMap::iterator LRI;
1326 bool New;
1327 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1328 if (New) {
1329 if (!MO.isKill()) {
1330 if (mayLiveOut(VirtReg)) {
1331 LRI->LiveOut = true;
1332 } else {
1333 // It is a last (killing) use without the kill flag; add the flag now.
1334 MO.setIsKill(true);
1335 }
1336 }
1337 } else {
1338 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1339 }
1340
1341 if (LowerTiedOps && MO.isTied() && lowerTiedUse(MI, MO, *LRI))
1342 return;
1343
1344 // If necessary allocate a register.
1345 if (!LRI->PhysReg) {
1346 assert(!MO.isTied() && "tied op should be allocated");
1347 Register Hint;
1348 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1349 Hint = MI.getOperand(0).getReg();
1350 if (Hint.isVirtual()) {
1351 assert(!shouldAllocateRegister(Hint));
1352 Hint = Register();
1353 } else {
1354 assert(Hint.isPhysical() &&
1355 "Copy destination should already be assigned");
1356 }
1357 }
1358 allocVirtReg(MI, *LRI, Hint, false);
1359 }
1360
1361 LRI->LastUse = &MI;
1362
1363 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1364 BundleVirtRegsMap[VirtReg] = *LRI;
1365 }
1366 markRegUsedInInstr(LRI->PhysReg);
1367 setPhysReg(MO, *LRI);
1368}
1369
1370/// Clear dead flags on defs of any register which also has a live def on \p MI.
1372 for (const MachineOperand &MO : MI.all_defs()) {
1373 if (!MO.isDead())
1374 MI.clearRegisterDeads(MO.getReg());
1375 }
1376}
1377
1378/// Query a physical register to use as a filler in contexts where the
1379/// allocation has failed. This will raise an error, but not abort the
1380/// compilation.
1381MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1382 MachineInstr &MI,
1383 const TargetRegisterClass &RC) {
1384 MachineFunction &MF = *MI.getMF();
1385
1386 // Avoid repeating the error every time a register is used.
1387 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1388 if (EmitError)
1389 MF.getProperties().setFailedRegAlloc();
1390
1391 // If the allocation order was empty, all registers in the class were
1392 // probably reserved. Fall back to taking the first register in the class,
1393 // even if it's reserved.
1394 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1395 if (AllocationOrder.empty()) {
1396 const Function &Fn = MF.getFunction();
1397 if (EmitError) {
1398 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1399 "no registers from class available to allocate", Fn,
1400 MI.getDebugLoc()));
1401 }
1402
1403 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1404 assert(!RawRegs.empty() && "register classes cannot have no registers");
1405 return RawRegs.front();
1406 }
1407
1408 if (!LR.Error && EmitError) {
1409 // Nothing we can do: Report an error and keep going with an invalid
1410 // allocation.
1411 if (MI.isInlineAsm()) {
1412 MI.emitInlineAsmError(
1413 "inline assembly requires more registers than available");
1414 } else {
1415 const Function &Fn = MBB->getParent()->getFunction();
1416 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1417 "ran out of registers during register allocation", Fn,
1418 MI.getDebugLoc()));
1419 }
1420 }
1421
1422 return AllocationOrder.front();
1423}
1424
1425/// Changes MO to refer to Assignment.PhysReg, considering subregs.
1426void RegAllocFastImpl::setPhysReg(MachineOperand &MO,
1427 const LiveReg &Assignment) {
1428 MCRegister PhysReg = Assignment.PhysReg;
1429 assert(PhysReg && "assignments should always be to a valid physreg");
1430
1431 if (LLVM_UNLIKELY(Assignment.Error)) {
1432 // Make sure we don't set renamable in error scenarios, as we may have
1433 // assigned to a reserved register.
1434 if (MO.isUse())
1435 MO.setIsUndef(true);
1436 else
1437 HasErrorDef = true;
1438 }
1439
1440 if (!MO.getSubReg()) {
1441 MO.setReg(PhysReg);
1442 MO.setIsRenamable(!Assignment.Error);
1443 return;
1444 }
1445
1446 // Handle subregister index.
1447 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1448 MO.setIsRenamable(!Assignment.Error);
1449
1450 // Note: We leave the subreg number around a little longer in case of defs.
1451 // This is so that the register freeing logic in allocateInstruction can still
1452 // recognize this as subregister defs. The code there will clear the number.
1453 if (!MO.isDef())
1454 MO.setSubReg(0);
1455
1456 // A kill flag implies killing the full register, and a <def,read-undef> of
1457 // a sub-register requires an implicit def of the full register.
1458 if (MO.isKill())
1459 PendingImplicitOps.emplace_back(PhysReg, ImplicitKill);
1460 else if (MO.isDef() && MO.isUndef())
1461 PendingImplicitOps.emplace_back(PhysReg,
1462 MO.isDead() ? ImplicitDead : ImplicitDef);
1463}
1464
1465void RegAllocFastImpl::addImplicitOps(MachineInstr &MI) {
1466 for (auto [PhysReg, Kind] : PendingImplicitOps) {
1467 if (Kind == ImplicitKill)
1468 MI.addRegisterKilled(PhysReg, TRI, true);
1469 else if (Kind == ImplicitDead)
1470 MI.addRegisterDead(PhysReg, TRI, true);
1471 else
1472 MI.addRegisterDefined(PhysReg, TRI);
1473 }
1474 PendingImplicitOps.clear();
1475}
1476
1477#ifndef NDEBUG
1478
1479void RegAllocFastImpl::dumpState() const {
1480 for (MCRegUnit Unit : TRI->regunits()) {
1481 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1482 case regFree:
1483 break;
1484 case regPreAssigned:
1485 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1486 break;
1487 case regLiveIn:
1488 llvm_unreachable("Should not have regLiveIn in map");
1489 default: {
1490 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1491 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1492 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1493 if (I->LiveOut || I->Reloaded) {
1494 dbgs() << '[';
1495 if (I->LiveOut)
1496 dbgs() << 'O';
1497 if (I->Reloaded)
1498 dbgs() << 'R';
1499 dbgs() << ']';
1500 }
1501 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1502 break;
1503 }
1504 }
1505 }
1506 dbgs() << '\n';
1507 // Check that LiveVirtRegs is the inverse.
1508 for (const LiveReg &LR : LiveVirtRegs) {
1509 Register VirtReg = LR.VirtReg;
1510 assert(VirtReg.isVirtual() && "Bad map key");
1511 MCRegister PhysReg = LR.PhysReg;
1512 if (PhysReg) {
1513 assert(PhysReg.isPhysical() && "mapped to physreg");
1514 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1515 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1516 }
1517 }
1518 }
1519}
1520#endif
1521
1522/// Count number of defs consumed from each register class by \p Reg
1523void RegAllocFastImpl::addRegClassDefCounts(
1524 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1525 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1526
1527 if (Reg.isVirtual()) {
1528 if (!shouldAllocateRegister(Reg))
1529 return;
1530 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1531 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1532 RCIdx != RCIdxEnd; ++RCIdx) {
1533 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1534 // FIXME: Consider aliasing sub/super registers.
1535 if (OpRC->hasSubClassEq(IdxRC))
1536 ++RegClassDefCounts[RCIdx];
1537 }
1538
1539 return;
1540 }
1541
1542 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1543 RCIdx != RCIdxEnd; ++RCIdx) {
1544 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1545 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1546 if (IdxRC->contains(*Alias)) {
1547 ++RegClassDefCounts[RCIdx];
1548 break;
1549 }
1550 }
1551 }
1552}
1553
1554/// Early clobber, partial def, or tied to a use that carries a value: the
1555/// register is occupied while the uses are read.
1556static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO) {
1557 assert(MO.isDef() && "expected def operand");
1558 if (MO.isEarlyClobber() || MO.readsReg())
1559 return true;
1560 return MO.isTied() &&
1561 !MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO))).isUndef();
1562}
1563
1564/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1565/// that are to be allocated. Those are ordered in a way that small classes,
1566/// early clobbers and livethroughs are allocated first.
1567void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1568 DefOperandIndexes.clear();
1569
1570 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1571 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1572 const MachineOperand &MO = MI.getOperand(I);
1573 if (!MO.isReg())
1574 continue;
1575 Register Reg = MO.getReg();
1576 if (MO.readsReg()) {
1577 if (Reg.isPhysical()) {
1578 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1579 markPhysRegUsedInInstr(Reg);
1580 }
1581 }
1582
1583 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1584 DefOperandIndexes.push_back(I);
1585 }
1586
1587 // Most instructions only have one virtual def, so there's no point in
1588 // computing the possible number of defs for every register class.
1589 if (DefOperandIndexes.size() <= 1)
1590 return;
1591
1592 // Track number of defs which may consume a register from the class. This is
1593 // used to assign registers for possibly-too-small classes first. Example:
1594 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1595 // registers first so that the gr32 don't use the gr32_abcd registers before
1596 // we assign these.
1597 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1598
1599 for (const MachineOperand &MO : MI.all_defs())
1600 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1601
1602 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1603 const MachineOperand &MO0 = MI.getOperand(I0);
1604 const MachineOperand &MO1 = MI.getOperand(I1);
1605 Register Reg0 = MO0.getReg();
1606 Register Reg1 = MO1.getReg();
1607 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1608 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1609
1610 // Identify regclass that are easy to use up completely just in this
1611 // instruction.
1612 unsigned ClassSize0 = RegClassInfo->getOrder(&RC0).size();
1613 unsigned ClassSize1 = RegClassInfo->getOrder(&RC1).size();
1614
1615 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1616 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1617 if (SmallClass0 > SmallClass1)
1618 return true;
1619 if (SmallClass0 < SmallClass1)
1620 return false;
1621
1622 // Allocate early clobbers and livethrough operands first.
1623 bool Livethrough0 = isLiveThroughDef(MI, MO0);
1624 bool Livethrough1 = isLiveThroughDef(MI, MO1);
1625 if (Livethrough0 > Livethrough1)
1626 return true;
1627 if (Livethrough0 < Livethrough1)
1628 return false;
1629
1630 // Tie-break rule: operand index.
1631 return I0 < I1;
1632 });
1633}
1634
1635void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1636 // Backwards, a def frees a register and a use occupies it. The phases:
1637 // * pre-assigned physreg defs
1638 // * virtual register defs
1639 // * free the def operands' registers
1640 // * displace registers clobbered by regmasks
1641 // * pre-assigned physreg uses
1642 // * virtual register uses, inserting reloads and tied-operand copies
1643 // * undef uses
1644 // * free early-clobber defs
1645 //
1646 // Freeing follows the def allocation so a def is not handed a register this
1647 // instruction also writes, and precedes the uses so a use may take one. It
1648 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1649 // freed last so that no use lands on them.
1650
1651 InstrGen += 2;
1652 // In the event we ever get more than 2**31 instructions...
1653 if (LLVM_UNLIKELY(InstrGen == 0)) {
1654 UsedInInstr.assign(UsedInInstr.size(), 0);
1655 InstrGen = 2;
1656 }
1657 RegMasks.clear();
1658 LiveDefRegs.clear();
1659 BundleVirtRegsMap.clear();
1660 assert(PendingImplicitOps.empty() && "implicit operands not added");
1661
1662 // Scan for special cases; Apply pre-assigned register defs to state.
1663 bool HasPhysRegUse = false;
1664 bool HasRegMask = false;
1665 bool HasVRegDef = false;
1666 bool HasDef = false;
1667 bool HasEarlyClobber = false;
1668 bool HasTiedDef = false;
1669 bool NeedToAssignLiveThroughs = false;
1670 for (MachineOperand &MO : MI.operands()) {
1671 if (MO.isReg()) {
1672 Register Reg = MO.getReg();
1673 if (Reg.isVirtual()) {
1674 if (!shouldAllocateRegister(Reg))
1675 continue;
1676 if (MO.isDef()) {
1677 HasDef = true;
1678 HasVRegDef = true;
1679 if (MO.isEarlyClobber())
1680 HasEarlyClobber = true;
1681 if (LowerTiedOps && MO.isTied())
1682 HasTiedDef = true;
1683 if (isLiveThroughDef(MI, MO))
1684 NeedToAssignLiveThroughs = true;
1685 }
1686 } else if (Reg.isPhysical()) {
1687 if (!MRI->isReserved(Reg)) {
1688 if (MO.isDef()) {
1689 HasDef = true;
1690 bool displacedAny = definePhysReg(MI, Reg);
1691 if (MO.isEarlyClobber())
1692 HasEarlyClobber = true;
1693 if (!displacedAny)
1694 MO.setIsDead(true);
1695 if (!MO.isDead())
1696 LiveDefRegs.push_back(Reg.asMCReg());
1697 }
1698 if (MO.readsReg())
1699 HasPhysRegUse = true;
1700 }
1701 }
1702 } else if (MO.isRegMask()) {
1703 HasRegMask = true;
1704 RegMasks.push_back(MO.getRegMask());
1705 }
1706 }
1707
1708 // Allocate virtreg defs.
1709 if (HasDef) {
1710 if (HasVRegDef) {
1711 // Special handling for early clobbers, tied operands or subregister defs:
1712 // Compared to "normal" defs these:
1713 // - Must not use a register that is pre-assigned for a use operand.
1714 // - In order to solve tricky inline assembly constraints we change the
1715 // heuristic to figure out a good operand order before doing
1716 // assignments.
1717 if (NeedToAssignLiveThroughs) {
1718 findAndSortDefOperandIndexes(MI);
1719 for (unsigned OpIdx : DefOperandIndexes) {
1720 MachineOperand &MO = MI.getOperand(OpIdx);
1721 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1722 Register Reg = MO.getReg();
1723 if (isLiveThroughDef(MI, MO))
1724 defineLiveThroughVirtReg(MI, MO, Reg);
1725 else
1726 defineVirtReg(MI, MO, Reg);
1727 }
1728 } else {
1729 for (MachineOperand &MO : MI.all_defs())
1730 if (MO.getReg().isVirtual())
1731 defineVirtReg(MI, MO, MO.getReg());
1732 }
1733 addImplicitOps(MI);
1734 }
1735
1736 // Free registers occupied by defs.
1737 // Iterate operands in reverse order, so we see the implicit super register
1738 // defs first (we added them earlier in case of <def,read-undef>).
1739 for (MachineOperand &MO : reverse(MI.all_defs())) {
1740 Register Reg = MO.getReg();
1741
1742 // A dead def is kept alive by a non-dead def of the same register or a
1743 // super-register, so clear the inconsistent dead flag.
1744 if (Reg.isPhysical() && MO.isDead() &&
1745 hasLiveDefOfSuperReg(Reg.asMCReg()))
1746 MO.setIsDead(false);
1747
1748 // subreg defs don't free the full register. We left the subreg number
1749 // around as a marker in setPhysReg() to recognize this case here.
1750 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1751 MO.setSubReg(0);
1752 continue;
1753 }
1754
1755 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1756 "tied def assigned to clobbered register");
1757
1758 // Do not free live-through defs.
1759 if (isLiveThroughDef(MI, MO))
1760 continue;
1761 if (!Reg)
1762 continue;
1763 if (Reg.isVirtual()) {
1764 assert(!shouldAllocateRegister(Reg));
1765 continue;
1766 }
1768 if (MRI->isReserved(Reg))
1769 continue;
1770 freePhysReg(Reg);
1771 unmarkRegUsedInInstr(Reg);
1772 }
1773 }
1774
1775 // A regmask is a def of every clobbered register: reload what lives in one
1776 // below MI. Nothing is reserved, so the uses may still take those registers.
1777 if (HasRegMask) {
1778 assert(!RegMasks.empty() && "expected RegMask");
1779 // MRI bookkeeping.
1780 for (const auto *RM : RegMasks)
1782
1783 for (const LiveReg &LR : LiveVirtRegs) {
1784 MCRegister PhysReg = LR.PhysReg;
1785 if (PhysReg && isClobberedByRegMasks(PhysReg))
1786 displacePhysReg(MI, PhysReg);
1787 }
1788 }
1789
1790 // Apply pre-assigned register uses to state.
1791 if (HasPhysRegUse) {
1792 for (MachineOperand &MO : MI.operands()) {
1793 if (!MO.isReg() || !MO.readsReg())
1794 continue;
1795 Register Reg = MO.getReg();
1796 if (!Reg.isPhysical())
1797 continue;
1798 if (MRI->isReserved(Reg))
1799 continue;
1800 if (!usePhysReg(MI, Reg))
1801 MO.setIsKill(true);
1802 }
1803 }
1804
1805 // Allocate virtreg uses and insert reloads as necessary. Given
1806 // %1 = OP %0, %0(tied-def 0), allocate tied %0 first, so that %0 takes %1's
1807 // register. In operand order, the untied %0 would take another register and
1808 // the tied use would need a copy.
1809 bool HasUndefUse = false;
1810 bool TiedOnly = HasTiedDef;
1811 do {
1812 for (MachineOperand &MO : MI.all_uses()) {
1813 Register Reg = MO.getReg();
1814 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg) ||
1815 (TiedOnly && !MO.isTied()))
1816 continue;
1817
1818 if (MO.isUndef()) {
1819 HasUndefUse = true;
1820 continue;
1821 }
1822
1823 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1824 // to physregs, so a def block allocated later can no longer see them.
1825 mayLiveIn(Reg);
1826
1827 assert(!MO.isInternalRead() && "Bundles not supported");
1828 assert(MO.readsReg() && "reading use");
1829 useVirtReg(MI, MO, Reg);
1830 }
1831 } while (std::exchange(TiedOnly, false));
1832 addImplicitOps(MI);
1833
1834 // Allocate undef operands. This is a separate step because in a situation
1835 // like ` = OP undef %X, %X` both operands need the same register assign
1836 // so we should perform the normal assignment first.
1837 if (HasUndefUse) {
1838 for (MachineOperand &MO : MI.all_uses()) {
1839 Register Reg = MO.getReg();
1840 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1841 continue;
1842
1843 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1844 allocVirtRegUndef(MO);
1845 }
1846 }
1847
1848 // Free early clobbers. Last, because they must not share a register with any
1849 // use.
1850 if (HasEarlyClobber) {
1851 for (MachineOperand &MO : reverse(MI.all_defs())) {
1852 if (!MO.isEarlyClobber())
1853 continue;
1854 assert(!MO.getSubReg() && "should be already handled in def processing");
1855
1856 Register Reg = MO.getReg();
1857 if (!Reg)
1858 continue;
1859 if (Reg.isVirtual()) {
1860 assert(!shouldAllocateRegister(Reg));
1861 continue;
1862 }
1863 assert(Reg.isPhysical() && "should have register assigned");
1864
1865 // We sometimes get odd situations like:
1866 // early-clobber %x0 = INSTRUCTION %x0
1867 // which is semantically questionable as the early-clobber should
1868 // apply before the use. But in practice we consider the use to
1869 // happen before the early clobber now. Don't free the early clobber
1870 // register in this case.
1871 if (MI.readsRegister(Reg, TRI))
1872 continue;
1873
1874 freePhysReg(Reg);
1875 }
1876 }
1877
1878 LLVM_DEBUG(dbgs() << "<< " << MI);
1879 if (MI.isCopy() &&
1880 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1881 MI.getOperand(0).isDead()) &&
1882 MI.getNumOperands() == 2) {
1883 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1884 Coalesced.push_back(&MI);
1885 }
1886}
1887
1888void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1889 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1890 // mostly constants and frame indices.
1891 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1892 for (const auto &MO : MI.debug_operands()) {
1893 if (!MO.isReg())
1894 continue;
1895 Register Reg = MO.getReg();
1896 if (!Reg.isVirtual())
1897 continue;
1898 if (!shouldAllocateRegister(Reg))
1899 continue;
1900
1901 // Already spilled to a stackslot?
1902 int SS = StackSlotForVirtReg[Reg];
1903 if (SS != -1) {
1904 // Modify DBG_VALUE now that the value is in a spill slot.
1906 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1907 continue;
1908 }
1909
1910 // See if this virtual register has already been allocated to a physical
1911 // register or spilled to a stack slot.
1912 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1914 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1915
1916 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1917 // Update every use of Reg within MI.
1918 for (auto &RegMO : DbgOps)
1919 setPhysReg(*RegMO, *LRI);
1920 } else {
1921 DanglingDbgValues[Reg].push_back(&MI);
1922 }
1923
1924 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1925 // that future spills of Reg will have DBG_VALUEs.
1926 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1927 }
1928}
1929
1930void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1931 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1932 ++BundledMI;
1933 while (BundledMI->isBundledWithPred()) {
1934 for (MachineOperand &MO : BundledMI->operands()) {
1935 if (!MO.isReg())
1936 continue;
1937
1938 Register Reg = MO.getReg();
1939 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1940 continue;
1941
1942 auto DI = BundleVirtRegsMap.find(Reg);
1943 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1944
1945 setPhysReg(MO, DI->second);
1946 }
1947
1948 ++BundledMI;
1949 }
1950 addImplicitOps(MI);
1951}
1952
1953void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1954 this->MBB = &MBB;
1955 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1956
1957 PosIndexes.unsetInitialized();
1958 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1959 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1960
1961 for (const auto &LiveReg : MBB.liveouts())
1962 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1963
1964 Coalesced.clear();
1965
1966 // Lowering a tied operand inserts a copy ahead of MI. Its registers are
1967 // already assigned, so visiting it would evict what still lives in the
1968 // source.
1969 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
1970 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1971
1972 // Special handling for debug values. Note that they are not allowed to
1973 // affect codegen of the other instructions in any way.
1974 if (MI.isDebugValue()) {
1975 handleDebugValue(MI);
1976 continue;
1977 }
1978
1979 allocateInstruction(MI);
1980
1981 // An error assignment may give a live and a dead def the same register.
1982 if (HasErrorDef) {
1984 HasErrorDef = false;
1985 }
1986
1987 // Once BUNDLE header is assigned registers, same assignments need to be
1988 // done for bundled MIs.
1989 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1990 handleBundle(MI);
1991 }
1992 }
1993
1994 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1995
1996 // Spill all physical registers holding virtual registers now.
1997 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1998 reloadAtBegin(MBB);
1999
2000 // Erase all the coalesced copies. We are delaying it until now because
2001 // LiveVirtRegs might refer to the instrs.
2002 for (MachineInstr *MI : Coalesced)
2003 MBB.erase(MI);
2004 NumCoalesced += Coalesced.size();
2005
2006 for (auto &UDBGPair : DanglingDbgValues) {
2007 for (MachineInstr *DbgValue : UDBGPair.second) {
2008 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
2009 // Nothing to do if the vreg was spilled in the meantime.
2010 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
2011 continue;
2012 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
2013 << '\n');
2014 DbgValue->setDebugValueUndef();
2015 }
2016 }
2017 DanglingDbgValues.clear();
2018
2019 LLVM_DEBUG(MBB.dump());
2020}
2021
2022/// Expand REG_SEQUENCE and INSERT_SUBREG into subregister COPYs: the lowering
2023/// TwoAddressInstructionPass performs when it runs before allocation, plus the
2024/// base-value copy its tie processing provides.
2025void RegAllocFastImpl::expandSubregPseudo(MachineInstr &MI) {
2026 MachineBasicBlock &MBB = *MI.getParent();
2027 const DebugLoc &DL = MI.getDebugLoc();
2028 if (MI.isInsertSubreg()) {
2029 // %d = INSERT_SUBREG %base, %sub, idx -> %d = COPY %base
2030 // %d.idx = COPY %sub
2031 const MachineOperand &BaseMO = MI.getOperand(1);
2032 if (!BaseMO.isUndef())
2033 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY),
2034 MI.getOperand(0).getReg())
2035 .addReg(BaseMO.getReg(), RegState::NoFlags, BaseMO.getSubReg());
2036 unsigned SubIdx = MI.getOperand(3).getImm();
2037 MI.removeOperand(3);
2038 assert(MI.getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
2039 MI.getOperand(0).setSubReg(SubIdx);
2040 MI.getOperand(0).setIsUndef(MI.getOperand(1).isUndef());
2041 MI.removeOperand(1);
2042 MI.setDesc(TII->get(TargetOpcode::COPY));
2043 return;
2044 }
2045
2046 // %d = REG_SEQUENCE %s1, idx1, ... -> undef %d.idx1 = COPY %s1
2047 // %d.idx2 = COPY %s2 ...
2048 assert(MI.isRegSequence());
2049 Register Dst = MI.getOperand(0).getReg();
2050 // An undef source needs no copy: the read-undef flag on the first copy
2051 // defines the whole register. One is still needed where a use reads that
2052 // lane on its own, which would otherwise read an undefined subregister.
2053 LaneBitmask ReadLanes = LaneBitmask::getNone();
2054 for (const MachineOperand &Use : MRI->use_nodbg_operands(Dst))
2055 if (unsigned UseSubIdx = Use.getSubReg())
2056 ReadLanes |= TRI->getSubRegIndexLaneMask(UseSubIdx);
2057
2058 bool DefEmitted = false;
2059 for (unsigned I = 1, E = MI.getNumOperands(); I + 1 < E; I += 2) {
2060 const MachineOperand &SrcMO = MI.getOperand(I);
2061 unsigned SubIdx = MI.getOperand(I + 1).getImm();
2062 if (SrcMO.isUndef() &&
2063 (ReadLanes & TRI->getSubRegIndexLaneMask(SubIdx)).none())
2064 continue;
2065 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY))
2066 .addReg(Dst, RegState::Define | getUndefRegState(!DefEmitted), SubIdx)
2067 .addReg(SrcMO.getReg(), getUndefRegState(SrcMO.isUndef()),
2068 SrcMO.getSubReg());
2069 DefEmitted = true;
2070 }
2071 // Every source was undef: uses of Dst still need a definition.
2072 if (!DefEmitted) {
2073 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
2074 while (MI.getNumOperands() > 1)
2075 MI.removeOperand(MI.getNumOperands() - 1);
2076 return;
2077 }
2078 MI.eraseFromParent();
2079}
2080
2081bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF,
2082 RegisterClassInfo &RCI) {
2083 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
2084 << "********** Function: " << MF.getName() << '\n');
2085 MRI = &MF.getRegInfo();
2086 const TargetSubtargetInfo &STI = MF.getSubtarget();
2087 TRI = STI.getRegisterInfo();
2088 TII = STI.getInstrInfo();
2089 MFI = &MF.getFrameInfo();
2090 RegClassInfo = &RCI;
2092 // Keep the shared analysis in step with the set just frozen.
2093 RegClassInfo->updateReservedRegs(MRI->getReservedRegs());
2094 unsigned NumRegUnits = TRI->getNumRegUnits();
2095 InstrGen = 0;
2096 UsedInInstr.assign(NumRegUnits, 0);
2097
2098 // MIR that already went through TwoAddressInstructionPass carries
2099 // TiedOpsRewritten, so partial pipelines (-run-pass, -start-before) follow
2100 // the input they are given.
2101 LowerTiedOps = !MF.getProperties().hasTiedOpsRewritten();
2102 if (LowerTiedOps) {
2103 for (MachineBasicBlock &MBB : MF)
2104 for (MachineInstr &MI : make_early_inc_range(MBB))
2105 if (MI.isRegSequence() || MI.isInsertSubreg())
2106 expandSubregPseudo(MI);
2107 }
2108
2109 // initialize the virtual->physical register map to have a 'null'
2110 // mapping for all virtual registers
2111 unsigned NumVirtRegs = MRI->getNumVirtRegs();
2112 StackSlotForVirtReg.resize(NumVirtRegs);
2113 LiveVirtRegs.setUniverse(NumVirtRegs);
2114 MayLiveAcrossBlocks.clear();
2115 MayLiveAcrossBlocks.resize(NumVirtRegs);
2116
2117 // Loop over all of the basic blocks, eliminating virtual register references
2118 for (MachineBasicBlock &MBB : MF)
2119 allocateBasicBlock(MBB);
2120
2121 if (ClearVirtRegs) {
2122 // All machine operands and other references to virtual registers have been
2123 // replaced. Remove the virtual registers.
2124 MRI->clearVirtRegs();
2125 }
2126
2127 StackSlotForVirtReg.clear();
2128 LiveDbgValueMap.clear();
2129 return true;
2130}
2131
2134 MFPropsModifier _(*this, MF);
2135 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
2136 bool Changed = Impl.runOnMachineFunction(
2138 if (!Changed)
2139 return PreservedAnalyses::all();
2141 PA.preserveSet<CFGAnalyses>();
2142 return PA;
2143}
2144
2146 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2147 bool PrintFilterName = Opts.FilterName != "all";
2148 bool PrintNoClearVRegs = !Opts.ClearVRegs;
2149 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
2150
2151 OS << "regallocfast";
2152 if (PrintFilterName || PrintNoClearVRegs) {
2153 OS << '<';
2154 if (PrintFilterName)
2155 OS << "filter=" << Opts.FilterName;
2156 if (PrintSemicolon)
2157 OS << ';';
2158 if (PrintNoClearVRegs)
2159 OS << "no-clear-vregs";
2160 OS << '>';
2161 }
2162}
2163
2164FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
2165
2167 bool ClearVirtRegs) {
2168 return new RegAllocFast(Ftor, ClearVirtRegs);
2169}
#define DBG(...)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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:348
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_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
static Register getTiedUseReg(const MachineInstr &MI, const MachineOperand &DefMO)
The register DefMO's tied use reads, when the two end up in the same register: a subregister index on...
static bool isCoalescable(const MachineInstr &MI)
static const MachineOperand & getTiedOperand(const MachineInstr &MI, const MachineOperand &MO)
The operand MO is tied to.
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)
static void clearDeadsOfLiveDefs(MachineInstr &MI)
Clear dead flags on defs of any register which also has a live def on MI.
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
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
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:483
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:350
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
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:68
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
iterator_range< use_nodbg_iterator > use_nodbg_operands(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,...
const BitVector & getReservedRegs() const
getReservedRegs - Returns a reference to the frozen set of reserved registers.
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
iterator_range< def_iterator > def_operands(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 updateReservedRegs(const BitVector &ReservedInput)
Update cached register class information using ReservedInput, MRI's current reserved-register set.
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
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
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
#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
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
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.
@ Renamable
Register that may be renamed.
LLVM_ABI void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg)
Update a DBG_VALUE whose value has been spilled to FrameIndex.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
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
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr RegState getUndefRegState(bool B)
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
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81