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