LLVM 24.0.0git
VirtRegMap.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
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// This file implements the VirtRegMap class.
10//
11// It also contains implementations of the Spiller interface, which, given a
12// virtual register map and a machine function, eliminates all virtual
13// references by replacing them with physical register references - adding spill
14// code as necessary.
15//
16//===----------------------------------------------------------------------===//
17
20#include "llvm/ADT/Statistic.h"
39#include "llvm/Config/llvm-config.h"
40#include "llvm/MC/LaneBitmask.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
45#include <cassert>
46#include <iterator>
47#include <utility>
48
49using namespace llvm;
50
51#define DEBUG_TYPE "regalloc"
52
53STATISTIC(NumSpillSlots, "Number of spill slots allocated");
54STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
55
56//===----------------------------------------------------------------------===//
57// VirtRegMap implementation
58//===----------------------------------------------------------------------===//
59
61
62INITIALIZE_PASS(VirtRegMapWrapperLegacy, "virtregmap", "Virtual Register Map",
63 false, true)
64
65void VirtRegMap::init(MachineFunction &mf) {
66 MRI = &mf.getRegInfo();
67 TRI = mf.getSubtarget().getRegisterInfo();
68 MF = &mf;
69
70 Virt2PhysMap.clear();
71 Virt2StackSlotMap.clear();
72 Virt2SplitMap.clear();
73 Virt2ShapeMap.clear();
74
75 grow();
76
77 // Drain any VirtRegMap state stashed by MIRParser on MRI. Must run after
78 // grow() so that Virt2*Map have capacity for every vreg referenced by the
79 // stash.
80 for (const auto &P : MRI->getPendingVirtRegMapEntries()) {
81 if (P.AssignedPhys.isValid())
82 assignVirt2Phys(P.VReg, P.AssignedPhys);
83 // Guard against self-reference; the parser also rejects this, but a
84 // belt-and-braces check keeps Virt2SplitMap meaningful.
85 if (P.SplitFrom.isValid() && P.SplitFrom != P.VReg)
86 setIsSplitFromReg(P.VReg, P.SplitFrom);
87 }
88 MRI->clearPendingVirtRegMapEntries();
89}
90
92 unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
93 Virt2PhysMap.resize(NumRegs);
94 Virt2StackSlotMap.resize(NumRegs);
95 Virt2SplitMap.resize(NumRegs);
96}
97
99 assert(virtReg.isVirtual() && physReg.isPhysical());
100 assert(!Virt2PhysMap[virtReg] &&
101 "attempt to assign physical register to already mapped "
102 "virtual register");
103 assert(!getRegInfo().isReserved(physReg) &&
104 "Attempt to map virtReg to a reserved physReg");
105 Virt2PhysMap[virtReg] = physReg;
106}
107
108unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
109 unsigned Size = TRI->getSpillSize(*RC);
110 Align Alignment = TRI->getSpillAlign(*RC);
111 // Set preferred alignment if we are still able to realign the stack
112 auto &ST = MF->getSubtarget();
113 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
114 if (Alignment > CurrentAlign && !TRI->canRealignStack(*MF)) {
115 Alignment = CurrentAlign;
116 }
117 int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment,
118 TRI->getSpillStackID(*RC));
119 ++NumSpillSlots;
120 return SS;
121}
122
124 Register Hint = MRI->getSimpleHint(VirtReg);
125 if (!Hint.isValid())
126 return false;
127 if (Hint.isVirtual())
128 Hint = getPhys(Hint);
129 return Register(getPhys(VirtReg)) == Hint;
130}
131
133 std::pair<unsigned, Register> Hint = MRI->getRegAllocationHint(VirtReg);
134 if (Hint.second.isPhysical())
135 return true;
136 if (Hint.second.isVirtual())
137 return hasPhys(Hint.second);
138 return false;
139}
140
142 assert(virtReg.isVirtual());
143 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
144 "attempt to assign stack slot to already spilled register");
145 const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
146 return Virt2StackSlotMap[virtReg] = createSpillSlot(RC);
147}
148
150 assert(virtReg.isVirtual());
151 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
152 "attempt to assign stack slot to already spilled register");
153 assert((SS >= 0 ||
154 (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
155 "illegal fixed frame index");
156 Virt2StackSlotMap[virtReg] = SS;
157}
158
159void VirtRegMap::print(raw_ostream &OS, const Module*) const {
160 OS << "********** REGISTER MAP **********\n";
161 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
163 if (Virt2PhysMap[Reg]) {
164 OS << '[' << printReg(Reg, TRI) << " -> "
165 << printReg(Virt2PhysMap[Reg], TRI) << "] "
166 << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
167 }
168 }
169
170 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
172 if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
173 OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
174 << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
175 }
176 }
177 OS << '\n';
178}
179
180#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
182 print(dbgs());
183}
184#endif
185
186AnalysisKey VirtRegMapAnalysis::Key;
187
194
201
202//===----------------------------------------------------------------------===//
203// VirtRegRewriter
204//===----------------------------------------------------------------------===//
205//
206// The VirtRegRewriter is the last of the register allocator passes.
207// It rewrites virtual registers to physical registers as specified in the
208// VirtRegMap analysis. It also updates live-in information on basic blocks
209// according to LiveIntervals.
210//
211namespace {
212
213class VirtRegRewriter {
214 MachineFunction *MF = nullptr;
215 const TargetRegisterInfo *TRI = nullptr;
216 const TargetInstrInfo *TII = nullptr;
217 MachineRegisterInfo *MRI = nullptr;
218 SlotIndexes *Indexes = nullptr;
219 LiveIntervals *LIS = nullptr;
220 LiveRegMatrix *LRM = nullptr;
221 VirtRegMap *VRM = nullptr;
222 LiveDebugVariables *DebugVars = nullptr;
223 DenseSet<Register> RewriteRegs;
224 bool ClearVirtRegs;
225
226 void rewrite();
227 void addMBBLiveIns();
228 bool readsUndefSubreg(const MachineInstr &MI, const MachineOperand &MO) const;
229 void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
230 void handleIdentityCopy(MachineInstr &MI);
231 void expandCopyBundle(MachineInstr &MI) const;
232 bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
233 LaneBitmask liveOutUndefPhiLanesForUndefSubregDef(
234 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
235 MCRegister PhysReg, const MachineInstr &MI) const;
236
237public:
238 VirtRegRewriter(bool ClearVirtRegs, SlotIndexes *Indexes, LiveIntervals *LIS,
239 LiveRegMatrix *LRM, VirtRegMap *VRM,
240 LiveDebugVariables *DebugVars)
241 : Indexes(Indexes), LIS(LIS), LRM(LRM), VRM(VRM), DebugVars(DebugVars),
242 ClearVirtRegs(ClearVirtRegs) {}
243
244 bool run(MachineFunction &);
245};
246
247class VirtRegRewriterLegacy : public MachineFunctionPass {
248public:
249 static char ID;
250 bool ClearVirtRegs;
251 VirtRegRewriterLegacy(bool ClearVirtRegs = true)
252 : MachineFunctionPass(ID), ClearVirtRegs(ClearVirtRegs) {}
253
254 void getAnalysisUsage(AnalysisUsage &AU) const override;
255
256 bool runOnMachineFunction(MachineFunction&) override;
257
258 MachineFunctionProperties getSetProperties() const override {
259 if (ClearVirtRegs) {
260 return MachineFunctionProperties().setNoVRegs();
261 }
262
263 return MachineFunctionProperties();
264 }
265};
266
267} // end anonymous namespace
268
269char VirtRegRewriterLegacy::ID = 0;
270
271char &llvm::VirtRegRewriterID = VirtRegRewriterLegacy::ID;
272
273INITIALIZE_PASS_BEGIN(VirtRegRewriterLegacy, "virt-reg-rewriter",
274 "Virtual Register Rewriter", false, false)
281INITIALIZE_PASS_END(VirtRegRewriterLegacy, "virt-reg-rewriter",
282 "Virtual Register Rewriter", false, false)
283
284void VirtRegRewriterLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
285 AU.setPreservesCFG();
286 AU.addRequired<LiveIntervalsWrapperPass>();
287 AU.addPreserved<LiveIntervalsWrapperPass>();
288 AU.addRequired<SlotIndexesWrapperPass>();
289 AU.addPreserved<SlotIndexesWrapperPass>();
290 AU.addRequired<LiveDebugVariablesWrapperLegacy>();
291 AU.addRequired<LiveStacksWrapperLegacy>();
292 AU.addPreserved<LiveStacksWrapperLegacy>();
293 AU.addRequired<VirtRegMapWrapperLegacy>();
294 AU.addRequired<LiveRegMatrixWrapperLegacy>();
295
296 if (!ClearVirtRegs)
297 AU.addPreserved<LiveDebugVariablesWrapperLegacy>();
298
300}
301
302bool VirtRegRewriterLegacy::runOnMachineFunction(MachineFunction &MF) {
303 VirtRegMap &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
304 LiveIntervals &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
305 LiveRegMatrix &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
306 SlotIndexes &Indexes = getAnalysis<SlotIndexesWrapperPass>().getSI();
307 LiveDebugVariables &DebugVars =
308 getAnalysis<LiveDebugVariablesWrapperLegacy>().getLDV();
309
310 VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
311 return R.run(MF);
312}
313
317 MFPropsModifier _(*this, MF);
318
319 VirtRegMap &VRM = MFAM.getResult<VirtRegMapAnalysis>(MF);
322 SlotIndexes &Indexes = MFAM.getResult<SlotIndexesAnalysis>(MF);
323 LiveDebugVariables &DebugVars =
325
326 VirtRegRewriter R(ClearVirtRegs, &Indexes, &LIS, &LRM, &VRM, &DebugVars);
327 if (!R.run(MF))
328 return PreservedAnalyses::all();
329
331 PA.preserveSet<CFGAnalyses>();
332 PA.preserve<LiveIntervalsAnalysis>();
333 PA.preserve<SlotIndexesAnalysis>();
334 PA.preserve<LiveStacksAnalysis>();
335 // LiveDebugVariables is preserved by default, so clear it
336 // if this VRegRewriter is the last one in the pipeline.
337 if (ClearVirtRegs)
338 PA.abandon<LiveDebugVariablesAnalysis>();
339 return PA;
340}
341
342bool VirtRegRewriter::run(MachineFunction &fn) {
343 MF = &fn;
345 TII = MF->getSubtarget().getInstrInfo();
346 MRI = &MF->getRegInfo();
347
348 LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
349 << "********** Function: " << MF->getName() << '\n');
350 LLVM_DEBUG(VRM->dump());
351
352 // Add kill flags while we still have virtual registers.
353 LIS->addKillFlags(VRM);
354
355 // Live-in lists on basic blocks are required for physregs.
356 addMBBLiveIns();
357
358 // Rewrite virtual registers.
359 rewrite();
360
361 if (ClearVirtRegs) {
362 // Write out new DBG_VALUE instructions.
363
364 // We only do this if ClearVirtRegs is specified since this should be the
365 // final run of the pass and we don't want to emit them multiple times.
366 DebugVars->emitDebugValues(VRM);
367
368 // All machine operands and other references to virtual registers have been
369 // replaced. Remove the virtual registers and release all the transient data.
370 VRM->clearAllVirt();
371 MRI->clearVirtRegs();
372 }
373
374 return true;
375}
376
377void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
378 MCRegister PhysReg) const {
379 assert(!LI.empty());
380 assert(LI.hasSubRanges());
381
382 using SubRangeIteratorPair =
383 std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
384
388 for (const LiveInterval::SubRange &SR : LI.subranges()) {
389 SubRanges.push_back(std::make_pair(&SR, SR.begin()));
390 if (!First.isValid() || SR.segments.front().start < First)
391 First = SR.segments.front().start;
392 if (!Last.isValid() || SR.segments.back().end > Last)
393 Last = SR.segments.back().end;
394 }
395
396 // Check all mbb start positions between First and Last while
397 // simultaneously advancing an iterator for each subrange.
399 MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
400 SlotIndex MBBBegin = MBBI->first;
401 // Advance all subrange iterators so that their end position is just
402 // behind MBBBegin (or the iterator is at the end).
403 LaneBitmask LaneMask;
404 for (auto &RangeIterPair : SubRanges) {
405 const LiveInterval::SubRange *SR = RangeIterPair.first;
406 LiveInterval::const_iterator &SRI = RangeIterPair.second;
407 while (SRI != SR->end() && SRI->end <= MBBBegin)
408 ++SRI;
409 if (SRI == SR->end())
410 continue;
411 if (SRI->start <= MBBBegin)
412 LaneMask |= SR->LaneMask;
413 }
414 if (LaneMask.none())
415 continue;
416 MachineBasicBlock *MBB = MBBI->second;
417 MBB->addLiveIn(PhysReg, LaneMask);
418 }
419}
420
421// Compute MBB live-in lists from virtual register live ranges and their
422// assignments.
423void VirtRegRewriter::addMBBLiveIns() {
424 for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
425 Register VirtReg = Register::index2VirtReg(Idx);
426 if (MRI->reg_nodbg_empty(VirtReg))
427 continue;
428 LiveInterval &LI = LIS->getInterval(VirtReg);
429 if (LI.empty() || LIS->intervalIsInOneMBB(LI))
430 continue;
431 // This is a virtual register that is live across basic blocks. Its
432 // assigned PhysReg must be marked as live-in to those blocks.
433 MCRegister PhysReg = VRM->getPhys(VirtReg);
434 if (!PhysReg) {
435 // There may be no physical register assigned if only some register
436 // classes were already allocated.
437 assert(!ClearVirtRegs && "Unmapped virtual register");
438 continue;
439 }
440
441 if (LI.hasSubRanges()) {
442 addLiveInsForSubRanges(LI, PhysReg);
443 } else {
444 // Go over MBB begin positions and see if we have segments covering them.
445 // The following works because segments and the MBBIndex list are both
446 // sorted by slot indexes.
448 for (const auto &Seg : LI) {
449 I = Indexes->getMBBLowerBound(I, Seg.start);
450 for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
451 MachineBasicBlock *MBB = I->second;
452 MBB->addLiveIn(PhysReg);
453 }
454 }
455 }
456 }
457
458 // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
459 // each MBB's LiveIns set before calling addLiveIn on them.
460 for (MachineBasicBlock &MBB : *MF)
462}
463
464/// Returns true if the given machine operand \p MO of \p MI only reads
465/// undefined lanes. The function only works for use operands with a
466/// subregister set.
467bool VirtRegRewriter::readsUndefSubreg(const MachineInstr &MI,
468 const MachineOperand &MO) const {
469 // Shortcut if the operand is already marked undef.
470 if (MO.isUndef())
471 return true;
472
473 Register Reg = MO.getReg();
474 const LiveInterval &LI = LIS->getInterval(Reg);
475 SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
476 // This code is only meant to handle reading undefined subregisters which
477 // we couldn't properly detect before.
478 assert(LI.liveAt(BaseIndex) &&
479 "Reads of completely dead register should be marked undef already");
480 unsigned SubRegIdx = MO.getSubReg();
481 assert(SubRegIdx != 0 && LI.hasSubRanges());
482 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
483 // See if any of the relevant subregister liveranges is defined at this point.
484 for (const LiveInterval::SubRange &SR : LI.subranges()) {
485 if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
486 return false;
487 }
488 return true;
489}
490
491void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
492 if (!MI.isIdentityCopy())
493 return;
494 LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
495 ++NumIdCopies;
496
497 Register DstReg = MI.getOperand(0).getReg();
498
499 // We may have deferred allocation of the virtual register, and the rewrite
500 // regs code doesn't handle the liveness update.
501 if (DstReg.isVirtual())
502 return;
503
504 RewriteRegs.insert(DstReg);
505
506 // Copies like:
507 // %r0 = COPY undef %r0
508 // %al = COPY %al, implicit-def %eax
509 // give us additional liveness information: The target (super-)register
510 // must not be valid before this point. Replace the COPY with a KILL
511 // instruction to maintain this information.
512 if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
513 MI.setDesc(TII->get(TargetOpcode::KILL));
514 LLVM_DEBUG(dbgs() << " replace by: " << MI);
515 return;
516 }
517
518 if (Indexes)
520 MI.eraseFromBundle();
521 LLVM_DEBUG(dbgs() << " deleted.\n");
522}
523
524/// The liverange splitting logic sometimes produces bundles of copies when
525/// subregisters are involved. Expand these into a sequence of copy instructions
526/// after processing the last in the bundle. Does not update LiveIntervals
527/// which we shouldn't need for this instruction anymore.
528void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
529 if (!MI.isCopy() && !MI.isKill())
530 return;
531
532 if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
534
535 // Only do this when the complete bundle is made out of COPYs and KILLs.
538 std::next(MI.getReverseIterator()), E = MBB.instr_rend();
539 I != E && I->isBundledWithSucc(); ++I) {
540 if (!I->isCopy() && !I->isKill())
541 return;
542 MIs.push_back(&*I);
543 }
544 MachineInstr *FirstMI = MIs.back();
545
546 auto anyRegsAlias = [](const MachineInstr *Dst,
548 const TargetRegisterInfo *TRI) {
549 for (const MachineInstr *Src : Srcs)
550 if (Src != Dst)
551 if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
552 Src->getOperand(1).getReg()))
553 return true;
554 return false;
555 };
556
557 // If any of the destination registers in the bundle of copies alias any of
558 // the source registers, try to schedule the instructions to avoid any
559 // clobbering.
560 for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
561 for (int I = E; I--; )
562 if (!anyRegsAlias(MIs[I], ArrayRef(MIs).take_front(E), TRI)) {
563 if (I + 1 != E)
564 std::swap(MIs[I], MIs[E - 1]);
565 --E;
566 }
567 if (PrevE == E) {
568 MF->getFunction().getContext().emitError(
569 "register rewriting failed: cycle in copy bundle");
570 break;
571 }
572 }
573
574 MachineInstr *BundleStart = FirstMI;
575 for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
576 // If instruction is in the middle of the bundle, move it before the
577 // bundle starts, otherwise, just unbundle it. When we get to the last
578 // instruction, the bundle will have been completely undone.
579 if (BundledMI != BundleStart) {
580 BundledMI->removeFromBundle();
581 MBB.insert(BundleStart, BundledMI);
582 } else if (BundledMI->isBundledWithSucc()) {
583 BundledMI->unbundleFromSucc();
584 BundleStart = &*std::next(BundledMI->getIterator());
585 }
586
587 if (Indexes && BundledMI != FirstMI)
588 Indexes->insertMachineInstrInMaps(*BundledMI);
589 }
590 }
591}
592
593/// Check whether (part of) \p SuperPhysReg is live through \p MI.
594/// \pre \p MI defines a subregister of a virtual register that
595/// has been assigned to \p SuperPhysReg.
596bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
597 MCRegister SuperPhysReg) const {
598 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
599 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
600 SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
601 for (MCRegUnit Unit : TRI->regunits(SuperPhysReg)) {
602 const LiveRange &UnitRange = LIS->getRegUnit(Unit);
603 // If the regunit is live both before and after MI,
604 // we assume it is live through.
605 // Generally speaking, this is not true, because something like
606 // "RU = op RU" would match that description.
607 // However, we know that we are trying to assess whether
608 // a def of a virtual reg, vreg, is live at the same time of RU.
609 // If we are in the "RU = op RU" situation, that means that vreg
610 // is defined at the same time as RU (i.e., "vreg, RU = op RU").
611 // Thus, vreg and RU interferes and vreg cannot be assigned to
612 // SuperPhysReg. Therefore, this situation cannot happen.
613 if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
614 return true;
615 }
616 return false;
617}
618
619/// Compute a lanemask for undef lanes which need to be preserved out of the
620/// defining block for a register assignment for a subregister def. \p PhysReg
621/// is assigned to \p LI, which is the main range.
622LaneBitmask VirtRegRewriter::liveOutUndefPhiLanesForUndefSubregDef(
623 const LiveInterval &LI, const MachineBasicBlock &MBB, unsigned SubReg,
624 MCRegister PhysReg, const MachineInstr &MI) const {
625 LaneBitmask UndefMask = ~TRI->getSubRegIndexLaneMask(SubReg);
626 LaneBitmask LiveOutUndefLanes;
627
628 for (const LiveInterval::SubRange &SR : LI.subranges()) {
629 // Figure out which lanes are undef live into a successor.
630 LaneBitmask NeedImpDefLanes = UndefMask & SR.LaneMask;
631 if (NeedImpDefLanes.any() && !LIS->isLiveOutOfMBB(SR, &MBB)) {
632 for (const MachineBasicBlock *Succ : MBB.successors()) {
633 if (LIS->isLiveInToMBB(SR, Succ))
634 LiveOutUndefLanes |= NeedImpDefLanes;
635 }
636 }
637 }
638
639 SlotIndex MIIndex = LIS->getInstructionIndex(MI);
640 SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
641 LaneBitmask InterferingLanes =
642 LRM->checkInterferenceLanes(BeforeMIUses, MIIndex.getRegSlot(), PhysReg);
643 LiveOutUndefLanes &= ~InterferingLanes;
644
645 LLVM_DEBUG(if (LiveOutUndefLanes.any()) {
646 dbgs() << "Need live out undef defs for " << printReg(PhysReg)
647 << LiveOutUndefLanes << " from " << printMBBReference(MBB) << '\n';
648 });
649
650 return LiveOutUndefLanes;
651}
652
653void VirtRegRewriter::rewrite() {
654 bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
655 SmallVector<Register, 8> SuperDeads;
656 SmallVector<Register, 8> SuperDefs;
657 SmallVector<Register, 8> SuperKills;
658
659 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
660 MBBI != MBBE; ++MBBI) {
661 LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
663 for (MachineOperand &MO : MI.operands()) {
664 // Make sure MRI knows about registers clobbered by regmasks.
665 if (MO.isRegMask())
667
668 if (!MO.isReg() || !MO.getReg().isVirtual())
669 continue;
670 Register VirtReg = MO.getReg();
671 MCRegister PhysReg = VRM->getPhys(VirtReg);
672 if (!PhysReg)
673 continue;
674
675 assert(Register(PhysReg).isPhysical());
676
677 RewriteRegs.insert(PhysReg);
678 assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
679
680 // Preserve semantics of sub-register operands.
681 unsigned SubReg = MO.getSubReg();
682 if (SubReg != 0) {
683 if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
684 // A virtual register kill refers to the whole register, so we may
685 // have to add implicit killed operands for the super-register. A
686 // partial redef always kills and redefines the super-register.
687 if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
688 (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
689 SuperKills.push_back(PhysReg);
690
691 if (MO.isDef()) {
692 // Also add implicit defs for the super-register.
693 if (MO.isDead())
694 SuperDeads.push_back(PhysReg);
695 else
696 SuperDefs.push_back(PhysReg);
697 }
698 } else {
699 if (MO.isUse()) {
700 if (readsUndefSubreg(MI, MO))
701 // We need to add an <undef> flag if the subregister is
702 // completely undefined (and we are not adding super-register
703 // defs).
704 MO.setIsUndef(true);
705 } else if (!MO.isDead()) {
706 assert(MO.isDef());
707 if (MO.isUndef()) {
708 const LiveInterval &LI = LIS->getInterval(VirtReg);
709
710 LaneBitmask LiveOutUndefLanes =
711 liveOutUndefPhiLanesForUndefSubregDef(LI, *MBBI, SubReg,
712 PhysReg, MI);
713 if (LiveOutUndefLanes.any()) {
714 SmallVector<unsigned, 16> CoveringIndexes;
715
716 // TODO: Just use one super register def if none of the lanes
717 // are needed?
718 if (!TRI->getCoveringSubRegIndexes(MRI->getRegClass(VirtReg),
719 LiveOutUndefLanes,
720 CoveringIndexes))
722 "cannot represent required subregister defs");
723
724 // Try to represent the minimum needed live out def as a
725 // sequence of subregister defs.
726 //
727 // FIXME: It would be better if we could directly represent
728 // liveness with a lanemask instead of spamming operands.
729 for (unsigned SubIdx : CoveringIndexes)
730 SuperDefs.push_back(TRI->getSubReg(PhysReg, SubIdx));
731 }
732 }
733 }
734 }
735
736 // The def undef and def internal flags only make sense for
737 // sub-register defs, and we are substituting a full physreg. An
738 // implicit killed operand from the SuperKills list will represent the
739 // partial read of the super-register.
740 if (MO.isDef()) {
741 MO.setIsUndef(false);
742 MO.setIsInternalRead(false);
743 }
744
745 // PhysReg operands cannot have subregister indexes.
746 PhysReg = TRI->getSubReg(PhysReg, SubReg);
747 assert(PhysReg.isValid() && "Invalid SubReg for physical register");
748 MO.setSubReg(0);
749 }
750 // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
751 // we need the inlining here.
752 MO.setReg(PhysReg);
753 MO.setIsRenamable(true);
754 }
755
756 // Add any missing super-register kills after rewriting the whole
757 // instruction.
758 while (!SuperKills.empty())
759 MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
760
761 while (!SuperDeads.empty())
762 MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
763
764 while (!SuperDefs.empty())
765 MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
766
767 LLVM_DEBUG(dbgs() << "> " << MI);
768
769 expandCopyBundle(MI);
770
771 // We can remove identity copies right now.
772 handleIdentityCopy(MI);
773 }
774 }
775
776 if (LIS) {
777 // Don't bother maintaining accurate LiveIntervals for registers which were
778 // already allocated.
779 for (Register PhysReg : RewriteRegs) {
780 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
781 LIS->removeRegUnit(Unit);
782 }
783 }
784 }
785
786 RewriteRegs.clear();
787}
788
791 OS << "virt-reg-rewriter";
792 if (!ClearVirtRegs)
793 OS << "<no-clear-vregs>";
794}
795
797 return new VirtRegRewriterLegacy(ClearVirtRegs);
798}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
ModuleAnalysisManager MAM
#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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static bool isPhysical(const MachineOperand &MO)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVM_ABI void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void addKillFlags(const VirtRegMap *)
Add kill flags to any instruction that kills a virtual register.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void removeRegUnit(MCRegUnit Unit)
Remove computed live range for register unit Unit.
LiveInterval & getInterval(Register Reg)
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
bool isLiveOutOfMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
This class represents the liveness of a register, stack slot, etc.
Segments::const_iterator const_iterator
bool liveAt(SlotIndex index) const
bool empty() const
LLVM_ABI LaneBitmask checkInterferenceLanes(SlotIndex Start, SlotIndex End, MCRegister PhysReg)
Check for interference in the segment [Start, End) that may prevent assignment to PhysReg,...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI void print(raw_ostream &OS, const SlotIndexes *=nullptr, bool IsStandalone=true) const
reverse_instr_iterator instr_rend()
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.
iterator_range< succ_iterator > successors()
Instructions::reverse_iterator reverse_instr_iterator
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.
BasicBlockListType::iterator iterator
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setIsInternalRead(bool Val=true)
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.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
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 Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
MBBIndexIterator getMBBLowerBound(MBBIndexIterator Start, SlotIndex Idx) const
Get an iterator pointing to the first IdxMBBPair with SlotIndex greater than or equal to Idx.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
MBBIndexIterator MBBIndexBegin() const
Returns an iterator for the begin of the idx2MBBMap.
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM_ABI VirtRegMap run(MachineFunction &MF, MachineFunctionAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static LLVM_ABI char ID
Definition VirtRegMap.h:196
LLVM_ABI bool hasKnownPreference(Register VirtReg) const
returns true if VirtReg has a known preferred register.
LLVM_ABI int assignVirt2StackSlot(Register virtReg)
create a mapping for the specifed virtual register to the next available stack slot
void clearAllVirt()
clears all virtual to physical register mappings
Definition VirtRegMap.h:123
LLVM_ABI void init(MachineFunction &MF)
LLVM_ABI bool hasPreferredPhys(Register VirtReg) const
returns true if VirtReg is assigned to its preferred physreg.
LLVM_ABI void dump() const
MachineRegisterInfo & getRegInfo() const
Definition VirtRegMap.h:78
LLVM_ABI void assignVirt2Phys(Register virtReg, MCRegister physReg)
creates a mapping for the specified virtual register to the specified physical register
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:89
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr) const
LLVM_ABI void grow()
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition VirtRegMap.h:85
static constexpr int NO_STACK_SLOT
Definition VirtRegMap.h:64
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)>) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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.
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:313
This is an optimization pass for GlobalISel generic memory operations.
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
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI char & VirtRegRewriterID
VirtRegRewriter pass.
LLVM_ABI FunctionPass * createVirtRegRewriter(bool ClearVirtRegs=true)
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
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53