LLVM 24.0.0git
LiveIntervals.cpp
Go to the documentation of this file.
1//===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file This file implements the LiveInterval analysis pass which is used
10/// by the Linear Scan Register allocator. This pass linearizes the
11/// basic blocks of the function in DFS order and computes live intervals for
12/// each virtual and physical register.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/Statistic.h"
34#include "llvm/CodeGen/Passes.h"
40#include "llvm/Config/llvm-config.h"
42#include "llvm/IR/Statepoint.h"
44#include "llvm/MC/LaneBitmask.h"
46#include "llvm/Pass.h"
49#include "llvm/Support/Debug.h"
52#include <algorithm>
53#include <cassert>
54#include <cstdint>
55#include <iterator>
56#include <tuple>
57#include <utility>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "regalloc"
62
63STATISTIC(NumUnreferencedIntervals,
64 "Number of intervals removed for unreferenced virtual registers");
65
66AnalysisKey LiveIntervalsAnalysis::Key;
67
71 auto Res = Result(MF, MFAM.getResult<SlotIndexesAnalysis>(MF),
73 LLVM_DEBUG(Res.dump());
74 return Res;
75}
76
80 OS << "Live intervals for machine function: " << MF.getName() << ":\n";
83}
84
88 "Live Interval Analysis", false, false)
92 "Live Interval Analysis", false, true)
93
95 LIS.Indexes = &getAnalysis<SlotIndexesWrapperPass>().getSI();
96 LIS.DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
97 LIS.analyze(MF);
99 return false;
100}
101
102#ifndef NDEBUG
104 "precompute-phys-liveness", cl::Hidden,
105 cl::desc("Eagerly compute live intervals for all physreg units."));
106#else
107static bool EnablePrecomputePhysRegs = false;
108#endif // NDEBUG
109
119
122
124
126 MachineFunction &MF, const PreservedAnalyses &PA,
127 MachineFunctionAnalysisManager::Invalidator &Inv) {
128 auto PAC = PA.getChecker<LiveIntervalsAnalysis>();
129
130 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<MachineFunction>>())
131 return true;
132
133 // LiveIntervals holds pointers to these results, so check for their
134 // invalidation.
135 return Inv.invalidate<SlotIndexesAnalysis>(MF, PA) ||
136 Inv.invalidate<MachineDominatorTreeAnalysis>(MF, PA);
137}
138
139void LiveIntervals::clear() {
140 // Free the live intervals themselves.
141 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i) {
142 if (LiveInterval *LI = VirtRegIntervals[Register::index2VirtReg(i)])
143 LI->~LiveInterval();
144 }
145 VirtRegIntervals.clear();
146 RegMaskSlots.clear();
147 RegMaskBits.clear();
148 RegMaskBlocks.clear();
149 ShrinkBlocks.clear();
150
151 for (LiveRange *LR : RegUnitRanges) {
152 if (LR)
153 LR->~LiveRange();
154 }
155 RegUnitRanges.clear();
156
157 IntervalRecycler.clear(RangeAllocator);
158 RegUnitRangeRecycler.clear(RangeAllocator);
159 RangeAllocator.Reset();
160
161 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
162 VNInfoAllocator.Reset();
163}
164
165void LiveIntervals::analyze(MachineFunction &fn) {
166 MF = &fn;
167 MRI = &MF->getRegInfo();
168 TRI = MF->getSubtarget().getRegisterInfo();
169
170 if (!LICalc)
171 LICalc = std::make_unique<LiveIntervalCalc>();
172
173 // Allocate space for all virtual registers.
174 VirtRegIntervals.resize(MRI->getNumVirtRegs());
175 ShrinkBlocks.assign(MF->getNumBlockIDs(), {});
176
177 computeVirtRegs();
178 computeRegMasks();
179 computeLiveInRegUnits();
180
182 // For stress testing, precompute live ranges of all physical register
183 // units, including reserved registers.
184 for (MCRegUnit Unit : TRI->regunits())
185 getRegUnit(Unit);
186 }
187}
188
190 unsigned Removed = 0;
191 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
193 if (hasInterval(Reg) && MRI->reg_empty(Reg)) {
194 removeInterval(Reg);
195 ++Removed;
196 }
197 }
198 NumUnreferencedIntervals += Removed;
199 return Removed;
200}
201
203 OS << "********** INTERVALS **********\n";
204
205 // Dump the regunits.
206 for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
207 if (LiveRange *LR = RegUnitRanges[Unit])
208 OS << printRegUnit(static_cast<MCRegUnit>(Unit), TRI) << ' ' << *LR
209 << '\n';
210
211 // Dump the virtregs.
212 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
214 if (hasInterval(Reg))
215 OS << getInterval(Reg) << '\n';
216 }
217
218 OS << "RegMasks:";
219 for (SlotIndex Idx : RegMaskSlots)
220 OS << ' ' << Idx;
221 OS << '\n';
222
223 printInstrs(OS);
224}
225
226void LiveIntervals::printInstrs(raw_ostream &OS) const {
227 OS << "********** MACHINEINSTRS **********\n";
228 MF->print(OS, Indexes);
229}
230
231#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
232LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
233 printInstrs(dbgs());
234}
235#endif
236
237#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
239#endif
240
241LiveInterval *LiveIntervals::createInterval(Register reg) {
242 float Weight = reg.isPhysical() ? huge_valf : 0.0F;
243 return new (IntervalRecycler.Allocate(RangeAllocator))
244 LiveInterval(reg, Weight);
245}
246
247LiveRange *LiveIntervals::createRegUnitRange() {
248 return new (RegUnitRangeRecycler.Allocate(RangeAllocator)) LiveRange();
249}
250
251/// Compute the live interval of a virtual register, based on defs and uses.
252bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
253 assert(LICalc && "LICalc not initialized.");
254 assert(LI.empty() && "Should only compute empty intervals.");
255 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
256 LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg()));
257 return computeDeadValues(LI, nullptr);
258}
259
260void LiveIntervals::computeVirtRegs() {
261 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
263 if (MRI->reg_nodbg_empty(Reg))
264 continue;
265 LiveInterval &LI = createEmptyInterval(Reg);
266 bool NeedSplit = computeVirtRegInterval(LI);
267 if (NeedSplit) {
269 splitSeparateComponents(LI, SplitLIs);
270 }
271 }
272}
273
274void LiveIntervals::computeRegMasks() {
275 RegMaskBlocks.resize(MF->getNumBlockIDs());
276
277 // Find all instructions with regmask operands.
278 for (const MachineBasicBlock &MBB : *MF) {
279 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
280 RMB.first = RegMaskSlots.size();
281
282 // Some block starts, such as EH funclets, create masks.
283 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
284 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
285 RegMaskBits.push_back(Mask);
286 }
287
288 // Unwinders may clobber additional registers.
289 // FIXME: This functionality can possibly be merged into
290 // MachineBasicBlock::getBeginClobberMask().
291 if (MBB.isEHPad())
292 if (auto *Mask = TRI->getCustomEHPadPreservedMask(*MBB.getParent())) {
293 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
294 RegMaskBits.push_back(Mask);
295 }
296
297 for (const MachineInstr &MI : MBB) {
298 for (const MachineOperand &MO : MI.operands()) {
299 if (!MO.isRegMask())
300 continue;
301 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
302 RegMaskBits.push_back(MO.getRegMask());
303 }
304 }
305
306 // Some block ends, such as funclet returns, create masks. Put the mask on
307 // the last instruction of the block, because MBB slot index intervals are
308 // half-open.
309 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
310 assert(!MBB.empty() && "empty return block?");
311 RegMaskSlots.push_back(
312 Indexes->getInstructionIndex(MBB.back()).getRegSlot());
313 RegMaskBits.push_back(Mask);
314 }
315
316 // Compute the number of register mask instructions in this block.
317 RMB.second = RegMaskSlots.size() - RMB.first;
318 }
319}
320
321void LiveIntervals::reassignRegMaskSlots(MachineBasicBlock &Orig,
322 MachineBasicBlock &SplitBB) {
323 assert(&Orig != &SplitBB && "expected distinct blocks");
324 std::pair<unsigned, unsigned> &OrigRMB = RegMaskBlocks[Orig.getNumber()];
325 std::pair<unsigned, unsigned> &SplitRMB = RegMaskBlocks[SplitBB.getNumber()];
326
327 // RegMaskSlots is sorted, so the slots that moved are those at or after
328 // SplitBB's start index.
329 ArrayRef<SlotIndex> OrigSlots =
330 getRegMaskSlots().slice(OrigRMB.first, OrigRMB.second);
331 unsigned KeptCount = llvm::lower_bound(OrigSlots, getMBBStartIdx(&SplitBB)) -
332 OrigSlots.begin();
333 if (KeptCount == OrigRMB.second)
334 return; // No regmask slots moved into SplitBB.
335
336 SplitRMB.first = OrigRMB.first + KeptCount;
337 SplitRMB.second = OrigRMB.second - KeptCount;
338 OrigRMB.second = KeptCount;
339}
340
341void LiveIntervals::insertMBBInMapsImpl(
342 MachineBasicBlock *MBB, [[maybe_unused]] bool AssumeRegMaskEmpty) {
343#ifdef EXPENSIVE_CHECKS
344 assert((!AssumeRegMaskEmpty ||
345 none_of(*MBB,
346 [](const MachineInstr &MI) {
347 return any_of(MI.operands(), [](const MachineOperand &MO) {
348 return MO.isRegMask();
349 });
350 })) &&
351 "insertMBBInMaps expects a block with no regmask operands; use "
352 "LiveIntervals::splitAt() to split a block containing calls");
353#endif
354 Indexes->insertMBBInMaps(MBB);
355 assert(unsigned(MBB->getNumber()) == RegMaskBlocks.size() &&
356 "Blocks must be added in order.");
357 RegMaskBlocks.push_back(std::make_pair(RegMaskSlots.size(), 0));
358 ShrinkBlocks.emplace_back();
359}
360
361//===----------------------------------------------------------------------===//
362// Register Unit Liveness
363//===----------------------------------------------------------------------===//
364//
365// Fixed interference typically comes from ABI boundaries: Function arguments
366// and return values are passed in fixed registers, and so are exception
367// pointers entering landing pads. Certain instructions require values to be
368// present in specific registers. That is also represented through fixed
369// interference.
370//
371
372/// Compute the live range of a register unit, based on the uses and defs of
373/// aliasing registers. The range should be empty, or contain only dead
374/// phi-defs from ABI blocks.
375void LiveIntervals::computeRegUnitRange(LiveRange &LR, MCRegUnit Unit) {
376 assert(LICalc && "LICalc not initialized.");
377 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
378
379 // The physregs aliasing Unit are the roots and their super-registers.
380 // Create all values as dead defs before extending to uses. Note that roots
381 // may share super-registers. That's OK because createDeadDef() is
382 // idempotent. It is very rare for a register unit to have multiple roots, so
383 // uniquing super-registers is probably not worthwhile.
384 bool IsReserved = false;
386 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
387 bool IsRootReserved = true;
388 for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
389 for (const MachineOperand &MO : MRI->def_operands(Reg))
390 DefIdxs.push_back(Indexes->getInstructionIndex(*MO.getParent())
391 .getRegSlot(MO.isEarlyClobber()));
392 // A register unit is considered reserved if all its roots and all their
393 // super registers are reserved.
394 if (!MRI->isReserved(Reg))
395 IsRootReserved = false;
396 }
397 IsReserved |= IsRootReserved;
398 }
399 assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
400 "reserved computation mismatch");
401
402 llvm::sort(DefIdxs);
403 for (SlotIndex DefIdx : DefIdxs)
404 LR.createDeadDef(DefIdx, VNInfoAllocator);
405
406 // Now extend LR to reach all uses.
407 // Ignore uses of reserved registers. We only track defs of those.
408 if (!IsReserved) {
409 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
410 for (MCPhysReg Reg : TRI->superregs_inclusive(*Root)) {
411 if (!MRI->reg_empty(Reg))
412 LICalc->extendToUses(LR, Reg);
413 }
414 }
415 }
416}
417
418/// Precompute the live ranges of any register units that are live-in to an ABI
419/// block somewhere. Register values can appear without a corresponding def when
420/// entering the entry block or a landing pad.
421void LiveIntervals::computeLiveInRegUnits() {
422 RegUnitRanges.resize(TRI->getNumRegUnits());
423 LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
424
425 // Keep track of the live range sets allocated.
427
428 // Check all basic blocks for live-ins.
429 for (const MachineBasicBlock &MBB : *MF) {
430 // We only care about ABI blocks: Entry + landing pads.
431 if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
432 continue;
433
434 // Create phi-defs at Begin for all live-in registers.
435 SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
436 LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
437 for (const auto &LI : MBB.liveins()) {
438 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
439 LiveRange *LR = RegUnitRanges[static_cast<unsigned>(Unit)];
440 if (!LR) {
441 LR = RegUnitRanges[static_cast<unsigned>(Unit)] =
442 createRegUnitRange();
443 NewRanges.push_back(Unit);
444 }
445 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
446 (void)VNI;
447 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
448 }
449 }
450 LLVM_DEBUG(dbgs() << '\n');
451 }
452 LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
453
454 // Compute the 'normal' part of the ranges.
455 for (MCRegUnit Unit : NewRanges)
456 computeRegUnitRange(*RegUnitRanges[static_cast<unsigned>(Unit)], Unit);
457}
458
461 for (VNInfo *VNI : VNIs) {
462 if (VNI->isUnused())
463 continue;
464 SlotIndex Def = VNI->def;
465 LR.segments.push_back(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
466 }
467
469 [](const LiveRange::Segment &A, const LiveRange::Segment &B) {
470 return A.start < B.start;
471 });
472}
473
474void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
475 ShrinkToUsesWorkList &WorkList,
476 Register Reg, LaneBitmask LaneMask) {
477 // Keep track of the PHIs that are in use.
478 SmallPtrSet<VNInfo*, 8> UsedPHIs;
479 // Start a new tag; entries from earlier calls are now stale.
480 if (++ShrinkTag == 0) {
481 ShrinkBlocks.assign(ShrinkBlocks.size(), {});
482 ShrinkTag = 1;
483 }
484
485 auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
486 -> const LiveRange& {
487 if (M.none())
488 return I;
489 for (const LiveInterval::SubRange &SR : I.subranges()) {
490 if ((SR.LaneMask & M).any()) {
491 assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
492 return SR;
493 }
494 }
495 llvm_unreachable("Subrange for mask not found");
496 };
497
498 const LiveInterval &LI = getInterval(Reg);
499 const LiveRange &OldRange = getSubRange(LI, LaneMask);
500
501 // Live-in segments are found in worklist order, so collect them (at most one
502 // per block) and add them all at the end.
504
505 // Extend intervals to reach all uses in WorkList.
506 while (!WorkList.empty()) {
507 SlotIndex Idx = WorkList.back().first;
508 VNInfo *VNI = WorkList.back().second;
509 WorkList.pop_back();
510 const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
511 SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
512
513 // Extend the live range for VNI to be live at Idx. Segments only holds def
514 // segments during the walk, and none extend past their block.
516 Segments, [Idx](const LiveRange::Segment &S) { return S.start < Idx; });
517 if (Def != Segments.begin() && (--Def)->start >= BlockStart) {
518 assert(Def->valno == VNI && "Unexpected existing value number");
519 Def->end = std::max(Def->end, Idx);
520 // Is this a PHIDef we haven't seen before?
521 if (!VNI->isPHIDef() || VNI->def != BlockStart ||
522 !UsedPHIs.insert(VNI).second)
523 continue;
524 // The PHI is live, make sure the predecessors are live-out.
525 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
526 unsigned &Tag = ShrinkBlocks[Pred->getNumber()].LiveOutTag;
527 if (Tag == ShrinkTag)
528 continue;
529 Tag = ShrinkTag;
530 SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
531 // A predecessor is not required to have a live-out value for a PHI.
532 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
533 WorkList.push_back(std::make_pair(Stop, PVNI));
534 }
535 continue;
536 }
537
538 ShrinkBlockState &BS = ShrinkBlocks[MBB->getNumber()];
539 if (BS.LiveInTag == ShrinkTag) {
540 LiveRange::Segment &S = LiveIns[BS.LiveIn];
541 assert(S.valno == VNI && "Unexpected existing value number");
542 S.end = std::max(S.end, Idx);
543 continue;
544 }
545
546 BS.LiveInTag = ShrinkTag;
547 BS.LiveIn = LiveIns.size();
548
549 // VNI is live-in to MBB.
550 LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
551 LiveIns.push_back(LiveRange::Segment(BlockStart, Idx, VNI));
552
553 // Make sure VNI is live-out from the predecessors.
554 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
555 unsigned &Tag = ShrinkBlocks[Pred->getNumber()].LiveOutTag;
556 if (Tag == ShrinkTag)
557 continue;
558 Tag = ShrinkTag;
559 SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
560 if (VNInfo *OldVNI =
561 LaneMask.none() ? VNI : OldRange.getVNInfoBefore(Stop)) {
562 assert(OldVNI == VNI && "Wrong value out of predecessor");
563 (void)OldVNI;
564 WorkList.push_back(std::make_pair(Stop, VNI));
565 } else {
566#ifndef NDEBUG
567 // There was no old VNI. Verify that Stop is jointly dominated
568 // by <undef>s for this live range.
570 LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
571 assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
572 "Missing value out of predecessor for subrange");
573#endif
574 }
575 }
576 }
577
578 llvm::sort(LiveIns,
579 [](const LiveRange::Segment &A, const LiveRange::Segment &B) {
580 return A.start < B.start;
581 });
582 Segments.addSegments(LiveIns);
583}
584
587 LaneBitmask SubRangeMask) {
588 LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
589 assert(li->reg().isVirtual() && "Can only shrink virtual registers");
590
591 // Shrink subregister live ranges.
592 if (li->hasSubRanges() && SubRangeMask.any()) {
593 SubRangeUseList Uses;
594 collectSubRangeUses(li->reg(), Uses);
595 bool NeedsCleanup = false;
596 for (LiveInterval::SubRange &S : li->subranges()) {
597 if ((S.LaneMask & SubRangeMask).none())
598 continue;
599 shrinkSubRangeToUses(S, li->reg(), Uses);
600 if (S.empty())
601 NeedsCleanup = true;
602 }
603
604 if (NeedsCleanup)
606 }
607
608 // Find all the values used, including PHI kills.
609 ShrinkToUsesWorkList WorkList;
610
611 // Visit all operands reading li->reg().
612 Register Reg = li->reg();
613 for (const MachineOperand &MO : MRI->reg_nodbg_operands(Reg)) {
614 if (!MO.readsReg())
615 continue;
616 const MachineInstr &UseMI = *MO.getParent();
617 SlotIndex Idx =
618 getInstructionIndex(UseMI).getRegSlot(MO.isEarlyClobberDefOrUse());
619 LiveQueryResult LRQ = li->Query(Idx);
620 VNInfo *VNI = LRQ.valueIn();
621 if (!VNI) {
622 // This shouldn't happen: the operand reads Reg, but there is no live
623 // value. It is likely caused by a target getting <undef> flags wrong.
625 dbgs() << Idx << '\t' << UseMI
626 << "Warning: Instr claims to read non-existent value in "
627 << *li << '\n');
628 continue;
629 }
630 // An untied use may read a register redefined by an early-clobber def.
631 if (VNInfo *DefVNI = LRQ.valueDefined())
632 Idx = DefVNI->def;
633
634 // Merge adjacent operands of the same instruction, keeping the latest use.
635 if (!WorkList.empty() &&
636 SlotIndex::isSameInstr(WorkList.back().first, Idx)) {
637 WorkList.back().first = std::max(WorkList.back().first, Idx);
638 continue;
639 }
640 WorkList.push_back(std::make_pair(Idx, VNI));
641 }
642
643 // Create new live ranges with only minimal live segments per def.
644 LiveRange NewLR;
645 createSegmentsForValues(NewLR, li->vnis());
646 extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
647
648 // Move the trimmed segments back.
649 li->segments.swap(NewLR.segments);
650
651 // Handle dead values.
652 bool CanSeparate = computeDeadValues(*li, dead);
653 LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
654 return CanSeparate;
655}
656
657bool LiveIntervals::computeDeadValues(LiveInterval &LI,
659 bool MayHaveSplitComponents = false;
660
661 for (VNInfo *VNI : LI.valnos) {
662 if (VNI->isUnused())
663 continue;
664 SlotIndex Def = VNI->def;
666 assert(I != LI.end() && "Missing segment for VNI");
667
668 // Is the register live before? Otherwise we may have to add a read-undef
669 // flag for subregister defs.
670 Register VReg = LI.reg();
671 if (MRI->shouldTrackSubRegLiveness(VReg)) {
672 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
674 MI->setRegisterDefReadUndef(VReg);
675 }
676 }
677
678 if (I->end != Def.getDeadSlot())
679 continue;
680 if (VNI->isPHIDef()) {
681 // This is a dead PHI. Remove it.
682 VNI->markUnused();
683 LI.removeSegment(I);
684 LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
685 } else {
686 // This is a dead def. Make sure the instruction knows.
687 MachineInstr *MI = getInstructionFromIndex(Def);
688 assert(MI && "No instruction defining live value");
689 MI->addRegisterDead(LI.reg(), TRI);
690
691 if (dead && MI->allDefsAreDead()) {
692 LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
693 dead->push_back(MI);
694 }
695 }
696 MayHaveSplitComponents = true;
697 }
698 return MayHaveSplitComponents;
699}
700
702 SubRangeUseList Uses;
703 collectSubRangeUses(Reg, Uses);
704 shrinkSubRangeToUses(SR, Reg, Uses);
705}
706
707void LiveIntervals::collectSubRangeUses(Register Reg,
708 SubRangeUseList &Uses) const {
709 for (const MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
710 // Skip "undef" uses.
711 if (!MO.readsReg())
712 continue;
713 unsigned SubReg = MO.getSubReg();
714 LaneBitmask LaneMask =
715 SubReg ? TRI->getSubRegIndexLaneMask(SubReg) : LaneBitmask::getAll();
716 // A use tied to an early-clobber def is read at the early-clobber slot.
717 // Using the normal register slot can extend a subrange beyond the main
718 // range when rebuilding it below.
719 SlotIndex Idx = getInstructionIndex(*MO.getParent())
720 .getRegSlot(MO.isEarlyClobberDefOrUse());
721 // Merge adjacent operands of the same instruction.
722 if (!Uses.empty() && Uses.back().first == Idx) {
723 Uses.back().second |= LaneMask;
724 continue;
725 }
726 Uses.emplace_back(Idx, LaneMask);
727 }
728}
729
730void LiveIntervals::shrinkSubRangeToUses(LiveInterval::SubRange &SR,
733 LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
734 assert(Reg.isVirtual() && "Can only shrink virtual registers");
735 // Find all the values used, including PHI kills.
736 ShrinkToUsesWorkList WorkList;
737
738 for (const SubRangeUse &Use : Uses) {
739 // Maybe the instruction only reads subregisters we don't care about.
740 if ((Use.second & SR.LaneMask).none())
741 continue;
742
743 SlotIndex Idx = Use.first;
744 LiveQueryResult LRQ = SR.Query(Idx);
745 VNInfo *VNI = LRQ.valueIn();
746 // For Subranges it is possible that only undef values are left in that
747 // part of the subregister, so there is no real liverange at the use
748 if (!VNI)
749 continue;
750
751 // An untied use may read a register redefined by an early-clobber def.
752 if (VNInfo *DefVNI = LRQ.valueDefined())
753 Idx = DefVNI->def;
754
755 WorkList.push_back(std::make_pair(Idx, VNI));
756 }
757
758 // Create a new live ranges with only minimal live segments per def.
759 LiveRange NewLR;
760 createSegmentsForValues(NewLR, SR.vnis());
761 extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
762
763 // Move the trimmed ranges back.
764 SR.segments.swap(NewLR.segments);
765
766 // Remove dead PHI value numbers
767 for (VNInfo *VNI : SR.valnos) {
768 if (VNI->isUnused())
769 continue;
770 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
771 assert(Segment != nullptr && "Missing segment for VNI");
772 if (Segment->end != VNI->def.getDeadSlot())
773 continue;
774 if (VNI->isPHIDef()) {
775 // This is a dead PHI. Remove it.
776 LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
777 << " may separate interval\n");
778 VNI->markUnused();
779 SR.removeSegment(*Segment);
780 }
781 }
782
783 LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
784}
785
787 ArrayRef<SlotIndex> Indices,
788 ArrayRef<SlotIndex> Undefs) {
789 assert(LICalc && "LICalc not initialized.");
790 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
791 for (SlotIndex Idx : Indices)
792 LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
793}
794
796 SmallVectorImpl<SlotIndex> *EndPoints) {
797 LiveQueryResult LRQ = LR.Query(Kill);
798 // LR may have liveness reachable from early clobber slot, which may be
799 // only live-in instead of live-out of the instruction.
800 // For example, LR =[1r, 3r), Kill = 3e, we have to prune [3e, 3r) of LR.
801 VNInfo *VNI = LRQ.valueOutOrDead() ? LRQ.valueOutOrDead() : LRQ.valueIn();
802 if (!VNI)
803 return;
804
805 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
806 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
807
808 // If VNI isn't live out from KillMBB, the value is trivially pruned.
809 if (LRQ.endPoint() < MBBEnd) {
810 LR.removeSegment(Kill, LRQ.endPoint());
811 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
812 return;
813 }
814
815 // VNI is live out of KillMBB.
816 LR.removeSegment(Kill, MBBEnd);
817 if (EndPoints) EndPoints->push_back(MBBEnd);
818
819 // Find all blocks that are reachable from KillMBB without leaving VNI's live
820 // range. It is possible that KillMBB itself is reachable, so start a DFS
821 // from each successor.
823 VisitedTy Visited;
824 for (MachineBasicBlock *Succ : KillMBB->successors()) {
826 I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
827 I != E;) {
829
830 // Check if VNI is live in to MBB.
831 SlotIndex MBBStart, MBBEnd;
832 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
833 LiveQueryResult LRQ = LR.Query(MBBStart);
834 if (LRQ.valueIn() != VNI) {
835 // This block isn't part of the VNI segment. Prune the search.
836 I.skipChildren();
837 continue;
838 }
839
840 // Prune the search if VNI is killed in MBB.
841 if (LRQ.endPoint() < MBBEnd) {
842 LR.removeSegment(MBBStart, LRQ.endPoint());
843 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
844 I.skipChildren();
845 continue;
846 }
847
848 // VNI is live through MBB.
849 LR.removeSegment(MBBStart, MBBEnd);
850 if (EndPoints) EndPoints->push_back(MBBEnd);
851 ++I;
852 }
853 }
854}
855
856//===----------------------------------------------------------------------===//
857// Register allocator hooks.
858//
859
861 // Keep track of regunit ranges.
863
864 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
866 if (MRI->reg_nodbg_empty(Reg))
867 continue;
868 const LiveInterval &LI = getInterval(Reg);
869 if (LI.empty())
870 continue;
871
872 // Target may have not allocated this yet.
873 Register PhysReg = VRM->getPhys(Reg);
874 if (!PhysReg)
875 continue;
876
877 // Find the regunit intervals for the assigned register. They may overlap
878 // the virtual register live range, cancelling any kills.
879 RU.clear();
880 LaneBitmask ArtificialLanes;
881 for (MCRegUnitMaskIterator UI(PhysReg, TRI); UI.isValid(); ++UI) {
882 auto [Unit, Bitmask] = *UI;
883 // Record lane mask for all artificial RegUnits for this physreg.
884 if (TRI->isArtificialRegUnit(Unit))
885 ArtificialLanes |= Bitmask;
886 const LiveRange &RURange = getRegUnit(Unit);
887 if (RURange.empty())
888 continue;
889 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
890 }
891 // Every instruction that kills Reg corresponds to a segment range end
892 // point.
893 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
894 ++RI) {
895 // A block index indicates an MBB edge.
896 if (RI->end.isBlock())
897 continue;
899 if (!MI)
900 continue;
901
902 // Check if any of the regunits are live beyond the end of RI. That could
903 // happen when a physreg is defined as a copy of a virtreg:
904 //
905 // %eax = COPY %5
906 // FOO %5 <--- MI, cancel kill because %eax is live.
907 // BAR killed %eax
908 //
909 // There should be no kill flag on FOO when %5 is rewritten as %eax.
910 for (auto &RUP : RU) {
911 const LiveRange &RURange = *RUP.first;
912 LiveRange::const_iterator &I = RUP.second;
913 if (I == RURange.end())
914 continue;
915 I = RURange.advanceTo(I, RI->end);
916 if (I == RURange.end() || I->start >= RI->end)
917 continue;
918 // I is overlapping RI.
919 goto CancelKill;
920 }
921
922 if (MRI->subRegLivenessEnabled()) {
923 // When reading a partial undefined value we must not add a kill flag.
924 // The regalloc might have used the undef lane for something else.
925 // Example:
926 // %1 = ... ; R32: %1
927 // %2:high16 = ... ; R64: %2
928 // = read killed %2 ; R64: %2
929 // = read %1 ; R32: %1
930 // The <kill> flag is correct for %2, but the register allocator may
931 // assign R0L to %1, and R0 to %2 because the low 32bits of R0
932 // are actually never written by %2. After assignment the <kill>
933 // flag at the read instruction is invalid.
934 LaneBitmask DefinedLanesMask;
935 if (LI.hasSubRanges()) {
936 // Compute a mask of lanes that are defined.
937 // Artificial regunits are not independently allocatable so the
938 // register allocator cannot have used them to represent any other
939 // values. That's why we mark them as 'defined' here, as this
940 // otherwise prevents kill flags from being added.
941 DefinedLanesMask = ArtificialLanes;
942 for (const LiveInterval::SubRange &SR : LI.subranges())
943 for (const LiveRange::Segment &Segment : SR.segments) {
944 if (Segment.start >= RI->end)
945 break;
946 if (Segment.end == RI->end) {
947 DefinedLanesMask |= SR.LaneMask;
948 break;
949 }
950 }
951 } else
952 DefinedLanesMask = LaneBitmask::getAll();
953
954 bool IsFullWrite = false;
955 for (const MachineOperand &MO : MI->operands()) {
956 if (!MO.isReg() || MO.getReg() != Reg)
957 continue;
958 if (MO.isUse()) {
959 // Reading any undefined lanes?
960 unsigned SubReg = MO.getSubReg();
961 LaneBitmask UseMask = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
962 : MRI->getMaxLaneMaskForVReg(Reg);
963 if ((UseMask & ~DefinedLanesMask).any())
964 goto CancelKill;
965 } else if (MO.getSubReg() == 0) {
966 // Writing to the full register?
967 assert(MO.isDef());
968 IsFullWrite = true;
969 }
970 }
971
972 // If an instruction writes to a subregister, a new segment starts in
973 // the LiveInterval. But as this is only overriding part of the register
974 // adding kill-flags is not correct here after registers have been
975 // assigned.
976 if (!IsFullWrite) {
977 // Next segment has to be adjacent in the subregister write case.
978 LiveRange::const_iterator N = std::next(RI);
979 if (N != LI.end() && N->start == RI->end)
980 goto CancelKill;
981 }
982 }
983
984 MI->addRegisterKilled(Reg, nullptr);
985 continue;
986CancelKill:
987 MI->clearRegisterKills(Reg, nullptr);
988 }
989 }
990}
991
994 assert(!LI.empty() && "LiveInterval is empty.");
995
996 // A local live range must be fully contained inside the block, meaning it is
997 // defined and killed at instructions, not at block boundaries. It is not
998 // live in or out of any block.
999 //
1000 // It is technically possible to have a PHI-defined live range identical to a
1001 // single block, but we are going to return false in that case.
1002
1003 SlotIndex Start = LI.beginIndex();
1004 if (Start.isBlock())
1005 return nullptr;
1006
1007 SlotIndex Stop = LI.endIndex();
1008 if (Stop.isBlock())
1009 return nullptr;
1010
1011 // getMBBFromIndex doesn't need to search the MBB table when both indexes
1012 // belong to proper instructions.
1013 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
1014 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
1015 return MBB1 == MBB2 ? MBB1 : nullptr;
1016}
1017
1018bool
1019LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
1020 for (const VNInfo *PHI : LI.valnos) {
1021 if (PHI->isUnused() || !PHI->isPHIDef())
1022 continue;
1023 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
1024 // Conservatively return true instead of scanning huge predecessor lists.
1025 if (PHIMBB->pred_size() > 100)
1026 return true;
1027 for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
1028 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
1029 return true;
1030 }
1031 return false;
1032}
1033
1034float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
1035 const MachineBlockFrequencyInfo *MBFI,
1036 const MachineInstr &MI,
1037 ProfileSummaryInfo *PSI) {
1038 return getSpillWeight(isDef, isUse, MBFI, MI.getParent(), PSI);
1039}
1040
1041float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
1042 const MachineBlockFrequencyInfo *MBFI,
1043 const MachineBasicBlock *MBB,
1044 ProfileSummaryInfo *PSI) {
1045 const auto *MF = MBB->getParent();
1046 return getSpillWeight(isDef, isUse, MBFI, MBB,
1047 PSI && llvm::shouldOptimizeForSize(MF, PSI, MBFI));
1048}
1049
1050float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
1051 const MachineBlockFrequencyInfo *MBFI,
1052 const MachineInstr &MI, bool OptForSize) {
1053 return getSpillWeight(isDef, isUse, MBFI, MI.getParent(), OptForSize);
1054}
1055
1056float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
1057 const MachineBlockFrequencyInfo *MBFI,
1058 const MachineBasicBlock *MBB,
1059 bool OptForSize) {
1060 float Weight = isDef + isUse;
1061 // When optimizing for size we only consider the codesize impact of spilling
1062 // the register, not the runtime impact.
1063 if (OptForSize)
1064 return Weight;
1065 return Weight * MBFI->getBlockFreqRelativeToEntryBlock(MBB);
1066}
1067
1071 VNInfo *VN = Interval.getNextValue(
1072 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1074 LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
1075 getMBBEndIdx(startInst.getParent()), VN);
1076 Interval.addSegment(S);
1077
1078 return S;
1079}
1080
1081//===----------------------------------------------------------------------===//
1082// Register mask functions
1083//===----------------------------------------------------------------------===//
1084/// Check whether use of reg in MI is live-through. Live-through means that
1085/// the value is alive on exit from Machine instruction. The example of such
1086/// use is a deopt value in statepoint instruction.
1088 if (MI->getOpcode() != TargetOpcode::STATEPOINT)
1089 return false;
1090 StatepointOpers SO(MI);
1092 return false;
1093 for (unsigned Idx = SO.getNumDeoptArgsIdx(), E = SO.getNumGCPtrIdx(); Idx < E;
1094 ++Idx) {
1095 const MachineOperand &MO = MI->getOperand(Idx);
1096 if (MO.isReg() && MO.getReg() == Reg)
1097 return true;
1098 }
1099 return false;
1100}
1101
1103 BitVector &UsableRegs) {
1104 if (LI.empty())
1105 return false;
1106 LiveInterval::const_iterator LiveI = LI.begin(), LiveE = LI.end();
1107
1108 // Use a smaller arrays for local live ranges.
1109 ArrayRef<SlotIndex> Slots;
1112 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
1113 Bits = getRegMaskBitsInBlock(MBB->getNumber());
1114 } else {
1115 Slots = getRegMaskSlots();
1116 Bits = getRegMaskBits();
1117 }
1118
1119 // We are going to enumerate all the register mask slots contained in LI.
1120 // Start with a binary search of RegMaskSlots to find a starting point.
1121 ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
1122 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
1123
1124 // No slots in range, LI begins after the last call.
1125 if (SlotI == SlotE)
1126 return false;
1127
1128 bool Found = false;
1129 // Utility to union regmasks.
1130 auto unionBitMask = [&](unsigned Idx) {
1131 if (!Found) {
1132 // This is the first overlap. Initialize UsableRegs to all ones.
1133 UsableRegs.clear();
1134 UsableRegs.resize(TRI->getNumRegs(), true);
1135 Found = true;
1136 }
1137 // Remove usable registers clobbered by this mask.
1138 UsableRegs.clearBitsNotInMask(Bits[Idx]);
1139 };
1140 while (true) {
1141 assert(*SlotI >= LiveI->start);
1142 // Loop over all slots overlapping this segment.
1143 while (*SlotI < LiveI->end) {
1144 // *SlotI overlaps LI. Collect mask bits.
1145 unionBitMask(SlotI - Slots.begin());
1146 if (++SlotI == SlotE)
1147 return Found;
1148 }
1149 // If segment ends with live-through use we need to collect its regmask.
1150 if (*SlotI == LiveI->end)
1152 if (hasLiveThroughUse(MI, LI.reg()))
1153 unionBitMask(SlotI++ - Slots.begin());
1154 // *SlotI is beyond the current LI segment.
1155 // Special advance implementation to not miss next LiveI->end.
1156 if (++LiveI == LiveE || SlotI == SlotE || *SlotI > LI.endIndex())
1157 return Found;
1158 while (LiveI->end < *SlotI)
1159 ++LiveI;
1160 // Advance SlotI until it overlaps.
1161 while (*SlotI < LiveI->start)
1162 if (++SlotI == SlotE)
1163 return Found;
1164 }
1165}
1166
1167//===----------------------------------------------------------------------===//
1168// IntervalUpdate class.
1169//===----------------------------------------------------------------------===//
1170
1171/// Toolkit used by handleMove to trim or extend live intervals.
1173private:
1174 LiveIntervals& LIS;
1175 const MachineRegisterInfo& MRI;
1176 const TargetRegisterInfo& TRI;
1177 SlotIndex OldIdx;
1178 SlotIndex NewIdx;
1180 bool UpdateFlags;
1181
1182public:
1183 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
1184 const TargetRegisterInfo& TRI,
1185 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
1186 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
1187 UpdateFlags(UpdateFlags) {}
1188
1189 // FIXME: UpdateFlags is a workaround that creates live intervals for all
1190 // physregs, even those that aren't needed for regalloc, in order to update
1191 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
1192 // flags, and postRA passes will use a live register utility instead.
1193 LiveRange *getRegUnitLI(MCRegUnit Unit) {
1194 if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
1195 return &LIS.getRegUnit(Unit);
1196 return LIS.getCachedRegUnit(Unit);
1197 }
1198
1199 /// Update all live ranges touched by MI, assuming a move from OldIdx to
1200 /// NewIdx.
1202 LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
1203 << *MI);
1204 bool hasRegMask = false;
1205 for (MachineOperand &MO : MI->operands()) {
1206 if (MO.isRegMask())
1207 hasRegMask = true;
1208 if (!MO.isReg())
1209 continue;
1210 if (MO.isUse()) {
1211 if (!MO.readsReg())
1212 continue;
1213 // Aggressively clear all kill flags.
1214 // They are reinserted by VirtRegRewriter.
1215 MO.setIsKill(false);
1216 }
1217
1218 Register Reg = MO.getReg();
1219 if (!Reg)
1220 continue;
1221 if (Reg.isVirtual()) {
1222 LiveInterval &LI = LIS.getInterval(Reg);
1223 if (LI.hasSubRanges()) {
1224 unsigned SubReg = MO.getSubReg();
1225 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1226 : MRI.getMaxLaneMaskForVReg(Reg);
1227 for (LiveInterval::SubRange &S : LI.subranges()) {
1228 if ((S.LaneMask & LaneMask).none())
1229 continue;
1230 updateRange(S, VirtRegOrUnit(Reg), S.LaneMask);
1231 }
1232 }
1233 updateRange(LI, VirtRegOrUnit(Reg), LaneBitmask::getNone());
1234 // If main range has a hole and we are moving a subrange use across
1235 // the hole updateRange() cannot properly handle it since it only
1236 // gets the LiveRange and not the whole LiveInterval. As a result
1237 // we may end up with a main range not covering all subranges.
1238 // This is extremely rare case, so let's check and reconstruct the
1239 // main range.
1240 if (LI.hasSubRanges()) {
1241 unsigned SubReg = MO.getSubReg();
1242 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1243 : MRI.getMaxLaneMaskForVReg(Reg);
1244 for (LiveInterval::SubRange &S : LI.subranges()) {
1245 if ((S.LaneMask & LaneMask).none() || LI.covers(S))
1246 continue;
1247 LI.clear();
1248 LIS.constructMainRangeFromSubranges(LI);
1249 break;
1250 }
1251 }
1252
1253 continue;
1254 }
1255
1256 // For physregs, only update the regunits that actually have a
1257 // precomputed live range.
1258 for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg()))
1259 if (LiveRange *LR = getRegUnitLI(Unit))
1260 updateRange(*LR, VirtRegOrUnit(Unit), LaneBitmask::getNone());
1261 }
1262 if (hasRegMask)
1263 updateRegMaskSlots();
1264 }
1265
1266private:
1267 /// Update a single live range, assuming an instruction has been moved from
1268 /// OldIdx to NewIdx.
1269 void updateRange(LiveRange &LR, VirtRegOrUnit VRegOrUnit,
1270 LaneBitmask LaneMask) {
1271 if (!Updated.insert(&LR).second)
1272 return;
1273 LLVM_DEBUG({
1274 dbgs() << " ";
1275 if (VRegOrUnit.isVirtualReg()) {
1276 dbgs() << printReg(VRegOrUnit.asVirtualReg());
1277 if (LaneMask.any())
1278 dbgs() << " L" << PrintLaneMask(LaneMask);
1279 } else {
1280 dbgs() << printRegUnit(VRegOrUnit.asMCRegUnit(), &TRI);
1281 }
1282 dbgs() << ":\t" << LR << '\n';
1283 });
1284 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1285 handleMoveDown(LR);
1286 else
1287 handleMoveUp(LR, VRegOrUnit, LaneMask);
1288 LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n');
1289 assert(LR.verify());
1290 }
1291
1292 /// Update LR to reflect an instruction has been moved downwards from OldIdx
1293 /// to NewIdx (OldIdx < NewIdx).
1294 void handleMoveDown(LiveRange &LR) {
1295 LiveRange::iterator E = LR.end();
1296 // Segment going into OldIdx.
1297 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1298
1299 // No value live before or after OldIdx? Nothing to do.
1300 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1301 return;
1302
1303 LiveRange::iterator OldIdxOut;
1304 // Do we have a value live-in to OldIdx?
1305 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1306 // If the live-in value already extends to NewIdx, there is nothing to do.
1307 if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1308 return;
1309 // Aggressively remove all kill flags from the old kill point.
1310 // Kill flags shouldn't be used while live intervals exist, they will be
1311 // reinserted by VirtRegRewriter.
1312 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1313 for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1314 if (MOP.isReg() && MOP.isUse())
1315 MOP.setIsKill(false);
1316
1317 // Is there a def before NewIdx which is not OldIdx?
1318 LiveRange::iterator Next = std::next(OldIdxIn);
1319 if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1320 SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1321 // If we are here then OldIdx was just a use but not a def. We only have
1322 // to ensure liveness extends to NewIdx.
1323 LiveRange::iterator NewIdxIn =
1324 LR.advanceTo(Next, NewIdx.getBaseIndex());
1325 // Extend the segment before NewIdx if necessary.
1326 if (NewIdxIn == E ||
1327 !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1328 LiveRange::iterator Prev = std::prev(NewIdxIn);
1329 Prev->end = NewIdx.getRegSlot();
1330 }
1331 // Extend OldIdxIn.
1332 OldIdxIn->end = Next->start;
1333 return;
1334 }
1335
1336 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1337 // invalid by overlapping ranges.
1338 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1339 OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1340 // If this was not a kill, then there was no def and we're done.
1341 if (!isKill)
1342 return;
1343
1344 // Did we have a Def at OldIdx?
1345 OldIdxOut = Next;
1346 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1347 return;
1348 } else {
1349 OldIdxOut = OldIdxIn;
1350 }
1351
1352 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1353 // to the segment starting there.
1354 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1355 "No def?");
1356 VNInfo *OldIdxVNI = OldIdxOut->valno;
1357 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1358
1359 // If the defined value extends beyond NewIdx, just move the beginning
1360 // of the segment to NewIdx.
1361 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1362 if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1363 OldIdxVNI->def = NewIdxDef;
1364 OldIdxOut->start = OldIdxVNI->def;
1365 return;
1366 }
1367
1368 // If we are here then we have a Definition at OldIdx which ends before
1369 // NewIdx.
1370
1371 // Is there an existing Def at NewIdx?
1372 LiveRange::iterator AfterNewIdx
1373 = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1374 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1375 if (!OldIdxDefIsDead &&
1376 SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1377 // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1378 VNInfo *DefVNI;
1379 if (OldIdxOut != LR.begin() &&
1380 !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1381 OldIdxOut->start)) {
1382 // There is no gap between OldIdxOut and its predecessor anymore,
1383 // merge them.
1384 LiveRange::iterator IPrev = std::prev(OldIdxOut);
1385 DefVNI = OldIdxVNI;
1386 IPrev->end = OldIdxOut->end;
1387 } else {
1388 // The value is live in to OldIdx
1389 LiveRange::iterator INext = std::next(OldIdxOut);
1390 assert(INext != E && "Must have following segment");
1391 // We merge OldIdxOut and its successor. As we're dealing with subreg
1392 // reordering, there is always a successor to OldIdxOut in the same BB
1393 // We don't need INext->valno anymore and will reuse for the new segment
1394 // we create later.
1395 DefVNI = OldIdxVNI;
1396 INext->start = OldIdxOut->end;
1397 INext->valno->def = INext->start;
1398 }
1399 // If NewIdx is behind the last segment, extend that and append a new one.
1400 if (AfterNewIdx == E) {
1401 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1402 // one position.
1403 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1404 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1405 std::copy(std::next(OldIdxOut), E, OldIdxOut);
1406 // The last segment is undefined now, reuse it for a dead def.
1407 LiveRange::iterator NewSegment = std::prev(E);
1408 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1409 DefVNI);
1410 DefVNI->def = NewIdxDef;
1411
1412 LiveRange::iterator Prev = std::prev(NewSegment);
1413 Prev->end = NewIdxDef;
1414 } else {
1415 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1416 // one position.
1417 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1418 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1419 std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1420 LiveRange::iterator Prev = std::prev(AfterNewIdx);
1421 // We have two cases:
1422 if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1423 // Case 1: NewIdx is inside a liverange. Split this liverange at
1424 // NewIdxDef into the segment "Prev" followed by "NewSegment".
1425 LiveRange::iterator NewSegment = AfterNewIdx;
1426 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1427 Prev->valno->def = NewIdxDef;
1428
1429 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1430 DefVNI->def = Prev->start;
1431 } else {
1432 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1433 // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1434 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1435 DefVNI->def = NewIdxDef;
1436 assert(DefVNI != AfterNewIdx->valno);
1437 }
1438 }
1439 return;
1440 }
1441
1442 if (AfterNewIdx != E &&
1443 SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1444 // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1445 // that value.
1446 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1447 LR.removeValNo(OldIdxVNI);
1448 } else {
1449 // There was no existing def at NewIdx. We need to create a dead def
1450 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1451 // a new segment at the place where we want to construct the dead def.
1452 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1453 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1454 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1455 std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1456 // We can reuse OldIdxVNI now.
1457 LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1458 VNInfo *NewSegmentVNI = OldIdxVNI;
1459 NewSegmentVNI->def = NewIdxDef;
1460 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1461 NewSegmentVNI);
1462 }
1463 }
1464
1465 /// Update LR to reflect an instruction has been moved upwards from OldIdx
1466 /// to NewIdx (NewIdx < OldIdx).
1467 void handleMoveUp(LiveRange &LR, VirtRegOrUnit VRegOrUnit,
1468 LaneBitmask LaneMask) {
1469 LiveRange::iterator E = LR.end();
1470 // Segment going into OldIdx.
1471 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1472
1473 // No value live before or after OldIdx? Nothing to do.
1474 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1475 return;
1476
1477 LiveRange::iterator OldIdxOut;
1478 // Do we have a value live-in to OldIdx?
1479 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1480 // If the live-in value isn't killed here, then we have no Def at
1481 // OldIdx, moreover the value must be live at NewIdx so there is nothing
1482 // to do.
1483 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1484 if (!isKill)
1485 return;
1486
1487 // At this point we have to move OldIdxIn->end back to the nearest
1488 // previous use or (dead-)def but no further than NewIdx.
1489 SlotIndex DefBeforeOldIdx
1490 = std::max(OldIdxIn->start.getDeadSlot(),
1491 NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1492 OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, VRegOrUnit, LaneMask);
1493
1494 // Did we have a Def at OldIdx? If not we are done now.
1495 OldIdxOut = std::next(OldIdxIn);
1496 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1497 return;
1498 } else {
1499 OldIdxOut = OldIdxIn;
1500 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1501 }
1502
1503 // If we are here then there is a Definition at OldIdx. OldIdxOut points
1504 // to the segment starting there.
1505 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1506 "No def?");
1507 VNInfo *OldIdxVNI = OldIdxOut->valno;
1508 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1509 bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1510
1511 // Is there an existing def at NewIdx?
1512 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1513 LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1514 if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1515 assert(NewIdxOut->valno != OldIdxVNI &&
1516 "Same value defined more than once?");
1517 // If OldIdx was a dead def remove it.
1518 if (!OldIdxDefIsDead) {
1519 // Remove segment starting at NewIdx and move begin of OldIdxOut to
1520 // NewIdx so it can take its place.
1521 OldIdxVNI->def = NewIdxDef;
1522 OldIdxOut->start = NewIdxDef;
1523 LR.removeValNo(NewIdxOut->valno);
1524 } else {
1525 // Simply remove the dead def at OldIdx.
1526 LR.removeValNo(OldIdxVNI);
1527 }
1528 } else {
1529 // Previously nothing was live after NewIdx, so all we have to do now is
1530 // move the begin of OldIdxOut to NewIdx.
1531 if (!OldIdxDefIsDead) {
1532 // Do we have any intermediate Defs between OldIdx and NewIdx?
1533 if (OldIdxIn != E &&
1534 SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1535 // OldIdx is not a dead def and NewIdx is before predecessor start.
1536 LiveRange::iterator NewIdxIn = NewIdxOut;
1537 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1538 const SlotIndex SplitPos = NewIdxDef;
1539 OldIdxVNI = OldIdxIn->valno;
1540
1541 SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
1542 LiveRange::iterator Prev = std::prev(OldIdxIn);
1543 if (OldIdxIn != LR.begin() &&
1544 SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
1545 // If the segment before OldIdx read a value defined earlier than
1546 // NewIdx, the moved instruction also reads and forwards that
1547 // value. Extend the lifetime of the new def point.
1548
1549 // Extend to where the previous range started, unless there is
1550 // another redef first.
1551 NewDefEndPoint = std::min(OldIdxIn->start,
1552 std::next(NewIdxOut)->start);
1553 }
1554
1555 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1556 OldIdxOut->valno->def = OldIdxIn->start;
1557 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1558 OldIdxOut->valno);
1559 // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1560 // We Slide [NewIdxIn, OldIdxIn) down one position.
1561 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1562 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1563 std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1564 // NewIdxIn is now considered undef so we can reuse it for the moved
1565 // value.
1566 LiveRange::iterator NewSegment = NewIdxIn;
1567 LiveRange::iterator Next = std::next(NewSegment);
1568 if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1569 // There is no gap between NewSegment and its predecessor.
1570 *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1571 Next->valno);
1572
1573 *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1574 Next->valno->def = SplitPos;
1575 } else {
1576 // There is a gap between NewSegment and its predecessor
1577 // Value becomes live in.
1578 *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1579 NewSegment->valno->def = SplitPos;
1580 }
1581 } else {
1582 // Leave the end point of a live def.
1583 OldIdxOut->start = NewIdxDef;
1584 OldIdxVNI->def = NewIdxDef;
1585 if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1586 OldIdxIn->end = NewIdxDef;
1587 }
1588 } else if (OldIdxIn != E
1589 && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1590 && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1591 // OldIdxVNI is a dead def that has been moved into the middle of
1592 // another value in LR. That can happen when LR is a whole register,
1593 // but the dead def is a write to a subreg that is dead at NewIdx.
1594 // The dead def may have been moved across other values
1595 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1596 // down one position.
1597 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1598 // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1599 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1600 // Modify the segment at NewIdxOut and the following segment to meet at
1601 // the point of the dead def, with the following segment getting
1602 // OldIdxVNI as its value number.
1603 *NewIdxOut = LiveRange::Segment(
1604 NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1605 *(NewIdxOut + 1) = LiveRange::Segment(
1606 NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1607 OldIdxVNI->def = NewIdxDef;
1608 // Retag the segments that were shifted down from [NewIdxOut + 2,
1609 // OldIdxOut]. Retagging can make a segment touch another segment with
1610 // the same value number, so merge as we go. Stop at the original end
1611 // slot instead of using a segment count because merging may erase
1612 // segments.
1613 const SlotIndex RetagEnd = OldIdxOut->end;
1614 for (LiveRange::iterator Idx = NewIdxOut + 2;
1615 Idx != LR.end() && Idx->start < RetagEnd;) {
1616 Idx->valno = OldIdxVNI;
1617 Idx = std::next(LR.mergeAdjacentSegments(Idx));
1618 }
1619 // Aggressively remove all dead flags from the former dead definition.
1620 // Kill/dead flags shouldn't be used while live intervals exist; they
1621 // will be reinserted by VirtRegRewriter.
1622 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1623 for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1624 if (MO->isReg() && !MO->isUse())
1625 MO->setIsDead(false);
1626 } else {
1627 // OldIdxVNI is a dead def. It may have been moved across other values
1628 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1629 // down one position.
1630 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1631 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1632 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1633 // OldIdxVNI can be reused now to build a new dead def segment.
1634 LiveRange::iterator NewSegment = NewIdxOut;
1635 VNInfo *NewSegmentVNI = OldIdxVNI;
1636 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1637 NewSegmentVNI);
1638 NewSegmentVNI->def = NewIdxDef;
1639 }
1640 }
1641 }
1642
1643 void updateRegMaskSlots() {
1645 llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1646 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1647 "No RegMask at OldIdx.");
1648 *RI = NewIdx.getRegSlot();
1649 assert((RI == LIS.RegMaskSlots.begin() ||
1650 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1651 "Cannot move regmask instruction above another call");
1652 assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1653 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1654 "Cannot move regmask instruction below another call");
1655 }
1656
1657 // Return the last use of reg between NewIdx and OldIdx.
1658 SlotIndex findLastUseBefore(SlotIndex Before, VirtRegOrUnit VRegOrUnit,
1659 LaneBitmask LaneMask) {
1660 if (VRegOrUnit.isVirtualReg()) {
1661 SlotIndex LastUse = Before;
1662 for (MachineOperand &MO :
1663 MRI.use_nodbg_operands(VRegOrUnit.asVirtualReg())) {
1664 if (MO.isUndef())
1665 continue;
1666 unsigned SubReg = MO.getSubReg();
1667 if (SubReg != 0 && LaneMask.any()
1668 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1669 continue;
1670
1671 const MachineInstr &MI = *MO.getParent();
1672 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1673 if (InstSlot > LastUse && InstSlot < OldIdx)
1674 LastUse = InstSlot.getRegSlot();
1675 }
1676 return LastUse;
1677 }
1678
1679 // This is a regunit interval, so scanning the use list could be very
1680 // expensive. Scan upwards from OldIdx instead.
1681 assert(Before < OldIdx && "Expected upwards move");
1682 SlotIndexes *Indexes = LIS.getSlotIndexes();
1683 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1684
1685 // OldIdx may not correspond to an instruction any longer, so set MII to
1686 // point to the next instruction after OldIdx, or MBB->end().
1688 if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1689 Indexes->getNextNonNullIndex(OldIdx)))
1690 if (MI->getParent() == MBB)
1691 MII = MI;
1692
1694 while (MII != Begin) {
1695 if ((--MII)->isDebugOrPseudoInstr())
1696 continue;
1697 SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1698
1699 // Stop searching when Before is reached.
1700 if (!SlotIndex::isEarlierInstr(Before, Idx))
1701 return Before;
1702
1703 // Check if MII uses Reg.
1704 for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1705 if (MO->isReg() && !MO->isUndef() && MO->getReg().isPhysical() &&
1706 TRI.hasRegUnit(MO->getReg(), VRegOrUnit.asMCRegUnit()))
1707 return Idx.getRegSlot();
1708 }
1709 // Didn't reach Before. It must be the first instruction in the block.
1710 return Before;
1711 }
1712};
1713
1715 // It is fine to move a bundle as a whole, but not an individual instruction
1716 // inside it.
1717 assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1718 "Cannot move instruction in bundle");
1719 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1720 Indexes->removeMachineInstrFromMaps(MI);
1721 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1722 assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1723 OldIndex < getMBBEndIdx(MI.getParent()) &&
1724 "Cannot handle moves across basic block boundaries.");
1725
1726 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1727 HME.updateAllRanges(&MI);
1728}
1729
1731 bool UpdateFlags) {
1732 assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) &&
1733 "Bundle start is not a bundle");
1735 const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart);
1736 auto BundleEnd = getBundleEnd(BundleStart.getIterator());
1737
1738 auto I = BundleStart.getIterator();
1739 I++;
1740 while (I != BundleEnd) {
1741 if (!Indexes->hasIndex(*I))
1742 continue;
1743 SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true);
1744 ToProcess.push_back(OldIndex);
1745 Indexes->removeMachineInstrFromMaps(*I, true);
1746 I++;
1747 }
1748 for (SlotIndex OldIndex : ToProcess) {
1749 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1750 HME.updateAllRanges(&BundleStart);
1751 }
1752
1753 // Fix up dead defs
1754 const SlotIndex Index = getInstructionIndex(BundleStart);
1755 for (MachineOperand &MO : BundleStart.operands()) {
1756 if (!MO.isReg())
1757 continue;
1758 Register Reg = MO.getReg();
1759 if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) {
1760 LiveInterval &LI = getInterval(Reg);
1761 LiveQueryResult LRQ = LI.Query(Index);
1762 if (LRQ.isDeadDef())
1763 MO.setIsDead();
1764 }
1765 }
1766}
1767
1768void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1770 const SlotIndex EndIdx, LiveRange &LR,
1771 const Register Reg,
1772 LaneBitmask LaneMask) {
1773 LiveInterval::iterator LII = LR.find(EndIdx);
1774 SlotIndex lastUseIdx;
1775 if (LII != LR.end() && LII->start < EndIdx) {
1776 lastUseIdx = LII->end;
1777 } else if (LII == LR.begin()) {
1778 // We may not have a liverange at all if this is a subregister untouched
1779 // between \p Begin and \p End.
1780 } else {
1781 --LII;
1782 }
1783
1784 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1785 --I;
1786 MachineInstr &MI = *I;
1787 if (MI.isDebugOrPseudoInstr())
1788 continue;
1789
1790 SlotIndex instrIdx = getInstructionIndex(MI);
1791 bool isStartValid = getInstructionFromIndex(LII->start);
1792 bool isEndValid = getInstructionFromIndex(LII->end);
1793
1794 // FIXME: This doesn't currently handle early-clobber or multiple removed
1795 // defs inside of the region to repair.
1796 for (const MachineOperand &MO : MI.operands()) {
1797 if (!MO.isReg() || MO.getReg() != Reg)
1798 continue;
1799
1800 unsigned SubReg = MO.getSubReg();
1801 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1802 if ((Mask & LaneMask).none())
1803 continue;
1804
1805 if (MO.isDef()) {
1806 if (!isStartValid) {
1807 if (LII->end.isDead()) {
1808 LII = LR.removeSegment(LII, true);
1809 if (LII != LR.begin())
1810 --LII;
1811 } else {
1812 LII->start = instrIdx.getRegSlot();
1813 LII->valno->def = instrIdx.getRegSlot();
1814 if (MO.getSubReg() && !MO.isUndef())
1815 lastUseIdx = instrIdx.getRegSlot();
1816 else
1817 lastUseIdx = SlotIndex();
1818 continue;
1819 }
1820 }
1821
1822 if (!lastUseIdx.isValid()) {
1823 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1824 LiveRange::Segment S(instrIdx.getRegSlot(),
1825 instrIdx.getDeadSlot(), VNI);
1826 LII = LR.addSegment(S);
1827 } else if (LII->start != instrIdx.getRegSlot()) {
1828 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1829 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1830 LII = LR.addSegment(S);
1831 }
1832
1833 if (MO.getSubReg() && !MO.isUndef())
1834 lastUseIdx = instrIdx.getRegSlot();
1835 else
1836 lastUseIdx = SlotIndex();
1837 } else if (MO.isUse()) {
1838 // FIXME: This should probably be handled outside of this branch,
1839 // either as part of the def case (for defs inside of the region) or
1840 // after the loop over the region.
1841 if (!isEndValid && !LII->end.isBlock())
1842 LII->end = instrIdx.getRegSlot();
1843 if (!lastUseIdx.isValid())
1844 lastUseIdx = instrIdx.getRegSlot();
1845 }
1846 }
1847 }
1848
1849 bool isStartValid = getInstructionFromIndex(LII->start);
1850 if (!isStartValid && LII->end.isDead())
1851 LR.removeSegment(*LII, true);
1852}
1853
1854void
1858 ArrayRef<Register> OrigRegs) {
1859 // Find anchor points, which are at the beginning/end of blocks or at
1860 // instructions that already have indexes.
1861 while (Begin != MBB->begin() && !Indexes->hasIndex(*std::prev(Begin)))
1862 --Begin;
1863 while (End != MBB->end() && !Indexes->hasIndex(*End))
1864 ++End;
1865
1866 SlotIndex EndIdx;
1867 if (End == MBB->end())
1868 EndIdx = getMBBEndIdx(MBB).getPrevSlot();
1869 else
1870 EndIdx = getInstructionIndex(*End);
1871
1872 Indexes->repairIndexesInRange(MBB, Begin, End);
1873
1874 // Make sure a live interval exists for all register operands in the range.
1875 SmallVector<Register> RegsToRepair(OrigRegs);
1876 for (MachineBasicBlock::iterator I = End; I != Begin;) {
1877 --I;
1878 MachineInstr &MI = *I;
1879 if (MI.isDebugOrPseudoInstr())
1880 continue;
1881 for (const MachineOperand &MO : MI.operands()) {
1882 if (MO.isReg() && MO.getReg().isVirtual()) {
1883 Register Reg = MO.getReg();
1884 if (MO.getSubReg() && hasInterval(Reg) &&
1885 MRI->shouldTrackSubRegLiveness(Reg)) {
1886 LiveInterval &LI = getInterval(Reg);
1887 if (!LI.hasSubRanges()) {
1888 // If the new instructions refer to subregs but the old instructions
1889 // did not, throw away any old live interval so it will be
1890 // recomputed with subranges.
1891 removeInterval(Reg);
1892 } else if (MO.isDef()) {
1893 // Similarly if a subreg def has no precise subrange match then
1894 // assume we need to recompute all subranges.
1895 unsigned SubReg = MO.getSubReg();
1896 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1897 if (llvm::none_of(LI.subranges(),
1898 [Mask](LiveInterval::SubRange &SR) {
1899 return SR.LaneMask == Mask;
1900 })) {
1901 removeInterval(Reg);
1902 }
1903 }
1904 }
1905 if (!hasInterval(Reg)) {
1907 // Don't bother to repair a freshly calculated live interval.
1908 llvm::erase(RegsToRepair, Reg);
1909 }
1910 }
1911 }
1912 }
1913
1914 for (Register Reg : RegsToRepair) {
1915 if (!Reg.isVirtual())
1916 continue;
1917
1918 LiveInterval &LI = getInterval(Reg);
1919 // FIXME: Should we support undefs that gain defs?
1920 if (!LI.hasAtLeastOneValue())
1921 continue;
1922
1923 for (LiveInterval::SubRange &S : LI.subranges())
1924 repairOldRegInRange(Begin, End, EndIdx, S, Reg, S.LaneMask);
1926
1927 repairOldRegInRange(Begin, End, EndIdx, LI, Reg);
1928 }
1929}
1930
1932 for (MCRegUnit Unit : TRI->regunits(Reg)) {
1933 if (LiveRange *LR = getCachedRegUnit(Unit))
1934 if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1935 LR->removeValNo(VNI);
1936 }
1937}
1938
1940 // LI may not have the main range computed yet, but its subranges may
1941 // be present.
1942 VNInfo *VNI = LI.getVNInfoAt(Pos);
1943 if (VNI != nullptr) {
1944 assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1945 LI.removeValNo(VNI);
1946 }
1947
1948 // Also remove the value defined in subranges.
1949 for (LiveInterval::SubRange &S : LI.subranges()) {
1950 if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1951 if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1952 S.removeValNo(SVNI);
1953 }
1955}
1956
1959 ConnectedVNInfoEqClasses ConEQ(*this);
1960 unsigned NumComp = ConEQ.Classify(LI);
1961 if (NumComp <= 1)
1962 return;
1963 LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1964 Register Reg = LI.reg();
1965 for (unsigned I = 1; I < NumComp; ++I) {
1966 Register NewVReg = MRI->cloneVirtualRegister(Reg);
1967 LiveInterval &NewLI = createEmptyInterval(NewVReg);
1968 SplitLIs.push_back(&NewLI);
1969 }
1970 ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1971}
1972
1974 assert(LICalc && "LICalc not initialized.");
1975 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1976 LICalc->constructMainRangeFromSubranges(LI);
1977}
MachineInstrBuilder & UseMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
MachineBasicBlock & MBB
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_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
static cl::opt< bool > EnablePrecomputePhysRegs("precompute-phys-liveness", cl::Hidden, cl::desc("Eagerly compute live intervals for all physreg units."))
static bool hasLiveThroughUse(const MachineInstr *MI, Register Reg)
Check whether use of reg in MI is live-through.
static void createSegmentsForValues(LiveRange &LR, iterator_range< LiveInterval::vni_iterator > VNIs)
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
std::pair< uint64_t, uint64_t > Interval
Promote Memory to Register
Definition Mem2Reg.cpp:110
#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
Remove Loads Into Fake Uses
SI Optimize VGPR LiveRange
This file defines the SmallPtrSet class.
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
Toolkit used by handleMove to trim or extend live intervals.
HMEditor(LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
LiveRange * getRegUnitLI(MCRegUnit Unit)
void updateAllRanges(MachineInstr *MI)
Update all live ranges touched by MI, assuming a move from OldIdx to NewIdx.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
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.
LLVM_ABI AnalysisUsage & addRequiredTransitiveID(char &ID)
Definition Pass.cpp:304
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
const_pointer iterator
Definition ArrayRef.h:47
iterator begin() const
Definition ArrayRef.h:129
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
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear a bit in this vector for every '0' bit in Mask.
Definition BitVector.h:761
ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a LiveInterval into equivalence cl...
LLVM_ABI void Distribute(LiveInterval &LI, LiveInterval *LIV[], MachineRegisterInfo &MRI)
Distribute values in LI into a separate LiveIntervals for each connected component.
LLVM_ABI unsigned Classify(const LiveRange &LR)
Classify the values in LR into connected components.
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
LLVM_ABI void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool runOnMachineFunction(MachineFunction &) override
Pass entry point; Calculates LiveIntervals.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< Register > OrigRegs)
Update live intervals for instructions in a range of iterators.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
LLVM_ABI bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
LLVM_ABI bool checkRegMaskInterference(const LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndexes * getSlotIndexes() const
LLVM_ABI unsigned removeUnreferencedIntervals()
Remove intervals for virtual registers no instruction refers to any more.
ArrayRef< const uint32_t * > getRegMaskBits() const
Returns an array of register mask pointers corresponding to getRegMaskSlots().
LiveInterval & getOrCreateEmptyInterval(Register Reg)
Return an existing interval for Reg.
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.
LLVM_ABI bool invalidate(MachineFunction &MF, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &Inv)
VNInfo::Allocator & getVNInfoAllocator()
ArrayRef< const uint32_t * > getRegMaskBitsInBlock(unsigned MBBNum) const
Returns an array of mask pointers corresponding to getRegMaskSlotsInBlock(MBBNum).
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
static LLVM_ABI float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &MI, ProfileSummaryInfo *PSI=nullptr)
Calculate the spill weight to assign to a single instruction.
ArrayRef< SlotIndex > getRegMaskSlots() const
Returns a sorted array of slot indices of all instructions with register mask operands.
ArrayRef< SlotIndex > getRegMaskSlotsInBlock(unsigned MBBNum) const
Returns a sorted array of slot indices of all instructions with register mask operands in the basic b...
LiveInterval & getInterval(Register Reg)
friend class LiveIntervalsAnalysis
LLVM_ABI void pruneValue(LiveRange &LR, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
If LR has a live value at Kill, prune its live range by removing any liveness reachable from Kill.
void removeInterval(Register Reg)
Interval removal.
LLVM_ABI void handleMoveIntoNewBundle(MachineInstr &BundleStart, bool UpdateFlags=false)
Update intervals of operands of all instructions in the newly created bundle specified by BundleStart...
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
LLVM_ABI void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos.
LLVM_ABI LiveInterval::Segment addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB.
LLVM_ABI void constructMainRangeFromSubranges(LiveInterval &LI)
For live interval LI with correct SubRanges construct matching information for the main live range.
LiveInterval & createEmptyInterval(Register Reg)
Interval creation.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void dump() const
LLVM_ABI void print(raw_ostream &O) const
Implement the dump method.
LLVM_ABI void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
LLVM_ABI void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
Result of a LiveRange query.
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
bool isDeadDef() const
Return true if this instruction has a dead def.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
static LLVM_ABI bool isJointlyDominated(const MachineBasicBlock *MBB, ArrayRef< SlotIndex > Defs, const SlotIndexes &Indexes)
A diagnostic function to check if the end of the block MBB is jointly dominated by the blocks corresp...
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
Segments::iterator iterator
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
iterator_range< vni_iterator > vnis()
Segments::const_iterator const_iterator
LLVM_ABI VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
LLVM_ABI iterator mergeAdjacentSegments(iterator I)
Merge the segment pointed to by I with its immediate neighbors when they use the same value number an...
LLVM_ABI bool covers(const LiveRange &Other) const
Returns true if all segments of the Other live range are completely covered by this live range.
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position,...
LLVM_ABI void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
bool empty() const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool verify() const
Walk the range and assert if any invariants fail to hold.
iterator begin()
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
VNInfoList valnos
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
bool hasAtLeastOneValue() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none.
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
MCRegUnitMaskIterator enumerates a list of register units and their associated lane masks for Reg.
bool isValid() const
Returns true if this iterator is not yet at the end.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
bool isEHPad() const
Returns true if the block is a landing pad.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI const uint32_t * getBeginClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the start of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI const uint32_t * getEndClobberMask(const TargetRegisterInfo *TRI) const
Get the clobber mask for the end of the basic block.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
double getBlockFreqRelativeToEntryBlock(const MachineBasicBlock *MBB) const
Compute the frequency of the block, relative to the entry block.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
mop_range operands()
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
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
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:276
Analysis providing profile information.
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
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
bool isValid() const
Returns true if this is a valid index.
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void swap(SmallVectorImpl &RHS)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level Statepoint operands.
Definition StackMaps.h:159
unsigned getNumDeoptArgsIdx() const
Get index of Number Deopt Arguments operand.
Definition StackMaps.h:200
uint64_t getFlags() const
Return the statepoint flags.
Definition StackMaps.h:223
LLVM_ABI unsigned getNumGCPtrIdx()
Get index of number of GC pointers.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
VNInfo - Value Number Information.
void markUnused()
Mark this value as unused.
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:89
Wrapper class representing a virtual register or register unit.
Definition Register.h:175
constexpr bool isVirtualReg() const
Definition Register.h:191
constexpr MCRegUnit asMCRegUnit() const
Definition Register.h:195
constexpr Register asVirtualReg() const
Definition Register.h:200
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
@ Kill
The last use of a register.
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2145
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
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
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
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
MachineBasicBlock::instr_iterator getBundleEnd(MachineBasicBlock::instr_iterator I)
Returns an iterator pointing beyond the bundle containing I.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ DeoptLiveIn
Mark the deopt arguments associated with the statepoint as only being "live-in".
Definition Statepoint.h:49
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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.
LLVM_ABI char & LiveIntervalsID
LiveIntervals - This analysis keeps track of the live ranges of virtual and physical registers.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
This represents a simple continuous liveness interval for a value.