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