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 // A hint makes a register cheaper to take, but can't make one that can't
1071 // be spilled, e.g. one that MI clobbers, available.
1072 if (Cost == spillImpossible)
1073 continue;
1074
1075 if (PhysReg == Hint0 || PhysReg == Hint1)
1076 Cost -= spillPrefBonus;
1077
1078 if (Cost < BestCost) {
1079 BestReg = PhysReg;
1080 BestCost = Cost;
1081 }
1082 }
1083
1084 if (!BestReg) {
1085 // Nothing we can do: Report an error and keep going with an invalid
1086 // allocation.
1087 LR.PhysReg = getErrorAssignment(LR, MI, RC);
1088 LR.Error = true;
1089 return;
1090 }
1091
1092 displacePhysReg(MI, BestReg);
1093 assignVirtToPhysReg(MI, LR, BestReg);
1094}
1095
1096void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1097 assert(MO.isUndef() && "expected undef use");
1098 Register VirtReg = MO.getReg();
1099 assert(VirtReg.isVirtual() && "Expected virtreg");
1100 if (!shouldAllocateRegister(VirtReg))
1101 return;
1102
1103 // If there are multiple undef uses, give them the same register. The def is
1104 // already freed, so take the register from the tie, not the lookup below.
1105 MachineInstr &MI = *MO.getParent();
1106 for (const MachineOperand &Tied : MI.all_uses()) {
1107 if (!Tied.isTied() || Tied.getReg() != VirtReg)
1108 continue;
1109 MCRegister DefReg = getTiedOperand(MI, Tied).getReg().asMCReg();
1110 for (MachineOperand &O : MI.all_uses()) {
1111 if (O.getReg() != VirtReg)
1112 continue;
1113 // The def is already narrowed, so a tie takes its register whole.
1114 unsigned SubIdx = O.isTied() ? 0 : O.getSubReg();
1115 O.setReg(SubIdx ? TRI->getSubReg(DefReg, SubIdx) : DefReg);
1116 O.setSubReg(0);
1117 O.setIsRenamable(!MRI->isReserved(O.getReg()));
1118 }
1119 return;
1120 }
1121
1122 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1123 MCRegister PhysReg;
1124 bool IsRenamable = true;
1125 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1126 PhysReg = LRI->PhysReg;
1127 } else {
1128 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1129 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1130 if (AllocationOrder.empty()) {
1131 // All registers in the class were reserved.
1132 //
1133 // It might be OK to take any entry from the class as this is an undef
1134 // use, but accepting this would give different behavior than greedy and
1135 // basic.
1136 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1137 LRI->Error = true;
1138 IsRenamable = false;
1139 } else
1140 PhysReg = AllocationOrder.front();
1141 }
1142
1143 unsigned SubRegIdx = MO.getSubReg();
1144 if (SubRegIdx != 0) {
1145 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1146 MO.setSubReg(0);
1147 }
1148 MO.setReg(PhysReg);
1149 MO.setIsRenamable(IsRenamable);
1150}
1151
1152/// Variation of defineVirtReg() with special handling for livethrough regs
1153/// (tied or earlyclobber) that may interfere with preassigned uses.
1154void RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1155 MachineOperand &MO,
1156 Register VirtReg) {
1157 if (!shouldAllocateRegister(VirtReg))
1158 return;
1159 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1160 if (LRI != LiveVirtRegs.end()) {
1161 MCRegister PrevReg = LRI->PhysReg;
1162 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1163 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1164 << " (tied/earlyclobber resolution)\n");
1165 freePhysReg(PrevReg);
1166 LRI->PhysReg = MCRegister();
1167 allocVirtReg(MI, *LRI, Register(), true);
1168 MachineBasicBlock::iterator InsertBefore =
1169 std::next((MachineBasicBlock::iterator)MI.getIterator());
1170 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1171 << printReg(PrevReg, TRI) << '\n');
1172 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1173 TII->get(TargetOpcode::COPY), PrevReg)
1174 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1175 }
1176 if (MO.getSubReg() && !MO.isUndef()) {
1177 LRI->LastUse = &MI;
1178 }
1179 }
1180 defineVirtReg(MI, MO, VirtReg, true);
1181}
1182
1183/// Allocates a register for VirtReg definition. Typically the register is
1184/// already assigned from a use of the virtreg, however we still need to
1185/// perform an allocation if:
1186/// - It is a dead definition without any uses.
1187/// - The value is live out and all uses are in different basic blocks.
1188void RegAllocFastImpl::defineVirtReg(MachineInstr &MI, MachineOperand &MO,
1189 Register VirtReg, bool LookAtPhysRegUses) {
1190 assert(VirtReg.isVirtual() && "Not a virtual register");
1191 if (!shouldAllocateRegister(VirtReg))
1192 return;
1193 LiveRegMap::iterator LRI;
1194 bool New;
1195 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1196 if (New) {
1197 if (!MO.isDead()) {
1198 if (mayLiveOut(VirtReg)) {
1199 LRI->LiveOut = true;
1200 } else {
1201 // It is a dead def without the dead flag; add the flag now.
1202 MO.setIsDead(true);
1203 }
1204 }
1205 }
1206 if (!LRI->PhysReg) {
1207 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1208 } else {
1209 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1210 "TODO: preassign mismatch");
1211 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1212 << " use existing assignment to "
1213 << printReg(LRI->PhysReg, TRI) << '\n');
1214 }
1215
1216 MCRegister PhysReg = LRI->PhysReg;
1217 // Either flag means a reader below depends on the slot.
1218 if (LRI->Reloaded || LRI->LiveOut) {
1219 if (!MI.isImplicitDef()) {
1220 MachineBasicBlock::iterator SpillBefore =
1221 std::next((MachineBasicBlock::iterator)MI.getIterator());
1222 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1223 << " RL: " << LRI->Reloaded << '\n');
1224 bool Kill = LRI->LastUse == nullptr;
1225 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1226
1227 // We need to place additional spills for each indirect destination of an
1228 // INLINEASM_BR.
1229 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1230 int FI = StackSlotForVirtReg[VirtReg];
1231 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1232 for (MachineOperand &MO : MI.operands()) {
1233 if (MO.isMBB()) {
1234 MachineBasicBlock *Succ = MO.getMBB();
1235 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1236 &RC, VirtReg);
1237 ++NumStores;
1238 Succ->addLiveIn(PhysReg);
1239 }
1240 }
1241 }
1242
1243 LRI->LastUse = nullptr;
1244 } else if (!LRI->LastUse) {
1245 // No spill was inserted, so nothing below reads this def.
1246 MO.setIsDead(true);
1247 }
1248 // A def above spills only if a displacement above reloads again.
1249 LRI->LiveOut = false;
1250 LRI->Reloaded = false;
1251 }
1252 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1253 BundleVirtRegsMap[VirtReg] = *LRI;
1254 }
1255 markRegUsedInInstr(PhysReg);
1256 setPhysReg(MO, *LRI);
1257}
1258
1259/// Place MO's value in its tied def's register, by taking the register over or
1260/// copying into it. Return false if useVirtReg() should finish MO.
1261bool RegAllocFastImpl::lowerTiedUse(MachineInstr &MI, MachineOperand &MO,
1262 LiveReg &LR) {
1263 const MachineOperand &DefMO = getTiedOperand(MI, MO);
1264 assert(DefMO.getReg().isPhysical() && "tied def allocated before its use");
1265 MCRegister DefReg = DefMO.getReg().asMCReg();
1266 unsigned SubReg = MO.getSubReg();
1267 if (!LR.PhysReg) {
1268 // No register holds the value below MI, so it can live in DefReg, unless
1269 // MO reads a subregister, DefReg cannot hold the value, or an early-clobber
1270 // def would overwrite DefReg before another operand reads the value.
1271 bool MustCopy = SubReg || !MRI->isAllocatable(DefReg) ||
1272 !MRI->getRegClass(LR.VirtReg)->contains(DefReg) ||
1273 (DefMO.isEarlyClobber() &&
1274 any_of(MI.all_uses(), [&](const MachineOperand &O) {
1275 return &O != &MO && O.getReg() == LR.VirtReg;
1276 }));
1277 if (!MustCopy) {
1278 // The def is not live above MI, so the value can occupy DefReg there.
1279 freePhysReg(DefReg);
1280 assignVirtToPhysReg(MI, LR, DefReg);
1281 return false;
1282 }
1283 allocVirtReg(MI, LR, Register(), false);
1284 // The def phase reserved DefReg, so allocVirtReg skips it.
1285 assert((LR.Error || !TRI->regsOverlap(LR.PhysReg, DefReg)) &&
1286 "copy source overlaps the tied def");
1287 }
1288
1289 MCRegister SrcReg = SubReg ? TRI->getSubReg(LR.PhysReg, SubReg) : LR.PhysReg;
1290 // Only an already rewritten tie (%x = OP %x) finds the value in DefReg.
1291 if (SrcReg == DefReg)
1292 return false;
1293
1294 // The copy reads SrcReg above MI, so no other operand may take it.
1295 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(TargetOpcode::COPY), DefReg)
1296 .addReg(SrcReg);
1297 LR.LastUse = &MI;
1298 markRegUsedInInstr(LR.PhysReg);
1299
1300 bool Renamable = !MRI->isReserved(DefReg);
1301 auto ReadDefReg = [&](MachineOperand &O) {
1302 O.setReg(DefReg);
1303 O.setSubReg(0);
1304 O.setIsRenamable(Renamable);
1305 };
1306 ReadDefReg(MO);
1307 // The other reads of the value follow it into DefReg, so SrcReg dies at the
1308 // copy. They cannot when an early-clobber def overwrites DefReg first, and a
1309 // read tied to another def owes that def's register.
1310 if (!DefMO.isEarlyClobber()) {
1311 for (MachineOperand &O : MI.all_uses()) {
1312 if (O.isTied() || O.getReg() != LR.VirtReg || O.getSubReg() != SubReg)
1313 continue;
1314 ReadDefReg(O);
1315 O.setIsKill(false);
1316 }
1317 }
1318
1319 // The free-defs step skips tied defs, so DefReg still holds the def. Keep the
1320 // remaining uses off DefReg, which the copy overwrites.
1321 freePhysReg(DefReg);
1322 markRegUsedInInstr(DefReg);
1323 return true;
1324}
1325
1326/// Allocates a register for a VirtReg use.
1327void RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1328 Register VirtReg) {
1329 assert(VirtReg.isVirtual() && "Not a virtual register");
1330 if (!shouldAllocateRegister(VirtReg))
1331 return;
1332 LiveRegMap::iterator LRI;
1333 bool New;
1334 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1335 if (New) {
1336 if (!MO.isKill()) {
1337 if (mayLiveOut(VirtReg)) {
1338 LRI->LiveOut = true;
1339 } else {
1340 // It is a last (killing) use without the kill flag; add the flag now.
1341 MO.setIsKill(true);
1342 }
1343 }
1344 } else {
1345 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1346 }
1347
1348 if (LowerTiedOps && MO.isTied() && lowerTiedUse(MI, MO, *LRI))
1349 return;
1350
1351 // If necessary allocate a register.
1352 if (!LRI->PhysReg) {
1353 assert(!MO.isTied() && "tied op should be allocated");
1354 Register Hint;
1355 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1356 Hint = MI.getOperand(0).getReg();
1357 if (Hint.isVirtual()) {
1358 assert(!shouldAllocateRegister(Hint));
1359 Hint = Register();
1360 } else {
1361 assert(Hint.isPhysical() &&
1362 "Copy destination should already be assigned");
1363 }
1364 }
1365 allocVirtReg(MI, *LRI, Hint, false);
1366 }
1367
1368 LRI->LastUse = &MI;
1369
1370 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1371 BundleVirtRegsMap[VirtReg] = *LRI;
1372 }
1373 markRegUsedInInstr(LRI->PhysReg);
1374 setPhysReg(MO, *LRI);
1375}
1376
1377/// Clear dead flags on defs of any register which also has a live def on \p MI.
1379 for (const MachineOperand &MO : MI.all_defs()) {
1380 if (!MO.isDead())
1381 MI.clearRegisterDeads(MO.getReg());
1382 }
1383}
1384
1385/// Query a physical register to use as a filler in contexts where the
1386/// allocation has failed. This will raise an error, but not abort the
1387/// compilation.
1388MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1389 MachineInstr &MI,
1390 const TargetRegisterClass &RC) {
1391 MachineFunction &MF = *MI.getMF();
1392
1393 // Avoid repeating the error every time a register is used.
1394 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1395 if (EmitError)
1396 MF.getProperties().setFailedRegAlloc();
1397
1398 // If the allocation order was empty, all registers in the class were
1399 // probably reserved. Fall back to taking the first register in the class,
1400 // even if it's reserved.
1401 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1402 if (AllocationOrder.empty()) {
1403 const Function &Fn = MF.getFunction();
1404 if (EmitError) {
1405 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1406 "no registers from class available to allocate", Fn,
1407 MI.getDebugLoc()));
1408 }
1409
1410 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1411 assert(!RawRegs.empty() && "register classes cannot have no registers");
1412 return RawRegs.front();
1413 }
1414
1415 if (!LR.Error && EmitError) {
1416 // Nothing we can do: Report an error and keep going with an invalid
1417 // allocation.
1418 if (MI.isInlineAsm()) {
1419 MI.emitInlineAsmError(
1420 "inline assembly requires more registers than available");
1421 } else {
1422 const Function &Fn = MBB->getParent()->getFunction();
1423 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1424 "ran out of registers during register allocation", Fn,
1425 MI.getDebugLoc()));
1426 }
1427 }
1428
1429 return AllocationOrder.front();
1430}
1431
1432/// Changes MO to refer to Assignment.PhysReg, considering subregs.
1433void RegAllocFastImpl::setPhysReg(MachineOperand &MO,
1434 const LiveReg &Assignment) {
1435 MCRegister PhysReg = Assignment.PhysReg;
1436 assert(PhysReg && "assignments should always be to a valid physreg");
1437
1438 if (LLVM_UNLIKELY(Assignment.Error)) {
1439 // Make sure we don't set renamable in error scenarios, as we may have
1440 // assigned to a reserved register.
1441 if (MO.isUse())
1442 MO.setIsUndef(true);
1443 else
1444 HasErrorDef = true;
1445 }
1446
1447 if (!MO.getSubReg()) {
1448 MO.setReg(PhysReg);
1449 MO.setIsRenamable(!Assignment.Error);
1450 return;
1451 }
1452
1453 // Handle subregister index.
1454 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1455 MO.setIsRenamable(!Assignment.Error);
1456
1457 // Note: We leave the subreg number around a little longer in case of defs.
1458 // This is so that the register freeing logic in allocateInstruction can still
1459 // recognize this as subregister defs. The code there will clear the number.
1460 if (!MO.isDef())
1461 MO.setSubReg(0);
1462
1463 // A kill flag implies killing the full register, and a <def,read-undef> of
1464 // a sub-register requires an implicit def of the full register.
1465 if (MO.isKill())
1466 PendingImplicitOps.emplace_back(PhysReg, ImplicitKill);
1467 else if (MO.isDef() && MO.isUndef())
1468 PendingImplicitOps.emplace_back(PhysReg,
1469 MO.isDead() ? ImplicitDead : ImplicitDef);
1470}
1471
1472void RegAllocFastImpl::addImplicitOps(MachineInstr &MI) {
1473 for (auto [PhysReg, Kind] : PendingImplicitOps) {
1474 if (Kind == ImplicitKill)
1475 MI.addRegisterKilled(PhysReg, TRI, true);
1476 else if (Kind == ImplicitDead)
1477 MI.addRegisterDead(PhysReg, TRI, true);
1478 else
1479 MI.addRegisterDefined(PhysReg, TRI);
1480 }
1481 PendingImplicitOps.clear();
1482}
1483
1484#ifndef NDEBUG
1485
1486void RegAllocFastImpl::dumpState() const {
1487 for (MCRegUnit Unit : TRI->regunits()) {
1488 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1489 case regFree:
1490 break;
1491 case regPreAssigned:
1492 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1493 break;
1494 case regLiveIn:
1495 llvm_unreachable("Should not have regLiveIn in map");
1496 default: {
1497 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1498 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1499 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1500 if (I->LiveOut || I->Reloaded) {
1501 dbgs() << '[';
1502 if (I->LiveOut)
1503 dbgs() << 'O';
1504 if (I->Reloaded)
1505 dbgs() << 'R';
1506 dbgs() << ']';
1507 }
1508 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1509 break;
1510 }
1511 }
1512 }
1513 dbgs() << '\n';
1514 // Check that LiveVirtRegs is the inverse.
1515 for (const LiveReg &LR : LiveVirtRegs) {
1516 Register VirtReg = LR.VirtReg;
1517 assert(VirtReg.isVirtual() && "Bad map key");
1518 MCRegister PhysReg = LR.PhysReg;
1519 if (PhysReg) {
1520 assert(PhysReg.isPhysical() && "mapped to physreg");
1521 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1522 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1523 }
1524 }
1525 }
1526}
1527#endif
1528
1529/// Count number of defs consumed from each register class by \p Reg
1530void RegAllocFastImpl::addRegClassDefCounts(
1531 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1532 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1533
1534 if (Reg.isVirtual()) {
1535 if (!shouldAllocateRegister(Reg))
1536 return;
1537 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1538 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1539 RCIdx != RCIdxEnd; ++RCIdx) {
1540 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1541 // FIXME: Consider aliasing sub/super registers.
1542 if (OpRC->hasSubClassEq(IdxRC))
1543 ++RegClassDefCounts[RCIdx];
1544 }
1545
1546 return;
1547 }
1548
1549 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1550 RCIdx != RCIdxEnd; ++RCIdx) {
1551 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1552 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1553 if (IdxRC->contains(*Alias)) {
1554 ++RegClassDefCounts[RCIdx];
1555 break;
1556 }
1557 }
1558 }
1559}
1560
1561/// Early clobber, partial def, or tied to a use that carries a value: the
1562/// register is occupied while the uses are read.
1563static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO) {
1564 assert(MO.isDef() && "expected def operand");
1565 if (MO.isEarlyClobber() || MO.readsReg())
1566 return true;
1567 return MO.isTied() &&
1568 !MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO))).isUndef();
1569}
1570
1571/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1572/// that are to be allocated. Those are ordered in a way that small classes,
1573/// early clobbers and livethroughs are allocated first.
1574void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1575 DefOperandIndexes.clear();
1576
1577 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1578 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1579 const MachineOperand &MO = MI.getOperand(I);
1580 if (!MO.isReg())
1581 continue;
1582 Register Reg = MO.getReg();
1583 if (MO.readsReg()) {
1584 if (Reg.isPhysical()) {
1585 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1586 markPhysRegUsedInInstr(Reg);
1587 }
1588 }
1589
1590 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1591 DefOperandIndexes.push_back(I);
1592 }
1593
1594 // Most instructions only have one virtual def, so there's no point in
1595 // computing the possible number of defs for every register class.
1596 if (DefOperandIndexes.size() <= 1)
1597 return;
1598
1599 // Track number of defs which may consume a register from the class. This is
1600 // used to assign registers for possibly-too-small classes first. Example:
1601 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1602 // registers first so that the gr32 don't use the gr32_abcd registers before
1603 // we assign these.
1604 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1605
1606 for (const MachineOperand &MO : MI.all_defs())
1607 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1608
1609 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1610 const MachineOperand &MO0 = MI.getOperand(I0);
1611 const MachineOperand &MO1 = MI.getOperand(I1);
1612 Register Reg0 = MO0.getReg();
1613 Register Reg1 = MO1.getReg();
1614 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1615 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1616
1617 // Identify regclass that are easy to use up completely just in this
1618 // instruction.
1619 unsigned ClassSize0 = RegClassInfo->getOrder(&RC0).size();
1620 unsigned ClassSize1 = RegClassInfo->getOrder(&RC1).size();
1621
1622 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1623 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1624 if (SmallClass0 > SmallClass1)
1625 return true;
1626 if (SmallClass0 < SmallClass1)
1627 return false;
1628
1629 // Allocate early clobbers and livethrough operands first.
1630 bool Livethrough0 = isLiveThroughDef(MI, MO0);
1631 bool Livethrough1 = isLiveThroughDef(MI, MO1);
1632 if (Livethrough0 > Livethrough1)
1633 return true;
1634 if (Livethrough0 < Livethrough1)
1635 return false;
1636
1637 // Tie-break rule: operand index.
1638 return I0 < I1;
1639 });
1640}
1641
1642void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1643 // Backwards, a def frees a register and a use occupies it. The phases:
1644 // * pre-assigned physreg defs
1645 // * virtual register defs
1646 // * free the def operands' registers
1647 // * displace registers clobbered by regmasks
1648 // * pre-assigned physreg uses
1649 // * virtual register uses, inserting reloads and tied-operand copies
1650 // * undef uses
1651 // * free early-clobber defs
1652 //
1653 // Freeing follows the def allocation so a def is not handed a register this
1654 // instruction also writes, and precedes the uses so a use may take one. It
1655 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1656 // freed last so that no use lands on them.
1657
1658 InstrGen += 2;
1659 // In the event we ever get more than 2**31 instructions...
1660 if (LLVM_UNLIKELY(InstrGen == 0)) {
1661 UsedInInstr.assign(UsedInInstr.size(), 0);
1662 InstrGen = 2;
1663 }
1664 RegMasks.clear();
1665 LiveDefRegs.clear();
1666 BundleVirtRegsMap.clear();
1667 assert(PendingImplicitOps.empty() && "implicit operands not added");
1668
1669 // Scan for special cases; Apply pre-assigned register defs to state.
1670 bool HasPhysRegUse = false;
1671 bool HasRegMask = false;
1672 bool HasVRegDef = false;
1673 bool HasDef = false;
1674 bool HasEarlyClobber = false;
1675 bool HasTiedDef = false;
1676 bool NeedToAssignLiveThroughs = false;
1677 for (MachineOperand &MO : MI.operands()) {
1678 if (MO.isReg()) {
1679 Register Reg = MO.getReg();
1680 if (Reg.isVirtual()) {
1681 if (!shouldAllocateRegister(Reg))
1682 continue;
1683 if (MO.isDef()) {
1684 HasDef = true;
1685 HasVRegDef = true;
1686 if (MO.isEarlyClobber())
1687 HasEarlyClobber = true;
1688 if (LowerTiedOps && MO.isTied())
1689 HasTiedDef = true;
1690 if (isLiveThroughDef(MI, MO))
1691 NeedToAssignLiveThroughs = true;
1692 }
1693 } else if (Reg.isPhysical()) {
1694 if (!MRI->isReserved(Reg)) {
1695 if (MO.isDef()) {
1696 HasDef = true;
1697 bool displacedAny = definePhysReg(MI, Reg);
1698 if (MO.isEarlyClobber())
1699 HasEarlyClobber = true;
1700 if (!displacedAny)
1701 MO.setIsDead(true);
1702 if (!MO.isDead())
1703 LiveDefRegs.push_back(Reg.asMCReg());
1704 }
1705 if (MO.readsReg())
1706 HasPhysRegUse = true;
1707 }
1708 }
1709 } else if (MO.isRegMask()) {
1710 HasRegMask = true;
1711 RegMasks.push_back(MO.getRegMask());
1712 }
1713 }
1714
1715 // Allocate virtreg defs.
1716 if (HasDef) {
1717 if (HasVRegDef) {
1718 // Special handling for early clobbers, tied operands or subregister defs:
1719 // Compared to "normal" defs these:
1720 // - Must not use a register that is pre-assigned for a use operand.
1721 // - In order to solve tricky inline assembly constraints we change the
1722 // heuristic to figure out a good operand order before doing
1723 // assignments.
1724 if (NeedToAssignLiveThroughs) {
1725 findAndSortDefOperandIndexes(MI);
1726 for (unsigned OpIdx : DefOperandIndexes) {
1727 MachineOperand &MO = MI.getOperand(OpIdx);
1728 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1729 Register Reg = MO.getReg();
1730 if (isLiveThroughDef(MI, MO))
1731 defineLiveThroughVirtReg(MI, MO, Reg);
1732 else
1733 defineVirtReg(MI, MO, Reg);
1734 }
1735 } else {
1736 for (MachineOperand &MO : MI.all_defs())
1737 if (MO.getReg().isVirtual())
1738 defineVirtReg(MI, MO, MO.getReg());
1739 }
1740 addImplicitOps(MI);
1741 }
1742
1743 // Free registers occupied by defs.
1744 // Iterate operands in reverse order, so we see the implicit super register
1745 // defs first (we added them earlier in case of <def,read-undef>).
1746 for (MachineOperand &MO : reverse(MI.all_defs())) {
1747 Register Reg = MO.getReg();
1748
1749 // A dead def is kept alive by a non-dead def of the same register or a
1750 // super-register, so clear the inconsistent dead flag.
1751 if (Reg.isPhysical() && MO.isDead() &&
1752 hasLiveDefOfSuperReg(Reg.asMCReg()))
1753 MO.setIsDead(false);
1754
1755 // subreg defs don't free the full register. We left the subreg number
1756 // around as a marker in setPhysReg() to recognize this case here.
1757 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1758 MO.setSubReg(0);
1759 continue;
1760 }
1761
1762 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1763 "tied def assigned to clobbered register");
1764
1765 // Do not free live-through defs.
1766 if (isLiveThroughDef(MI, MO))
1767 continue;
1768 if (!Reg)
1769 continue;
1770 if (Reg.isVirtual()) {
1771 assert(!shouldAllocateRegister(Reg));
1772 continue;
1773 }
1775 if (MRI->isReserved(Reg))
1776 continue;
1777 freePhysReg(Reg);
1778 unmarkRegUsedInInstr(Reg);
1779 }
1780 }
1781
1782 // A regmask is a def of every clobbered register: reload what lives in one
1783 // below MI. Nothing is reserved, so the uses may still take those registers.
1784 if (HasRegMask) {
1785 assert(!RegMasks.empty() && "expected RegMask");
1786 // MRI bookkeeping.
1787 for (const auto *RM : RegMasks)
1789
1790 for (const LiveReg &LR : LiveVirtRegs) {
1791 MCRegister PhysReg = LR.PhysReg;
1792 if (PhysReg && isClobberedByRegMasks(PhysReg))
1793 displacePhysReg(MI, PhysReg);
1794 }
1795 }
1796
1797 // Apply pre-assigned register uses to state.
1798 if (HasPhysRegUse) {
1799 for (MachineOperand &MO : MI.operands()) {
1800 if (!MO.isReg() || !MO.readsReg())
1801 continue;
1802 Register Reg = MO.getReg();
1803 if (!Reg.isPhysical())
1804 continue;
1805 if (MRI->isReserved(Reg))
1806 continue;
1807 if (!usePhysReg(MI, Reg))
1808 MO.setIsKill(true);
1809 }
1810 }
1811
1812 // Allocate virtreg uses and insert reloads as necessary. Given
1813 // %1 = OP %0, %0(tied-def 0), allocate tied %0 first, so that %0 takes %1's
1814 // register. In operand order, the untied %0 would take another register and
1815 // the tied use would need a copy.
1816 bool HasUndefUse = false;
1817 bool TiedOnly = HasTiedDef;
1818 do {
1819 for (MachineOperand &MO : MI.all_uses()) {
1820 Register Reg = MO.getReg();
1821 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg) ||
1822 (TiedOnly && !MO.isTied()))
1823 continue;
1824
1825 if (MO.isUndef()) {
1826 HasUndefUse = true;
1827 continue;
1828 }
1829
1830 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1831 // to physregs, so a def block allocated later can no longer see them.
1832 mayLiveIn(Reg);
1833
1834 assert(!MO.isInternalRead() && "Bundles not supported");
1835 assert(MO.readsReg() && "reading use");
1836 useVirtReg(MI, MO, Reg);
1837 }
1838 } while (std::exchange(TiedOnly, false));
1839 addImplicitOps(MI);
1840
1841 // Allocate undef operands. This is a separate step because in a situation
1842 // like ` = OP undef %X, %X` both operands need the same register assign
1843 // so we should perform the normal assignment first.
1844 if (HasUndefUse) {
1845 for (MachineOperand &MO : MI.all_uses()) {
1846 Register Reg = MO.getReg();
1847 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1848 continue;
1849
1850 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1851 allocVirtRegUndef(MO);
1852 }
1853 }
1854
1855 // Free early clobbers. Last, because they must not share a register with any
1856 // use.
1857 if (HasEarlyClobber) {
1858 for (MachineOperand &MO : reverse(MI.all_defs())) {
1859 if (!MO.isEarlyClobber())
1860 continue;
1861 assert(!MO.getSubReg() && "should be already handled in def processing");
1862
1863 Register Reg = MO.getReg();
1864 if (!Reg)
1865 continue;
1866 if (Reg.isVirtual()) {
1867 assert(!shouldAllocateRegister(Reg));
1868 continue;
1869 }
1870 assert(Reg.isPhysical() && "should have register assigned");
1871
1872 // We sometimes get odd situations like:
1873 // early-clobber %x0 = INSTRUCTION %x0
1874 // which is semantically questionable as the early-clobber should
1875 // apply before the use. But in practice we consider the use to
1876 // happen before the early clobber now. Don't free the early clobber
1877 // register in this case.
1878 if (MI.readsRegister(Reg, TRI))
1879 continue;
1880
1881 freePhysReg(Reg);
1882 }
1883 }
1884
1885 LLVM_DEBUG(dbgs() << "<< " << MI);
1886 if (MI.isCopy() &&
1887 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1888 MI.getOperand(0).isDead()) &&
1889 MI.getNumOperands() == 2) {
1890 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1891 Coalesced.push_back(&MI);
1892 }
1893}
1894
1895void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1896 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1897 // mostly constants and frame indices.
1898 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1899 for (const auto &MO : MI.debug_operands()) {
1900 if (!MO.isReg())
1901 continue;
1902 Register Reg = MO.getReg();
1903 if (!Reg.isVirtual())
1904 continue;
1905 if (!shouldAllocateRegister(Reg))
1906 continue;
1907
1908 // Already spilled to a stackslot?
1909 int SS = StackSlotForVirtReg[Reg];
1910 if (SS != -1) {
1911 // Modify DBG_VALUE now that the value is in a spill slot.
1913 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1914 continue;
1915 }
1916
1917 // See if this virtual register has already been allocated to a physical
1918 // register or spilled to a stack slot.
1919 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1921 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1922
1923 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1924 // Update every use of Reg within MI.
1925 for (auto &RegMO : DbgOps)
1926 setPhysReg(*RegMO, *LRI);
1927 } else {
1928 DanglingDbgValues[Reg].push_back(&MI);
1929 }
1930
1931 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1932 // that future spills of Reg will have DBG_VALUEs.
1933 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1934 }
1935}
1936
1937void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1938 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1939 ++BundledMI;
1940 while (BundledMI->isBundledWithPred()) {
1941 for (MachineOperand &MO : BundledMI->operands()) {
1942 if (!MO.isReg())
1943 continue;
1944
1945 Register Reg = MO.getReg();
1946 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1947 continue;
1948
1949 auto DI = BundleVirtRegsMap.find(Reg);
1950 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1951
1952 setPhysReg(MO, DI->second);
1953 }
1954
1955 ++BundledMI;
1956 }
1957 addImplicitOps(MI);
1958}
1959
1960void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1961 this->MBB = &MBB;
1962 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1963
1964 PosIndexes.unsetInitialized();
1965 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1966 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1967
1968 for (const auto &LiveReg : MBB.liveouts())
1969 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1970
1971 Coalesced.clear();
1972
1973 // Lowering a tied operand inserts a copy ahead of MI. Its registers are
1974 // already assigned, so visiting it would evict what still lives in the
1975 // source.
1976 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
1977 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1978
1979 // Special handling for debug values. Note that they are not allowed to
1980 // affect codegen of the other instructions in any way.
1981 if (MI.isDebugValue()) {
1982 handleDebugValue(MI);
1983 continue;
1984 }
1985
1986 allocateInstruction(MI);
1987
1988 // An error assignment may give a live and a dead def the same register.
1989 if (HasErrorDef) {
1991 HasErrorDef = false;
1992 }
1993
1994 // Once BUNDLE header is assigned registers, same assignments need to be
1995 // done for bundled MIs.
1996 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1997 handleBundle(MI);
1998 }
1999 }
2000
2001 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
2002
2003 // Spill all physical registers holding virtual registers now.
2004 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
2005 reloadAtBegin(MBB);
2006
2007 // Erase all the coalesced copies. We are delaying it until now because
2008 // LiveVirtRegs might refer to the instrs.
2009 for (MachineInstr *MI : Coalesced)
2010 MBB.erase(MI);
2011 NumCoalesced += Coalesced.size();
2012
2013 for (auto &UDBGPair : DanglingDbgValues) {
2014 for (MachineInstr *DbgValue : UDBGPair.second) {
2015 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
2016 // Nothing to do if the vreg was spilled in the meantime.
2017 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
2018 continue;
2019 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
2020 << '\n');
2021 DbgValue->setDebugValueUndef();
2022 }
2023 }
2024 DanglingDbgValues.clear();
2025
2026 LLVM_DEBUG(MBB.dump());
2027}
2028
2029/// Expand REG_SEQUENCE and INSERT_SUBREG into subregister COPYs: the lowering
2030/// TwoAddressInstructionPass performs when it runs before allocation, plus the
2031/// base-value copy its tie processing provides.
2032void RegAllocFastImpl::expandSubregPseudo(MachineInstr &MI) {
2033 MachineBasicBlock &MBB = *MI.getParent();
2034 const DebugLoc &DL = MI.getDebugLoc();
2035 if (MI.isInsertSubreg()) {
2036 // %d = INSERT_SUBREG %base, %sub, idx -> %d = COPY %base
2037 // %d.idx = COPY %sub
2038 const MachineOperand &BaseMO = MI.getOperand(1);
2039 if (!BaseMO.isUndef())
2040 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY),
2041 MI.getOperand(0).getReg())
2042 .addReg(BaseMO.getReg(), RegState::NoFlags, BaseMO.getSubReg());
2043 unsigned SubIdx = MI.getOperand(3).getImm();
2044 MI.removeOperand(3);
2045 assert(MI.getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
2046 MI.getOperand(0).setSubReg(SubIdx);
2047 MI.getOperand(0).setIsUndef(MI.getOperand(1).isUndef());
2048 MI.removeOperand(1);
2049 MI.setDesc(TII->get(TargetOpcode::COPY));
2050 return;
2051 }
2052
2053 // %d = REG_SEQUENCE %s1, idx1, ... -> undef %d.idx1 = COPY %s1
2054 // %d.idx2 = COPY %s2 ...
2055 assert(MI.isRegSequence());
2056 Register Dst = MI.getOperand(0).getReg();
2057 // An undef source needs no copy: the read-undef flag on the first copy
2058 // defines the whole register. One is still needed where a use reads that
2059 // lane on its own, which would otherwise read an undefined subregister.
2060 LaneBitmask ReadLanes = LaneBitmask::getNone();
2061 for (const MachineOperand &Use : MRI->use_nodbg_operands(Dst))
2062 if (unsigned UseSubIdx = Use.getSubReg())
2063 ReadLanes |= TRI->getSubRegIndexLaneMask(UseSubIdx);
2064
2065 bool DefEmitted = false;
2066 for (unsigned I = 1, E = MI.getNumOperands(); I + 1 < E; I += 2) {
2067 const MachineOperand &SrcMO = MI.getOperand(I);
2068 unsigned SubIdx = MI.getOperand(I + 1).getImm();
2069 if (SrcMO.isUndef() &&
2070 (ReadLanes & TRI->getSubRegIndexLaneMask(SubIdx)).none())
2071 continue;
2072 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY))
2073 .addReg(Dst, RegState::Define | getUndefRegState(!DefEmitted), SubIdx)
2074 .addReg(SrcMO.getReg(), getUndefRegState(SrcMO.isUndef()),
2075 SrcMO.getSubReg());
2076 DefEmitted = true;
2077 }
2078 // Every source was undef: uses of Dst still need a definition.
2079 if (!DefEmitted) {
2080 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
2081 while (MI.getNumOperands() > 1)
2082 MI.removeOperand(MI.getNumOperands() - 1);
2083 return;
2084 }
2085 MI.eraseFromParent();
2086}
2087
2088bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF,
2089 RegisterClassInfo &RCI) {
2090 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
2091 << "********** Function: " << MF.getName() << '\n');
2092 MRI = &MF.getRegInfo();
2093 const TargetSubtargetInfo &STI = MF.getSubtarget();
2094 TRI = STI.getRegisterInfo();
2095 TII = STI.getInstrInfo();
2096 MFI = &MF.getFrameInfo();
2097 RegClassInfo = &RCI;
2099 // Keep the shared analysis in step with the set just frozen.
2100 RegClassInfo->updateReservedRegs(MRI->getReservedRegs());
2101 unsigned NumRegUnits = TRI->getNumRegUnits();
2102 InstrGen = 0;
2103 UsedInInstr.assign(NumRegUnits, 0);
2104
2105 // MIR that already went through TwoAddressInstructionPass carries
2106 // TiedOpsRewritten, so partial pipelines (-run-pass, -start-before) follow
2107 // the input they are given.
2108 LowerTiedOps = !MF.getProperties().hasTiedOpsRewritten();
2109 if (LowerTiedOps) {
2110 for (MachineBasicBlock &MBB : MF)
2111 for (MachineInstr &MI : make_early_inc_range(MBB))
2112 if (MI.isRegSequence() || MI.isInsertSubreg())
2113 expandSubregPseudo(MI);
2114 }
2115
2116 // initialize the virtual->physical register map to have a 'null'
2117 // mapping for all virtual registers
2118 unsigned NumVirtRegs = MRI->getNumVirtRegs();
2119 StackSlotForVirtReg.resize(NumVirtRegs);
2120 LiveVirtRegs.setUniverse(NumVirtRegs);
2121 MayLiveAcrossBlocks.clear();
2122 MayLiveAcrossBlocks.resize(NumVirtRegs);
2123
2124 // Loop over all of the basic blocks, eliminating virtual register references
2125 for (MachineBasicBlock &MBB : MF)
2126 allocateBasicBlock(MBB);
2127
2128 if (ClearVirtRegs) {
2129 // All machine operands and other references to virtual registers have been
2130 // replaced. Remove the virtual registers.
2131 MRI->clearVirtRegs();
2132 }
2133
2134 StackSlotForVirtReg.clear();
2135 LiveDbgValueMap.clear();
2136 return true;
2137}
2138
2141 MFPropsModifier _(*this, MF);
2142 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
2143 bool Changed = Impl.runOnMachineFunction(
2145 if (!Changed)
2146 return PreservedAnalyses::all();
2148 PA.preserveSet<CFGAnalyses>();
2149 return PA;
2150}
2151
2153 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2154 bool PrintFilterName = Opts.FilterName != "all";
2155 bool PrintNoClearVRegs = !Opts.ClearVRegs;
2156 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
2157
2158 OS << "regallocfast";
2159 if (PrintFilterName || PrintNoClearVRegs) {
2160 OS << '<';
2161 if (PrintFilterName)
2162 OS << "filter=" << Opts.FilterName;
2163 if (PrintSemicolon)
2164 OS << ';';
2165 if (PrintNoClearVRegs)
2166 OS << "no-clear-vregs";
2167 OS << '>';
2168 }
2169}
2170
2171FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
2172
2174 bool ClearVirtRegs) {
2175 return new RegAllocFast(Ftor, ClearVirtRegs);
2176}
#define DBG(...)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo & TII
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.
#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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
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
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
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
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 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:75
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:109
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