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