LCOV - code coverage report
Current view: top level - lib/CodeGen - LiveInterval.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 495 540 91.7 %
Date: 2017-09-14 15:23:50 Functions: 44 51 86.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- LiveInterval.cpp - Live Interval Representation --------------------===//
       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             : #include "llvm/CodeGen/LiveInterval.h"
      22             : #include "LiveRangeUtils.h"
      23             : #include "RegisterCoalescer.h"
      24             : #include "llvm/ADT/ArrayRef.h"
      25             : #include "llvm/ADT/STLExtras.h"
      26             : #include "llvm/ADT/SmallPtrSet.h"
      27             : #include "llvm/ADT/SmallVector.h"
      28             : #include "llvm/ADT/iterator_range.h"
      29             : #include "llvm/CodeGen/LiveIntervalAnalysis.h"
      30             : #include "llvm/CodeGen/MachineBasicBlock.h"
      31             : #include "llvm/CodeGen/MachineInstr.h"
      32             : #include "llvm/CodeGen/MachineOperand.h"
      33             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      34             : #include "llvm/CodeGen/SlotIndexes.h"
      35             : #include "llvm/MC/LaneBitmask.h"
      36             : #include "llvm/Support/Compiler.h"
      37             : #include "llvm/Support/Debug.h"
      38             : #include "llvm/Support/raw_ostream.h"
      39             : #include "llvm/Target/TargetRegisterInfo.h"
      40             : #include <algorithm>
      41             : #include <cassert>
      42             : #include <cstddef>
      43             : #include <iterator>
      44             : #include <utility>
      45             : 
      46             : using namespace llvm;
      47             : 
      48             : namespace {
      49             : 
      50             : //===----------------------------------------------------------------------===//
      51             : // Implementation of various methods necessary for calculation of live ranges.
      52             : // The implementation of the methods abstracts from the concrete type of the
      53             : // segment collection.
      54             : //
      55             : // Implementation of the class follows the Template design pattern. The base
      56             : // class contains generic algorithms that call collection-specific methods,
      57             : // which are provided in concrete subclasses. In order to avoid virtual calls
      58             : // these methods are provided by means of C++ template instantiation.
      59             : // The base class calls the methods of the subclass through method impl(),
      60             : // which casts 'this' pointer to the type of the subclass.
      61             : //
      62             : //===----------------------------------------------------------------------===//
      63             : 
      64             : template <typename ImplT, typename IteratorT, typename CollectionT>
      65             : class CalcLiveRangeUtilBase {
      66             : protected:
      67             :   LiveRange *LR;
      68             : 
      69             : protected:
      70    25017983 :   CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {}
      71             : 
      72             : public:
      73             :   using Segment = LiveRange::Segment;
      74             :   using iterator = IteratorT;
      75             : 
      76             :   /// A counterpart of LiveRange::createDeadDef: Make sure the range has a
      77             :   /// value defined at @p Def.
      78             :   /// If @p ForVNI is null, and there is no value defined at @p Def, a new
      79             :   /// value will be allocated using @p VNInfoAllocator.
      80             :   /// If @p ForVNI is null, the return value is the value defined at @p Def,
      81             :   /// either a pre-existing one, or the one newly created.
      82             :   /// If @p ForVNI is not null, then @p Def should be the location where
      83             :   /// @p ForVNI is defined. If the range does not have a value defined at
      84             :   /// @p Def, the value @p ForVNI will be used instead of allocating a new
      85             :   /// one. If the range already has a value defined at @p Def, it must be
      86             :   /// same as @p ForVNI. In either case, @p ForVNI will be the return value.
      87     4242741 :   VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator *VNInfoAllocator,
      88             :                         VNInfo *ForVNI) {
      89             :     assert(!Def.isDead() && "Cannot define a value at the dead slot");
      90             :     assert((!ForVNI || ForVNI->def == Def) &&
      91             :            "If ForVNI is specified, it must match Def");
      92     7023939 :     iterator I = impl().find(Def);
      93     9947025 :     if (I == segments().end()) {
      94     3271597 :       VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
      95    13086388 :       impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
      96     3271597 :       return VNI;
      97             :     }
      98             : 
      99     1833947 :     Segment *S = segmentAt(I);
     100      971144 :     if (SlotIndex::isSameInstr(Def, S->start)) {
     101             :       assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
     102             :       assert(S->valno->def == S->start && "Inconsistent existing value def");
     103             : 
     104             :       // It is possible to have both normal and early-clobber defs of the same
     105             :       // register on an instruction. It doesn't make a lot of sense, but it is
     106             :       // possible to specify in inline assembly.
     107             :       //
     108             :       // Just convert everything to early-clobber.
     109      172918 :       Def = std::min(Def, S->start);
     110       86459 :       if (Def != S->start)
     111           0 :         S->start = S->valno->def = Def;
     112       86459 :       return S->valno;
     113             :     }
     114             :     assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def");
     115      884685 :     VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
     116     3509880 :     segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
     117      884685 :     return VNI;
     118             :   }
     119             : 
     120    13295365 :   VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
     121    13295365 :     if (segments().empty())
     122             :       return nullptr;
     123    26590730 :     iterator I =
     124    13295365 :       impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
     125    13295365 :     if (I == segments().begin())
     126             :       return nullptr;
     127    13295276 :     --I;
     128    26590552 :     if (I->end <= StartIdx)
     129             :       return nullptr;
     130    26366964 :     if (I->end < Use)
     131       88558 :       extendSegmentEndTo(I, Use);
     132    13183482 :     return I->valno;
     133             :   }
     134             : 
     135     6700295 :   std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
     136             :       SlotIndex StartIdx, SlotIndex Use) {
     137     7698217 :     if (segments().empty())
     138           0 :       return std::make_pair(nullptr, false);
     139     6700295 :     SlotIndex BeforeUse = Use.getPrevSlot();
     140    13400590 :     iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr));
     141     7698217 :     if (I == segments().begin())
     142        8192 :       return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
     143     6698247 :     --I;
     144    13396494 :     if (I->end <= StartIdx)
     145     5382440 :       return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
     146    10705274 :     if (I->end < Use) {
     147    10778514 :       if (LR->isUndefIn(Undefs, I->end, BeforeUse))
     148           4 :         return std::make_pair(nullptr, true);
     149     4890375 :       extendSegmentEndTo(I, Use);
     150             :     }
     151     6350499 :     return std::make_pair(I->valno, false);
     152             :   }
     153             : 
     154             :   /// This method is used when we want to extend the segment specified
     155             :   /// by I to end at the specified endpoint. To do this, we should
     156             :   /// merge and eliminate all segments that this will overlap
     157             :   /// with. The iterator is not invalidated.
     158     5395871 :   void extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
     159             :     assert(I != segments().end() && "Not a valid segment!");
     160     6393665 :     Segment *S = segmentAt(I);
     161     5395871 :     VNInfo *ValNo = I->valno;
     162             : 
     163             :     // Search for the first segment that we can't merge with.
     164     5395871 :     iterator MergeTo = std::next(I);
     165    12626424 :     for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo)
     166             :       assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
     167             : 
     168             :     // If NewEnd was in the middle of a segment, make sure to get its endpoint.
     169    11789536 :     S->end = std::max(NewEnd, std::prev(MergeTo)->end);
     170             : 
     171             :     // If the newly formed segment now touches the segment after it and if they
     172             :     // have the same value number, merge the two segments into one segment.
     173     9228284 :     if (MergeTo != segments().end() && MergeTo->start <= I->end &&
     174      366278 :         MergeTo->valno == ValNo) {
     175       29512 :       S->end = MergeTo->end;
     176       29511 :       ++MergeTo;
     177             :     }
     178             : 
     179             :     // Erase any dead segments.
     180    16187613 :     segments().erase(std::next(I), MergeTo);
     181     5395871 :   }
     182             : 
     183             :   /// This method is used when we want to extend the segment specified
     184             :   /// by I to start at the specified endpoint.  To do this, we should
     185             :   /// merge and eliminate all segments that this will overlap with.
     186       60977 :   iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) {
     187             :     assert(I != segments().end() && "Not a valid segment!");
     188       60977 :     Segment *S = segmentAt(I);
     189       60977 :     VNInfo *ValNo = I->valno;
     190             : 
     191             :     // Search for the first segment that we can't merge with.
     192       60977 :     iterator MergeTo = I;
     193             :     do {
     194      121954 :       if (MergeTo == segments().begin()) {
     195          31 :         S->start = NewStart;
     196          62 :         segments().erase(MergeTo, I);
     197          31 :         return I;
     198             :       }
     199             :       assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
     200       60946 :       --MergeTo;
     201       60946 :     } while (NewStart <= MergeTo->start);
     202             : 
     203             :     // If we start in the middle of another segment, just delete a range and
     204             :     // extend that segment.
     205      121892 :     if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
     206           0 :       segmentAt(MergeTo)->end = S->end;
     207             :     } else {
     208             :       // Otherwise, extend the segment right after.
     209       60946 :       ++MergeTo;
     210       60946 :       Segment *MergeToSeg = segmentAt(MergeTo);
     211       60946 :       MergeToSeg->start = NewStart;
     212       60946 :       MergeToSeg->end = S->end;
     213             :     }
     214             : 
     215      243784 :     segments().erase(std::next(MergeTo), std::next(I));
     216       60946 :     return MergeTo;
     217             :   }
     218             : 
     219      779582 :   iterator addSegment(Segment S) {
     220      779582 :     SlotIndex Start = S.start, End = S.end;
     221     1559106 :     iterator I = impl().findInsertPos(S);
     222             : 
     223             :     // If the inserted segment starts in the middle or right at the end of
     224             :     // another segment, just extend that segment to contain the segment of S.
     225      779640 :     if (I != segments().begin()) {
     226          58 :       iterator B = std::prev(I);
     227      635157 :       if (S.valno == B->valno) {
     228     1616298 :         if (B->start <= Start && B->end >= Start) {
     229      416937 :           extendSegmentEndTo(B, End);
     230      416937 :           return B;
     231             :         }
     232             :       } else {
     233             :         // Check to make sure that we are not overlapping two live segments with
     234             :         // different valno's.
     235             :         assert(B->end <= Start &&
     236             :                "Cannot overlap two segments with differing ValID's"
     237             :                " (did you def the same reg twice in a MachineInstr?)");
     238             :       }
     239             :     }
     240             : 
     241             :     // Otherwise, if this segment ends in the middle of, or right next
     242             :     // to, another segment, merge it into that segment.
     243      362669 :     if (I != segments().end()) {
     244      126029 :       if (S.valno == I->valno) {
     245      177866 :         if (I->start <= End) {
     246       60977 :           I = extendSegmentStartTo(I, Start);
     247             : 
     248             :           // If S is a complete superset of a segment, we may need to grow its
     249             :           // endpoint as well.
     250       60977 :           if (End > I->end)
     251           1 :             extendSegmentEndTo(I, End);
     252           0 :           return I;
     253             :         }
     254             :       } else {
     255             :         // Check to make sure that we are not overlapping two live segments with
     256             :         // different valno's.
     257             :         assert(I->start >= End &&
     258             :                "Cannot overlap two segments with differing ValID's");
     259             :       }
     260             :     }
     261             : 
     262             :     // Otherwise, this is just a new segment that doesn't interact with
     263             :     // anything.
     264             :     // Insert it.
     265      301668 :     return segments().insert(I, S);
     266             :   }
     267             : 
     268             : private:
     269             :   ImplT &impl() { return *static_cast<ImplT *>(this); }
     270             : 
     271   100904781 :   CollectionT &segments() { return impl().segmentsColl(); }
     272             : 
     273     1860597 :   Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); }
     274             : };
     275             : 
     276             : //===----------------------------------------------------------------------===//
     277             : //   Instantiation of the methods for calculation of live ranges
     278             : //   based on a segment vector.
     279             : //===----------------------------------------------------------------------===//
     280             : 
     281             : class CalcLiveRangeUtilVector;
     282             : using CalcLiveRangeUtilVectorBase =
     283             :     CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
     284             :                           LiveRange::Segments>;
     285             : 
     286             : class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase {
     287             : public:
     288    45116920 :   CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {}
     289             : 
     290             : private:
     291             :   friend CalcLiveRangeUtilVectorBase;
     292             : 
     293    30725873 :   LiveRange::Segments &segmentsColl() { return LR->segments; }
     294             : 
     295     2672857 :   void insertAtEnd(const Segment &S) { LR->segments.push_back(S); }
     296             : 
     297     2781198 :   iterator find(SlotIndex Pos) { return LR->find(Pos); }
     298             : 
     299             :   iterator findInsertPos(Segment S) {
     300    79109048 :     return std::upper_bound(LR->begin(), LR->end(), S.start);
     301             :   }
     302             : };
     303             : 
     304             : //===----------------------------------------------------------------------===//
     305             : //   Instantiation of the methods for calculation of live ranges
     306             : //   based on a segment set.
     307             : //===----------------------------------------------------------------------===//
     308             : 
     309             : class CalcLiveRangeUtilSet;
     310             : using CalcLiveRangeUtilSetBase =
     311             :     CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator,
     312             :                           LiveRange::SegmentSet>;
     313             : 
     314             : class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase {
     315             : public:
     316     4919046 :   CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {}
     317             : 
     318             : private:
     319             :   friend CalcLiveRangeUtilSetBase;
     320             : 
     321    14613400 :   LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; }
     322             : 
     323             :   void insertAtEnd(const Segment &S) {
     324     2993700 :     LR->segmentSet->insert(LR->segmentSet->end(), S);
     325             :   }
     326             : 
     327     1461543 :   iterator find(SlotIndex Pos) {
     328             :     iterator I =
     329     7307715 :         LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr));
     330     4384629 :     if (I == LR->segmentSet->begin())
     331      708221 :       return I;
     332      753322 :     iterator PrevI = std::prev(I);
     333     1506644 :     if (Pos < (*PrevI).end)
     334        6955 :       return PrevI;
     335      746367 :     return I;
     336             :   }
     337             : 
     338      997980 :   iterator findInsertPos(Segment S) {
     339     2993940 :     iterator I = LR->segmentSet->upper_bound(S);
     340     4261602 :     if (I != LR->segmentSet->end() && !(S.start < *I))
     341             :       ++I;
     342      997980 :     return I;
     343             :   }
     344             : };
     345             : 
     346             : } // end anonymous namespace
     347             : 
     348             : //===----------------------------------------------------------------------===//
     349             : //   LiveRange methods
     350             : //===----------------------------------------------------------------------===//
     351             : 
     352    74806262 : LiveRange::iterator LiveRange::find(SlotIndex Pos) {
     353             :   // This algorithm is basically std::upper_bound.
     354             :   // Unfortunately, std::upper_bound cannot be used with mixed types until we
     355             :   // adopt C++0x. Many libraries can do it, but not all.
     356   218983968 :   if (empty() || Pos >= endIndex())
     357             :     return end();
     358    66138413 :   iterator I = begin();
     359    66138413 :   size_t Len = size();
     360             :   do {
     361    95142101 :     size_t Mid = Len >> 1;
     362   190284202 :     if (Pos < I[Mid].end) {
     363             :       Len = Mid;
     364             :     } else {
     365    14296142 :       I += Mid + 1;
     366    14296142 :       Len -= Mid + 1;
     367             :     }
     368    95142101 :   } while (Len);
     369             :   return I;
     370             : }
     371             : 
     372     4173097 : VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
     373             :   // Use the segment set, if it is available.
     374     8346194 :   if (segmentSet != nullptr)
     375     1461543 :     return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
     376             :   // Otherwise use the segment vector.
     377     2711554 :   return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
     378             : }
     379             : 
     380       69644 : VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
     381             :   // Use the segment set, if it is available.
     382      139288 :   if (segmentSet != nullptr)
     383           0 :     return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
     384             :   // Otherwise use the segment vector.
     385       69644 :   return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
     386             : }
     387             : 
     388             : // overlaps - Return true if the intersection of the two live ranges is
     389             : // not empty.
     390             : //
     391             : // An example for overlaps():
     392             : //
     393             : // 0: A = ...
     394             : // 4: B = ...
     395             : // 8: C = A + B ;; last use of A
     396             : //
     397             : // The live ranges should look like:
     398             : //
     399             : // A = [3, 11)
     400             : // B = [7, x)
     401             : // C = [11, y)
     402             : //
     403             : // A->overlaps(C) should return false since we want to be able to join
     404             : // A and C.
     405             : //
     406      321463 : bool LiveRange::overlapsFrom(const LiveRange& other,
     407             :                              const_iterator StartPos) const {
     408             :   assert(!empty() && "empty range");
     409      321463 :   const_iterator i = begin();
     410      321463 :   const_iterator ie = end();
     411      321463 :   const_iterator j = StartPos;
     412      321463 :   const_iterator je = other.end();
     413             : 
     414             :   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
     415             :          StartPos != other.end() && "Bogus start position hint!");
     416             : 
     417      642926 :   if (i->start < j->start) {
     418      333422 :     i = std::upper_bound(i, ie, j->start);
     419      166711 :     if (i != begin()) --i;
     420      309504 :   } else if (j->start < i->start) {
     421      154190 :     ++StartPos;
     422      238545 :     if (StartPos != other.end() && StartPos->start <= i->start) {
     423             :       assert(StartPos < other.end() && i < end());
     424      123092 :       j = std::upper_bound(j, je, i->start);
     425       61546 :       if (j != other.begin()) --j;
     426             :     }
     427             :   } else {
     428             :     return true;
     429             :   }
     430             : 
     431      320901 :   if (j == je) return false;
     432             : 
     433      531561 :   while (i != ie) {
     434      727708 :     if (i->start > j->start) {
     435      192279 :       std::swap(i, j);
     436             :       std::swap(ie, je);
     437             :     }
     438             : 
     439      727708 :     if (i->end > j->start)
     440             :       return true;
     441      105330 :     ++i;
     442             :   }
     443             : 
     444             :   return false;
     445             : }
     446             : 
     447     7622891 : bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
     448             :                          const SlotIndexes &Indexes) const {
     449             :   assert(!empty() && "empty range");
     450     7622891 :   if (Other.empty())
     451             :     return false;
     452             : 
     453             :   // Use binary searches to find initial positions.
     454     4288286 :   const_iterator I = find(Other.beginIndex());
     455     2144143 :   const_iterator IE = end();
     456     2144143 :   if (I == IE)
     457             :     return false;
     458     3807978 :   const_iterator J = Other.find(I->start);
     459     1903989 :   const_iterator JE = Other.end();
     460     1903989 :   if (J == JE)
     461             :     return false;
     462             : 
     463             :   while (true) {
     464             :     // J has just been advanced to satisfy:
     465             :     assert(J->end >= I->start);
     466             :     // Check for an overlap.
     467     3289424 :     if (J->start < I->end) {
     468             :       // I and J are overlapping. Find the later start.
     469     1792104 :       SlotIndex Def = std::max(I->start, J->start);
     470             :       // Allow the overlap if Def is a coalescable copy.
     471     1791676 :       if (Def.isBlock() ||
     472     1791248 :           !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
     473             :         return true;
     474             :     }
     475             :     // Advance the iterator that ends first to check for more overlaps.
     476     1866698 :     if (J->end > I->end) {
     477      751971 :       std::swap(I, J);
     478             :       std::swap(IE, JE);
     479             :     }
     480             :     // Advance J until J->end >= I->start.
     481             :     do
     482     1200458 :       if (++J == JE)
     483             :         return false;
     484     1083862 :     while (J->end < I->start);
     485             :   }
     486             : }
     487             : 
     488             : /// overlaps - Return true if the live range overlaps an interval specified
     489             : /// by [Start, End).
     490        4899 : bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
     491             :   assert(Start < End && "Invalid range");
     492       14697 :   const_iterator I = std::lower_bound(begin(), end(), End);
     493        5657 :   return I != begin() && (--I)->end > Start;
     494             : }
     495             : 
     496      610112 : bool LiveRange::covers(const LiveRange &Other) const {
     497      610112 :   if (empty())
     498           0 :     return Other.empty();
     499             : 
     500      610112 :   const_iterator I = begin();
     501     2459922 :   for (const Segment &O : Other.segments) {
     502      629586 :     I = advanceTo(I, O.start);
     503     1259172 :     if (I == end() || I->start > O.start)
     504             :       return false;
     505             : 
     506             :     // Check adjacent live segments and see if we can get behind O.end.
     507     2316792 :     while (I->end < O.end) {
     508      528810 :       const_iterator Last = I;
     509             :       // Get next segment and abort if it was not adjacent.
     510      528810 :       ++I;
     511     1057620 :       if (I == end() || Last->end != I->start)
     512             :         return false;
     513             :     }
     514             :   }
     515             :   return true;
     516             : }
     517             : 
     518             : /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
     519             : /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
     520             : /// it can be nuked later.
     521       83727 : void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
     522      167454 :   if (ValNo->id == getNumValNums()-1) {
     523             :     do {
     524      148958 :       valnos.pop_back();
     525       88941 :     } while (!valnos.empty() && valnos.back()->isUnused());
     526             :   } else {
     527             :     ValNo->markUnused();
     528             :   }
     529       83727 : }
     530             : 
     531             : /// RenumberValues - Renumber all values in order of appearance and delete the
     532             : /// remaining unused values.
     533       63745 : void LiveRange::RenumberValues() {
     534      127490 :   SmallPtrSet<VNInfo*, 8> Seen;
     535      127490 :   valnos.clear();
     536      387401 :   for (const Segment &S : segments) {
     537      196166 :     VNInfo *VNI = S.valno;
     538      196166 :     if (!Seen.insert(VNI).second)
     539       79733 :       continue;
     540             :     assert(!VNI->isUnused() && "Unused valno used by live segment");
     541      232866 :     VNI->id = (unsigned)valnos.size();
     542      116433 :     valnos.push_back(VNI);
     543             :   }
     544       63745 : }
     545             : 
     546          58 : void LiveRange::addSegmentToSet(Segment S) {
     547          58 :   CalcLiveRangeUtilSet(this).addSegment(S);
     548          58 : }
     549             : 
     550      779524 : LiveRange::iterator LiveRange::addSegment(Segment S) {
     551             :   // Use the segment set, if it is available.
     552     1559048 :   if (segmentSet != nullptr) {
     553           0 :     addSegmentToSet(S);
     554           0 :     return end();
     555             :   }
     556             :   // Otherwise use the segment vector.
     557      779524 :   return CalcLiveRangeUtilVector(this).addSegment(S);
     558             : }
     559             : 
     560           0 : void LiveRange::append(const Segment S) {
     561             :   // Check that the segment belongs to the back of the list.
     562             :   assert(segments.empty() || segments.back().end <= S.start);
     563           0 :   segments.push_back(S);
     564           0 : }
     565             : 
     566     6700295 : std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
     567             :     SlotIndex StartIdx, SlotIndex Kill) {
     568             :   // Use the segment set, if it is available.
     569    13400590 :   if (segmentSet != nullptr)
     570      997922 :     return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
     571             :   // Otherwise use the segment vector.
     572     5702373 :   return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
     573             : }
     574             : 
     575    13295365 : VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
     576             :   // Use the segment set, if it is available.
     577    26590730 :   if (segmentSet != nullptr)
     578           0 :     return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
     579             :   // Otherwise use the segment vector.
     580    13295365 :   return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
     581             : }
     582             : 
     583             : /// Remove the specified segment from this range.  Note that the segment must
     584             : /// be in a single Segment in its entirety.
     585      118019 : void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
     586             :                               bool RemoveDeadValNo) {
     587             :   // Find the Segment containing this span.
     588      118019 :   iterator I = find(Start);
     589             :   assert(I != end() && "Segment is not in range!");
     590             :   assert(I->containsInterval(Start, End)
     591             :          && "Segment is not entirely in range!");
     592             : 
     593             :   // If the span we are removing is at the start of the Segment, adjust it.
     594      118019 :   VNInfo *ValNo = I->valno;
     595      236038 :   if (I->start == Start) {
     596       66748 :     if (I->end == End) {
     597       32128 :       if (RemoveDeadValNo) {
     598             :         // Check if val# is dead.
     599          73 :         bool isDead = true;
     600         374 :         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
     601         228 :           if (II != I && II->valno == ValNo) {
     602             :             isDead = false;
     603             :             break;
     604             :           }
     605          73 :         if (isDead) {
     606             :           // Now that ValNo is dead, remove it.
     607          73 :           markValNoForDeletion(ValNo);
     608             :         }
     609             :       }
     610             : 
     611       32128 :       segments.erase(I);  // Removed the whole Segment.
     612             :     } else
     613        1246 :       I->start = End;
     614             :     return;
     615             :   }
     616             : 
     617             :   // Otherwise if the span we are removing is at the end of the Segment,
     618             :   // adjust the other way.
     619      169290 :   if (I->end == End) {
     620       84003 :     I->end = Start;
     621       84003 :     return;
     622             :   }
     623             : 
     624             :   // Otherwise, we are splitting the Segment into two pieces.
     625         642 :   SlotIndex OldEnd = I->end;
     626         642 :   I->end = Start;   // Trim the old segment.
     627             : 
     628             :   // Insert the new one.
     629        1926 :   segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
     630             : }
     631             : 
     632             : /// removeValNo - Remove all the segments defined by the specified value#.
     633             : /// Also remove the value# from value# list.
     634       83650 : void LiveRange::removeValNo(VNInfo *ValNo) {
     635       83650 :   if (empty()) return;
     636      603053 :   segments.erase(remove_if(*this, [ValNo](const Segment &S) {
     637             :     return S.valno == ValNo;
     638       83650 :   }), end());
     639             :   // Now that ValNo is dead, remove it.
     640       83650 :   markValNoForDeletion(ValNo);
     641             : }
     642             : 
     643      691253 : void LiveRange::join(LiveRange &Other,
     644             :                      const int *LHSValNoAssignments,
     645             :                      const int *RHSValNoAssignments,
     646             :                      SmallVectorImpl<VNInfo *> &NewVNInfo) {
     647      691253 :   verify();
     648             : 
     649             :   // Determine if any of our values are mapped.  This is uncommon, so we want
     650             :   // to avoid the range scan if not.
     651      691253 :   bool MustMapCurValNos = false;
     652      691253 :   unsigned NumVals = getNumValNums();
     653     1382506 :   unsigned NumNewVals = NewVNInfo.size();
     654     1915284 :   for (unsigned i = 0; i != NumVals; ++i) {
     655     1728448 :     unsigned LHSValID = LHSValNoAssignments[i];
     656     3414783 :     if (i != LHSValID ||
     657     8431675 :         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
     658             :       MustMapCurValNos = true;
     659             :       break;
     660             :     }
     661             :   }
     662             : 
     663             :   // If we have to apply a mapping to our base range assignment, rewrite it now.
     664     1195670 :   if (MustMapCurValNos && !empty()) {
     665             :     // Map the first live range.
     666             : 
     667      504417 :     iterator OutIt = begin();
     668     1008834 :     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
     669     2878584 :     for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
     670     3739500 :       VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
     671             :       assert(nextValNo && "Huh?");
     672             : 
     673             :       // If this live range has the same value # as its immediate predecessor,
     674             :       // and if they are neighbors, remove one Segment.  This happens when we
     675             :       // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
     676     2067054 :       if (OutIt->valno == nextValNo && OutIt->end == I->start) {
     677       14123 :         OutIt->end = I->end;
     678             :       } else {
     679             :         // Didn't merge. Move OutIt to the next segment,
     680     1855627 :         ++OutIt;
     681     1855627 :         OutIt->valno = nextValNo;
     682     1855627 :         if (OutIt != I) {
     683       21427 :           OutIt->start = I->start;
     684       21427 :           OutIt->end = I->end;
     685             :         }
     686             :       }
     687             :     }
     688             :     // If we merge some segments, chop off the end.
     689      504417 :     ++OutIt;
     690     1008834 :     segments.erase(OutIt, end());
     691             :   }
     692             : 
     693             :   // Rewrite Other values before changing the VNInfo ids.
     694             :   // This can leave Other in an invalid state because we're not coalescing
     695             :   // touching segments that now have identical values. That's OK since Other is
     696             :   // not supposed to be valid after calling join();
     697     2922091 :   for (Segment &S : Other.segments)
     698     1696664 :     S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
     699             : 
     700             :   // Update val# info. Renumber them and make sure they all belong to this
     701             :   // LiveRange now. Also remove dead val#'s.
     702             :   unsigned NumValNos = 0;
     703     6240135 :   for (unsigned i = 0; i < NumNewVals; ++i) {
     704     5548882 :     VNInfo *VNI = NewVNInfo[i];
     705     2774441 :     if (VNI) {
     706     2774441 :       if (NumValNos >= NumVals)
     707      125614 :         valnos.push_back(VNI);
     708             :       else
     709     5297654 :         valnos[NumValNos] = VNI;
     710     2774441 :       VNI->id = NumValNos++;  // Renumber val#.
     711             :     }
     712             :   }
     713      691253 :   if (NumNewVals < NumVals)
     714       13749 :     valnos.resize(NumNewVals);  // shrinkify
     715             : 
     716             :   // Okay, now insert the RHS live segments into the LHS.
     717     1382506 :   LiveRangeUpdater Updater(this);
     718     2922091 :   for (Segment &S : Other.segments)
     719      848332 :     Updater.add(S);
     720      691253 : }
     721             : 
     722             : /// Merge all of the segments in RHS into this live range as the specified
     723             : /// value number.  The segments in RHS are allowed to overlap with segments in
     724             : /// the current range, but only if the overlapping segments have the
     725             : /// specified value number.
     726       25099 : void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
     727             :                                        VNInfo *LHSValNo) {
     728       50198 :   LiveRangeUpdater Updater(this);
     729      145911 :   for (const Segment &S : RHS.segments)
     730       70614 :     Updater.add(S.start, S.end, LHSValNo);
     731       25099 : }
     732             : 
     733             : /// MergeValueInAsValue - Merge all of the live segments of a specific val#
     734             : /// in RHS into this live range as the specified value number.
     735             : /// The segments in RHS are allowed to overlap with segments in the
     736             : /// current range, it will replace the value numbers of the overlaped
     737             : /// segments with the specified value number.
     738       18271 : void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
     739             :                                     const VNInfo *RHSValNo,
     740             :                                     VNInfo *LHSValNo) {
     741       36542 :   LiveRangeUpdater Updater(this);
     742      178328 :   for (const Segment &S : RHS.segments)
     743      123515 :     if (S.valno == RHSValNo)
     744             :       Updater.add(S.start, S.end, LHSValNo);
     745       18271 : }
     746             : 
     747             : /// MergeValueNumberInto - This method is called when two value nubmers
     748             : /// are found to be equivalent.  This eliminates V1, replacing all
     749             : /// segments with the V1 value number with the V2 value number.  This can
     750             : /// cause merging of V1/V2 values numbers and compaction of the value space.
     751           4 : VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
     752             :   assert(V1 != V2 && "Identical value#'s are always equivalent!");
     753             : 
     754             :   // This code actually merges the (numerically) larger value number into the
     755             :   // smaller value number, which is likely to allow us to compactify the value
     756             :   // space.  The only thing we have to be careful of is to preserve the
     757             :   // instruction that defines the result value.
     758             : 
     759             :   // Make sure V2 is smaller than V1.
     760           4 :   if (V1->id < V2->id) {
     761           0 :     V1->copyFrom(*V2);
     762             :     std::swap(V1, V2);
     763             :   }
     764             : 
     765             :   // Merge V1 segments into V2.
     766          25 :   for (iterator I = begin(); I != end(); ) {
     767          17 :     iterator S = I++;
     768          17 :     if (S->valno != V1) continue;  // Not a V1 Segment.
     769             : 
     770             :     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
     771             :     // range, extend it.
     772           4 :     if (S != begin()) {
     773           4 :       iterator Prev = S-1;
     774           8 :       if (Prev->valno == V2 && Prev->end == S->start) {
     775           3 :         Prev->end = S->end;
     776             : 
     777             :         // Erase this live-range.
     778           6 :         segments.erase(S);
     779           3 :         I = Prev+1;
     780           3 :         S = Prev;
     781             :       }
     782             :     }
     783             : 
     784             :     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
     785             :     // Ensure that it is a V2 live-range.
     786           4 :     S->valno = V2;
     787             : 
     788             :     // If we can merge it into later V2 segments, do so now.  We ignore any
     789             :     // following V1 segments, as they will be merged in subsequent iterations
     790             :     // of the loop.
     791           4 :     if (I != end()) {
     792           8 :       if (I->start == S->end && I->valno == V2) {
     793           0 :         S->end = I->end;
     794           0 :         segments.erase(I);
     795           0 :         I = S+1;
     796             :       }
     797             :     }
     798             :   }
     799             : 
     800             :   // Now that V1 is dead, remove it.
     801           4 :   markValNoForDeletion(V1);
     802             : 
     803           4 :   return V2;
     804             : }
     805             : 
     806      770264 : void LiveRange::flushSegmentSet() {
     807             :   assert(segmentSet != nullptr && "segment set must have been created");
     808             :   assert(
     809             :       segments.empty() &&
     810             :       "segment set can be used only initially before switching to the array");
     811     3851320 :   segments.append(segmentSet->begin(), segmentSet->end());
     812     1540528 :   segmentSet = nullptr;
     813      770264 :   verify();
     814      770264 : }
     815             : 
     816      527242 : bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
     817      527242 :   ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
     818      527242 :   ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
     819             : 
     820             :   // If there are no regmask slots, we have nothing to search.
     821      527242 :   if (SlotI == SlotE)
     822             :     return false;
     823             : 
     824             :   // Start our search at the first segment that ends after the first slot.
     825      219595 :   const_iterator SegmentI = find(*SlotI);
     826      219595 :   const_iterator SegmentE = end();
     827             : 
     828             :   // If there are no segments that end after the first slot, we're done.
     829      219595 :   if (SegmentI == SegmentE)
     830             :     return false;
     831             : 
     832             :   // Look for each slot in the live range.
     833    27353112 :   for ( ; SlotI != SlotE; ++SlotI) {
     834             :     // Go to the next segment that ends after the current slot.
     835             :     // The slot may be within a hole in the range.
     836    13738580 :     SegmentI = advanceTo(SegmentI, *SlotI);
     837    13738580 :     if (SegmentI == SegmentE)
     838             :       return false;
     839             : 
     840             :     // If this segment contains the slot, we're done.
     841    13633232 :     if (SegmentI->contains(*SlotI))
     842             :       return true;
     843             :     // Otherwise, look for the next slot.
     844             :   }
     845             : 
     846             :   // We didn't find a segment containing any of the slots.
     847             :   return false;
     848             : }
     849             : 
     850      254569 : void LiveInterval::freeSubRange(SubRange *S) {
     851      254569 :   S->~SubRange();
     852             :   // Memory was allocated with BumpPtr allocator and is not freed here.
     853      254569 : }
     854             : 
     855     2292925 : void LiveInterval::removeEmptySubRanges() {
     856     2292925 :   SubRange **NextPtr = &SubRanges;
     857     2292925 :   SubRange *I = *NextPtr;
     858     2545401 :   while (I != nullptr) {
     859      755988 :     if (!I->empty()) {
     860      251036 :       NextPtr = &I->Next;
     861      251036 :       I = *NextPtr;
     862      251036 :       continue;
     863             :     }
     864             :     // Skip empty subranges until we find the first nonempty one.
     865             :     do {
     866        1503 :       SubRange *Next = I->Next;
     867        1503 :       freeSubRange(I);
     868        1503 :       I = Next;
     869        2945 :     } while (I != nullptr && I->empty());
     870        1440 :     *NextPtr = I;
     871             :   }
     872     2292925 : }
     873             : 
     874     2247577 : void LiveInterval::clearSubRanges() {
     875     2500643 :   for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
     876      253066 :     Next = I->Next;
     877      253066 :     freeSubRange(I);
     878             :   }
     879     2247577 :   SubRanges = nullptr;
     880     2247577 : }
     881             : 
     882      481947 : void LiveInterval::refineSubRanges(BumpPtrAllocator &Allocator,
     883             :     LaneBitmask LaneMask, std::function<void(LiveInterval::SubRange&)> Apply) {
     884      481947 :   LaneBitmask ToApply = LaneMask;
     885     2154756 :   for (SubRange &SR : subranges()) {
     886     1190862 :     LaneBitmask SRMask = SR.LaneMask;
     887     1190862 :     LaneBitmask Matching = SRMask & LaneMask;
     888     1190862 :     if (Matching.none())
     889      719826 :       continue;
     890             : 
     891             :     SubRange *MatchingRange;
     892      471036 :     if (SRMask == Matching) {
     893             :       // The subrange fits (it does not cover bits outside \p LaneMask).
     894             :       MatchingRange = &SR;
     895             :     } else {
     896             :       // We have to split the subrange into a matching and non-matching part.
     897             :       // Reduce lanemask of existing lane to non-matching part.
     898      155824 :       SR.LaneMask = SRMask & ~Matching;
     899             :       // Create a new subrange for the matching part
     900       77912 :       MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
     901             :     }
     902      471036 :     Apply(*MatchingRange);
     903      942072 :     ToApply &= ~Matching;
     904             :   }
     905             :   // Create a new subrange if there are uncovered bits left.
     906      481947 :   if (ToApply.any()) {
     907      121981 :     SubRange *NewRange = createSubRange(Allocator, ToApply);
     908             :     Apply(*NewRange);
     909             :   }
     910      481947 : }
     911             : 
     912     2110255 : unsigned LiveInterval::getSize() const {
     913     2110255 :   unsigned Sum = 0;
     914     9932982 :   for (const Segment &S : segments)
     915     7204434 :     Sum += S.start.distance(S.end);
     916     2110255 :   return Sum;
     917             : }
     918             : 
     919      346372 : void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
     920             :                                          LaneBitmask LaneMask,
     921             :                                          const MachineRegisterInfo &MRI,
     922             :                                          const SlotIndexes &Indexes) const {
     923             :   assert(TargetRegisterInfo::isVirtualRegister(reg));
     924      346372 :   LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg);
     925             :   assert((VRegMask & LaneMask).any());
     926      692744 :   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
     927     1754595 :   for (const MachineOperand &MO : MRI.def_operands(reg)) {
     928      715479 :     if (!MO.isUndef())
     929      553382 :       continue;
     930      162097 :     unsigned SubReg = MO.getSubReg();
     931             :     assert(SubReg != 0 && "Undef should only be set on subreg defs");
     932      324194 :     LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
     933      324194 :     LaneBitmask UndefMask = VRegMask & ~DefMask;
     934      162097 :     if ((UndefMask & LaneMask).any()) {
     935      120586 :       const MachineInstr &MI = *MO.getParent();
     936      120586 :       bool EarlyClobber = MO.isEarlyClobber();
     937      241172 :       SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
     938      120586 :       Undefs.push_back(Pos);
     939             :     }
     940             :   }
     941      346372 : }
     942             : 
     943           0 : raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
     944           0 :   return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
     945             : }
     946             : 
     947             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     948             : LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
     949             :   dbgs() << *this << '\n';
     950             : }
     951             : #endif
     952             : 
     953           0 : void LiveRange::print(raw_ostream &OS) const {
     954           0 :   if (empty())
     955           0 :     OS << "EMPTY";
     956             :   else {
     957           0 :     for (const Segment &S : segments) {
     958           0 :       OS << S;
     959             :       assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
     960             :     }
     961             :   }
     962             : 
     963             :   // Print value number info.
     964           0 :   if (getNumValNums()) {
     965           0 :     OS << "  ";
     966           0 :     unsigned vnum = 0;
     967           0 :     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
     968             :          ++i, ++vnum) {
     969           0 :       const VNInfo *vni = *i;
     970           0 :       if (vnum) OS << ' ';
     971           0 :       OS << vnum << '@';
     972           0 :       if (vni->isUnused()) {
     973             :         OS << 'x';
     974             :       } else {
     975           0 :         OS << vni->def;
     976           0 :         if (vni->isPHIDef())
     977           0 :           OS << "-phi";
     978             :       }
     979             :     }
     980             :   }
     981           0 : }
     982             : 
     983           0 : void LiveInterval::SubRange::print(raw_ostream &OS) const {
     984           0 :   OS << " L" << PrintLaneMask(LaneMask) << ' '
     985           0 :      << static_cast<const LiveRange&>(*this);
     986           0 : }
     987             : 
     988           0 : void LiveInterval::print(raw_ostream &OS) const {
     989           0 :   OS << PrintReg(reg) << ' ';
     990           0 :   super::print(OS);
     991             :   // Print subranges
     992           0 :   for (const SubRange &SR : subranges())
     993           0 :     OS << SR;
     994           0 : }
     995             : 
     996             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     997             : LLVM_DUMP_METHOD void LiveRange::dump() const {
     998             :   dbgs() << *this << '\n';
     999             : }
    1000             : 
    1001             : LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
    1002             :   dbgs() << *this << '\n';
    1003             : }
    1004             : 
    1005             : LLVM_DUMP_METHOD void LiveInterval::dump() const {
    1006             :   dbgs() << *this << '\n';
    1007             : }
    1008             : #endif
    1009             : 
    1010             : #ifndef NDEBUG
    1011             : void LiveRange::verify() const {
    1012             :   for (const_iterator I = begin(), E = end(); I != E; ++I) {
    1013             :     assert(I->start.isValid());
    1014             :     assert(I->end.isValid());
    1015             :     assert(I->start < I->end);
    1016             :     assert(I->valno != nullptr);
    1017             :     assert(I->valno->id < valnos.size());
    1018             :     assert(I->valno == valnos[I->valno->id]);
    1019             :     if (std::next(I) != E) {
    1020             :       assert(I->end <= std::next(I)->start);
    1021             :       if (I->end == std::next(I)->start)
    1022             :         assert(I->valno != std::next(I)->valno);
    1023             :     }
    1024             :   }
    1025             : }
    1026             : 
    1027             : void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
    1028             :   super::verify();
    1029             : 
    1030             :   // Make sure SubRanges are fine and LaneMasks are disjunct.
    1031             :   LaneBitmask Mask;
    1032             :   LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg)
    1033             :                                        : LaneBitmask::getAll();
    1034             :   for (const SubRange &SR : subranges()) {
    1035             :     // Subrange lanemask should be disjunct to any previous subrange masks.
    1036             :     assert((Mask & SR.LaneMask).none());
    1037             :     Mask |= SR.LaneMask;
    1038             : 
    1039             :     // subrange mask should not contained in maximum lane mask for the vreg.
    1040             :     assert((Mask & ~MaxMask).none());
    1041             :     // empty subranges must be removed.
    1042             :     assert(!SR.empty());
    1043             : 
    1044             :     SR.verify();
    1045             :     // Main liverange should cover subrange.
    1046             :     assert(covers(SR));
    1047             :   }
    1048             : }
    1049             : #endif
    1050             : 
    1051             : //===----------------------------------------------------------------------===//
    1052             : //                           LiveRangeUpdater class
    1053             : //===----------------------------------------------------------------------===//
    1054             : //
    1055             : // The LiveRangeUpdater class always maintains these invariants:
    1056             : //
    1057             : // - When LastStart is invalid, Spills is empty and the iterators are invalid.
    1058             : //   This is the initial state, and the state created by flush().
    1059             : //   In this state, isDirty() returns false.
    1060             : //
    1061             : // Otherwise, segments are kept in three separate areas:
    1062             : //
    1063             : // 1. [begin; WriteI) at the front of LR.
    1064             : // 2. [ReadI; end) at the back of LR.
    1065             : // 3. Spills.
    1066             : //
    1067             : // - LR.begin() <= WriteI <= ReadI <= LR.end().
    1068             : // - Segments in all three areas are fully ordered and coalesced.
    1069             : // - Segments in area 1 precede and can't coalesce with segments in area 2.
    1070             : // - Segments in Spills precede and can't coalesce with segments in area 2.
    1071             : // - No coalescing is possible between segments in Spills and segments in area
    1072             : //   1, and there are no overlapping segments.
    1073             : //
    1074             : // The segments in Spills are not ordered with respect to the segments in area
    1075             : // 1. They need to be merged.
    1076             : //
    1077             : // When they exist, Spills.back().start <= LastStart,
    1078             : //                 and WriteI[-1].start <= LastStart.
    1079             : 
    1080             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    1081             : void LiveRangeUpdater::print(raw_ostream &OS) const {
    1082             :   if (!isDirty()) {
    1083             :     if (LR)
    1084             :       OS << "Clean updater: " << *LR << '\n';
    1085             :     else
    1086             :       OS << "Null updater.\n";
    1087             :     return;
    1088             :   }
    1089             :   assert(LR && "Can't have null LR in dirty updater.");
    1090             :   OS << " updater with gap = " << (ReadI - WriteI)
    1091             :      << ", last start = " << LastStart
    1092             :      << ":\n  Area 1:";
    1093             :   for (const auto &S : make_range(LR->begin(), WriteI))
    1094             :     OS << ' ' << S;
    1095             :   OS << "\n  Spills:";
    1096             :   for (unsigned I = 0, E = Spills.size(); I != E; ++I)
    1097             :     OS << ' ' << Spills[I];
    1098             :   OS << "\n  Area 2:";
    1099             :   for (const auto &S : make_range(ReadI, LR->end()))
    1100             :     OS << ' ' << S;
    1101             :   OS << '\n';
    1102             : }
    1103             : 
    1104             : LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
    1105             :   print(errs());
    1106             : }
    1107             : #endif
    1108             : 
    1109             : // Determine if A and B should be coalesced.
    1110             : static inline bool coalescable(const LiveRange::Segment &A,
    1111             :                                const LiveRange::Segment &B) {
    1112             :   assert(A.start <= B.start && "Unordered live segments.");
    1113     6080062 :   if (A.end == B.start)
    1114     2064769 :     return A.valno == B.valno;
    1115     1950524 :   if (A.end < B.start)
    1116             :     return false;
    1117             :   assert(A.valno == B.valno && "Cannot overlap different values");
    1118             :   return true;
    1119             : }
    1120             : 
    1121     2280938 : void LiveRangeUpdater::add(LiveRange::Segment Seg) {
    1122             :   assert(LR && "Cannot add to a null destination");
    1123             : 
    1124             :   // Fall back to the regular add method if the live range
    1125             :   // is using the segment set instead of the segment vector.
    1126     4561876 :   if (LR->segmentSet != nullptr) {
    1127          58 :     LR->addSegmentToSet(Seg);
    1128          58 :     return;
    1129             :   }
    1130             : 
    1131             :   // Flush the state if Start moves backwards.
    1132     5873750 :   if (!LastStart.isValid() || LastStart > Seg.start) {
    1133     1020720 :     if (isDirty())
    1134       51830 :       flush();
    1135             :     // This brings us to an uninitialized state. Reinitialize.
    1136             :     assert(Spills.empty() && "Leftover spilled segments");
    1137     2041440 :     WriteI = ReadI = LR->begin();
    1138             :   }
    1139             : 
    1140             :   // Remember start for next time.
    1141     2280880 :   LastStart = Seg.start;
    1142             : 
    1143             :   // Advance ReadI until it ends after Seg.start.
    1144     4561760 :   LiveRange::iterator E = LR->end();
    1145     3528747 :   if (ReadI != E && ReadI->end <= Seg.start) {
    1146             :     // First try to close the gap between WriteI and ReadI with spills.
    1147      563383 :     if (ReadI != WriteI)
    1148        5575 :       mergeSpills();
    1149             :     // Then advance ReadI.
    1150      563383 :     if (ReadI == WriteI)
    1151      557985 :       ReadI = WriteI = LR->find(Seg.start);
    1152             :     else
    1153       44640 :       while (ReadI != E && ReadI->end <= Seg.start)
    1154       12330 :         *WriteI++ = *ReadI++;
    1155             :   }
    1156             : 
    1157             :   assert(ReadI == E || ReadI->end > Seg.start);
    1158             : 
    1159             :   // Check if the ReadI segment begins early.
    1160     3223810 :   if (ReadI != E && ReadI->start <= Seg.start) {
    1161             :     assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
    1162             :     // Bail if Seg is completely contained in ReadI.
    1163      148086 :     if (ReadI->end >= Seg.end)
    1164             :       return;
    1165             :     // Coalesce into Seg.
    1166       22108 :     Seg.start = ReadI->start;
    1167       22108 :     ++ReadI;
    1168             :   }
    1169             : 
    1170             :   // Coalesce as much as possible from ReadI into Seg.
    1171     4045701 :   while (ReadI != E && coalescable(Seg, *ReadI)) {
    1172     1063850 :     Seg.end = std::max(Seg.end, ReadI->end);
    1173      531925 :     ++ReadI;
    1174             :   }
    1175             : 
    1176             :   // Try coalescing Spills.back() into Seg.
    1177     2698056 :   if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
    1178       60538 :     Seg.start = Spills.back().start;
    1179       90807 :     Seg.end = std::max(Spills.back().end, Seg.end);
    1180       30269 :     Spills.pop_back();
    1181             :   }
    1182             : 
    1183             :   // Try coalescing Seg into WriteI[-1].
    1184     5680336 :   if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
    1185     2257496 :     WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
    1186     1128748 :     return;
    1187             :   }
    1188             : 
    1189             :   // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
    1190     1100197 :   if (WriteI != ReadI) {
    1191      519010 :     *WriteI++ = Seg;
    1192      519010 :     return;
    1193             :   }
    1194             : 
    1195             :   // Finally, append to LR or Spills.
    1196      581187 :   if (WriteI == E) {
    1197      368393 :     LR->segments.push_back(Seg);
    1198      736786 :     WriteI = ReadI = LR->end();
    1199             :   } else
    1200      212794 :     Spills.push_back(Seg);
    1201             : }
    1202             : 
    1203             : // Merge as many spilled segments as possible into the gap between WriteI
    1204             : // and ReadI. Advance WriteI to reflect the inserted instructions.
    1205      121024 : void LiveRangeUpdater::mergeSpills() {
    1206             :   // Perform a backwards merge of Spills and [SpillI;WriteI).
    1207      121024 :   size_t GapSize = ReadI - WriteI;
    1208      363072 :   size_t NumMoved = std::min(Spills.size(), GapSize);
    1209      121024 :   LiveRange::iterator Src = WriteI;
    1210      121024 :   LiveRange::iterator Dst = Src + NumMoved;
    1211      121024 :   LiveRange::iterator SpillSrc = Spills.end();
    1212      242048 :   LiveRange::iterator B = LR->begin();
    1213             : 
    1214             :   // This is the new WriteI position after merging spills.
    1215      121024 :   WriteI = Dst;
    1216             : 
    1217             :   // Now merge Src and Spills backwards.
    1218      433537 :   while (Src != Dst) {
    1219      529061 :     if (Src != B && Src[-1].start > SpillSrc[-1].start)
    1220      129988 :       *--Dst = *--Src;
    1221             :     else
    1222      182525 :       *--Dst = *--SpillSrc;
    1223             :   }
    1224             :   assert(NumMoved == size_t(Spills.end() - SpillSrc));
    1225      242048 :   Spills.erase(SpillSrc, Spills.end());
    1226      121024 : }
    1227             : 
    1228     1097908 : void LiveRangeUpdater::flush() {
    1229     1097908 :   if (!isDirty())
    1230             :     return;
    1231             :   // Clear the dirty state.
    1232     1020720 :   LastStart = SlotIndex();
    1233             : 
    1234             :   assert(LR && "Cannot add to a null destination");
    1235             : 
    1236             :   // Nothing to merge?
    1237     1020720 :   if (Spills.empty()) {
    1238     1810542 :     LR->segments.erase(WriteI, ReadI);
    1239      905271 :     LR->verify();
    1240             :     return;
    1241             :   }
    1242             : 
    1243             :   // Resize the WriteI - ReadI gap to match Spills.
    1244      115449 :   size_t GapSize = ReadI - WriteI;
    1245      230898 :   if (GapSize < Spills.size()) {
    1246             :     // The gap is too small. Make some room.
    1247      230722 :     size_t WritePos = WriteI - LR->begin();
    1248      346083 :     LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
    1249             :     // This also invalidated ReadI, but it is recomputed below.
    1250      230722 :     WriteI = LR->begin() + WritePos;
    1251             :   } else {
    1252             :     // Shrink the gap if necessary.
    1253         176 :     LR->segments.erase(WriteI + Spills.size(), ReadI);
    1254             :   }
    1255      230898 :   ReadI = WriteI + Spills.size();
    1256      115449 :   mergeSpills();
    1257      115449 :   LR->verify();
    1258             : }
    1259             : 
    1260     1304507 : unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
    1261             :   // Create initial equivalence classes.
    1262     2609014 :   EqClass.clear();
    1263     2609014 :   EqClass.grow(LR.getNumValNums());
    1264             : 
    1265     1304507 :   const VNInfo *used = nullptr, *unused = nullptr;
    1266             : 
    1267             :   // Determine connections.
    1268     5628314 :   for (const VNInfo *VNI : LR.valnos) {
    1269             :     // Group all unused values into one class.
    1270     1715012 :     if (VNI->isUnused()) {
    1271         219 :       if (unused)
    1272          16 :         EqClass.join(unused->id, VNI->id);
    1273         219 :       unused = VNI;
    1274         219 :       continue;
    1275             :     }
    1276     1714574 :     used = VNI;
    1277     1714574 :     if (VNI->isPHIDef()) {
    1278       90070 :       const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
    1279             :       assert(MBB && "Phi-def has no defining MBB");
    1280             :       // Connect to values live out of predecessors.
    1281       45035 :       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
    1282      184905 :            PE = MBB->pred_end(); PI != PE; ++PI)
    1283      189670 :         if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
    1284       94827 :           EqClass.join(VNI->id, PVNI->id);
    1285             :     } else {
    1286             :       // Normal value defined by an instruction. Check for two-addr redef.
    1287             :       // FIXME: This could be coincidental. Should we really check for a tied
    1288             :       // operand constraint?
    1289             :       // Note that VNI->def may be a use slot for an early clobber def.
    1290     1669539 :       if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
    1291      332988 :         EqClass.join(VNI->id, UVNI->id);
    1292             :     }
    1293             :   }
    1294             : 
    1295             :   // Lump all the unused values in with the last used value.
    1296     1304507 :   if (used && unused)
    1297         203 :     EqClass.join(used->id, unused->id);
    1298             : 
    1299     1304507 :   EqClass.compress();
    1300     1304507 :   return EqClass.getNumClasses();
    1301             : }
    1302             : 
    1303        4992 : void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
    1304             :                                           MachineRegisterInfo &MRI) {
    1305             :   // Rewrite instructions.
    1306        4992 :   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
    1307      112639 :        RE = MRI.reg_end(); RI != RE;) {
    1308      107647 :     MachineOperand &MO = *RI;
    1309      107647 :     MachineInstr *MI = RI->getParent();
    1310      107647 :     ++RI;
    1311             :     // DBG_VALUE instructions don't have slot indexes, so get the index of the
    1312             :     // instruction before them.
    1313             :     // Normally, DBG_VALUE instructions are removed before this function is
    1314             :     // called, but it is not a requirement.
    1315      107647 :     SlotIndex Idx;
    1316      107647 :     if (MI->isDebugValue())
    1317           1 :       Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
    1318             :     else
    1319      215292 :       Idx = LIS.getInstructionIndex(*MI);
    1320      107647 :     LiveQueryResult LRQ = LI.Query(Idx);
    1321      128221 :     const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
    1322             :     // In the case of an <undef> use that isn't tied to any def, VNI will be
    1323             :     // NULL. If the use is tied to a def, VNI will be the defined value.
    1324      107647 :     if (!VNI)
    1325           1 :       continue;
    1326      215292 :     if (unsigned EqClass = getEqClass(VNI))
    1327       53819 :       MO.setReg(LIV[EqClass-1]->reg);
    1328             :   }
    1329             : 
    1330             :   // Distribute subregister liveranges.
    1331        4992 :   if (LI.hasSubRanges()) {
    1332           5 :     unsigned NumComponents = EqClass.getNumClasses();
    1333          10 :     SmallVector<unsigned, 8> VNIMapping;
    1334          10 :     SmallVector<LiveInterval::SubRange*, 8> SubRanges;
    1335          10 :     BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
    1336          24 :     for (LiveInterval::SubRange &SR : LI.subranges()) {
    1337             :       // Create new subranges in the split intervals and construct a mapping
    1338             :       // for the VNInfos in the subrange.
    1339          28 :       unsigned NumValNos = SR.valnos.size();
    1340          14 :       VNIMapping.clear();
    1341          14 :       VNIMapping.reserve(NumValNos);
    1342          14 :       SubRanges.clear();
    1343          14 :       SubRanges.resize(NumComponents-1, nullptr);
    1344          40 :       for (unsigned I = 0; I < NumValNos; ++I) {
    1345          52 :         const VNInfo &VNI = *SR.valnos[I];
    1346             :         unsigned ComponentNum;
    1347          26 :         if (VNI.isUnused()) {
    1348           2 :           ComponentNum = 0;
    1349             :         } else {
    1350          48 :           const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
    1351             :           assert(MainRangeVNI != nullptr
    1352             :                  && "SubRange def must have corresponding main range def");
    1353          48 :           ComponentNum = getEqClass(MainRangeVNI);
    1354          38 :           if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
    1355          28 :             SubRanges[ComponentNum-1]
    1356          28 :               = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
    1357             :           }
    1358             :         }
    1359          26 :         VNIMapping.push_back(ComponentNum);
    1360             :       }
    1361          42 :       DistributeRange(SR, SubRanges.data(), VNIMapping);
    1362             :     }
    1363           5 :     LI.removeEmptySubRanges();
    1364             :   }
    1365             : 
    1366             :   // Distribute main liverange.
    1367       14976 :   DistributeRange(LI, LIV, EqClass);
    1368        4992 : }

Generated by: LCOV version 1.13