LLVM  5.0.0
LiveIntervalAnalysis.cpp
Go to the documentation of this file.
1 //===- LiveIntervalAnalysis.cpp - Live Interval Analysis ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This file implements the LiveInterval analysis pass which is used
11 /// by the Linear Scan Register allocator. This pass linearizes the
12 /// basic blocks of the function in DFS order and computes live intervals for
13 /// each virtual and physical register.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "LiveRangeCalc.h"
19 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/MC/LaneBitmask.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/Pass.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "regalloc"
59 
60 char LiveIntervals::ID = 0;
62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
63  "Live Interval Analysis", false, false)
68  "Live Interval Analysis", false, false)
69 
70 #ifndef NDEBUG
72  "precompute-phys-liveness", cl::Hidden,
73  cl::desc("Eagerly compute live intervals for all physreg units."));
74 #else
75 static bool EnablePrecomputePhysRegs = false;
76 #endif // NDEBUG
77 
78 namespace llvm {
79 
81  "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
82  cl::desc(
83  "Use segment set for the computation of the live ranges of physregs."));
84 
85 } // end namespace llvm
86 
88  AU.setPreservesCFG();
98 }
99 
102 }
103 
105  delete LRCalc;
106 }
107 
109  // Free the live intervals themselves.
110  for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
111  delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
112  VirtRegIntervals.clear();
113  RegMaskSlots.clear();
114  RegMaskBits.clear();
115  RegMaskBlocks.clear();
116 
117  for (LiveRange *LR : RegUnitRanges)
118  delete LR;
119  RegUnitRanges.clear();
120 
121  // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
122  VNInfoAllocator.Reset();
123 }
124 
126  MF = &fn;
127  MRI = &MF->getRegInfo();
128  TRI = MF->getSubtarget().getRegisterInfo();
129  TII = MF->getSubtarget().getInstrInfo();
130  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
131  Indexes = &getAnalysis<SlotIndexes>();
132  DomTree = &getAnalysis<MachineDominatorTree>();
133 
134  if (!LRCalc)
135  LRCalc = new LiveRangeCalc();
136 
137  // Allocate space for all virtual registers.
138  VirtRegIntervals.resize(MRI->getNumVirtRegs());
139 
140  computeVirtRegs();
141  computeRegMasks();
142  computeLiveInRegUnits();
143 
145  // For stress testing, precompute live ranges of all physical register
146  // units, including reserved registers.
147  for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
148  getRegUnit(i);
149  }
150  DEBUG(dump());
151  return true;
152 }
153 
154 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
155  OS << "********** INTERVALS **********\n";
156 
157  // Dump the regunits.
158  for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
159  if (LiveRange *LR = RegUnitRanges[Unit])
160  OS << PrintRegUnit(Unit, TRI) << ' ' << *LR << '\n';
161 
162  // Dump the virtregs.
163  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
165  if (hasInterval(Reg))
166  OS << getInterval(Reg) << '\n';
167  }
168 
169  OS << "RegMasks:";
170  for (SlotIndex Idx : RegMaskSlots)
171  OS << ' ' << Idx;
172  OS << '\n';
173 
174  printInstrs(OS);
175 }
176 
177 void LiveIntervals::printInstrs(raw_ostream &OS) const {
178  OS << "********** MACHINEINSTRS **********\n";
179  MF->print(OS, Indexes);
180 }
181 
182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
183 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
184  printInstrs(dbgs());
185 }
186 #endif
187 
188 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
189  float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? huge_valf : 0.0F;
190  return new LiveInterval(reg, Weight);
191 }
192 
193 /// Compute the live interval of a virtual register, based on defs and uses.
194 void LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
195  assert(LRCalc && "LRCalc not initialized.");
196  assert(LI.empty() && "Should only compute empty intervals.");
197  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
198  LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
199  computeDeadValues(LI, nullptr);
200 }
201 
202 void LiveIntervals::computeVirtRegs() {
203  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
205  if (MRI->reg_nodbg_empty(Reg))
206  continue;
208  }
209 }
210 
211 void LiveIntervals::computeRegMasks() {
212  RegMaskBlocks.resize(MF->getNumBlockIDs());
213 
214  // Find all instructions with regmask operands.
215  for (const MachineBasicBlock &MBB : *MF) {
216  std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
217  RMB.first = RegMaskSlots.size();
218 
219  // Some block starts, such as EH funclets, create masks.
220  if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
221  RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
222  RegMaskBits.push_back(Mask);
223  }
224 
225  for (const MachineInstr &MI : MBB) {
226  for (const MachineOperand &MO : MI.operands()) {
227  if (!MO.isRegMask())
228  continue;
229  RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
230  RegMaskBits.push_back(MO.getRegMask());
231  }
232  }
233 
234  // Some block ends, such as funclet returns, create masks. Put the mask on
235  // the last instruction of the block, because MBB slot index intervals are
236  // half-open.
237  if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
238  assert(!MBB.empty() && "empty return block?");
239  RegMaskSlots.push_back(
240  Indexes->getInstructionIndex(MBB.back()).getRegSlot());
241  RegMaskBits.push_back(Mask);
242  }
243 
244  // Compute the number of register mask instructions in this block.
245  RMB.second = RegMaskSlots.size() - RMB.first;
246  }
247 }
248 
249 //===----------------------------------------------------------------------===//
250 // Register Unit Liveness
251 //===----------------------------------------------------------------------===//
252 //
253 // Fixed interference typically comes from ABI boundaries: Function arguments
254 // and return values are passed in fixed registers, and so are exception
255 // pointers entering landing pads. Certain instructions require values to be
256 // present in specific registers. That is also represented through fixed
257 // interference.
258 //
259 
260 /// Compute the live range of a register unit, based on the uses and defs of
261 /// aliasing registers. The range should be empty, or contain only dead
262 /// phi-defs from ABI blocks.
263 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
264  assert(LRCalc && "LRCalc not initialized.");
265  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
266 
267  // The physregs aliasing Unit are the roots and their super-registers.
268  // Create all values as dead defs before extending to uses. Note that roots
269  // may share super-registers. That's OK because createDeadDefs() is
270  // idempotent. It is very rare for a register unit to have multiple roots, so
271  // uniquing super-registers is probably not worthwhile.
272  bool IsReserved = true;
273  for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
274  for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
275  Super.isValid(); ++Super) {
276  unsigned Reg = *Super;
277  if (!MRI->reg_empty(Reg))
278  LRCalc->createDeadDefs(LR, Reg);
279  // A register unit is considered reserved if all its roots and all their
280  // super registers are reserved.
281  if (!MRI->isReserved(Reg))
282  IsReserved = false;
283  }
284  }
285 
286  // Now extend LR to reach all uses.
287  // Ignore uses of reserved registers. We only track defs of those.
288  if (!IsReserved) {
289  for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
290  for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
291  Super.isValid(); ++Super) {
292  unsigned Reg = *Super;
293  if (!MRI->reg_empty(Reg))
294  LRCalc->extendToUses(LR, Reg);
295  }
296  }
297  }
298 
299  // Flush the segment set to the segment vector.
301  LR.flushSegmentSet();
302 }
303 
304 /// Precompute the live ranges of any register units that are live-in to an ABI
305 /// block somewhere. Register values can appear without a corresponding def when
306 /// entering the entry block or a landing pad.
307 void LiveIntervals::computeLiveInRegUnits() {
308  RegUnitRanges.resize(TRI->getNumRegUnits());
309  DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
310 
311  // Keep track of the live range sets allocated.
312  SmallVector<unsigned, 8> NewRanges;
313 
314  // Check all basic blocks for live-ins.
315  for (const MachineBasicBlock &MBB : *MF) {
316  // We only care about ABI blocks: Entry + landing pads.
317  if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
318  continue;
319 
320  // Create phi-defs at Begin for all live-in registers.
321  SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
322  DEBUG(dbgs() << Begin << "\tBB#" << MBB.getNumber());
323  for (const auto &LI : MBB.liveins()) {
324  for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
325  unsigned Unit = *Units;
326  LiveRange *LR = RegUnitRanges[Unit];
327  if (!LR) {
328  // Use segment set to speed-up initial computation of the live range.
329  LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
330  NewRanges.push_back(Unit);
331  }
332  VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
333  (void)VNI;
334  DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
335  }
336  }
337  DEBUG(dbgs() << '\n');
338  }
339  DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
340 
341  // Compute the 'normal' part of the ranges.
342  for (unsigned Unit : NewRanges)
343  computeRegUnitRange(*RegUnitRanges[Unit], Unit);
344 }
345 
348  for (VNInfo *VNI : VNIs) {
349  if (VNI->isUnused())
350  continue;
351  SlotIndex Def = VNI->def;
352  LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
353  }
354 }
355 
357 
358 static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes,
359  ShrinkToUsesWorkList &WorkList,
360  const LiveRange &OldRange) {
361  // Keep track of the PHIs that are in use.
362  SmallPtrSet<VNInfo*, 8> UsedPHIs;
363  // Blocks that have already been added to WorkList as live-out.
365 
366  // Extend intervals to reach all uses in WorkList.
367  while (!WorkList.empty()) {
368  SlotIndex Idx = WorkList.back().first;
369  VNInfo *VNI = WorkList.back().second;
370  WorkList.pop_back();
371  const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Idx.getPrevSlot());
372  SlotIndex BlockStart = Indexes.getMBBStartIdx(MBB);
373 
374  // Extend the live range for VNI to be live at Idx.
375  if (VNInfo *ExtVNI = LR.extendInBlock(BlockStart, Idx)) {
376  assert(ExtVNI == VNI && "Unexpected existing value number");
377  (void)ExtVNI;
378  // Is this a PHIDef we haven't seen before?
379  if (!VNI->isPHIDef() || VNI->def != BlockStart ||
380  !UsedPHIs.insert(VNI).second)
381  continue;
382  // The PHI is live, make sure the predecessors are live-out.
383  for (const MachineBasicBlock *Pred : MBB->predecessors()) {
384  if (!LiveOut.insert(Pred).second)
385  continue;
386  SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
387  // A predecessor is not required to have a live-out value for a PHI.
388  if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
389  WorkList.push_back(std::make_pair(Stop, PVNI));
390  }
391  continue;
392  }
393 
394  // VNI is live-in to MBB.
395  DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
396  LR.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
397 
398  // Make sure VNI is live-out from the predecessors.
399  for (const MachineBasicBlock *Pred : MBB->predecessors()) {
400  if (!LiveOut.insert(Pred).second)
401  continue;
402  SlotIndex Stop = Indexes.getMBBEndIdx(Pred);
403  assert(OldRange.getVNInfoBefore(Stop) == VNI &&
404  "Wrong value out of predecessor");
405  WorkList.push_back(std::make_pair(Stop, VNI));
406  }
407  }
408 }
409 
412  DEBUG(dbgs() << "Shrink: " << *li << '\n');
414  && "Can only shrink virtual registers");
415 
416  // Shrink subregister live ranges.
417  bool NeedsCleanup = false;
418  for (LiveInterval::SubRange &S : li->subranges()) {
419  shrinkToUses(S, li->reg);
420  if (S.empty())
421  NeedsCleanup = true;
422  }
423  if (NeedsCleanup)
424  li->removeEmptySubRanges();
425 
426  // Find all the values used, including PHI kills.
427  ShrinkToUsesWorkList WorkList;
428 
429  // Visit all instructions reading li->reg.
430  unsigned Reg = li->reg;
431  for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
432  if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg))
433  continue;
435  LiveQueryResult LRQ = li->Query(Idx);
436  VNInfo *VNI = LRQ.valueIn();
437  if (!VNI) {
438  // This shouldn't happen: readsVirtualRegister returns true, but there is
439  // no live value. It is likely caused by a target getting <undef> flags
440  // wrong.
441  DEBUG(dbgs() << Idx << '\t' << UseMI
442  << "Warning: Instr claims to read non-existent value in "
443  << *li << '\n');
444  continue;
445  }
446  // Special case: An early-clobber tied operand reads and writes the
447  // register one slot early.
448  if (VNInfo *DefVNI = LRQ.valueDefined())
449  Idx = DefVNI->def;
450 
451  WorkList.push_back(std::make_pair(Idx, VNI));
452  }
453 
454  // Create new live ranges with only minimal live segments per def.
455  LiveRange NewLR;
456  createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
457  extendSegmentsToUses(NewLR, *Indexes, WorkList, *li);
458 
459  // Move the trimmed segments back.
460  li->segments.swap(NewLR.segments);
461 
462  // Handle dead values.
463  bool CanSeparate = computeDeadValues(*li, dead);
464  DEBUG(dbgs() << "Shrunk: " << *li << '\n');
465  return CanSeparate;
466 }
467 
468 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
470  bool MayHaveSplitComponents = false;
471  for (VNInfo *VNI : LI.valnos) {
472  if (VNI->isUnused())
473  continue;
474  SlotIndex Def = VNI->def;
476  assert(I != LI.end() && "Missing segment for VNI");
477 
478  // Is the register live before? Otherwise we may have to add a read-undef
479  // flag for subregister defs.
480  unsigned VReg = LI.reg;
481  if (MRI->shouldTrackSubRegLiveness(VReg)) {
482  if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
484  MI->setRegisterDefReadUndef(VReg);
485  }
486  }
487 
488  if (I->end != Def.getDeadSlot())
489  continue;
490  if (VNI->isPHIDef()) {
491  // This is a dead PHI. Remove it.
492  VNI->markUnused();
493  LI.removeSegment(I);
494  DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
495  MayHaveSplitComponents = true;
496  } else {
497  // This is a dead def. Make sure the instruction knows.
499  assert(MI && "No instruction defining live value");
500  MI->addRegisterDead(LI.reg, TRI);
501  if (dead && MI->allDefsAreDead()) {
502  DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
503  dead->push_back(MI);
504  }
505  }
506  }
507  return MayHaveSplitComponents;
508 }
509 
511  DEBUG(dbgs() << "Shrink: " << SR << '\n');
513  && "Can only shrink virtual registers");
514  // Find all the values used, including PHI kills.
515  ShrinkToUsesWorkList WorkList;
516 
517  // Visit all instructions reading Reg.
518  SlotIndex LastIdx;
519  for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
520  // Skip "undef" uses.
521  if (!MO.readsReg())
522  continue;
523  // Maybe the operand is for a subregister we don't care about.
524  unsigned SubReg = MO.getSubReg();
525  if (SubReg != 0) {
526  LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
527  if ((LaneMask & SR.LaneMask).none())
528  continue;
529  }
530  // We only need to visit each instruction once.
531  MachineInstr *UseMI = MO.getParent();
532  SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
533  if (Idx == LastIdx)
534  continue;
535  LastIdx = Idx;
536 
537  LiveQueryResult LRQ = SR.Query(Idx);
538  VNInfo *VNI = LRQ.valueIn();
539  // For Subranges it is possible that only undef values are left in that
540  // part of the subregister, so there is no real liverange at the use
541  if (!VNI)
542  continue;
543 
544  // Special case: An early-clobber tied operand reads and writes the
545  // register one slot early.
546  if (VNInfo *DefVNI = LRQ.valueDefined())
547  Idx = DefVNI->def;
548 
549  WorkList.push_back(std::make_pair(Idx, VNI));
550  }
551 
552  // Create a new live ranges with only minimal live segments per def.
553  LiveRange NewLR;
555  extendSegmentsToUses(NewLR, *Indexes, WorkList, SR);
556 
557  // Move the trimmed ranges back.
558  SR.segments.swap(NewLR.segments);
559 
560  // Remove dead PHI value numbers
561  for (VNInfo *VNI : SR.valnos) {
562  if (VNI->isUnused())
563  continue;
564  const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
565  assert(Segment != nullptr && "Missing segment for VNI");
566  if (Segment->end != VNI->def.getDeadSlot())
567  continue;
568  if (VNI->isPHIDef()) {
569  // This is a dead PHI. Remove it.
570  DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
571  VNI->markUnused();
572  SR.removeSegment(*Segment);
573  }
574  }
575 
576  DEBUG(dbgs() << "Shrunk: " << SR << '\n');
577 }
578 
580  ArrayRef<SlotIndex> Indices,
581  ArrayRef<SlotIndex> Undefs) {
582  assert(LRCalc && "LRCalc not initialized.");
583  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
584  for (SlotIndex Idx : Indices)
585  LRCalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
586 }
587 
589  SmallVectorImpl<SlotIndex> *EndPoints) {
590  LiveQueryResult LRQ = LR.Query(Kill);
591  VNInfo *VNI = LRQ.valueOutOrDead();
592  if (!VNI)
593  return;
594 
595  MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
596  SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
597 
598  // If VNI isn't live out from KillMBB, the value is trivially pruned.
599  if (LRQ.endPoint() < MBBEnd) {
600  LR.removeSegment(Kill, LRQ.endPoint());
601  if (EndPoints) EndPoints->push_back(LRQ.endPoint());
602  return;
603  }
604 
605  // VNI is live out of KillMBB.
606  LR.removeSegment(Kill, MBBEnd);
607  if (EndPoints) EndPoints->push_back(MBBEnd);
608 
609  // Find all blocks that are reachable from KillMBB without leaving VNI's live
610  // range. It is possible that KillMBB itself is reachable, so start a DFS
611  // from each successor.
613  VisitedTy Visited;
614  for (MachineBasicBlock *Succ : KillMBB->successors()) {
616  I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
617  I != E;) {
618  MachineBasicBlock *MBB = *I;
619 
620  // Check if VNI is live in to MBB.
621  SlotIndex MBBStart, MBBEnd;
622  std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
623  LiveQueryResult LRQ = LR.Query(MBBStart);
624  if (LRQ.valueIn() != VNI) {
625  // This block isn't part of the VNI segment. Prune the search.
626  I.skipChildren();
627  continue;
628  }
629 
630  // Prune the search if VNI is killed in MBB.
631  if (LRQ.endPoint() < MBBEnd) {
632  LR.removeSegment(MBBStart, LRQ.endPoint());
633  if (EndPoints) EndPoints->push_back(LRQ.endPoint());
634  I.skipChildren();
635  continue;
636  }
637 
638  // VNI is live through MBB.
639  LR.removeSegment(MBBStart, MBBEnd);
640  if (EndPoints) EndPoints->push_back(MBBEnd);
641  ++I;
642  }
643  }
644 }
645 
646 //===----------------------------------------------------------------------===//
647 // Register allocator hooks.
648 //
649 
651  // Keep track of regunit ranges.
653  // Keep track of subregister ranges.
654  SmallVector<std::pair<const LiveInterval::SubRange*,
656 
657  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
658  unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
659  if (MRI->reg_nodbg_empty(Reg))
660  continue;
661  const LiveInterval &LI = getInterval(Reg);
662  if (LI.empty())
663  continue;
664 
665  // Find the regunit intervals for the assigned register. They may overlap
666  // the virtual register live range, cancelling any kills.
667  RU.clear();
668  for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid();
669  ++Unit) {
670  const LiveRange &RURange = getRegUnit(*Unit);
671  if (RURange.empty())
672  continue;
673  RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
674  }
675 
676  if (MRI->subRegLivenessEnabled()) {
677  SRs.clear();
678  for (const LiveInterval::SubRange &SR : LI.subranges()) {
679  SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
680  }
681  }
682 
683  // Every instruction that kills Reg corresponds to a segment range end
684  // point.
685  for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
686  ++RI) {
687  // A block index indicates an MBB edge.
688  if (RI->end.isBlock())
689  continue;
690  MachineInstr *MI = getInstructionFromIndex(RI->end);
691  if (!MI)
692  continue;
693 
694  // Check if any of the regunits are live beyond the end of RI. That could
695  // happen when a physreg is defined as a copy of a virtreg:
696  //
697  // %EAX = COPY %vreg5
698  // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
699  // BAR %EAX<kill>
700  //
701  // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
702  for (auto &RUP : RU) {
703  const LiveRange &RURange = *RUP.first;
704  LiveRange::const_iterator &I = RUP.second;
705  if (I == RURange.end())
706  continue;
707  I = RURange.advanceTo(I, RI->end);
708  if (I == RURange.end() || I->start >= RI->end)
709  continue;
710  // I is overlapping RI.
711  goto CancelKill;
712  }
713 
714  if (MRI->subRegLivenessEnabled()) {
715  // When reading a partial undefined value we must not add a kill flag.
716  // The regalloc might have used the undef lane for something else.
717  // Example:
718  // %vreg1 = ... ; R32: %vreg1
719  // %vreg2:high16 = ... ; R64: %vreg2
720  // = read %vreg2<kill> ; R64: %vreg2
721  // = read %vreg1 ; R32: %vreg1
722  // The <kill> flag is correct for %vreg2, but the register allocator may
723  // assign R0L to %vreg1, and R0 to %vreg2 because the low 32bits of R0
724  // are actually never written by %vreg2. After assignment the <kill>
725  // flag at the read instruction is invalid.
726  LaneBitmask DefinedLanesMask;
727  if (!SRs.empty()) {
728  // Compute a mask of lanes that are defined.
729  DefinedLanesMask = LaneBitmask::getNone();
730  for (auto &SRP : SRs) {
731  const LiveInterval::SubRange &SR = *SRP.first;
732  LiveRange::const_iterator &I = SRP.second;
733  if (I == SR.end())
734  continue;
735  I = SR.advanceTo(I, RI->end);
736  if (I == SR.end() || I->start >= RI->end)
737  continue;
738  // I is overlapping RI
739  DefinedLanesMask |= SR.LaneMask;
740  }
741  } else
742  DefinedLanesMask = LaneBitmask::getAll();
743 
744  bool IsFullWrite = false;
745  for (const MachineOperand &MO : MI->operands()) {
746  if (!MO.isReg() || MO.getReg() != Reg)
747  continue;
748  if (MO.isUse()) {
749  // Reading any undefined lanes?
750  LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
751  if ((UseMask & ~DefinedLanesMask).any())
752  goto CancelKill;
753  } else if (MO.getSubReg() == 0) {
754  // Writing to the full register?
755  assert(MO.isDef());
756  IsFullWrite = true;
757  }
758  }
759 
760  // If an instruction writes to a subregister, a new segment starts in
761  // the LiveInterval. But as this is only overriding part of the register
762  // adding kill-flags is not correct here after registers have been
763  // assigned.
764  if (!IsFullWrite) {
765  // Next segment has to be adjacent in the subregister write case.
766  LiveRange::const_iterator N = std::next(RI);
767  if (N != LI.end() && N->start == RI->end)
768  goto CancelKill;
769  }
770  }
771 
772  MI->addRegisterKilled(Reg, nullptr);
773  continue;
774 CancelKill:
775  MI->clearRegisterKills(Reg, nullptr);
776  }
777  }
778 }
779 
782  // A local live range must be fully contained inside the block, meaning it is
783  // defined and killed at instructions, not at block boundaries. It is not
784  // live in or or out of any block.
785  //
786  // It is technically possible to have a PHI-defined live range identical to a
787  // single block, but we are going to return false in that case.
788 
789  SlotIndex Start = LI.beginIndex();
790  if (Start.isBlock())
791  return nullptr;
792 
793  SlotIndex Stop = LI.endIndex();
794  if (Stop.isBlock())
795  return nullptr;
796 
797  // getMBBFromIndex doesn't need to search the MBB table when both indexes
798  // belong to proper instructions.
799  MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
800  MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
801  return MBB1 == MBB2 ? MBB1 : nullptr;
802 }
803 
804 bool
805 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
806  for (const VNInfo *PHI : LI.valnos) {
807  if (PHI->isUnused() || !PHI->isPHIDef())
808  continue;
809  const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
810  // Conservatively return true instead of scanning huge predecessor lists.
811  if (PHIMBB->pred_size() > 100)
812  return true;
813  for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
814  if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
815  return true;
816  }
817  return false;
818 }
819 
820 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
821  const MachineBlockFrequencyInfo *MBFI,
822  const MachineInstr &MI) {
823  BlockFrequency Freq = MBFI->getBlockFreq(MI.getParent());
824  const float Scale = 1.0f / MBFI->getEntryFreq();
825  return (isDef + isUse) * (Freq.getFrequency() * Scale);
826 }
827 
831  VNInfo *VN = Interval.getNextValue(
832  SlotIndex(getInstructionIndex(startInst).getRegSlot()),
834  LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
835  getMBBEndIdx(startInst.getParent()), VN);
836  Interval.addSegment(S);
837 
838  return S;
839 }
840 
841 //===----------------------------------------------------------------------===//
842 // Register mask functions
843 //===----------------------------------------------------------------------===//
844 
846  BitVector &UsableRegs) {
847  if (LI.empty())
848  return false;
849  LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
850 
851  // Use a smaller arrays for local live ranges.
852  ArrayRef<SlotIndex> Slots;
854  if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
855  Slots = getRegMaskSlotsInBlock(MBB->getNumber());
856  Bits = getRegMaskBitsInBlock(MBB->getNumber());
857  } else {
858  Slots = getRegMaskSlots();
859  Bits = getRegMaskBits();
860  }
861 
862  // We are going to enumerate all the register mask slots contained in LI.
863  // Start with a binary search of RegMaskSlots to find a starting point.
865  std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
866  ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
867 
868  // No slots in range, LI begins after the last call.
869  if (SlotI == SlotE)
870  return false;
871 
872  bool Found = false;
873  while (true) {
874  assert(*SlotI >= LiveI->start);
875  // Loop over all slots overlapping this segment.
876  while (*SlotI < LiveI->end) {
877  // *SlotI overlaps LI. Collect mask bits.
878  if (!Found) {
879  // This is the first overlap. Initialize UsableRegs to all ones.
880  UsableRegs.clear();
881  UsableRegs.resize(TRI->getNumRegs(), true);
882  Found = true;
883  }
884  // Remove usable registers clobbered by this mask.
885  UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
886  if (++SlotI == SlotE)
887  return Found;
888  }
889  // *SlotI is beyond the current LI segment.
890  LiveI = LI.advanceTo(LiveI, *SlotI);
891  if (LiveI == LiveE)
892  return Found;
893  // Advance SlotI until it overlaps.
894  while (*SlotI < LiveI->start)
895  if (++SlotI == SlotE)
896  return Found;
897  }
898 }
899 
900 //===----------------------------------------------------------------------===//
901 // IntervalUpdate class.
902 //===----------------------------------------------------------------------===//
903 
904 /// Toolkit used by handleMove to trim or extend live intervals.
906 private:
907  LiveIntervals& LIS;
908  const MachineRegisterInfo& MRI;
909  const TargetRegisterInfo& TRI;
910  SlotIndex OldIdx;
911  SlotIndex NewIdx;
913  bool UpdateFlags;
914 
915 public:
916  HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
917  const TargetRegisterInfo& TRI,
918  SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
919  : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
920  UpdateFlags(UpdateFlags) {}
921 
922  // FIXME: UpdateFlags is a workaround that creates live intervals for all
923  // physregs, even those that aren't needed for regalloc, in order to update
924  // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
925  // flags, and postRA passes will use a live register utility instead.
926  LiveRange *getRegUnitLI(unsigned Unit) {
927  if (UpdateFlags)
928  return &LIS.getRegUnit(Unit);
929  return LIS.getCachedRegUnit(Unit);
930  }
931 
932  /// Update all live ranges touched by MI, assuming a move from OldIdx to
933  /// NewIdx.
935  DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
936  bool hasRegMask = false;
937  for (MachineOperand &MO : MI->operands()) {
938  if (MO.isRegMask())
939  hasRegMask = true;
940  if (!MO.isReg())
941  continue;
942  if (MO.isUse()) {
943  if (!MO.readsReg())
944  continue;
945  // Aggressively clear all kill flags.
946  // They are reinserted by VirtRegRewriter.
947  MO.setIsKill(false);
948  }
949 
950  unsigned Reg = MO.getReg();
951  if (!Reg)
952  continue;
954  LiveInterval &LI = LIS.getInterval(Reg);
955  if (LI.hasSubRanges()) {
956  unsigned SubReg = MO.getSubReg();
957  LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
958  : MRI.getMaxLaneMaskForVReg(Reg);
959  for (LiveInterval::SubRange &S : LI.subranges()) {
960  if ((S.LaneMask & LaneMask).none())
961  continue;
962  updateRange(S, Reg, S.LaneMask);
963  }
964  }
965  updateRange(LI, Reg, LaneBitmask::getNone());
966  continue;
967  }
968 
969  // For physregs, only update the regunits that actually have a
970  // precomputed live range.
971  for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
972  if (LiveRange *LR = getRegUnitLI(*Units))
973  updateRange(*LR, *Units, LaneBitmask::getNone());
974  }
975  if (hasRegMask)
976  updateRegMaskSlots();
977  }
978 
979 private:
980  /// Update a single live range, assuming an instruction has been moved from
981  /// OldIdx to NewIdx.
982  void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
983  if (!Updated.insert(&LR).second)
984  return;
985  DEBUG({
986  dbgs() << " ";
988  dbgs() << PrintReg(Reg);
989  if (LaneMask.any())
990  dbgs() << " L" << PrintLaneMask(LaneMask);
991  } else {
992  dbgs() << PrintRegUnit(Reg, &TRI);
993  }
994  dbgs() << ":\t" << LR << '\n';
995  });
996  if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
997  handleMoveDown(LR);
998  else
999  handleMoveUp(LR, Reg, LaneMask);
1000  DEBUG(dbgs() << " -->\t" << LR << '\n');
1001  LR.verify();
1002  }
1003 
1004  /// Update LR to reflect an instruction has been moved downwards from OldIdx
1005  /// to NewIdx (OldIdx < NewIdx).
1006  void handleMoveDown(LiveRange &LR) {
1007  LiveRange::iterator E = LR.end();
1008  // Segment going into OldIdx.
1009  LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1010 
1011  // No value live before or after OldIdx? Nothing to do.
1012  if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1013  return;
1014 
1015  LiveRange::iterator OldIdxOut;
1016  // Do we have a value live-in to OldIdx?
1017  if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1018  // If the live-in value already extends to NewIdx, there is nothing to do.
1019  if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1020  return;
1021  // Aggressively remove all kill flags from the old kill point.
1022  // Kill flags shouldn't be used while live intervals exist, they will be
1023  // reinserted by VirtRegRewriter.
1024  if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1025  for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1026  if (MO->isReg() && MO->isUse())
1027  MO->setIsKill(false);
1028 
1029  // Is there a def before NewIdx which is not OldIdx?
1030  LiveRange::iterator Next = std::next(OldIdxIn);
1031  if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1032  SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1033  // If we are here then OldIdx was just a use but not a def. We only have
1034  // to ensure liveness extends to NewIdx.
1035  LiveRange::iterator NewIdxIn =
1036  LR.advanceTo(Next, NewIdx.getBaseIndex());
1037  // Extend the segment before NewIdx if necessary.
1038  if (NewIdxIn == E ||
1039  !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1040  LiveRange::iterator Prev = std::prev(NewIdxIn);
1041  Prev->end = NewIdx.getRegSlot();
1042  }
1043  // Extend OldIdxIn.
1044  OldIdxIn->end = Next->start;
1045  return;
1046  }
1047 
1048  // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1049  // invalid by overlapping ranges.
1050  bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1051  OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1052  // If this was not a kill, then there was no def and we're done.
1053  if (!isKill)
1054  return;
1055 
1056  // Did we have a Def at OldIdx?
1057  OldIdxOut = Next;
1058  if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1059  return;
1060  } else {
1061  OldIdxOut = OldIdxIn;
1062  }
1063 
1064  // If we are here then there is a Definition at OldIdx. OldIdxOut points
1065  // to the segment starting there.
1066  assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1067  "No def?");
1068  VNInfo *OldIdxVNI = OldIdxOut->valno;
1069  assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1070 
1071  // If the defined value extends beyond NewIdx, just move the beginning
1072  // of the segment to NewIdx.
1073  SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1074  if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1075  OldIdxVNI->def = NewIdxDef;
1076  OldIdxOut->start = OldIdxVNI->def;
1077  return;
1078  }
1079 
1080  // If we are here then we have a Definition at OldIdx which ends before
1081  // NewIdx.
1082 
1083  // Is there an existing Def at NewIdx?
1084  LiveRange::iterator AfterNewIdx
1085  = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1086  bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1087  if (!OldIdxDefIsDead &&
1088  SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1089  // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1090  VNInfo *DefVNI;
1091  if (OldIdxOut != LR.begin() &&
1092  !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1093  OldIdxOut->start)) {
1094  // There is no gap between OldIdxOut and its predecessor anymore,
1095  // merge them.
1096  LiveRange::iterator IPrev = std::prev(OldIdxOut);
1097  DefVNI = OldIdxVNI;
1098  IPrev->end = OldIdxOut->end;
1099  } else {
1100  // The value is live in to OldIdx
1101  LiveRange::iterator INext = std::next(OldIdxOut);
1102  assert(INext != E && "Must have following segment");
1103  // We merge OldIdxOut and its successor. As we're dealing with subreg
1104  // reordering, there is always a successor to OldIdxOut in the same BB
1105  // We don't need INext->valno anymore and will reuse for the new segment
1106  // we create later.
1107  DefVNI = OldIdxVNI;
1108  INext->start = OldIdxOut->end;
1109  INext->valno->def = INext->start;
1110  }
1111  // If NewIdx is behind the last segment, extend that and append a new one.
1112  if (AfterNewIdx == E) {
1113  // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1114  // one position.
1115  // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1116  // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1117  std::copy(std::next(OldIdxOut), E, OldIdxOut);
1118  // The last segment is undefined now, reuse it for a dead def.
1119  LiveRange::iterator NewSegment = std::prev(E);
1120  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1121  DefVNI);
1122  DefVNI->def = NewIdxDef;
1123 
1124  LiveRange::iterator Prev = std::prev(NewSegment);
1125  Prev->end = NewIdxDef;
1126  } else {
1127  // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1128  // one position.
1129  // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1130  // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1131  std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1132  LiveRange::iterator Prev = std::prev(AfterNewIdx);
1133  // We have two cases:
1134  if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1135  // Case 1: NewIdx is inside a liverange. Split this liverange at
1136  // NewIdxDef into the segment "Prev" followed by "NewSegment".
1137  LiveRange::iterator NewSegment = AfterNewIdx;
1138  *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1139  Prev->valno->def = NewIdxDef;
1140 
1141  *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1142  DefVNI->def = Prev->start;
1143  } else {
1144  // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1145  // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1146  *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1147  DefVNI->def = NewIdxDef;
1148  assert(DefVNI != AfterNewIdx->valno);
1149  }
1150  }
1151  return;
1152  }
1153 
1154  if (AfterNewIdx != E &&
1155  SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1156  // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1157  // that value.
1158  assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1159  LR.removeValNo(OldIdxVNI);
1160  } else {
1161  // There was no existing def at NewIdx. We need to create a dead def
1162  // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1163  // a new segment at the place where we want to construct the dead def.
1164  // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1165  // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1166  assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1167  std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1168  // We can reuse OldIdxVNI now.
1169  LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1170  VNInfo *NewSegmentVNI = OldIdxVNI;
1171  NewSegmentVNI->def = NewIdxDef;
1172  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1173  NewSegmentVNI);
1174  }
1175  }
1176 
1177  /// Update LR to reflect an instruction has been moved upwards from OldIdx
1178  /// to NewIdx (NewIdx < OldIdx).
1179  void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1180  LiveRange::iterator E = LR.end();
1181  // Segment going into OldIdx.
1182  LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1183 
1184  // No value live before or after OldIdx? Nothing to do.
1185  if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1186  return;
1187 
1188  LiveRange::iterator OldIdxOut;
1189  // Do we have a value live-in to OldIdx?
1190  if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1191  // If the live-in value isn't killed here, then we have no Def at
1192  // OldIdx, moreover the value must be live at NewIdx so there is nothing
1193  // to do.
1194  bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1195  if (!isKill)
1196  return;
1197 
1198  // At this point we have to move OldIdxIn->end back to the nearest
1199  // previous use or (dead-)def but no further than NewIdx.
1200  SlotIndex DefBeforeOldIdx
1201  = std::max(OldIdxIn->start.getDeadSlot(),
1202  NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1203  OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
1204 
1205  // Did we have a Def at OldIdx? If not we are done now.
1206  OldIdxOut = std::next(OldIdxIn);
1207  if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1208  return;
1209  } else {
1210  OldIdxOut = OldIdxIn;
1211  OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1212  }
1213 
1214  // If we are here then there is a Definition at OldIdx. OldIdxOut points
1215  // to the segment starting there.
1216  assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1217  "No def?");
1218  VNInfo *OldIdxVNI = OldIdxOut->valno;
1219  assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1220  bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1221 
1222  // Is there an existing def at NewIdx?
1223  SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1224  LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1225  if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1226  assert(NewIdxOut->valno != OldIdxVNI &&
1227  "Same value defined more than once?");
1228  // If OldIdx was a dead def remove it.
1229  if (!OldIdxDefIsDead) {
1230  // Remove segment starting at NewIdx and move begin of OldIdxOut to
1231  // NewIdx so it can take its place.
1232  OldIdxVNI->def = NewIdxDef;
1233  OldIdxOut->start = NewIdxDef;
1234  LR.removeValNo(NewIdxOut->valno);
1235  } else {
1236  // Simply remove the dead def at OldIdx.
1237  LR.removeValNo(OldIdxVNI);
1238  }
1239  } else {
1240  // Previously nothing was live after NewIdx, so all we have to do now is
1241  // move the begin of OldIdxOut to NewIdx.
1242  if (!OldIdxDefIsDead) {
1243  // Do we have any intermediate Defs between OldIdx and NewIdx?
1244  if (OldIdxIn != E &&
1245  SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1246  // OldIdx is not a dead def and NewIdx is before predecessor start.
1247  LiveRange::iterator NewIdxIn = NewIdxOut;
1248  assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1249  const SlotIndex SplitPos = NewIdxDef;
1250  OldIdxVNI = OldIdxIn->valno;
1251 
1252  // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1253  OldIdxOut->valno->def = OldIdxIn->start;
1254  *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1255  OldIdxOut->valno);
1256  // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1257  // We Slide [NewIdxIn, OldIdxIn) down one position.
1258  // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1259  // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1260  std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1261  // NewIdxIn is now considered undef so we can reuse it for the moved
1262  // value.
1263  LiveRange::iterator NewSegment = NewIdxIn;
1264  LiveRange::iterator Next = std::next(NewSegment);
1265  if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1266  // There is no gap between NewSegment and its predecessor.
1267  *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1268  Next->valno);
1269  *Next = LiveRange::Segment(SplitPos, Next->end, OldIdxVNI);
1270  Next->valno->def = SplitPos;
1271  } else {
1272  // There is a gap between NewSegment and its predecessor
1273  // Value becomes live in.
1274  *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1275  NewSegment->valno->def = SplitPos;
1276  }
1277  } else {
1278  // Leave the end point of a live def.
1279  OldIdxOut->start = NewIdxDef;
1280  OldIdxVNI->def = NewIdxDef;
1281  if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1282  OldIdxIn->end = NewIdx.getRegSlot();
1283  }
1284  } else {
1285  // OldIdxVNI is a dead def. It may have been moved across other values
1286  // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1287  // down one position.
1288  // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1289  // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1290  std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1291  // OldIdxVNI can be reused now to build a new dead def segment.
1292  LiveRange::iterator NewSegment = NewIdxOut;
1293  VNInfo *NewSegmentVNI = OldIdxVNI;
1294  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1295  NewSegmentVNI);
1296  NewSegmentVNI->def = NewIdxDef;
1297  }
1298  }
1299  }
1300 
1301  void updateRegMaskSlots() {
1303  std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1304  OldIdx);
1305  assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1306  "No RegMask at OldIdx.");
1307  *RI = NewIdx.getRegSlot();
1308  assert((RI == LIS.RegMaskSlots.begin() ||
1309  SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1310  "Cannot move regmask instruction above another call");
1311  assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1312  SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1313  "Cannot move regmask instruction below another call");
1314  }
1315 
1316  // Return the last use of reg between NewIdx and OldIdx.
1317  SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1318  LaneBitmask LaneMask) {
1320  SlotIndex LastUse = Before;
1321  for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1322  if (MO.isUndef())
1323  continue;
1324  unsigned SubReg = MO.getSubReg();
1325  if (SubReg != 0 && LaneMask.any()
1326  && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1327  continue;
1328 
1329  const MachineInstr &MI = *MO.getParent();
1330  SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1331  if (InstSlot > LastUse && InstSlot < OldIdx)
1332  LastUse = InstSlot.getRegSlot();
1333  }
1334  return LastUse;
1335  }
1336 
1337  // This is a regunit interval, so scanning the use list could be very
1338  // expensive. Scan upwards from OldIdx instead.
1339  assert(Before < OldIdx && "Expected upwards move");
1340  SlotIndexes *Indexes = LIS.getSlotIndexes();
1341  MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1342 
1343  // OldIdx may not correspond to an instruction any longer, so set MII to
1344  // point to the next instruction after OldIdx, or MBB->end().
1345  MachineBasicBlock::iterator MII = MBB->end();
1346  if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1347  Indexes->getNextNonNullIndex(OldIdx)))
1348  if (MI->getParent() == MBB)
1349  MII = MI;
1350 
1351  MachineBasicBlock::iterator Begin = MBB->begin();
1352  while (MII != Begin) {
1353  if ((--MII)->isDebugValue())
1354  continue;
1355  SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1356 
1357  // Stop searching when Before is reached.
1358  if (!SlotIndex::isEarlierInstr(Before, Idx))
1359  return Before;
1360 
1361  // Check if MII uses Reg.
1362  for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1363  if (MO->isReg() && !MO->isUndef() &&
1365  TRI.hasRegUnit(MO->getReg(), Reg))
1366  return Idx.getRegSlot();
1367  }
1368  // Didn't reach Before. It must be the first instruction in the block.
1369  return Before;
1370  }
1371 };
1372 
1373 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1374  assert(!MI.isBundled() && "Can't handle bundled instructions yet.");
1375  SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1376  Indexes->removeMachineInstrFromMaps(MI);
1377  SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1378  assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1379  OldIndex < getMBBEndIdx(MI.getParent()) &&
1380  "Cannot handle moves across basic block boundaries.");
1381 
1382  HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1383  HME.updateAllRanges(&MI);
1384 }
1385 
1387  MachineInstr &BundleStart,
1388  bool UpdateFlags) {
1389  SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1390  SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1391  HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1392  HME.updateAllRanges(&MI);
1393 }
1394 
1395 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1397  const SlotIndex endIdx,
1398  LiveRange &LR, const unsigned Reg,
1399  LaneBitmask LaneMask) {
1400  LiveInterval::iterator LII = LR.find(endIdx);
1401  SlotIndex lastUseIdx;
1402  if (LII == LR.begin()) {
1403  // This happens when the function is called for a subregister that only
1404  // occurs _after_ the range that is to be repaired.
1405  return;
1406  }
1407  if (LII != LR.end() && LII->start < endIdx)
1408  lastUseIdx = LII->end;
1409  else
1410  --LII;
1411 
1412  for (MachineBasicBlock::iterator I = End; I != Begin;) {
1413  --I;
1414  MachineInstr &MI = *I;
1415  if (MI.isDebugValue())
1416  continue;
1417 
1418  SlotIndex instrIdx = getInstructionIndex(MI);
1419  bool isStartValid = getInstructionFromIndex(LII->start);
1420  bool isEndValid = getInstructionFromIndex(LII->end);
1421 
1422  // FIXME: This doesn't currently handle early-clobber or multiple removed
1423  // defs inside of the region to repair.
1425  OE = MI.operands_end();
1426  OI != OE; ++OI) {
1427  const MachineOperand &MO = *OI;
1428  if (!MO.isReg() || MO.getReg() != Reg)
1429  continue;
1430 
1431  unsigned SubReg = MO.getSubReg();
1432  LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1433  if ((Mask & LaneMask).none())
1434  continue;
1435 
1436  if (MO.isDef()) {
1437  if (!isStartValid) {
1438  if (LII->end.isDead()) {
1439  SlotIndex prevStart;
1440  if (LII != LR.begin())
1441  prevStart = std::prev(LII)->start;
1442 
1443  // FIXME: This could be more efficient if there was a
1444  // removeSegment method that returned an iterator.
1445  LR.removeSegment(*LII, true);
1446  if (prevStart.isValid())
1447  LII = LR.find(prevStart);
1448  else
1449  LII = LR.begin();
1450  } else {
1451  LII->start = instrIdx.getRegSlot();
1452  LII->valno->def = instrIdx.getRegSlot();
1453  if (MO.getSubReg() && !MO.isUndef())
1454  lastUseIdx = instrIdx.getRegSlot();
1455  else
1456  lastUseIdx = SlotIndex();
1457  continue;
1458  }
1459  }
1460 
1461  if (!lastUseIdx.isValid()) {
1462  VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1463  LiveRange::Segment S(instrIdx.getRegSlot(),
1464  instrIdx.getDeadSlot(), VNI);
1465  LII = LR.addSegment(S);
1466  } else if (LII->start != instrIdx.getRegSlot()) {
1467  VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1468  LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1469  LII = LR.addSegment(S);
1470  }
1471 
1472  if (MO.getSubReg() && !MO.isUndef())
1473  lastUseIdx = instrIdx.getRegSlot();
1474  else
1475  lastUseIdx = SlotIndex();
1476  } else if (MO.isUse()) {
1477  // FIXME: This should probably be handled outside of this branch,
1478  // either as part of the def case (for defs inside of the region) or
1479  // after the loop over the region.
1480  if (!isEndValid && !LII->end.isBlock())
1481  LII->end = instrIdx.getRegSlot();
1482  if (!lastUseIdx.isValid())
1483  lastUseIdx = instrIdx.getRegSlot();
1484  }
1485  }
1486  }
1487 }
1488 
1489 void
1493  ArrayRef<unsigned> OrigRegs) {
1494  // Find anchor points, which are at the beginning/end of blocks or at
1495  // instructions that already have indexes.
1496  while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
1497  --Begin;
1498  while (End != MBB->end() && !Indexes->hasIndex(*End))
1499  ++End;
1500 
1501  SlotIndex endIdx;
1502  if (End == MBB->end())
1503  endIdx = getMBBEndIdx(MBB).getPrevSlot();
1504  else
1505  endIdx = getInstructionIndex(*End);
1506 
1507  Indexes->repairIndexesInRange(MBB, Begin, End);
1508 
1509  for (MachineBasicBlock::iterator I = End; I != Begin;) {
1510  --I;
1511  MachineInstr &MI = *I;
1512  if (MI.isDebugValue())
1513  continue;
1515  MOE = MI.operands_end();
1516  MOI != MOE; ++MOI) {
1517  if (MOI->isReg() &&
1518  TargetRegisterInfo::isVirtualRegister(MOI->getReg()) &&
1519  !hasInterval(MOI->getReg())) {
1520  createAndComputeVirtRegInterval(MOI->getReg());
1521  }
1522  }
1523  }
1524 
1525  for (unsigned Reg : OrigRegs) {
1527  continue;
1528 
1529  LiveInterval &LI = getInterval(Reg);
1530  // FIXME: Should we support undefs that gain defs?
1531  if (!LI.hasAtLeastOneValue())
1532  continue;
1533 
1534  for (LiveInterval::SubRange &S : LI.subranges())
1535  repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1536 
1537  repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1538  }
1539 }
1540 
1542  for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
1543  if (LiveRange *LR = getCachedRegUnit(*Unit))
1544  if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1545  LR->removeValNo(VNI);
1546  }
1547 }
1548 
1550  // LI may not have the main range computed yet, but its subranges may
1551  // be present.
1552  VNInfo *VNI = LI.getVNInfoAt(Pos);
1553  if (VNI != nullptr) {
1554  assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1555  LI.removeValNo(VNI);
1556  }
1557 
1558  // Also remove the value defined in subranges.
1559  for (LiveInterval::SubRange &S : LI.subranges()) {
1560  if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1561  if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1562  S.removeValNo(SVNI);
1563  }
1564  LI.removeEmptySubRanges();
1565 }
1566 
1568  SmallVectorImpl<LiveInterval*> &SplitLIs) {
1569  ConnectedVNInfoEqClasses ConEQ(*this);
1570  unsigned NumComp = ConEQ.Classify(LI);
1571  if (NumComp <= 1)
1572  return;
1573  DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1574  unsigned Reg = LI.reg;
1575  const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1576  for (unsigned I = 1; I < NumComp; ++I) {
1577  unsigned NewVReg = MRI->createVirtualRegister(RegClass);
1578  LiveInterval &NewLI = createEmptyInterval(NewVReg);
1579  SplitLIs.push_back(&NewLI);
1580  }
1581  ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1582 }
1583 
1585  assert(LRCalc && "LRCalc not initialized.");
1586  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1587  LRCalc->constructMainRangeFromSubranges(LI);
1588 }
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:372
void push_back(const T &Elt)
Definition: SmallVector.h:211
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:243
mop_iterator operands_end()
Definition: MachineInstr.h:301
bool isValid() const
Check if the iterator is at the end of the list.
A common definition of LaneBitmask for use in TableGen and CodeGen.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
Definition: LiveInterval.h:396
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef< SlotIndex > getRegMaskSlots() const
Returns a sorted array of slot indices of all instructions with register mask operands.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
SlotIndex getInstructionIndex(const MachineInstr &MI) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:414
const unsigned reg
Definition: LiveInterval.h:667
cl::opt< bool > UseSegmentSetForPhysRegs
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:61
void createDeadDefs(LiveRange &LR, unsigned Reg)
createDeadDefs - Create a dead def in LI for every def operand of Reg.
void updateAllRanges(MachineInstr *MI)
Update all live ranges touched by MI, assuming a move from OldIdx to NewIdx.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:449
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
void removePhysRegDefAt(unsigned Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
Definition: SlotIndexes.h:242
void setRegisterDefReadUndef(unsigned Reg, bool IsUndef=true)
Mark all subregister defs of register Reg with the undef flag.
bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
bool runOnMachineFunction(MachineFunction &) override
Pass entry point; Calculates LiveIntervals.
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Definition: Interval.h:37
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Segments::iterator iterator
Definition: LiveInterval.h:208
static LaneBitmask getAll()
Definition: LaneBitmask.h:77
vni_iterator vni_begin()
Definition: LiveInterval.h:220
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:638
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
MIBundleOperands - Iterate over all operands in a bundle of machine instructions. ...
iterator end() const
Definition: ArrayRef.h:138
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
void removeMachineInstrFromMaps(MachineInstr &MI)
Removes machine instruction (bundle) MI from the mapping.
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position...
Definition: LiveInterval.h:259
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
INITIALIZE_PASS_BEGIN(LiveIntervals,"liveintervals","Live Interval Analysis", false, false) INITIALIZE_PASS_END(LiveIntervals
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void constructMainRangeFromSubranges(LiveInterval &LI)
For live interval LI with correct SubRanges construct matching information for the main live range...
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
A live range for subregisters.
Definition: LiveInterval.h:645
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:162
I SRs[*I]
Live Interval false
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction, if any.
Definition: LiveInterval.h:147
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
void markUnused()
Mark this value as unused.
Definition: LiveInterval.h:84
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx. ...
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
void print(raw_ostream &O, const Module *=nullptr) const override
Implement the dump method.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:306
bool checkRegMaskInterference(LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
void dump() const
Definition: Pass.cpp:123
void flushSegmentSet()
Flush segment set into the regular segment vector.
bool empty() const
Definition: LiveInterval.h:370
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:409
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
void Distribute(LiveInterval &LI, LiveInterval *LIV[], MachineRegisterInfo &MRI)
Distribute values in LI into a separate LiveIntervals for each connected component.
LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB...
iterator_range< succ_iterator > successors()
This class represents the liveness of a register, stack slot, etc.
Definition: LiveInterval.h:157
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
Definition: SlotIndexes.h:204
void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
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 clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:367
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MCSuperRegIterator enumerates all super-registers of Reg.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
ArrayRef< SlotIndex > getRegMaskSlotsInBlock(unsigned MBBNum) const
Returns a sorted array of slot indices of all instructions with register mask operands in the basic b...
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
Definition: Allocator.h:192
ArrayRef< const uint32_t * > getRegMaskBits() const
Returns an array of register mask pointers corresponding to getRegMaskSlots().
iterator end()
Definition: LiveInterval.h:212
bool hasIndex(const MachineInstr &instr) const
Returns true if the given machine instr is mapped to an index, otherwise returns false.
Definition: SlotIndexes.h:409
VNInfo::Allocator & getVNInfoAllocator()
bool isReg() const
isReg - Tests if this is a MO_Register operand.
iterator_range< subrange_iterator > subranges()
Definition: LiveInterval.h:723
unsigned SubReg
Result of a LiveRange query.
Definition: LiveInterval.h:90
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
bool isUndef() const
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
Definition: SlotIndexes.h:227
Live Interval Analysis
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
Definition: SlotIndexes.h:260
constexpr bool any() const
Definition: LaneBitmask.h:53
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
bool isUnused() const
Returns true if this value is unused.
Definition: LiveInterval.h:81
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
Definition: SlotIndexes.h:430
void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
SlotIndexes pass.
Definition: SlotIndexes.h:331
void constructMainRangeFromSubranges(LiveInterval &LI)
For live interval LI with correct SubRanges construct matching information for the main live range...
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
MCRegUnitRootIterator enumerates the root registers of a register unit.
Segments segments
Definition: LiveInterval.h:199
bool isBundled() const
Return true if this instruction part of a bundle.
Definition: MachineInstr.h:230
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
Definition: LiveInterval.h:129
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses...
static void extendSegmentsToUses(LiveRange &LR, const SlotIndexes &Indexes, ShrinkToUsesWorkList &WorkList, const LiveRange &OldRange)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
AnalysisUsage & addPreservedID(const void *ID)
void extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg, ArrayRef< SlotIndex > Undefs)
Extend the live range of LR to reach Use.
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.cpp:29
char & LiveIntervalsID
LiveIntervals - This analysis keeps track of the live ranges of virtual and physical registers...
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
LiveRange * getCachedRegUnit(unsigned Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo)
Clear all kill flags affecting Reg.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
Definition: SlotIndexes.h:290
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
bool isDebugValue() const
Definition: MachineInstr.h:785
void reset(const MachineFunction *MF, SlotIndexes *, MachineDominatorTree *, VNInfo::Allocator *)
reset - Prepare caches for a new set of non-overlapping live ranges.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
Definition: SlotIndexes.h:577
void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
bool hasAtLeastOneValue() const
Definition: LiveInterval.h:297
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
Definition: BitVector.h:777
SlotIndexes * getSlotIndexes() const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
Definition: LiveInterval.h:529
bool isValid() const
Returns true if this is a valid index.
Definition: SlotIndexes.h:152
iterator_range< reg_instr_iterator > reg_instructions(unsigned Reg) const
unsigned const MachineRegisterInfo * MRI
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
void swap(SmallVectorImpl &RHS)
Definition: SmallVector.h:693
std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Use)
Attempt to extend a value defined after StartIdx to include Use.
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
MachineInstrBuilder & UseMI
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
unsigned Classify(const LiveRange &LR)
Classify the values in LR into connected components.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
Live Interval static false cl::opt< bool > EnablePrecomputePhysRegs("precompute-phys-liveness", cl::Hidden, cl::desc("Eagerly compute live intervals for all physreg units."))
Represent the analysis usage information of a pass.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
void initializeLiveIntervalsPass(PassRegistry &)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
iterator begin() const
Definition: ArrayRef.h:137
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
Definition: LiveInterval.h:135
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
HMEditor(LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
iterator_range< pred_iterator > predecessors()
void verify() const
Walk the range and assert if any invariants fail to hold.
void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< unsigned > OrigRegs)
Update live intervals for instructions in a range of iterators.
unsigned getSubReg() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Definition: LiveInterval.h:78
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
Definition: SlotIndexes.h:424
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
unsigned id
The ID number of this value.
Definition: LiveInterval.h:58
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified segment from this range.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Toolkit used by handleMove to trim or extend live intervals.
ArrayRef< const uint32_t * > getRegMaskBitsInBlock(unsigned MBBNum) const
Returns an array of mask pointers corresponding to getRegMaskSlotsInBlock(MBBNum).
Printable PrintRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
Definition: SlotIndexes.h:198
Segments::const_iterator const_iterator
Definition: LiveInterval.h:209
ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a LiveInterval into equivalence cl...
Definition: LiveInterval.h:918
MachineOperand class - Representation of each machine instruction operand.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
Definition: SlotIndexes.h:533
static LaneBitmask getNone()
Definition: LaneBitmask.h:76
const size_t N
LiveRange * getRegUnitLI(unsigned Unit)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
LiveInterval & getInterval(unsigned Reg)
static float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &Instr)
Calculate the spill weight to assign to a single instruction.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:497
A range adaptor for a pair of iterators.
void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
typename SuperClass::iterator iterator
Definition: SmallVector.h:325
LiveInterval & createEmptyInterval(unsigned Reg)
Interval creation.
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
VNInfoList valnos
Definition: LiveInterval.h:200
void calculate(LiveInterval &LI, bool TrackSubRegs)
Calculates liveness for the register specified in live interval LI.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:373
Representation of each machine instruction.
Definition: MachineInstr.h:59
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
Definition: SlotIndexes.h:210
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addKillFlags(const VirtRegMap *)
Add kill flags to any instruction that kills a virtual register.
VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
createDeadDef - Make sure the range has a value defined at Def.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
Definition: LiveInterval.h:380
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream...
AnalysisUsage & addRequiredTransitiveID(char &ID)
Definition: Pass.cpp:301
AnalysisUsage & addRequiredTransitive()
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:487
bool hasInterval(unsigned Reg) const
bool reg_empty(unsigned RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
Definition: SlotIndexes.h:255
std::vector< uint8_t > Unit
Definition: FuzzerDefs.h:105
iterator begin()
Definition: LiveInterval.h:211
unsigned getReg() const
getReg - Returns the register number.
bool isValid() const
isValid - Returns true until all the operands have been visited.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
VNInfo * getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
Definition: LiveInterval.h:319
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
mop_iterator operands_begin()
Definition: MachineInstr.h:300
static LLVM_ATTRIBUTE_UNUSED Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition: LaneBitmask.h:87
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
void handleMoveIntoBundle(MachineInstr &MI, MachineInstr &BundleStart, bool UpdateFlags=false)
Update intervals for operands of MI so that they begin/end on the SlotIndex for BundleStart.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
bool addRegisterKilled(unsigned IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned getPhys(unsigned virtReg) const
returns the physical register mapped to the specified virtual register
Definition: VirtRegMap.h:98
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
Definition: LiveInterval.h:424
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
Definition: LiveInterval.h:105
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool hasSubRanges() const
Returns true if subregister liveness information is available.
Definition: LiveInterval.h:751
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:84
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
vni_iterator vni_end()
Definition: LiveInterval.h:221
unsigned pred_size() const
bool reg_nodbg_empty(unsigned RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions...
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
Definition: LiveInterval.h:417
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level...
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block...
LiveInterval & createAndComputeVirtRegInterval(unsigned Reg)
static void createSegmentsForValues(LiveRange &LR, iterator_range< LiveInterval::vni_iterator > VNIs)
void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos...
void resize(size_type N)
Definition: SmallVector.h:352
const std::pair< SlotIndex, SlotIndex > & getMBBRange(unsigned Num) const
Return the (start,end) range of the given basic block number.
Definition: SlotIndexes.h:476