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