LLVM 24.0.0git
LiveInterval.cpp
Go to the documentation of this file.
1//===- LiveInterval.cpp - Live Interval Representation --------------------===//
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
21#include "LiveRangeUtils.h"
22#include "RegisterCoalescer.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/STLExtras.h"
37#include "llvm/Config/llvm-config.h"
38#include "llvm/MC/LaneBitmask.h"
40#include "llvm/Support/Debug.h"
42#include <algorithm>
43#include <cassert>
44#include <cstddef>
45#include <iterator>
46#include <utility>
47
48using namespace llvm;
49
50namespace {
51
52//===----------------------------------------------------------------------===//
53// Implementation of various methods necessary for calculation of live ranges.
54// The implementation of the methods abstracts from the concrete type of the
55// segment collection.
56//
57// Implementation of the class follows the Template design pattern. The base
58// class contains generic algorithms that call collection-specific methods,
59// which are provided in concrete subclasses. In order to avoid virtual calls
60// these methods are provided by means of C++ template instantiation.
61// The base class calls the methods of the subclass through method impl(),
62// which casts 'this' pointer to the type of the subclass.
63//
64//===----------------------------------------------------------------------===//
65
66template <typename ImplT, typename IteratorT, typename CollectionT>
67class CalcLiveRangeUtilBase {
68protected:
69 LiveRange *LR;
70
71protected:
72 CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {}
73
74public:
75 using Segment = LiveRange::Segment;
76 using iterator = IteratorT;
77
78 /// A counterpart of LiveRange::createDeadDef: Make sure the range has a
79 /// value defined at @p Def.
80 /// If @p ForVNI is null, and there is no value defined at @p Def, a new
81 /// value will be allocated using @p VNInfoAllocator.
82 /// If @p ForVNI is null, the return value is the value defined at @p Def,
83 /// either a pre-existing one, or the one newly created.
84 /// If @p ForVNI is not null, then @p Def should be the location where
85 /// @p ForVNI is defined. If the range does not have a value defined at
86 /// @p Def, the value @p ForVNI will be used instead of allocating a new
87 /// one. If the range already has a value defined at @p Def, it must be
88 /// same as @p ForVNI. In either case, @p ForVNI will be the return value.
89 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator *VNInfoAllocator,
90 VNInfo *ForVNI) {
91 assert(!Def.isDead() && "Cannot define a value at the dead slot");
92 assert((!ForVNI || ForVNI->def == Def) &&
93 "If ForVNI is specified, it must match Def");
94 iterator I = impl().find(Def);
95 if (I == segments().end()) {
96 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
97 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
98 return VNI;
99 }
100
101 Segment *S = segmentAt(I);
102 if (SlotIndex::isSameInstr(Def, S->start)) {
103 assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
104 assert(S->valno->def == S->start && "Inconsistent existing value def");
105
106 // It is possible to have both normal and early-clobber defs of the same
107 // register on an instruction. It doesn't make a lot of sense, but it is
108 // possible to specify in inline assembly.
109 //
110 // Just convert everything to early-clobber.
111 Def = std::min(Def, S->start);
112 if (Def != S->start)
113 S->start = S->valno->def = Def;
114 return S->valno;
115 }
116 assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def");
117 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
118 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
119 return VNI;
120 }
121
122 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
123 if (segments().empty())
124 return nullptr;
125 iterator I =
126 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
127 if (I == segments().begin())
128 return nullptr;
129 --I;
130 if (I->end <= StartIdx)
131 return nullptr;
132 if (I->end < Use)
133 extendSegmentEndTo(I, Use);
134 return I->valno;
135 }
136
137 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
138 SlotIndex StartIdx, SlotIndex Use) {
139 if (segments().empty())
140 return std::make_pair(nullptr, false);
141 SlotIndex BeforeUse = Use.getPrevSlot();
142 iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr));
143 if (I == segments().begin())
144 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
145 --I;
146 if (I->end <= StartIdx)
147 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
148 if (I->end < Use) {
149 if (LR->isUndefIn(Undefs, I->end, BeforeUse))
150 return std::make_pair(nullptr, true);
151 extendSegmentEndTo(I, Use);
152 }
153 return std::make_pair(I->valno, false);
154 }
155
156 /// This method is used when we want to extend the segment specified
157 /// by I to end at the specified endpoint. To do this, we should
158 /// merge and eliminate all segments that this will overlap
159 /// with. The iterator is not invalidated.
160 void extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
161 assert(I != segments().end() && "Not a valid segment!");
162 Segment *S = segmentAt(I);
163 VNInfo *ValNo = I->valno;
164
165 // Search for the first segment that we can't merge with.
166 iterator MergeTo = std::next(I);
167 for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo)
168 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
169
170 // If NewEnd was in the middle of a segment, make sure to get its endpoint.
171 S->end = std::max(NewEnd, std::prev(MergeTo)->end);
172
173 // If the newly formed segment now touches the segment after it and if they
174 // have the same value number, merge the two segments into one segment.
175 if (MergeTo != segments().end() && MergeTo->start <= I->end &&
176 MergeTo->valno == ValNo) {
177 S->end = MergeTo->end;
178 ++MergeTo;
179 }
180
181 // Erase any dead segments.
182 segments().erase(std::next(I), MergeTo);
183 }
184
185 /// This method is used when we want to extend the segment specified
186 /// by I to start at the specified endpoint. To do this, we should
187 /// merge and eliminate all segments that this will overlap with.
188 iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) {
189 assert(I != segments().end() && "Not a valid segment!");
190 Segment *S = segmentAt(I);
191 VNInfo *ValNo = I->valno;
192
193 // Search for the first segment that we can't merge with.
194 iterator MergeTo = I;
195 do {
196 if (MergeTo == segments().begin()) {
197 S->start = NewStart;
198 segments().erase(MergeTo, I);
199 return I;
200 }
201 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
202 --MergeTo;
203 } while (NewStart <= MergeTo->start);
204
205 // If we start in the middle of another segment, just delete a range and
206 // extend that segment.
207 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
208 segmentAt(MergeTo)->end = S->end;
209 } else {
210 // Otherwise, extend the segment right after.
211 ++MergeTo;
212 Segment *MergeToSeg = segmentAt(MergeTo);
213 MergeToSeg->start = NewStart;
214 MergeToSeg->end = S->end;
215 }
216
217 segments().erase(std::next(MergeTo), std::next(I));
218 return MergeTo;
219 }
220
221 iterator addSegment(Segment S) {
222 SlotIndex Start = S.start, End = S.end;
223 iterator I = impl().findInsertPos(S);
224
225 // If the inserted segment starts in the middle or right at the end of
226 // another segment, just extend that segment to contain the segment of S.
227 if (I != segments().begin()) {
228 iterator B = std::prev(I);
229 if (S.valno == B->valno) {
230 if (B->start <= Start && B->end >= Start) {
231 extendSegmentEndTo(B, End);
232 return B;
233 }
234 } else {
235 // Check to make sure that we are not overlapping two live segments with
236 // different valno's.
237 assert(B->end <= Start &&
238 "Cannot overlap two segments with differing ValID's"
239 " (did you def the same reg twice in a MachineInstr?)");
240 }
241 }
242
243 // Otherwise, if this segment ends in the middle of, or right next
244 // to, another segment, merge it into that segment.
245 if (I != segments().end()) {
246 if (S.valno == I->valno) {
247 if (I->start <= End) {
248 I = extendSegmentStartTo(I, Start);
249
250 // If S is a complete superset of a segment, we may need to grow its
251 // endpoint as well.
252 if (End > I->end)
253 extendSegmentEndTo(I, End);
254 return I;
255 }
256 } else {
257 // Check to make sure that we are not overlapping two live segments with
258 // different valno's.
259 assert(I->start >= End &&
260 "Cannot overlap two segments with differing ValID's");
261 }
262 }
263
264 // Otherwise, this is just a new segment that doesn't interact with
265 // anything.
266 // Insert it.
267 return segments().insert(I, S);
268 }
269
270private:
271 ImplT &impl() { return *static_cast<ImplT *>(this); }
272
273 CollectionT &segments() { return impl().segmentsColl(); }
274
275 Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); }
276};
277
278//===----------------------------------------------------------------------===//
279// Instantiation of the methods for calculation of live ranges
280// based on a segment vector.
281//===----------------------------------------------------------------------===//
282
283class CalcLiveRangeUtilVector;
284using CalcLiveRangeUtilVectorBase =
285 CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
287
288class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase {
289public:
290 CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {}
291
292private:
293 friend CalcLiveRangeUtilVectorBase;
294
295 LiveRange::Segments &segmentsColl() { return LR->segments; }
296
297 void insertAtEnd(const Segment &S) { LR->segments.push_back(S); }
298
299 iterator find(SlotIndex Pos) { return LR->find(Pos); }
300
301 iterator findInsertPos(Segment S) { return llvm::upper_bound(*LR, S.start); }
302};
303
304//===----------------------------------------------------------------------===//
305// Instantiation of the methods for calculation of live ranges
306// based on a segment set.
307//===----------------------------------------------------------------------===//
308
309class CalcLiveRangeUtilSet;
310using CalcLiveRangeUtilSetBase =
311 CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator,
313
314class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase {
315public:
316 CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {}
317
318private:
319 friend CalcLiveRangeUtilSetBase;
320
321 LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; }
322
323 void insertAtEnd(const Segment &S) {
324 LR->segmentSet->insert(LR->segmentSet->end(), S);
325 }
326
327 iterator find(SlotIndex Pos) {
328 iterator I =
329 LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr));
330 if (I == LR->segmentSet->begin())
331 return I;
332 iterator PrevI = std::prev(I);
333 if (Pos < (*PrevI).end)
334 return PrevI;
335 return I;
336 }
337
338 iterator findInsertPos(Segment S) {
339 iterator I = LR->segmentSet->upper_bound(S);
340 if (I != LR->segmentSet->end() && !(S.start < *I))
341 ++I;
342 return I;
343 }
344};
345
346} // end anonymous namespace
347
348//===----------------------------------------------------------------------===//
349// LiveRange methods
350//===----------------------------------------------------------------------===//
351
353 return llvm::partition_point(*this,
354 [&](const Segment &X) { return X.end <= Pos; });
355}
356
358 // Use the segment set, if it is available.
359 if (segmentSet != nullptr)
360 return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
361 // Otherwise use the segment vector.
362 return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
363}
364
366 // Use the segment set, if it is available.
367 if (segmentSet != nullptr)
368 return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
369 // Otherwise use the segment vector.
370 return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
371}
372
373// overlaps - Return true if the intersection of the two live ranges is
374// not empty.
375//
376// An example for overlaps():
377//
378// 0: A = ...
379// 4: B = ...
380// 8: C = A + B ;; last use of A
381//
382// The live ranges should look like:
383//
384// A = [3, 11)
385// B = [7, x)
386// C = [11, y)
387//
388// A->overlaps(C) should return false since we want to be able to join
389// A and C.
390//
392 const_iterator StartPos) const {
393 assert(!empty() && "empty range");
394 const_iterator i = begin();
395 const_iterator ie = end();
396 const_iterator j = StartPos;
397 const_iterator je = other.end();
398
399 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
400 StartPos != other.end() && "Bogus start position hint!");
401
402 if (i->start < j->start) {
403 i = std::upper_bound(i, ie, j->start);
404 if (i != begin()) --i;
405 } else if (j->start < i->start) {
406 ++StartPos;
407 if (StartPos != other.end() && StartPos->start <= i->start) {
408 assert(StartPos < other.end() && i < end());
409 j = std::upper_bound(j, je, i->start);
410 if (j != other.begin()) --j;
411 }
412 } else {
413 return true;
414 }
415
416 if (j == je) return false;
417
418 while (i != ie) {
419 if (i->start > j->start) {
420 std::swap(i, j);
421 std::swap(ie, je);
422 }
423
424 if (i->end > j->start)
425 return true;
426 ++i;
427 }
428
429 return false;
430}
431
433 const SlotIndexes &Indexes) const {
434 assert(!empty() && "empty range");
435 if (Other.empty())
436 return false;
437
438 // Use binary searches to find initial positions.
439 const_iterator I = find(Other.beginIndex());
440 const_iterator IE = end();
441 if (I == IE)
442 return false;
443 const_iterator J = Other.find(I->start);
444 const_iterator JE = Other.end();
445 if (J == JE)
446 return false;
447
448 while (true) {
449 // J has just been advanced to satisfy:
450 assert(J->end > I->start);
451 // Check for an overlap.
452 if (J->start < I->end) {
453 // I and J are overlapping. Find the later start.
454 SlotIndex Def = std::max(I->start, J->start);
455 // Allow the overlap if Def is a coalescable copy.
456 if (Def.isBlock() ||
457 !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
458 return true;
459 }
460 // Advance the iterator that ends first to check for more overlaps.
461 if (J->end > I->end) {
462 std::swap(I, J);
463 std::swap(IE, JE);
464 }
465 // Advance J until J->end > I->start.
466 do
467 if (++J == JE)
468 return false;
469 while (J->end <= I->start);
470 }
471}
472
473/// overlaps - Return true if the live range overlaps an interval specified
474/// by [Start, End).
476 assert(Start < End && "Invalid range");
478 return I != begin() && (--I)->end > Start;
479}
480
482 if (empty())
483 return Other.empty();
484
486 for (const Segment &O : Other.segments) {
487 I = advanceTo(I, O.start);
488 if (I == end() || I->start > O.start)
489 return false;
490
491 // Check adjacent live segments and see if we can get behind O.end.
492 while (I->end < O.end) {
494 // Get next segment and abort if it was not adjacent.
495 ++I;
496 if (I == end() || Last->end != I->start)
497 return false;
498 }
499 }
500 return true;
501}
502
503/// ValNo is dead, remove it. If it is the largest value number, just nuke it
504/// (and any other deleted values neighboring it), otherwise mark it as ~1U so
505/// it can be nuked later.
506void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
507 if (ValNo->id == getNumValNums()-1) {
508 do {
510 } while (!valnos.empty() && valnos.back()->isUnused());
511 } else {
512 ValNo->markUnused();
513 }
514}
515
516/// RenumberValues - Renumber all values in order of appearance and delete the
517/// remaining unused values.
520 valnos.clear();
521 for (const Segment &S : segments) {
522 VNInfo *VNI = S.valno;
523 if (!Seen.insert(VNI).second)
524 continue;
525 assert(!VNI->isUnused() && "Unused valno used by live segment");
526 VNI->id = (unsigned)valnos.size();
527 valnos.push_back(VNI);
528 }
529}
530
531void LiveRange::addSegmentToSet(Segment S) {
532 CalcLiveRangeUtilSet(this).addSegment(S);
533}
534
536 // Use the segment set, if it is available.
537 if (segmentSet != nullptr) {
538 addSegmentToSet(S);
539 return end();
540 }
541 // Otherwise use the segment vector.
542 return CalcLiveRangeUtilVector(this).addSegment(S);
543}
544
546 assert(segmentSet == nullptr && "Cannot merge with active segment set");
547 assert(I != end() && "Cannot merge end iterator");
548
549 if (I != begin()) {
550 iterator Prev = std::prev(I);
551 if (Prev->valno == I->valno && Prev->end == I->start) {
552 Prev->end = I->end;
553 segments.erase(I);
554 I = Prev;
555 }
556 }
557
558 iterator Next = std::next(I);
559 if (Next != end() && I->valno == Next->valno && I->end == Next->start) {
560 I->end = Next->end;
561 segments.erase(Next);
562 }
563
564 return I;
565}
566
568 // Check that the segment belongs to the back of the list.
569 assert(segments.empty() || segments.back().end <= S.start);
570 segments.push_back(S);
571}
572
573std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
574 SlotIndex StartIdx, SlotIndex Kill) {
575 // Use the segment set, if it is available.
576 if (segmentSet != nullptr)
577 return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
578 // Otherwise use the segment vector.
579 return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
580}
581
583 // Use the segment set, if it is available.
584 if (segmentSet != nullptr)
585 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
586 // Otherwise use the segment vector.
587 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
588}
589
591 bool RemoveDeadValNo) {
592 // Find the Segment containing this span.
593 iterator I = find(Start);
594
595 // No Segment found, so nothing to do.
596 if (I == end())
597 return;
598
599 assert(I->containsInterval(Start, End)
600 && "Segment is not entirely in range!");
601
602 // If the span we are removing is at the start of the Segment, adjust it.
603 VNInfo *ValNo = I->valno;
604 if (I->start == Start) {
605 if (I->end == End) {
606 segments.erase(I); // Removed the whole Segment.
607
608 if (RemoveDeadValNo)
609 removeValNoIfDead(ValNo);
610 } else
611 I->start = End;
612 return;
613 }
614
615 // Otherwise if the span we are removing is at the end of the Segment,
616 // adjust the other way.
617 if (I->end == End) {
618 I->end = Start;
619 return;
620 }
621
622 // Otherwise, we are splitting the Segment into two pieces.
623 SlotIndex OldEnd = I->end;
624 I->end = Start; // Trim the old segment.
625
626 // Insert the new one.
627 segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
628}
629
631 VNInfo *ValNo = I->valno;
632 I = segments.erase(I);
633 if (RemoveDeadValNo)
634 removeValNoIfDead(ValNo);
635 return I;
636}
637
639 if (none_of(*this, [=](const Segment &S) { return S.valno == ValNo; }))
640 markValNoForDeletion(ValNo);
641}
642
643/// removeValNo - Remove all the segments defined by the specified value#.
644/// Also remove the value# from value# list.
646 if (empty()) return;
648 [ValNo](const Segment &S) { return S.valno == ValNo; });
649 // Now that ValNo is dead, remove it.
650 markValNoForDeletion(ValNo);
651}
652
654 const int *LHSValNoAssignments,
655 const int *RHSValNoAssignments,
656 SmallVectorImpl<VNInfo *> &NewVNInfo) {
657 assert(verify());
658 assert(Other.verify());
659
660 // Determine if any of our values are mapped. This is uncommon, so we want
661 // to avoid the range scan if not.
662 bool MustMapCurValNos = false;
663 unsigned NumVals = getNumValNums();
664 unsigned NumNewVals = NewVNInfo.size();
665 for (unsigned i = 0; i != NumVals; ++i) {
666 unsigned LHSValID = LHSValNoAssignments[i];
667 if (i != LHSValID ||
668 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
669 MustMapCurValNos = true;
670 break;
671 }
672 }
673
674 // If we have to apply a mapping to our base range assignment, rewrite it now.
675 if (MustMapCurValNos && !empty()) {
676 // Map the first live range.
677
678 iterator OutIt = begin();
679 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
680 for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
681 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
682 assert(nextValNo && "Huh?");
683
684 // If this live range has the same value # as its immediate predecessor,
685 // and if they are neighbors, remove one Segment. This happens when we
686 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
687 if (OutIt->valno == nextValNo && OutIt->end == I->start) {
688 OutIt->end = I->end;
689 } else {
690 // Didn't merge. Move OutIt to the next segment,
691 ++OutIt;
692 OutIt->valno = nextValNo;
693 if (OutIt != I) {
694 OutIt->start = I->start;
695 OutIt->end = I->end;
696 }
697 }
698 }
699 // If we merge some segments, chop off the end.
700 ++OutIt;
701 segments.erase(OutIt, end());
702 }
703
704 // Rewrite Other values before changing the VNInfo ids.
705 // This can leave Other in an invalid state because we're not coalescing
706 // touching segments that now have identical values. That's OK since Other is
707 // not supposed to be valid after calling join();
708 for (Segment &S : Other.segments)
709 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
710
711 // Update val# info. Renumber them and make sure they all belong to this
712 // LiveRange now. Also remove dead val#'s.
713 unsigned NumValNos = 0;
714 for (unsigned i = 0; i < NumNewVals; ++i) {
715 VNInfo *VNI = NewVNInfo[i];
716 if (VNI) {
717 if (NumValNos >= NumVals)
718 valnos.push_back(VNI);
719 else
720 valnos[NumValNos] = VNI;
721 VNI->id = NumValNos++; // Renumber val#.
722 }
723 }
724 if (NumNewVals < NumVals)
725 valnos.resize(NumNewVals); // shrinkify
726
727 // Okay, now insert the RHS live segments into the LHS.
728 LiveRangeUpdater Updater(this);
729 for (Segment &S : Other.segments)
730 Updater.add(S);
731}
732
733/// Merge all of the segments in RHS into this live range as the specified
734/// value number. The segments in RHS are allowed to overlap with segments in
735/// the current range, but only if the overlapping segments have the
736/// specified value number.
738 VNInfo *LHSValNo) {
739 LiveRangeUpdater Updater(this);
740 for (const Segment &S : RHS.segments)
741 Updater.add(S.start, S.end, LHSValNo);
742}
743
744/// MergeValueInAsValue - Merge all of the live segments of a specific val#
745/// in RHS into this live range as the specified value number.
746/// The segments in RHS are allowed to overlap with segments in the
747/// current range, it will replace the value numbers of the overlaped
748/// segments with the specified value number.
750 const VNInfo *RHSValNo,
751 VNInfo *LHSValNo) {
752 LiveRangeUpdater Updater(this);
753 for (const Segment &S : RHS.segments)
754 if (S.valno == RHSValNo)
755 Updater.add(S.start, S.end, LHSValNo);
756}
757
758/// MergeValueNumberInto - This method is called when two value nubmers
759/// are found to be equivalent. This eliminates V1, replacing all
760/// segments with the V1 value number with the V2 value number. This can
761/// cause merging of V1/V2 values numbers and compaction of the value space.
763 assert(V1 != V2 && "Identical value#'s are always equivalent!");
764
765 // This code actually merges the (numerically) larger value number into the
766 // smaller value number, which is likely to allow us to compactify the value
767 // space. The only thing we have to be careful of is to preserve the
768 // instruction that defines the result value.
769
770 // Make sure V2 is smaller than V1.
771 if (V1->id < V2->id) {
772 V1->copyFrom(*V2);
773 std::swap(V1, V2);
774 }
775
776 // Merge V1 segments into V2.
777 for (iterator I = begin(); I != end(); ) {
778 iterator S = I++;
779 if (S->valno != V1) continue; // Not a V1 Segment.
780
781 // After changing this segment to V2, it may touch an adjacent V2 segment.
782 // Merge with either neighbor before continuing.
783 S->valno = V2;
784 I = std::next(mergeAdjacentSegments(S));
785 }
786
787 // Now that V1 is dead, remove it.
788 markValNoForDeletion(V1);
789
790 return V2;
791}
792
794 assert(segmentSet != nullptr && "segment set must have been created");
795 assert(
796 segments.empty() &&
797 "segment set can be used only initially before switching to the array");
798 segments.append(segmentSet->begin(), segmentSet->end());
799 segmentSet = nullptr;
800 assert(verify());
801}
802
804 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
805 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
806
807 // If there are no regmask slots, we have nothing to search.
808 if (SlotI == SlotE)
809 return false;
810
811 // Start our search at the first segment that ends after the first slot.
812 const_iterator SegmentI = find(*SlotI);
813 const_iterator SegmentE = end();
814
815 // If there are no segments that end after the first slot, we're done.
816 if (SegmentI == SegmentE)
817 return false;
818
819 // Look for each slot in the live range.
820 for ( ; SlotI != SlotE; ++SlotI) {
821 // Go to the next segment that ends after the current slot.
822 // The slot may be within a hole in the range.
823 SegmentI = advanceTo(SegmentI, *SlotI);
824 if (SegmentI == SegmentE)
825 return false;
826
827 // If this segment contains the slot, we're done.
828 if (SegmentI->contains(*SlotI))
829 return true;
830 // Otherwise, look for the next slot.
831 }
832
833 // We didn't find a segment containing any of the slots.
834 return false;
835}
836
837void LiveInterval::freeSubRange(SubRange *S) {
838 S->~SubRange();
839 // Memory was allocated with BumpPtr allocator and is not freed here.
840}
841
843 SubRange **NextPtr = &SubRanges;
844 SubRange *I = *NextPtr;
845 while (I != nullptr) {
846 if (!I->empty()) {
847 NextPtr = &I->Next;
848 I = *NextPtr;
849 continue;
850 }
851 // Skip empty subranges until we find the first nonempty one.
852 do {
853 SubRange *Next = I->Next;
854 freeSubRange(I);
855 I = Next;
856 } while (I != nullptr && I->empty());
857 *NextPtr = I;
858 }
859}
860
862 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
863 Next = I->Next;
864 freeSubRange(I);
865 }
866 SubRanges = nullptr;
867}
868
869/// For each VNI in \p SR, check whether or not that value defines part
870/// of the mask describe by \p LaneMask and if not, remove that value
871/// from \p SR.
873 LaneBitmask LaneMask,
874 const SlotIndexes &Indexes,
875 const TargetRegisterInfo &TRI,
876 unsigned ComposeSubRegIdx) {
877 // Phys reg should not be tracked at subreg level.
878 // Same for noreg (Reg == 0).
879 if (!Reg || !Reg.isVirtual())
880 return;
881 // Remove the values that don't define those lanes.
882 SmallVector<VNInfo *, 8> ToBeRemoved;
883 for (VNInfo *VNI : SR.valnos) {
884 if (VNI->isUnused())
885 continue;
886 // PHI definitions don't have MI attached, so there is nothing
887 // we can use to strip the VNI.
888 if (VNI->isPHIDef())
889 continue;
890 const MachineInstr *MI = Indexes.getInstructionFromIndex(VNI->def);
891 assert(MI && "Cannot find the definition of a value");
892 bool hasDef = false;
893 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
894 if (!MOI->isReg() || !MOI->isDef())
895 continue;
896 if (MOI->getReg() != Reg)
897 continue;
898 LaneBitmask OrigMask = TRI.getSubRegIndexLaneMask(MOI->getSubReg());
899 LaneBitmask ExpectedDefMask =
900 ComposeSubRegIdx
901 ? TRI.composeSubRegIndexLaneMask(ComposeSubRegIdx, OrigMask)
902 : OrigMask;
903 if ((ExpectedDefMask & LaneMask).none())
904 continue;
905 hasDef = true;
906 break;
907 }
908
909 if (!hasDef)
910 ToBeRemoved.push_back(VNI);
911 }
912 for (VNInfo *VNI : ToBeRemoved)
913 SR.removeValNo(VNI);
914
915 // If the subrange is empty at this point, the MIR is invalid. Do not assert
916 // and let the verifier catch this case.
917}
918
920 BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
921 std::function<void(LiveInterval::SubRange &)> Apply,
922 const SlotIndexes &Indexes, const TargetRegisterInfo &TRI,
923 unsigned ComposeSubRegIdx) {
924 LaneBitmask ToApply = LaneMask;
925 for (SubRange &SR : subranges()) {
926 LaneBitmask SRMask = SR.LaneMask;
927 LaneBitmask Matching = SRMask & LaneMask;
928 if (Matching.none())
929 continue;
930
931 SubRange *MatchingRange;
932 if (SRMask == Matching) {
933 // The subrange fits (it does not cover bits outside \p LaneMask).
934 MatchingRange = &SR;
935 } else {
936 // We have to split the subrange into a matching and non-matching part.
937 // Reduce lanemask of existing lane to non-matching part.
938 SR.LaneMask = SRMask & ~Matching;
939 // Create a new subrange for the matching part
940 MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
941 // Now that the subrange is split in half, make sure we
942 // only keep in the subranges the VNIs that touch the related half.
943 stripValuesNotDefiningMask(reg(), *MatchingRange, Matching, Indexes, TRI,
944 ComposeSubRegIdx);
945 stripValuesNotDefiningMask(reg(), SR, SR.LaneMask, Indexes, TRI,
946 ComposeSubRegIdx);
947 }
948 Apply(*MatchingRange);
949 ToApply &= ~Matching;
950 }
951 // Create a new subrange if there are uncovered bits left.
952 if (ToApply.any()) {
953 SubRange *NewRange = createSubRange(Allocator, ToApply);
954 Apply(*NewRange);
955 }
956}
957
958unsigned LiveInterval::getSize() const {
959 unsigned Sum = 0;
960 for (const Segment &S : segments)
961 Sum += S.start.distance(S.end);
962 return Sum;
963}
964
966 LaneBitmask LaneMask,
968 const SlotIndexes &Indexes) const {
969 assert(reg().isVirtual());
970 LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg());
971 assert((VRegMask & LaneMask).any());
972 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
973 for (const MachineOperand &MO : MRI.def_operands(reg())) {
974 if (!MO.isUndef())
975 continue;
976 unsigned SubReg = MO.getSubReg();
977 assert(SubReg != 0 && "Undef should only be set on subreg defs");
978 LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
979 LaneBitmask UndefMask = VRegMask & ~DefMask;
980 if ((UndefMask & LaneMask).any()) {
981 const MachineInstr &MI = *MO.getParent();
982 bool EarlyClobber = MO.isEarlyClobber();
984 Undefs.push_back(Pos);
985 }
986 }
987}
988
990 return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
991}
992
993#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
995 dbgs() << *this << '\n';
996}
997#endif
998
999void VNInfo::print(raw_ostream &OS) const {
1000 OS << id << '@';
1001 if (isUnused()) {
1002 OS << 'x';
1003 } else {
1004 OS << def;
1005 if (isPHIDef())
1006 OS << "-phi";
1007 }
1008}
1009
1011 if (empty())
1012 OS << "EMPTY";
1013 else {
1014 for (const Segment &S : segments) {
1015 OS << S;
1016 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
1017 }
1018 }
1019
1020 // Print value number info.
1021 if (getNumValNums()) {
1022 OS << ' ';
1023 unsigned vnum = 0;
1024 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
1025 ++i, ++vnum) {
1026 const VNInfo *vni = *i;
1027 if (vnum)
1028 OS << ' ';
1029 OS << *vni;
1030 assert(vnum == vni->id && "Bad VNInfo");
1031 }
1032 }
1033}
1034
1036 OS << " L" << PrintLaneMask(LaneMask) << ' '
1037 << static_cast<const LiveRange &>(*this);
1038}
1039
1041 OS << printReg(reg()) << ' ';
1042 super::print(OS);
1043 // Print subranges
1044 for (const SubRange &SR : subranges())
1045 OS << SR;
1046 OS << " weight:" << Weight;
1047}
1048
1049#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1050LLVM_DUMP_METHOD void VNInfo::dump() const { dbgs() << *this << '\n'; }
1051
1052LLVM_DUMP_METHOD void LiveRange::dump() const { dbgs() << *this << '\n'; }
1053
1055 dbgs() << *this << '\n';
1056}
1057
1059 dbgs() << *this << '\n';
1060}
1061#endif
1062
1063#ifndef NDEBUG
1064bool LiveRange::verify() const {
1065 for (const_iterator I = begin(), E = end(); I != E; ++I) {
1066 if (!I->start.isValid())
1067 return false;
1068 if (!I->end.isValid())
1069 return false;
1070 if (I->start >= I->end)
1071 return false;
1072 if (I->valno == nullptr)
1073 return false;
1074 if (I->valno->id >= valnos.size())
1075 return false;
1076 if (I->valno != valnos[I->valno->id])
1077 return false;
1078 if (std::next(I) != E) {
1079 if (I->end > std::next(I)->start)
1080 return false;
1081 if (I->end == std::next(I)->start) {
1082 if (I->valno == std::next(I)->valno)
1083 return false;
1084 }
1085 }
1086 }
1087
1088 return true;
1089}
1090
1092 if (!super::verify())
1093 return false;
1094
1095 // Make sure SubRanges are fine and LaneMasks are disjunct.
1096 LaneBitmask Mask;
1097 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg())
1099 for (const SubRange &SR : subranges()) {
1100 // Subrange lanemask should be disjunct to any previous subrange masks.
1101 if ((Mask & SR.LaneMask).any())
1102 return false;
1103
1104 Mask |= SR.LaneMask;
1105
1106 // subrange mask should not contained in maximum lane mask for the vreg.
1107 if ((Mask & ~MaxMask).any())
1108 return false;
1109
1110 // empty subranges must be removed.
1111 if (SR.empty())
1112 return false;
1113
1114 if (!SR.verify())
1115 return false;
1116
1117 // Main liverange should cover subrange.
1118 if (!covers(SR))
1119 return false;
1120 }
1121
1122 return true;
1123}
1124#endif
1125
1126//===----------------------------------------------------------------------===//
1127// LiveRangeUpdater class
1128//===----------------------------------------------------------------------===//
1129//
1130// The LiveRangeUpdater class always maintains these invariants:
1131//
1132// - When LastStart is invalid, Spills is empty and the iterators are invalid.
1133// This is the initial state, and the state created by flush().
1134// In this state, isDirty() returns false.
1135//
1136// Otherwise, segments are kept in three separate areas:
1137//
1138// 1. [begin; WriteI) at the front of LR.
1139// 2. [ReadI; end) at the back of LR.
1140// 3. Spills.
1141//
1142// - LR.begin() <= WriteI <= ReadI <= LR.end().
1143// - Segments in all three areas are fully ordered and coalesced.
1144// - Segments in area 1 precede and can't coalesce with segments in area 2.
1145// - Segments in Spills precede and can't coalesce with segments in area 2.
1146// - No coalescing is possible between segments in Spills and segments in area
1147// 1, and there are no overlapping segments.
1148//
1149// The segments in Spills are not ordered with respect to the segments in area
1150// 1. They need to be merged.
1151//
1152// When they exist, Spills.back().start <= LastStart,
1153// and WriteI[-1].start <= LastStart.
1154
1155#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1157 if (!isDirty()) {
1158 if (LR)
1159 OS << "Clean updater: " << *LR << '\n';
1160 else
1161 OS << "Null updater.\n";
1162 return;
1163 }
1164 assert(LR && "Can't have null LR in dirty updater.");
1165 OS << " updater with gap = " << (ReadI - WriteI)
1166 << ", last start = " << LastStart
1167 << ":\n Area 1:";
1168 for (const auto &S : make_range(LR->begin(), WriteI))
1169 OS << ' ' << S;
1170 OS << "\n Spills:";
1171 for (const LiveRange::Segment &Spill : Spills)
1172 OS << ' ' << Spill;
1173 OS << "\n Area 2:";
1174 for (const auto &S : make_range(ReadI, LR->end()))
1175 OS << ' ' << S;
1176 OS << '\n';
1177}
1178
1182#endif
1183
1184// Determine if A and B should be coalesced.
1185static inline bool coalescable(const LiveRange::Segment &A,
1186 const LiveRange::Segment &B) {
1187 assert(A.start <= B.start && "Unordered live segments.");
1188 if (A.end == B.start)
1189 return A.valno == B.valno;
1190 if (A.end < B.start)
1191 return false;
1192 assert(A.valno == B.valno && "Cannot overlap different values");
1193 return true;
1194}
1195
1197 assert(LR && "Cannot add to a null destination");
1198
1199 // Fall back to the regular add method if the live range
1200 // is using the segment set instead of the segment vector.
1201 if (LR->segmentSet != nullptr) {
1202 LR->addSegmentToSet(Seg);
1203 return;
1204 }
1205
1206 // Flush the state if Start moves backwards.
1207 if (!LastStart.isValid() || LastStart > Seg.start) {
1208 if (isDirty())
1209 flush();
1210 // This brings us to an uninitialized state. Reinitialize.
1211 assert(Spills.empty() && "Leftover spilled segments");
1212 WriteI = ReadI = LR->begin();
1213 }
1214
1215 // Remember start for next time.
1216 LastStart = Seg.start;
1217
1218 // Advance ReadI until it ends after Seg.start.
1219 LiveRange::iterator E = LR->end();
1220 if (ReadI != E && ReadI->end <= Seg.start) {
1221 // First try to close the gap between WriteI and ReadI with spills.
1222 if (ReadI != WriteI)
1223 mergeSpills();
1224 // Then advance ReadI.
1225 if (ReadI == WriteI)
1226 ReadI = WriteI = LR->find(Seg.start);
1227 else
1228 while (ReadI != E && ReadI->end <= Seg.start)
1229 *WriteI++ = *ReadI++;
1230 }
1231
1232 assert(ReadI == E || ReadI->end > Seg.start);
1233
1234 // Check if the ReadI segment begins early.
1235 if (ReadI != E && ReadI->start <= Seg.start) {
1236 assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
1237 // Bail if Seg is completely contained in ReadI.
1238 if (ReadI->end >= Seg.end)
1239 return;
1240 // Coalesce into Seg.
1241 Seg.start = ReadI->start;
1242 ++ReadI;
1243 }
1244
1245 // Coalesce as much as possible from ReadI into Seg.
1246 while (ReadI != E && coalescable(Seg, *ReadI)) {
1247 Seg.end = std::max(Seg.end, ReadI->end);
1248 ++ReadI;
1249 }
1250
1251 // Try coalescing Spills.back() into Seg.
1252 if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
1253 Seg.start = Spills.back().start;
1254 Seg.end = std::max(Spills.back().end, Seg.end);
1255 Spills.pop_back();
1256 }
1257
1258 // Try coalescing Seg into WriteI[-1].
1259 if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
1260 WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
1261 return;
1262 }
1263
1264 // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
1265 if (WriteI != ReadI) {
1266 *WriteI++ = Seg;
1267 return;
1268 }
1269
1270 // Finally, append to LR or Spills.
1271 if (WriteI == E) {
1272 LR->segments.push_back(Seg);
1273 WriteI = ReadI = LR->end();
1274 } else
1275 Spills.push_back(Seg);
1276}
1277
1278// Merge as many spilled segments as possible into the gap between WriteI
1279// and ReadI. Advance WriteI to reflect the inserted instructions.
1280void LiveRangeUpdater::mergeSpills() {
1281 // Perform a backwards merge of Spills and [SpillI;WriteI).
1282 size_t GapSize = ReadI - WriteI;
1283 size_t NumMoved = std::min(Spills.size(), GapSize);
1284 LiveRange::iterator Src = WriteI;
1285 LiveRange::iterator Dst = Src + NumMoved;
1286 LiveRange::iterator SpillSrc = Spills.end();
1287 LiveRange::iterator B = LR->begin();
1288
1289 // This is the new WriteI position after merging spills.
1290 WriteI = Dst;
1291
1292 // Now merge Src and Spills backwards.
1293 while (Src != Dst) {
1294 if (Src != B && Src[-1].start > SpillSrc[-1].start)
1295 *--Dst = *--Src;
1296 else
1297 *--Dst = *--SpillSrc;
1298 }
1299 assert(NumMoved == size_t(Spills.end() - SpillSrc));
1300 Spills.erase(SpillSrc, Spills.end());
1301}
1302
1304 if (!isDirty())
1305 return;
1306 // Clear the dirty state.
1307 LastStart = SlotIndex();
1308
1309 assert(LR && "Cannot add to a null destination");
1310
1311 // Nothing to merge?
1312 if (Spills.empty()) {
1313 LR->segments.erase(WriteI, ReadI);
1314 assert(LR->verify());
1315 return;
1316 }
1317
1318 // Resize the WriteI - ReadI gap to match Spills.
1319 size_t GapSize = ReadI - WriteI;
1320 if (GapSize < Spills.size()) {
1321 // The gap is too small. Make some room.
1322 size_t WritePos = WriteI - LR->begin();
1323 LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
1324 // This also invalidated ReadI, but it is recomputed below.
1325 WriteI = LR->begin() + WritePos;
1326 } else {
1327 // Shrink the gap if necessary.
1328 LR->segments.erase(WriteI + Spills.size(), ReadI);
1329 }
1330 ReadI = WriteI + Spills.size();
1331 mergeSpills();
1332 assert(LR->verify());
1333}
1334
1336 // Create initial equivalence classes.
1337 EqClass.clear();
1338 EqClass.grow(LR.getNumValNums());
1339
1340 const MachineDominatorTree &MDT = LIS.getDomTree();
1341 const VNInfo *used = nullptr, *unused = nullptr;
1342 bool HasUnreachablePHIDef = false;
1343
1344 // Determine connections.
1345 for (const VNInfo *VNI : LR.valnos) {
1346 // Group all unused values into one class.
1347 if (VNI->isUnused()) {
1348 if (unused)
1349 EqClass.join(unused->id, VNI->id);
1350 unused = VNI;
1351 continue;
1352 }
1353 used = VNI;
1354 if (VNI->isPHIDef()) {
1355 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
1356 assert(MBB && "Phi-def has no defining MBB");
1357 HasUnreachablePHIDef |= !MDT.isReachableFromEntry(MBB);
1358 // Connect to values live out of predecessors.
1359 for (MachineBasicBlock *Pred : MBB->predecessors())
1360 if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(Pred)))
1361 EqClass.join(VNI->id, PVNI->id);
1362 } else {
1363 // Normal value defined by an instruction. Check for two-addr redef.
1364 // FIXME: This could be coincidental. Should we really check for a tied
1365 // operand constraint?
1366 // Note that VNI->def may be a use slot for an early clobber def.
1367 if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
1368 EqClass.join(VNI->id, UVNI->id);
1369 }
1370 }
1371
1372 // Lump all the unused values in with the last used value.
1373 if (used && unused)
1374 EqClass.join(used->id, unused->id);
1375
1376 if (HasUnreachablePHIDef) {
1377 const VNInfo *Defined = nullptr;
1378 unsigned NumVals = LR.getNumValNums();
1379 BitVector KeepSeparate(NumVals);
1380 SmallVector<unsigned, 8> Leaders(NumVals);
1381 for (const VNInfo *VNI : LR.valnos) {
1382 if (VNI->isUnused())
1383 continue;
1384
1385 unsigned Leader = EqClass.findLeader(VNI->id);
1386 Leaders[VNI->id] = Leader;
1387 if (!VNI->isPHIDef()) {
1388 KeepSeparate.set(Leader);
1389 Defined = VNI;
1390 } else if (MDT.isReachableFromEntry(LIS.getMBBFromIndex(VNI->def))) {
1391 KeepSeparate.set(Leader);
1392 }
1393 }
1394
1395 if (Defined) {
1396 for (const VNInfo *VNI : LR.valnos) {
1397 if (VNI->isUnused())
1398 continue;
1399
1400 unsigned Leader = Leaders[VNI->id];
1401 if (KeepSeparate.test(Leader))
1402 continue;
1403
1404 EqClass.join(Defined->id, VNI->id);
1405 KeepSeparate.set(Leader);
1406 }
1407 }
1408 }
1409
1410 EqClass.compress();
1411 return EqClass.getNumClasses();
1412}
1413
1416 // Rewrite instructions.
1417 for (MachineOperand &MO :
1418 llvm::make_early_inc_range(MRI.reg_operands(LI.reg()))) {
1419 MachineInstr *MI = MO.getParent();
1420 const VNInfo *VNI;
1421 if (MI->isDebugValue()) {
1422 // DBG_VALUE instructions don't have slot indexes, so get the index of
1423 // the instruction before them. The value is defined there too.
1424 SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
1425 VNI = LI.Query(Idx).valueOut();
1426 } else {
1427 SlotIndex Idx = LIS.getInstructionIndex(*MI);
1428 LiveQueryResult LRQ = LI.Query(Idx);
1429 VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
1430 }
1431 // In the case of an <undef> use that isn't tied to any def, VNI will be
1432 // NULL. If the use is tied to a def, VNI will be the defined value.
1433 if (!VNI)
1434 continue;
1435 if (unsigned EqClass = getEqClass(VNI))
1436 MO.setReg(LIV[EqClass - 1]->reg());
1437 }
1438
1439 // Distribute subregister liveranges.
1440 if (LI.hasSubRanges()) {
1441 unsigned NumComponents = EqClass.getNumClasses();
1442 SmallVector<unsigned, 8> VNIMapping;
1444 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1445 for (LiveInterval::SubRange &SR : LI.subranges()) {
1446 // Create new subranges in the split intervals and construct a mapping
1447 // for the VNInfos in the subrange.
1448 unsigned NumValNos = SR.valnos.size();
1449 VNIMapping.clear();
1450 VNIMapping.reserve(NumValNos);
1451 SubRanges.clear();
1452 SubRanges.resize(NumComponents-1, nullptr);
1453 for (unsigned I = 0; I < NumValNos; ++I) {
1454 const VNInfo &VNI = *SR.valnos[I];
1455 unsigned ComponentNum;
1456 if (VNI.isUnused()) {
1457 ComponentNum = 0;
1458 } else {
1459 const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
1460 assert(MainRangeVNI != nullptr
1461 && "SubRange def must have corresponding main range def");
1462 ComponentNum = getEqClass(MainRangeVNI);
1463 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
1464 SubRanges[ComponentNum-1]
1465 = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
1466 }
1467 }
1468 VNIMapping.push_back(ComponentNum);
1469 }
1470 DistributeRange(SR, SubRanges.data(), VNIMapping);
1471 }
1473 }
1474
1475 // Distribute main liverange.
1476 DistributeRange(LI, LIV, EqClass);
1477}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
static void createDeadDef(SlotIndexes &Indexes, VNInfo::Allocator &Alloc, LiveRange &LR, const MachineOperand &MO)
static bool coalescable(const LiveRange::Segment &A, const LiveRange::Segment &B)
static void stripValuesNotDefiningMask(Register Reg, LiveInterval::SubRange &SR, LaneBitmask LaneMask, const SlotIndexes &Indexes, const TargetRegisterInfo &TRI, unsigned ComposeSubRegIdx)
For each VNI in SR, check whether or not that value defines part of the mask describe by LaneMask and...
This file contains helper functions to modify live ranges.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
place backedge safepoints impl
MachineRegisterInfo & MRI
SI Optimize VGPR LiveRange
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
const_pointer iterator
Definition ArrayRef.h:47
iterator begin() const
Definition ArrayRef.h:129
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
A helper class for register coalescers.
bool isCoalescable(const MachineInstr *) const
Return true if MI is a copy instruction that will become an identity copy after coalescing.
LLVM_ABI void Distribute(LiveInterval &LI, LiveInterval *LIV[], MachineRegisterInfo &MRI)
Distribute values in LI into a separate LiveIntervals for each connected component.
LLVM_ABI unsigned Classify(const LiveRange &LR)
Classify the values in LR into connected components.
unsigned getEqClass(const VNInfo *VNI) const
getEqClass - Classify creates equivalence classes numbered 0..N.
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
A live range for subregisters.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void dump() const
LiveInterval - This class represents the liveness of a register, or stack slot.
LLVM_ABI void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
LLVM_ABI void dump() const
LLVM_ABI unsigned getSize() const
getSize - Returns the sum of sizes of all the LiveRange's.
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...
iterator_range< subrange_iterator > subranges()
LLVM_ABI void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, std::function< void(LiveInterval::SubRange &)> Apply, const SlotIndexes &Indexes, const TargetRegisterInfo &TRI, unsigned ComposeSubRegIdx=0)
Refines the subranges to support LaneMask.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
LLVM_ABI void clearSubRanges()
Removes all subregister liveness information.
Result of a LiveRange query.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
LLVM_ABI void print(raw_ostream &) const
LLVM_ABI void flush()
Flush the updater state to LR so it is valid and contains all added segments.
LLVM_ABI void dump() const
bool isDirty() const
Return true if the LR is currently in an invalid state, and flush() needs to be called.
LLVM_ABI void add(LiveRange::Segment)
Add a segment to LR and coalesce when possible, just like LR.addSegment().
This class represents the liveness of a register, stack slot, etc.
LiveRange(bool UseSegmentSet=false)
Constructs a new LiveRange object.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
Segments::iterator iterator
LLVM_ABI void join(LiveRange &Other, const int *ValNoAssignments, const int *RHSValNoAssignments, SmallVectorImpl< VNInfo * > &NewVNInfo)
join - Join two live ranges (this, and other) together.
LLVM_ABI void MergeValueInAsValue(const LiveRange &RHS, const VNInfo *RHSValNo, VNInfo *LHSValNo)
MergeValueInAsValue - Merge all of the segments of a specific val# in RHS into this live range as the...
Segments::const_iterator const_iterator
LLVM_ABI VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
LLVM_ABI iterator mergeAdjacentSegments(iterator I)
Merge the segment pointed to by I with its immediate neighbors when they use the same value number an...
std::set< Segment > SegmentSet
LLVM_ABI bool isLiveAtIndexes(ArrayRef< SlotIndex > Slots) const
LLVM_ABI bool covers(const LiveRange &Other) const
Returns true if all segments of the Other live range are completely covered by this live range.
vni_iterator vni_begin()
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position,...
std::unique_ptr< SegmentSet > segmentSet
LLVM_ABI void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
bool empty() const
LLVM_ABI void RenumberValues()
RenumberValues - Renumber all values in order of appearance and remove unused values.
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
LLVM_ABI bool overlapsFrom(const LiveRange &Other, const_iterator StartPos) const
overlapsFrom - Return true if the intersection of the two live ranges is not empty.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
LLVM_ABI std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
bool verify() const
Walk the range and assert if any invariants fail to hold.
LLVM_ABI void append(const LiveRange::Segment S)
Append a segment to the list of segments.
friend class LiveRangeUpdater
LLVM_ABI VNInfo * MergeValueNumberInto(VNInfo *V1, VNInfo *V2)
MergeValueNumberInto - This method is called when two value numbers are found to be equivalent.
unsigned getNumValNums() const
iterator begin()
VNInfoList valnos
LLVM_ABI void MergeSegmentsInAsValue(const LiveRange &RHS, VNInfo *LHSValNo)
Merge all of the live segments of a specific val# in RHS into this live range as the specified value ...
vni_iterator vni_end()
SmallVector< Segment, 2 > Segments
VNInfoList::const_iterator const_vni_iterator
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
LLVM_ABI void removeValNoIfDead(VNInfo *ValNo)
Mark ValNo for deletion if no segments in this range use it.
LLVM_ABI void dump() const
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void flushSegmentSet()
Flush segment set into the regular segment vector.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
bool isValid() const
isValid - Returns true until all the operands have been visited.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
SlotIndex getNextSlot() const
Returns the next slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
VNInfo - Value Number Information.
LLVM_ABI void dump() const
LLVM_ABI void print(raw_ostream &OS) const
void markUnused()
Mark this value as unused.
BumpPtrAllocator Allocator
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
BBIterator iterator
Definition BasicBlock.h:87
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
@ Kill
The last use of a register.
@ EarlyClobber
Register definition happens before uses.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2145
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
static void DistributeRange(LiveRangeT &LR, LiveRangeT *SplitLRs[], EqClassesT VNIClasses)
Helper function that distributes live range value numbers and the corresponding segments of a primary...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
ListT< IteratorSpecifierT< T, I, E > > IteratorT
Definition ClauseT.h:290
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
This represents a simple continuous liveness interval for a value.
LLVM_ABI void dump() const