LLVM  9.0.0svn
LiveInterval.h
Go to the documentation of this file.
1 //===- llvm/CodeGen/LiveInterval.h - Interval representation ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LiveRange and LiveInterval classes. Given some
10 // numbering of each the machine instructions an interval [i, j) is said to be a
11 // live range for register v if there is no instruction with number j' >= j
12 // such that v is live at j' and there is no instruction with number i' < i such
13 // that v is live at i'. In this implementation ranges can have holes,
14 // i.e. a range might look like [1,20), [50,65), [1000,1001). Each
15 // individual segment is represented as an instance of LiveRange::Segment,
16 // and the whole range is represented as an instance of LiveRange.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLVM_CODEGEN_LIVEINTERVAL_H
21 #define LLVM_CODEGEN_LIVEINTERVAL_H
22 
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/IntEqClasses.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/MC/LaneBitmask.h"
30 #include "llvm/Support/Allocator.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <functional>
36 #include <memory>
37 #include <set>
38 #include <tuple>
39 #include <utility>
40 
41 namespace llvm {
42 
43  class CoalescerPair;
44  class LiveIntervals;
45  class MachineRegisterInfo;
46  class raw_ostream;
47 
48  /// VNInfo - Value Number Information.
49  /// This class holds information about a machine level values, including
50  /// definition and use points.
51  ///
52  class VNInfo {
53  public:
55 
56  /// The ID number of this value.
57  unsigned id;
58 
59  /// The index of the defining instruction.
61 
62  /// VNInfo constructor.
63  VNInfo(unsigned i, SlotIndex d) : id(i), def(d) {}
64 
65  /// VNInfo constructor, copies values from orig, except for the value number.
66  VNInfo(unsigned i, const VNInfo &orig) : id(i), def(orig.def) {}
67 
68  /// Copy from the parameter into this VNInfo.
69  void copyFrom(VNInfo &src) {
70  def = src.def;
71  }
72 
73  /// Returns true if this value is defined by a PHI instruction (or was,
74  /// PHI instructions may have been eliminated).
75  /// PHI-defs begin at a block boundary, all other defs begin at register or
76  /// EC slots.
77  bool isPHIDef() const { return def.isBlock(); }
78 
79  /// Returns true if this value is unused.
80  bool isUnused() const { return !def.isValid(); }
81 
82  /// Mark this value as unused.
83  void markUnused() { def = SlotIndex(); }
84  };
85 
86  /// Result of a LiveRange query. This class hides the implementation details
87  /// of live ranges, and it should be used as the primary interface for
88  /// examining live ranges around instructions.
90  VNInfo *const EarlyVal;
91  VNInfo *const LateVal;
92  const SlotIndex EndPoint;
93  const bool Kill;
94 
95  public:
96  LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint,
97  bool Kill)
98  : EarlyVal(EarlyVal), LateVal(LateVal), EndPoint(EndPoint), Kill(Kill)
99  {}
100 
101  /// Return the value that is live-in to the instruction. This is the value
102  /// that will be read by the instruction's use operands. Return NULL if no
103  /// value is live-in.
104  VNInfo *valueIn() const {
105  return EarlyVal;
106  }
107 
108  /// Return true if the live-in value is killed by this instruction. This
109  /// means that either the live range ends at the instruction, or it changes
110  /// value.
111  bool isKill() const {
112  return Kill;
113  }
114 
115  /// Return true if this instruction has a dead def.
116  bool isDeadDef() const {
117  return EndPoint.isDead();
118  }
119 
120  /// Return the value leaving the instruction, if any. This can be a
121  /// live-through value, or a live def. A dead def returns NULL.
122  VNInfo *valueOut() const {
123  return isDeadDef() ? nullptr : LateVal;
124  }
125 
126  /// Returns the value alive at the end of the instruction, if any. This can
127  /// be a live-through value, a live def or a dead def.
129  return LateVal;
130  }
131 
132  /// Return the value defined by this instruction, if any. This includes
133  /// dead defs, it is the value created by the instruction's def operands.
134  VNInfo *valueDefined() const {
135  return EarlyVal == LateVal ? nullptr : LateVal;
136  }
137 
138  /// Return the end point of the last live range segment to interact with
139  /// the instruction, if any.
140  ///
141  /// The end point is an invalid SlotIndex only if the live range doesn't
142  /// intersect the instruction at all.
143  ///
144  /// The end point may be at or past the end of the instruction's basic
145  /// block. That means the value was live out of the block.
146  SlotIndex endPoint() const {
147  return EndPoint;
148  }
149  };
150 
151  /// This class represents the liveness of a register, stack slot, etc.
152  /// It manages an ordered list of Segment objects.
153  /// The Segments are organized in a static single assignment form: At places
154  /// where a new value is defined or different values reach a CFG join a new
155  /// segment with a new value number is used.
156  class LiveRange {
157  public:
158  /// This represents a simple continuous liveness interval for a value.
159  /// The start point is inclusive, the end point exclusive. These intervals
160  /// are rendered as [start,end).
161  struct Segment {
162  SlotIndex start; // Start point of the interval (inclusive)
163  SlotIndex end; // End point of the interval (exclusive)
164  VNInfo *valno = nullptr; // identifier for the value contained in this
165  // segment.
166 
167  Segment() = default;
168 
170  : start(S), end(E), valno(V) {
171  assert(S < E && "Cannot create empty or backwards segment");
172  }
173 
174  /// Return true if the index is covered by this segment.
175  bool contains(SlotIndex I) const {
176  return start <= I && I < end;
177  }
178 
179  /// Return true if the given interval, [S, E), is covered by this segment.
181  assert((S < E) && "Backwards interval?");
182  return (start <= S && S < end) && (start < E && E <= end);
183  }
184 
185  bool operator<(const Segment &Other) const {
186  return std::tie(start, end) < std::tie(Other.start, Other.end);
187  }
188  bool operator==(const Segment &Other) const {
189  return start == Other.start && end == Other.end;
190  }
191 
192  void dump() const;
193  };
194 
197 
198  Segments segments; // the liveness segments
199  VNInfoList valnos; // value#'s
200 
201  // The segment set is used temporarily to accelerate initial computation
202  // of live ranges of physical registers in computeRegUnitRange.
203  // After that the set is flushed to the segment vector and deleted.
204  using SegmentSet = std::set<Segment>;
205  std::unique_ptr<SegmentSet> segmentSet;
206 
208  using const_iterator = Segments::const_iterator;
209 
210  iterator begin() { return segments.begin(); }
211  iterator end() { return segments.end(); }
212 
213  const_iterator begin() const { return segments.begin(); }
214  const_iterator end() const { return segments.end(); }
215 
218 
219  vni_iterator vni_begin() { return valnos.begin(); }
220  vni_iterator vni_end() { return valnos.end(); }
221 
222  const_vni_iterator vni_begin() const { return valnos.begin(); }
223  const_vni_iterator vni_end() const { return valnos.end(); }
224 
225  /// Constructs a new LiveRange object.
226  LiveRange(bool UseSegmentSet = false)
227  : segmentSet(UseSegmentSet ? llvm::make_unique<SegmentSet>()
228  : nullptr) {}
229 
230  /// Constructs a new LiveRange object by copying segments and valnos from
231  /// another LiveRange.
233  assert(Other.segmentSet == nullptr &&
234  "Copying of LiveRanges with active SegmentSets is not supported");
235  assign(Other, Allocator);
236  }
237 
238  /// Copies values numbers and live segments from \p Other into this range.
240  if (this == &Other)
241  return;
242 
243  assert(Other.segmentSet == nullptr &&
244  "Copying of LiveRanges with active SegmentSets is not supported");
245  // Duplicate valnos.
246  for (const VNInfo *VNI : Other.valnos)
247  createValueCopy(VNI, Allocator);
248  // Now we can copy segments and remap their valnos.
249  for (const Segment &S : Other.segments)
250  segments.push_back(Segment(S.start, S.end, valnos[S.valno->id]));
251  }
252 
253  /// advanceTo - Advance the specified iterator to point to the Segment
254  /// containing the specified position, or end() if the position is past the
255  /// end of the range. If no Segment contains this position, but the
256  /// position is in a hole, this method returns an iterator pointing to the
257  /// Segment immediately after the hole.
259  assert(I != end());
260  if (Pos >= endIndex())
261  return end();
262  while (I->end <= Pos) ++I;
263  return I;
264  }
265 
267  assert(I != end());
268  if (Pos >= endIndex())
269  return end();
270  while (I->end <= Pos) ++I;
271  return I;
272  }
273 
274  /// find - Return an iterator pointing to the first segment that ends after
275  /// Pos, or end(). This is the same as advanceTo(begin(), Pos), but faster
276  /// when searching large ranges.
277  ///
278  /// If Pos is contained in a Segment, that segment is returned.
279  /// If Pos is in a hole, the following Segment is returned.
280  /// If Pos is beyond endIndex, end() is returned.
281  iterator find(SlotIndex Pos);
282 
284  return const_cast<LiveRange*>(this)->find(Pos);
285  }
286 
287  void clear() {
288  valnos.clear();
289  segments.clear();
290  }
291 
292  size_t size() const {
293  return segments.size();
294  }
295 
296  bool hasAtLeastOneValue() const { return !valnos.empty(); }
297 
298  bool containsOneValue() const { return valnos.size() == 1; }
299 
300  unsigned getNumValNums() const { return (unsigned)valnos.size(); }
301 
302  /// getValNumInfo - Returns pointer to the specified val#.
303  ///
304  inline VNInfo *getValNumInfo(unsigned ValNo) {
305  return valnos[ValNo];
306  }
307  inline const VNInfo *getValNumInfo(unsigned ValNo) const {
308  return valnos[ValNo];
309  }
310 
311  /// containsValue - Returns true if VNI belongs to this range.
312  bool containsValue(const VNInfo *VNI) const {
313  return VNI && VNI->id < getNumValNums() && VNI == getValNumInfo(VNI->id);
314  }
315 
316  /// getNextValue - Create a new value number and return it. MIIdx specifies
317  /// the instruction that defines the value number.
319  VNInfo *VNI =
320  new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
321  valnos.push_back(VNI);
322  return VNI;
323  }
324 
325  /// createDeadDef - Make sure the range has a value defined at Def.
326  /// If one already exists, return it. Otherwise allocate a new value and
327  /// add liveness for a dead def.
329 
330  /// Create a def of value @p VNI. Return @p VNI. If there already exists
331  /// a definition at VNI->def, the value defined there must be @p VNI.
332  VNInfo *createDeadDef(VNInfo *VNI);
333 
334  /// Create a copy of the given value. The new value will be identical except
335  /// for the Value number.
337  VNInfo::Allocator &VNInfoAllocator) {
338  VNInfo *VNI =
339  new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), *orig);
340  valnos.push_back(VNI);
341  return VNI;
342  }
343 
344  /// RenumberValues - Renumber all values in order of appearance and remove
345  /// unused values.
346  void RenumberValues();
347 
348  /// MergeValueNumberInto - This method is called when two value numbers
349  /// are found to be equivalent. This eliminates V1, replacing all
350  /// segments with the V1 value number with the V2 value number. This can
351  /// cause merging of V1/V2 values numbers and compaction of the value space.
352  VNInfo* MergeValueNumberInto(VNInfo *V1, VNInfo *V2);
353 
354  /// Merge all of the live segments of a specific val# in RHS into this live
355  /// range as the specified value number. The segments in RHS are allowed
356  /// to overlap with segments in the current range, it will replace the
357  /// value numbers of the overlaped live segments with the specified value
358  /// number.
359  void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo);
360 
361  /// MergeValueInAsValue - Merge all of the segments of a specific val#
362  /// in RHS into this live range as the specified value number.
363  /// The segments in RHS are allowed to overlap with segments in the
364  /// current range, but only if the overlapping segments have the
365  /// specified value number.
366  void MergeValueInAsValue(const LiveRange &RHS,
367  const VNInfo *RHSValNo, VNInfo *LHSValNo);
368 
369  bool empty() const { return segments.empty(); }
370 
371  /// beginIndex - Return the lowest numbered slot covered.
373  assert(!empty() && "Call to beginIndex() on empty range.");
374  return segments.front().start;
375  }
376 
377  /// endNumber - return the maximum point of the range of the whole,
378  /// exclusive.
379  SlotIndex endIndex() const {
380  assert(!empty() && "Call to endIndex() on empty range.");
381  return segments.back().end;
382  }
383 
384  bool expiredAt(SlotIndex index) const {
385  return index >= endIndex();
386  }
387 
388  bool liveAt(SlotIndex index) const {
389  const_iterator r = find(index);
390  return r != end() && r->start <= index;
391  }
392 
393  /// Return the segment that contains the specified index, or null if there
394  /// is none.
396  const_iterator I = FindSegmentContaining(Idx);
397  return I == end() ? nullptr : &*I;
398  }
399 
400  /// Return the live segment that contains the specified index, or null if
401  /// there is none.
403  iterator I = FindSegmentContaining(Idx);
404  return I == end() ? nullptr : &*I;
405  }
406 
407  /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
409  const_iterator I = FindSegmentContaining(Idx);
410  return I == end() ? nullptr : I->valno;
411  }
412 
413  /// getVNInfoBefore - Return the VNInfo that is live up to but not
414  /// necessarilly including Idx, or NULL. Use this to find the reaching def
415  /// used by an instruction at this SlotIndex position.
417  const_iterator I = FindSegmentContaining(Idx.getPrevSlot());
418  return I == end() ? nullptr : I->valno;
419  }
420 
421  /// Return an iterator to the segment that contains the specified index, or
422  /// end() if there is none.
424  iterator I = find(Idx);
425  return I != end() && I->start <= Idx ? I : end();
426  }
427 
429  const_iterator I = find(Idx);
430  return I != end() && I->start <= Idx ? I : end();
431  }
432 
433  /// overlaps - Return true if the intersection of the two live ranges is
434  /// not empty.
435  bool overlaps(const LiveRange &other) const {
436  if (other.empty())
437  return false;
438  return overlapsFrom(other, other.begin());
439  }
440 
441  /// overlaps - Return true if the two ranges have overlapping segments
442  /// that are not coalescable according to CP.
443  ///
444  /// Overlapping segments where one range is defined by a coalescable
445  /// copy are allowed.
446  bool overlaps(const LiveRange &Other, const CoalescerPair &CP,
447  const SlotIndexes&) const;
448 
449  /// overlaps - Return true if the live range overlaps an interval specified
450  /// by [Start, End).
451  bool overlaps(SlotIndex Start, SlotIndex End) const;
452 
453  /// overlapsFrom - Return true if the intersection of the two live ranges
454  /// is not empty. The specified iterator is a hint that we can begin
455  /// scanning the Other range starting at I.
456  bool overlapsFrom(const LiveRange &Other, const_iterator StartPos) const;
457 
458  /// Returns true if all segments of the @p Other live range are completely
459  /// covered by this live range.
460  /// Adjacent live ranges do not affect the covering:the liverange
461  /// [1,5](5,10] covers (3,7].
462  bool covers(const LiveRange &Other) const;
463 
464  /// Add the specified Segment to this range, merging segments as
465  /// appropriate. This returns an iterator to the inserted segment (which
466  /// may have grown since it was inserted).
467  iterator addSegment(Segment S);
468 
469  /// Attempt to extend a value defined after @p StartIdx to include @p Use.
470  /// Both @p StartIdx and @p Use should be in the same basic block. In case
471  /// of subranges, an extension could be prevented by an explicit "undef"
472  /// caused by a <def,read-undef> on a non-overlapping lane. The list of
473  /// location of such "undefs" should be provided in @p Undefs.
474  /// The return value is a pair: the first element is VNInfo of the value
475  /// that was extended (possibly nullptr), the second is a boolean value
476  /// indicating whether an "undef" was encountered.
477  /// If this range is live before @p Use in the basic block that starts at
478  /// @p StartIdx, and there is no intervening "undef", extend it to be live
479  /// up to @p Use, and return the pair {value, false}. If there is no
480  /// segment before @p Use and there is no "undef" between @p StartIdx and
481  /// @p Use, return {nullptr, false}. If there is an "undef" before @p Use,
482  /// return {nullptr, true}.
483  std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
484  SlotIndex StartIdx, SlotIndex Kill);
485 
486  /// Simplified version of the above "extendInBlock", which assumes that
487  /// no register lanes are undefined by <def,read-undef> operands.
488  /// If this range is live before @p Use in the basic block that starts
489  /// at @p StartIdx, extend it to be live up to @p Use, and return the
490  /// value. If there is no segment before @p Use, return nullptr.
491  VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Kill);
492 
493  /// join - Join two live ranges (this, and other) together. This applies
494  /// mappings to the value numbers in the LHS/RHS ranges as specified. If
495  /// the ranges are not joinable, this aborts.
496  void join(LiveRange &Other,
497  const int *ValNoAssignments,
498  const int *RHSValNoAssignments,
499  SmallVectorImpl<VNInfo *> &NewVNInfo);
500 
501  /// True iff this segment is a single segment that lies between the
502  /// specified boundaries, exclusively. Vregs live across a backedge are not
503  /// considered local. The boundaries are expected to lie within an extended
504  /// basic block, so vregs that are not live out should contain no holes.
505  bool isLocal(SlotIndex Start, SlotIndex End) const {
506  return beginIndex() > Start.getBaseIndex() &&
507  endIndex() < End.getBoundaryIndex();
508  }
509 
510  /// Remove the specified segment from this range. Note that the segment
511  /// must be a single Segment in its entirety.
512  void removeSegment(SlotIndex Start, SlotIndex End,
513  bool RemoveDeadValNo = false);
514 
515  void removeSegment(Segment S, bool RemoveDeadValNo = false) {
516  removeSegment(S.start, S.end, RemoveDeadValNo);
517  }
518 
519  /// Remove segment pointed to by iterator @p I from this range. This does
520  /// not remove dead value numbers.
522  return segments.erase(I);
523  }
524 
525  /// Query Liveness at Idx.
526  /// The sub-instruction slot of Idx doesn't matter, only the instruction
527  /// it refers to is considered.
529  // Find the segment that enters the instruction.
531  const_iterator E = end();
532  if (I == E)
533  return LiveQueryResult(nullptr, nullptr, SlotIndex(), false);
534 
535  // Is this an instruction live-in segment?
536  // If Idx is the start index of a basic block, include live-in segments
537  // that start at Idx.getBaseIndex().
538  VNInfo *EarlyVal = nullptr;
539  VNInfo *LateVal = nullptr;
540  SlotIndex EndPoint;
541  bool Kill = false;
542  if (I->start <= Idx.getBaseIndex()) {
543  EarlyVal = I->valno;
544  EndPoint = I->end;
545  // Move to the potentially live-out segment.
546  if (SlotIndex::isSameInstr(Idx, I->end)) {
547  Kill = true;
548  if (++I == E)
549  return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
550  }
551  // Special case: A PHIDef value can have its def in the middle of a
552  // segment if the value happens to be live out of the layout
553  // predecessor.
554  // Such a value is not live-in.
555  if (EarlyVal->def == Idx.getBaseIndex())
556  EarlyVal = nullptr;
557  }
558  // I now points to the segment that may be live-through, or defined by
559  // this instr. Ignore segments starting after the current instr.
560  if (!SlotIndex::isEarlierInstr(Idx, I->start)) {
561  LateVal = I->valno;
562  EndPoint = I->end;
563  }
564  return LiveQueryResult(EarlyVal, LateVal, EndPoint, Kill);
565  }
566 
567  /// removeValNo - Remove all the segments defined by the specified value#.
568  /// Also remove the value# from value# list.
569  void removeValNo(VNInfo *ValNo);
570 
571  /// Returns true if the live range is zero length, i.e. no live segments
572  /// span instructions. It doesn't pay to spill such a range.
573  bool isZeroLength(SlotIndexes *Indexes) const {
574  for (const Segment &S : segments)
575  if (Indexes->getNextNonNullIndex(S.start).getBaseIndex() <
576  S.end.getBaseIndex())
577  return false;
578  return true;
579  }
580 
581  // Returns true if any segment in the live range contains any of the
582  // provided slot indexes. Slots which occur in holes between
583  // segments will not cause the function to return true.
584  bool isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const;
585 
586  bool operator<(const LiveRange& other) const {
587  const SlotIndex &thisIndex = beginIndex();
588  const SlotIndex &otherIndex = other.beginIndex();
589  return thisIndex < otherIndex;
590  }
591 
592  /// Returns true if there is an explicit "undef" between @p Begin
593  /// @p End.
595  SlotIndex End) const {
596  return std::any_of(Undefs.begin(), Undefs.end(),
597  [Begin,End] (SlotIndex Idx) -> bool {
598  return Begin <= Idx && Idx < End;
599  });
600  }
601 
602  /// Flush segment set into the regular segment vector.
603  /// The method is to be called after the live range
604  /// has been created, if use of the segment set was
605  /// activated in the constructor of the live range.
606  void flushSegmentSet();
607 
608  void print(raw_ostream &OS) const;
609  void dump() const;
610 
611  /// Walk the range and assert if any invariants fail to hold.
612  ///
613  /// Note that this is a no-op when asserts are disabled.
614 #ifdef NDEBUG
615  void verify() const {}
616 #else
617  void verify() const;
618 #endif
619 
620  protected:
621  /// Append a segment to the list of segments.
622  void append(const LiveRange::Segment S);
623 
624  private:
625  friend class LiveRangeUpdater;
626  void addSegmentToSet(Segment S);
627  void markValNoForDeletion(VNInfo *V);
628  };
629 
630  inline raw_ostream &operator<<(raw_ostream &OS, const LiveRange &LR) {
631  LR.print(OS);
632  return OS;
633  }
634 
635  /// LiveInterval - This class represents the liveness of a register,
636  /// or stack slot.
637  class LiveInterval : public LiveRange {
638  public:
639  using super = LiveRange;
640 
641  /// A live range for subregisters. The LaneMask specifies which parts of the
642  /// super register are covered by the interval.
643  /// (@sa TargetRegisterInfo::getSubRegIndexLaneMask()).
644  class SubRange : public LiveRange {
645  public:
646  SubRange *Next = nullptr;
648 
649  /// Constructs a new SubRange object.
650  SubRange(LaneBitmask LaneMask) : LaneMask(LaneMask) {}
651 
652  /// Constructs a new SubRange object by copying liveness from @p Other.
653  SubRange(LaneBitmask LaneMask, const LiveRange &Other,
655  : LiveRange(Other, Allocator), LaneMask(LaneMask) {}
656 
657  void print(raw_ostream &OS) const;
658  void dump() const;
659  };
660 
661  private:
662  SubRange *SubRanges = nullptr; ///< Single linked list of subregister live
663  /// ranges.
664 
665  public:
666  const unsigned reg; // the register or stack slot of this interval.
667  float weight; // weight of this interval
668 
669  LiveInterval(unsigned Reg, float Weight) : reg(Reg), weight(Weight) {}
670 
672  clearSubRanges();
673  }
674 
675  template<typename T>
677  T *P;
678 
679  public:
681 
683  P = P->Next;
684  return *this;
685  }
687  SingleLinkedListIterator res = *this;
688  ++*this;
689  return res;
690  }
692  return P != Other.operator->();
693  }
695  return P == Other.operator->();
696  }
697  T &operator*() const {
698  return *P;
699  }
700  T *operator->() const {
701  return P;
702  }
703  };
704 
707 
709  return subrange_iterator(SubRanges);
710  }
712  return subrange_iterator(nullptr);
713  }
714 
716  return const_subrange_iterator(SubRanges);
717  }
719  return const_subrange_iterator(nullptr);
720  }
721 
723  return make_range(subrange_begin(), subrange_end());
724  }
725 
727  return make_range(subrange_begin(), subrange_end());
728  }
729 
730  /// Creates a new empty subregister live range. The range is added at the
731  /// beginning of the subrange list; subrange iterators stay valid.
733  LaneBitmask LaneMask) {
734  SubRange *Range = new (Allocator) SubRange(LaneMask);
735  appendSubRange(Range);
736  return Range;
737  }
738 
739  /// Like createSubRange() but the new range is filled with a copy of the
740  /// liveness information in @p CopyFrom.
742  LaneBitmask LaneMask,
743  const LiveRange &CopyFrom) {
744  SubRange *Range = new (Allocator) SubRange(LaneMask, CopyFrom, Allocator);
745  appendSubRange(Range);
746  return Range;
747  }
748 
749  /// Returns true if subregister liveness information is available.
750  bool hasSubRanges() const {
751  return SubRanges != nullptr;
752  }
753 
754  /// Removes all subregister liveness information.
755  void clearSubRanges();
756 
757  /// Removes all subranges without any segments (subranges without segments
758  /// are not considered valid and should only exist temporarily).
759  void removeEmptySubRanges();
760 
761  /// getSize - Returns the sum of sizes of all the LiveRange's.
762  ///
763  unsigned getSize() const;
764 
765  /// isSpillable - Can this interval be spilled?
766  bool isSpillable() const {
767  return weight != huge_valf;
768  }
769 
770  /// markNotSpillable - Mark interval as not spillable
772  weight = huge_valf;
773  }
774 
775  /// For a given lane mask @p LaneMask, compute indexes at which the
776  /// lane is marked undefined by subregister <def,read-undef> definitions.
777  void computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
778  LaneBitmask LaneMask,
779  const MachineRegisterInfo &MRI,
780  const SlotIndexes &Indexes) const;
781 
782  /// Refines the subranges to support \p LaneMask. This may only be called
783  /// for LI.hasSubrange()==true. Subregister ranges are split or created
784  /// until \p LaneMask can be matched exactly. \p Mod is executed on the
785  /// matching subranges.
786  ///
787  /// Example:
788  /// Given an interval with subranges with lanemasks L0F00, L00F0 and
789  /// L000F, refining for mask L0018. Will split the L00F0 lane into
790  /// L00E0 and L0010 and the L000F lane into L0007 and L0008. The Mod
791  /// function will be applied to the L0010 and L0008 subranges.
792  void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
793  std::function<void(LiveInterval::SubRange&)> Apply);
794 
795  bool operator<(const LiveInterval& other) const {
796  const SlotIndex &thisIndex = beginIndex();
797  const SlotIndex &otherIndex = other.beginIndex();
798  return std::tie(thisIndex, reg) < std::tie(otherIndex, other.reg);
799  }
800 
801  void print(raw_ostream &OS) const;
802  void dump() const;
803 
804  /// Walks the interval and assert if any invariants fail to hold.
805  ///
806  /// Note that this is a no-op when asserts are disabled.
807 #ifdef NDEBUG
808  void verify(const MachineRegisterInfo *MRI = nullptr) const {}
809 #else
810  void verify(const MachineRegisterInfo *MRI = nullptr) const;
811 #endif
812 
813  private:
814  /// Appends @p Range to SubRanges list.
815  void appendSubRange(SubRange *Range) {
816  Range->Next = SubRanges;
817  SubRanges = Range;
818  }
819 
820  /// Free memory held by SubRange.
821  void freeSubRange(SubRange *S);
822  };
823 
825  const LiveInterval::SubRange &SR) {
826  SR.print(OS);
827  return OS;
828  }
829 
830  inline raw_ostream &operator<<(raw_ostream &OS, const LiveInterval &LI) {
831  LI.print(OS);
832  return OS;
833  }
834 
836 
837  inline bool operator<(SlotIndex V, const LiveRange::Segment &S) {
838  return V < S.start;
839  }
840 
841  inline bool operator<(const LiveRange::Segment &S, SlotIndex V) {
842  return S.start < V;
843  }
844 
845  /// Helper class for performant LiveRange bulk updates.
846  ///
847  /// Calling LiveRange::addSegment() repeatedly can be expensive on large
848  /// live ranges because segments after the insertion point may need to be
849  /// shifted. The LiveRangeUpdater class can defer the shifting when adding
850  /// many segments in order.
851  ///
852  /// The LiveRange will be in an invalid state until flush() is called.
854  LiveRange *LR;
855  SlotIndex LastStart;
856  LiveRange::iterator WriteI;
857  LiveRange::iterator ReadI;
859  void mergeSpills();
860 
861  public:
862  /// Create a LiveRangeUpdater for adding segments to LR.
863  /// LR will temporarily be in an invalid state until flush() is called.
864  LiveRangeUpdater(LiveRange *lr = nullptr) : LR(lr) {}
865 
866  ~LiveRangeUpdater() { flush(); }
867 
868  /// Add a segment to LR and coalesce when possible, just like
869  /// LR.addSegment(). Segments should be added in increasing start order for
870  /// best performance.
871  void add(LiveRange::Segment);
872 
873  void add(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
874  add(LiveRange::Segment(Start, End, VNI));
875  }
876 
877  /// Return true if the LR is currently in an invalid state, and flush()
878  /// needs to be called.
879  bool isDirty() const { return LastStart.isValid(); }
880 
881  /// Flush the updater state to LR so it is valid and contains all added
882  /// segments.
883  void flush();
884 
885  /// Select a different destination live range.
886  void setDest(LiveRange *lr) {
887  if (LR != lr && isDirty())
888  flush();
889  LR = lr;
890  }
891 
892  /// Get the current destination live range.
893  LiveRange *getDest() const { return LR; }
894 
895  void dump() const;
896  void print(raw_ostream&) const;
897  };
898 
900  X.print(OS);
901  return OS;
902  }
903 
904  /// ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a
905  /// LiveInterval into equivalence clases of connected components. A
906  /// LiveInterval that has multiple connected components can be broken into
907  /// multiple LiveIntervals.
908  ///
909  /// Given a LiveInterval that may have multiple connected components, run:
910  ///
911  /// unsigned numComps = ConEQ.Classify(LI);
912  /// if (numComps > 1) {
913  /// // allocate numComps-1 new LiveIntervals into LIS[1..]
914  /// ConEQ.Distribute(LIS);
915  /// }
916 
918  LiveIntervals &LIS;
919  IntEqClasses EqClass;
920 
921  public:
922  explicit ConnectedVNInfoEqClasses(LiveIntervals &lis) : LIS(lis) {}
923 
924  /// Classify the values in \p LR into connected components.
925  /// Returns the number of connected components.
926  unsigned Classify(const LiveRange &LR);
927 
928  /// getEqClass - Classify creates equivalence classes numbered 0..N. Return
929  /// the equivalence class assigned the VNI.
930  unsigned getEqClass(const VNInfo *VNI) const { return EqClass[VNI->id]; }
931 
932  /// Distribute values in \p LI into a separate LiveIntervals
933  /// for each connected component. LIV must have an empty LiveInterval for
934  /// each additional connected component. The first connected component is
935  /// left in \p LI.
936  void Distribute(LiveInterval &LI, LiveInterval *LIV[],
938  };
939 
940 } // end namespace llvm
941 
942 #endif // LLVM_CODEGEN_LIVEINTERVAL_H
std::set< Segment > SegmentSet
Definition: LiveInterval.h:204
bool empty() const
Definition: LiveInterval.h:369
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:77
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:258
A common definition of LaneBitmask for use in TableGen and CodeGen.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
VNInfo(unsigned i, SlotIndex d)
VNInfo constructor.
Definition: LiveInterval.h:63
const unsigned reg
Definition: LiveInterval.h:666
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:320
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
Definition: SlotIndexes.h:241
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:60
This class represents lattice values for constants.
Definition: AllocatorList.h:23
iterator begin() const
Definition: ArrayRef.h:136
const_subrange_iterator subrange_begin() const
Definition: LiveInterval.h:715
Segment * getSegmentContaining(SlotIndex Idx)
Return the live segment that contains the specified index, or null if there is none.
Definition: LiveInterval.h:402
VNInfoList::iterator vni_iterator
Definition: LiveInterval.h:216
Segments::iterator iterator
Definition: LiveInterval.h:207
SubRange(LaneBitmask LaneMask)
Constructs a new SubRange object.
Definition: LiveInterval.h:650
void push_back(const T &Elt)
Definition: SmallVector.h:211
vni_iterator vni_begin()
Definition: LiveInterval.h:219
bool isUndefIn(ArrayRef< SlotIndex > Undefs, SlotIndex Begin, SlotIndex End) const
Returns true if there is an explicit "undef" between Begin End.
Definition: LiveInterval.h:594
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:637
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position...
Definition: LiveInterval.h:258
unsigned Reg
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
Definition: SlotIndexes.h:236
LiveRangeUpdater(LiveRange *lr=nullptr)
Create a LiveRangeUpdater for adding segments to LR.
Definition: LiveInterval.h:864
bool isDeadDef() const
Return true if this instruction has a dead def.
Definition: LiveInterval.h:116
LiveInterval(unsigned Reg, float Weight)
Definition: LiveInterval.h:669
A live range for subregisters.
Definition: LiveInterval.h:644
bool isValid() const
Returns true if this is a valid index.
Definition: SlotIndexes.h:151
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:161
void markUnused()
Mark this value as unused.
Definition: LiveInterval.h:83
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1348
SubRange * createSubRangeFrom(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, const LiveRange &CopyFrom)
Like createSubRange() but the new range is filled with a copy of the liveness information in CopyFrom...
Definition: LiveInterval.h:741
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
Definition: LiveInterval.h:122
VNInfo - Value Number Information.
Definition: LiveInterval.h:52
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
const_iterator find(SlotIndex Pos) const
Definition: LiveInterval.h:283
This class represents the liveness of a register, stack slot, etc.
Definition: LiveInterval.h:156
bool isUnused() const
Returns true if this value is unused.
Definition: LiveInterval.h:80
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
Definition: SlotIndexes.h:203
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:479
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
Definition: SlotIndexes.h:226
bool operator<(const Segment &Other) const
Definition: LiveInterval.h:185
iterator end()
Definition: LiveInterval.h:211
A helper class for register coalescers.
iterator_range< subrange_iterator > subranges()
Definition: LiveInterval.h:722
Result of a LiveRange query.
Definition: LiveInterval.h:89
const_iterator end() const
Definition: LiveInterval.h:214
SingleLinkedListIterator< T > & operator++()
Definition: LiveInterval.h:682
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Definition: StringExtras.h:370
bool hasSubRanges() const
Returns true if subregister liveness information is available.
Definition: LiveInterval.h:750
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:808
unsigned getEqClass(const VNInfo *VNI) const
getEqClass - Classify creates equivalence classes numbered 0..N.
Definition: LiveInterval.h:930
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
Definition: SlotIndexes.h:433
bool contains(SlotIndex I) const
Return true if the index is covered by this segment.
Definition: LiveInterval.h:175
SlotIndexes pass.
Definition: SlotIndexes.h:328
const_iterator advanceTo(const_iterator I, SlotIndex Pos) const
Definition: LiveInterval.h:266
LiveQueryResult(VNInfo *EarlyVal, VNInfo *LateVal, SlotIndex EndPoint, bool Kill)
Definition: LiveInterval.h:96
Segments segments
Definition: LiveInterval.h:198
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
bool operator<(const LiveRange &other) const
Definition: LiveInterval.h:586
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.cpp:28
LiveRange(const LiveRange &Other, BumpPtrAllocator &Allocator)
Constructs a new LiveRange object by copying segments and valnos from another LiveRange.
Definition: LiveInterval.h:232
size_t size() const
Definition: LiveInterval.h:292
bool isKill() const
Return true if the live-in value is killed by this instruction.
Definition: LiveInterval.h:111
bool isZeroLength(SlotIndexes *Indexes) const
Returns true if the live range is zero length, i.e.
Definition: LiveInterval.h:573
void print(raw_ostream &OS) const
void copyFrom(VNInfo &src)
Copy from the parameter into this VNInfo.
Definition: LiveInterval.h:69
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
Definition: LiveInterval.h:104
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
Definition: LiveInterval.h:528
bool containsOneValue() const
Definition: LiveInterval.h:298
iterator_range< const_subrange_iterator > subranges() const
Definition: LiveInterval.h:726
BumpPtrAllocator Allocator
Definition: LiveInterval.h:54
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:408
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:434
#define P(N)
SubRange(LaneBitmask LaneMask, const LiveRange &Other, BumpPtrAllocator &Allocator)
Constructs a new SubRange object by copying liveness from Other.
Definition: LiveInterval.h:653
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
Definition: LiveInterval.h:379
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
Definition: LiveInterval.h:732
void removeSegment(Segment S, bool RemoveDeadValNo=false)
Definition: LiveInterval.h:515
unsigned const MachineRegisterInfo * MRI
VNInfoList::const_iterator const_vni_iterator
Definition: LiveInterval.h:217
bool expiredAt(SlotIndex index) const
Definition: LiveInterval.h:384
void print(raw_ostream &OS) const
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:388
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LiveRange(bool UseSegmentSet=false)
Constructs a new LiveRange object.
Definition: LiveInterval.h:226
bool containsValue(const VNInfo *VNI) const
containsValue - Returns true if VNI belongs to this range.
Definition: LiveInterval.h:312
void setDest(LiveRange *lr)
Select a different destination live range.
Definition: LiveInterval.h:886
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:1192
void add(SlotIndex Start, SlotIndex End, VNInfo *VNI)
Definition: LiveInterval.h:873
bool operator<(const LiveInterval &other) const
Definition: LiveInterval.h:795
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
iterator removeSegment(iterator I)
Remove segment pointed to by iterator I from this range.
Definition: LiveInterval.h:521
iterator erase(const_iterator CI)
Definition: SmallVector.h:437
void print(raw_ostream &) const
const_vni_iterator vni_begin() const
Definition: LiveInterval.h:222
size_t size() const
Definition: SmallVector.h:52
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
VNInfo(unsigned i, const VNInfo &orig)
VNInfo constructor, copies values from orig, except for the value number.
Definition: LiveInterval.h:66
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction, if any.
Definition: LiveInterval.h:146
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
const_iterator FindSegmentContaining(SlotIndex Idx) const
Definition: LiveInterval.h:428
unsigned id
The ID number of this value.
Definition: LiveInterval.h:57
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
ConnectedVNInfoEqClasses(LiveIntervals &lis)
Definition: LiveInterval.h:922
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
Definition: SlotIndexes.h:197
Segments::const_iterator const_iterator
Definition: LiveInterval.h:208
ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a LiveInterval into equivalence cl...
Definition: LiveInterval.h:917
bool isDirty() const
Return true if the LR is currently in an invalid state, and flush() needs to be called.
Definition: LiveInterval.h:879
const_iterator begin() const
Definition: LiveInterval.h:213
iterator end() const
Definition: ArrayRef.h:137
bool operator==(const SingleLinkedListIterator< T > &Other)
Definition: LiveInterval.h:694
std::unique_ptr< SegmentSet > segmentSet
Definition: LiveInterval.h:205
void markNotSpillable()
markNotSpillable - Mark interval as not spillable
Definition: LiveInterval.h:771
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
Definition: LiveInterval.h:416
A range adaptor for a pair of iterators.
bool hasAtLeastOneValue() const
Definition: LiveInterval.h:296
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
Definition: LiveInterval.h:128
LiveRange * getDest() const
Get the current destination live range.
Definition: LiveInterval.h:893
typename SuperClass::iterator iterator
Definition: SmallVector.h:319
VNInfoList valnos
Definition: LiveInterval.h:199
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
Definition: LiveInterval.h:304
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
bool operator==(const Segment &Other) const
Definition: LiveInterval.h:188
unsigned getNumValNums() const
Definition: LiveInterval.h:300
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
Definition: LiveInterval.h:435
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
Definition: LiveInterval.h:239
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
Definition: SlotIndexes.h:289
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
#define I(x, y, z)
Definition: MD5.cpp:58
static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc, LiveRange &LR, const MachineOperand &MO)
bool operator!=(const SingleLinkedListIterator< T > &Other)
Definition: LiveInterval.h:691
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2038
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
Definition: LiveInterval.h:395
iterator begin()
Definition: LiveInterval.h:210
Helper class for performant LiveRange bulk updates.
Definition: LiveInterval.h:853
VNInfo * getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
Definition: LiveInterval.h:318
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:325
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:766
const VNInfo * getValNumInfo(unsigned ValNo) const
Definition: LiveInterval.h:307
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:372
bool isLocal(SlotIndex Start, SlotIndex End) const
True iff this segment is a single segment that lies between the specified boundaries, exclusively.
Definition: LiveInterval.h:505
const_subrange_iterator subrange_end() const
Definition: LiveInterval.h:718
SingleLinkedListIterator< T > operator++(int)
Definition: LiveInterval.h:686
Segment(SlotIndex S, SlotIndex E, VNInfo *V)
Definition: LiveInterval.h:169
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
subrange_iterator subrange_end()
Definition: LiveInterval.h:711
print Print MemDeps of function
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
Definition: LiveInterval.h:423
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
Definition: LiveInterval.h:134
subrange_iterator subrange_begin()
Definition: LiveInterval.h:708
void print(raw_ostream &OS) const
const_vni_iterator vni_end() const
Definition: LiveInterval.h:223
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:83
vni_iterator vni_end()
Definition: LiveInterval.h:220
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
Definition: SlotIndexes.h:248
VNInfo * createValueCopy(const VNInfo *orig, VNInfo::Allocator &VNInfoAllocator)
Create a copy of the given value.
Definition: LiveInterval.h:336
bool containsInterval(SlotIndex S, SlotIndex E) const
Return true if the given interval, [S, E), is covered by this segment.
Definition: LiveInterval.h:180