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 "RegisterCoalescer.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/Target/TargetRegisterInfo.h" 31 #include <algorithm> 32 using namespace llvm; 33 34 namespace { 35 //===----------------------------------------------------------------------===// 36 // Implementation of various methods necessary for calculation of live ranges. 37 // The implementation of the methods abstracts from the concrete type of the 38 // segment collection. 39 // 40 // Implementation of the class follows the Template design pattern. The base 41 // class contains generic algorithms that call collection-specific methods, 42 // which are provided in concrete subclasses. In order to avoid virtual calls 43 // these methods are provided by means of C++ template instantiation. 44 // The base class calls the methods of the subclass through method impl(), 45 // which casts 'this' pointer to the type of the subclass. 46 // 47 //===----------------------------------------------------------------------===// 48 49 template <typename ImplT, typename IteratorT, typename CollectionT> 50 class CalcLiveRangeUtilBase { 51 protected: 52 LiveRange *LR; 53 54 protected: 55 CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {} 56 57 public: 58 typedef LiveRange::Segment Segment; 59 typedef IteratorT iterator; 60 61 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator) { 62 assert(!Def.isDead() && "Cannot define a value at the dead slot"); 63 64 iterator I = impl().find(Def); 65 if (I == segments().end()) { 66 VNInfo *VNI = LR->getNextValue(Def, VNInfoAllocator); 67 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI)); 68 return VNI; 69 } 70 71 Segment *S = segmentAt(I); 72 if (SlotIndex::isSameInstr(Def, S->start)) { 73 assert(S->valno->def == S->start && "Inconsistent existing value def"); 74 75 // It is possible to have both normal and early-clobber defs of the same 76 // register on an instruction. It doesn't make a lot of sense, but it is 77 // possible to specify in inline assembly. 78 // 79 // Just convert everything to early-clobber. 80 Def = std::min(Def, S->start); 81 if (Def != S->start) 82 S->start = S->valno->def = Def; 83 return S->valno; 84 } 85 assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def"); 86 VNInfo *VNI = LR->getNextValue(Def, VNInfoAllocator); 87 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI)); 88 return VNI; 89 } 90 91 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) { 92 if (segments().empty()) 93 return nullptr; 94 iterator I = 95 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr)); 96 if (I == segments().begin()) 97 return nullptr; 98 --I; 99 if (I->end <= StartIdx) 100 return nullptr; 101 if (I->end < Use) 102 extendSegmentEndTo(I, Use); 103 return I->valno; 104 } 105 106 /// This method is used when we want to extend the segment specified 107 /// by I to end at the specified endpoint. To do this, we should 108 /// merge and eliminate all segments that this will overlap 109 /// with. The iterator is not invalidated. 110 void extendSegmentEndTo(iterator I, SlotIndex NewEnd) { 111 assert(I != segments().end() && "Not a valid segment!"); 112 Segment *S = segmentAt(I); 113 VNInfo *ValNo = I->valno; 114 115 // Search for the first segment that we can't merge with. 116 iterator MergeTo = std::next(I); 117 for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo) 118 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!"); 119 120 // If NewEnd was in the middle of a segment, make sure to get its endpoint. 121 S->end = std::max(NewEnd, std::prev(MergeTo)->end); 122 123 // If the newly formed segment now touches the segment after it and if they 124 // have the same value number, merge the two segments into one segment. 125 if (MergeTo != segments().end() && MergeTo->start <= I->end && 126 MergeTo->valno == ValNo) { 127 S->end = MergeTo->end; 128 ++MergeTo; 129 } 130 131 // Erase any dead segments. 132 segments().erase(std::next(I), MergeTo); 133 } 134 135 /// This method is used when we want to extend the segment specified 136 /// by I to start at the specified endpoint. To do this, we should 137 /// merge and eliminate all segments that this will overlap with. 138 iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) { 139 assert(I != segments().end() && "Not a valid segment!"); 140 Segment *S = segmentAt(I); 141 VNInfo *ValNo = I->valno; 142 143 // Search for the first segment that we can't merge with. 144 iterator MergeTo = I; 145 do { 146 if (MergeTo == segments().begin()) { 147 S->start = NewStart; 148 segments().erase(MergeTo, I); 149 return I; 150 } 151 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!"); 152 --MergeTo; 153 } while (NewStart <= MergeTo->start); 154 155 // If we start in the middle of another segment, just delete a range and 156 // extend that segment. 157 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) { 158 segmentAt(MergeTo)->end = S->end; 159 } else { 160 // Otherwise, extend the segment right after. 161 ++MergeTo; 162 Segment *MergeToSeg = segmentAt(MergeTo); 163 MergeToSeg->start = NewStart; 164 MergeToSeg->end = S->end; 165 } 166 167 segments().erase(std::next(MergeTo), std::next(I)); 168 return MergeTo; 169 } 170 171 iterator addSegment(Segment S) { 172 SlotIndex Start = S.start, End = S.end; 173 iterator I = impl().findInsertPos(S); 174 175 // If the inserted segment starts in the middle or right at the end of 176 // another segment, just extend that segment to contain the segment of S. 177 if (I != segments().begin()) { 178 iterator B = std::prev(I); 179 if (S.valno == B->valno) { 180 if (B->start <= Start && B->end >= Start) { 181 extendSegmentEndTo(B, End); 182 return B; 183 } 184 } else { 185 // Check to make sure that we are not overlapping two live segments with 186 // different valno's. 187 assert(B->end <= Start && 188 "Cannot overlap two segments with differing ValID's" 189 " (did you def the same reg twice in a MachineInstr?)"); 190 } 191 } 192 193 // Otherwise, if this segment ends in the middle of, or right next 194 // to, another segment, merge it into that segment. 195 if (I != segments().end()) { 196 if (S.valno == I->valno) { 197 if (I->start <= End) { 198 I = extendSegmentStartTo(I, Start); 199 200 // If S is a complete superset of a segment, we may need to grow its 201 // endpoint as well. 202 if (End > I->end) 203 extendSegmentEndTo(I, End); 204 return I; 205 } 206 } else { 207 // Check to make sure that we are not overlapping two live segments with 208 // different valno's. 209 assert(I->start >= End && 210 "Cannot overlap two segments with differing ValID's"); 211 } 212 } 213 214 // Otherwise, this is just a new segment that doesn't interact with 215 // anything. 216 // Insert it. 217 return segments().insert(I, S); 218 } 219 220 private: 221 ImplT &impl() { return *static_cast<ImplT *>(this); } 222 223 CollectionT &segments() { return impl().segmentsColl(); } 224 225 Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); } 226 }; 227 228 //===----------------------------------------------------------------------===// 229 // Instantiation of the methods for calculation of live ranges 230 // based on a segment vector. 231 //===----------------------------------------------------------------------===// 232 233 class CalcLiveRangeUtilVector; 234 typedef CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator, 235 LiveRange::Segments> CalcLiveRangeUtilVectorBase; 236 237 class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase { 238 public: 239 CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {} 240 241 private: 242 friend CalcLiveRangeUtilVectorBase; 243 244 LiveRange::Segments &segmentsColl() { return LR->segments; } 245 246 void insertAtEnd(const Segment &S) { LR->segments.push_back(S); } 247 248 iterator find(SlotIndex Pos) { return LR->find(Pos); } 249 250 iterator findInsertPos(Segment S) { 251 return std::upper_bound(LR->begin(), LR->end(), S.start); 252 } 253 }; 254 255 //===----------------------------------------------------------------------===// 256 // Instantiation of the methods for calculation of live ranges 257 // based on a segment set. 258 //===----------------------------------------------------------------------===// 259 260 class CalcLiveRangeUtilSet; 261 typedef CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, 262 LiveRange::SegmentSet::iterator, 263 LiveRange::SegmentSet> CalcLiveRangeUtilSetBase; 264 265 class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase { 266 public: 267 CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {} 268 269 private: 270 friend CalcLiveRangeUtilSetBase; 271 272 LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; } 273 274 void insertAtEnd(const Segment &S) { 275 LR->segmentSet->insert(LR->segmentSet->end(), S); 276 } 277 278 iterator find(SlotIndex Pos) { 279 iterator I = 280 LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr)); 281 if (I == LR->segmentSet->begin()) 282 return I; 283 iterator PrevI = std::prev(I); 284 if (Pos < (*PrevI).end) 285 return PrevI; 286 return I; 287 } 288 289 iterator findInsertPos(Segment S) { 290 iterator I = LR->segmentSet->upper_bound(S); 291 if (I != LR->segmentSet->end() && !(S.start < *I)) 292 ++I; 293 return I; 294 } 295 }; 296 } // namespace 297 298 //===----------------------------------------------------------------------===// 299 // LiveRange methods 300 //===----------------------------------------------------------------------===// 301 302 LiveRange::iterator LiveRange::find(SlotIndex Pos) { 303 // This algorithm is basically std::upper_bound. 304 // Unfortunately, std::upper_bound cannot be used with mixed types until we 305 // adopt C++0x. Many libraries can do it, but not all. 306 if (empty() || Pos >= endIndex()) 307 return end(); 308 iterator I = begin(); 309 size_t Len = size(); 310 do { 311 size_t Mid = Len >> 1; 312 if (Pos < I[Mid].end) 313 Len = Mid; 314 else 315 I += Mid + 1, Len -= Mid + 1; 316 } while (Len); 317 return I; 318 } 319 320 VNInfo *LiveRange::createDeadDef(SlotIndex Def, 321 VNInfo::Allocator &VNInfoAllocator) { 322 // Use the segment set, if it is available. 323 if (segmentSet != nullptr) 324 return CalcLiveRangeUtilSet(this).createDeadDef(Def, VNInfoAllocator); 325 // Otherwise use the segment vector. 326 return CalcLiveRangeUtilVector(this).createDeadDef(Def, VNInfoAllocator); 327 } 328 329 // overlaps - Return true if the intersection of the two live ranges is 330 // not empty. 331 // 332 // An example for overlaps(): 333 // 334 // 0: A = ... 335 // 4: B = ... 336 // 8: C = A + B ;; last use of A 337 // 338 // The live ranges should look like: 339 // 340 // A = [3, 11) 341 // B = [7, x) 342 // C = [11, y) 343 // 344 // A->overlaps(C) should return false since we want to be able to join 345 // A and C. 346 // 347 bool LiveRange::overlapsFrom(const LiveRange& other, 348 const_iterator StartPos) const { 349 assert(!empty() && "empty range"); 350 const_iterator i = begin(); 351 const_iterator ie = end(); 352 const_iterator j = StartPos; 353 const_iterator je = other.end(); 354 355 assert((StartPos->start <= i->start || StartPos == other.begin()) && 356 StartPos != other.end() && "Bogus start position hint!"); 357 358 if (i->start < j->start) { 359 i = std::upper_bound(i, ie, j->start); 360 if (i != begin()) --i; 361 } else if (j->start < i->start) { 362 ++StartPos; 363 if (StartPos != other.end() && StartPos->start <= i->start) { 364 assert(StartPos < other.end() && i < end()); 365 j = std::upper_bound(j, je, i->start); 366 if (j != other.begin()) --j; 367 } 368 } else { 369 return true; 370 } 371 372 if (j == je) return false; 373 374 while (i != ie) { 375 if (i->start > j->start) { 376 std::swap(i, j); 377 std::swap(ie, je); 378 } 379 380 if (i->end > j->start) 381 return true; 382 ++i; 383 } 384 385 return false; 386 } 387 388 bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP, 389 const SlotIndexes &Indexes) const { 390 assert(!empty() && "empty range"); 391 if (Other.empty()) 392 return false; 393 394 // Use binary searches to find initial positions. 395 const_iterator I = find(Other.beginIndex()); 396 const_iterator IE = end(); 397 if (I == IE) 398 return false; 399 const_iterator J = Other.find(I->start); 400 const_iterator JE = Other.end(); 401 if (J == JE) 402 return false; 403 404 for (;;) { 405 // J has just been advanced to satisfy: 406 assert(J->end >= I->start); 407 // Check for an overlap. 408 if (J->start < I->end) { 409 // I and J are overlapping. Find the later start. 410 SlotIndex Def = std::max(I->start, J->start); 411 // Allow the overlap if Def is a coalescable copy. 412 if (Def.isBlock() || 413 !CP.isCoalescable(Indexes.getInstructionFromIndex(Def))) 414 return true; 415 } 416 // Advance the iterator that ends first to check for more overlaps. 417 if (J->end > I->end) { 418 std::swap(I, J); 419 std::swap(IE, JE); 420 } 421 // Advance J until J->end >= I->start. 422 do 423 if (++J == JE) 424 return false; 425 while (J->end < I->start); 426 } 427 } 428 429 /// overlaps - Return true if the live range overlaps an interval specified 430 /// by [Start, End). 431 bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const { 432 assert(Start < End && "Invalid range"); 433 const_iterator I = std::lower_bound(begin(), end(), End); 434 return I != begin() && (--I)->end > Start; 435 } 436 437 bool LiveRange::covers(const LiveRange &Other) const { 438 if (empty()) 439 return Other.empty(); 440 441 const_iterator I = begin(); 442 for (const Segment &O : Other.segments) { 443 I = advanceTo(I, O.start); 444 if (I == end() || I->start > O.start) 445 return false; 446 447 // Check adjacent live segments and see if we can get behind O.end. 448 while (I->end < O.end) { 449 const_iterator Last = I; 450 // Get next segment and abort if it was not adjacent. 451 ++I; 452 if (I == end() || Last->end != I->start) 453 return false; 454 } 455 } 456 return true; 457 } 458 459 /// ValNo is dead, remove it. If it is the largest value number, just nuke it 460 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so 461 /// it can be nuked later. 462 void LiveRange::markValNoForDeletion(VNInfo *ValNo) { 463 if (ValNo->id == getNumValNums()-1) { 464 do { 465 valnos.pop_back(); 466 } while (!valnos.empty() && valnos.back()->isUnused()); 467 } else { 468 ValNo->markUnused(); 469 } 470 } 471 472 /// RenumberValues - Renumber all values in order of appearance and delete the 473 /// remaining unused values. 474 void LiveRange::RenumberValues() { 475 SmallPtrSet<VNInfo*, 8> Seen; 476 valnos.clear(); 477 for (const Segment &S : segments) { 478 VNInfo *VNI = S.valno; 479 if (!Seen.insert(VNI).second) 480 continue; 481 assert(!VNI->isUnused() && "Unused valno used by live segment"); 482 VNI->id = (unsigned)valnos.size(); 483 valnos.push_back(VNI); 484 } 485 } 486 487 void LiveRange::addSegmentToSet(Segment S) { 488 CalcLiveRangeUtilSet(this).addSegment(S); 489 } 490 491 LiveRange::iterator LiveRange::addSegment(Segment S) { 492 // Use the segment set, if it is available. 493 if (segmentSet != nullptr) { 494 addSegmentToSet(S); 495 return end(); 496 } 497 // Otherwise use the segment vector. 498 return CalcLiveRangeUtilVector(this).addSegment(S); 499 } 500 501 void LiveRange::append(const Segment S) { 502 // Check that the segment belongs to the back of the list. 503 assert(segments.empty() || segments.back().end <= S.start); 504 segments.push_back(S); 505 } 506 507 /// extendInBlock - If this range is live before Kill in the basic 508 /// block that starts at StartIdx, extend it to be live up to Kill and return 509 /// the value. If there is no live range before Kill, return NULL. 510 VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) { 511 // Use the segment set, if it is available. 512 if (segmentSet != nullptr) 513 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill); 514 // Otherwise use the segment vector. 515 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill); 516 } 517 518 /// Remove the specified segment from this range. Note that the segment must 519 /// be in a single Segment in its entirety. 520 void LiveRange::removeSegment(SlotIndex Start, SlotIndex End, 521 bool RemoveDeadValNo) { 522 // Find the Segment containing this span. 523 iterator I = find(Start); 524 assert(I != end() && "Segment is not in range!"); 525 assert(I->containsInterval(Start, End) 526 && "Segment is not entirely in range!"); 527 528 // If the span we are removing is at the start of the Segment, adjust it. 529 VNInfo *ValNo = I->valno; 530 if (I->start == Start) { 531 if (I->end == End) { 532 if (RemoveDeadValNo) { 533 // Check if val# is dead. 534 bool isDead = true; 535 for (const_iterator II = begin(), EE = end(); II != EE; ++II) 536 if (II != I && II->valno == ValNo) { 537 isDead = false; 538 break; 539 } 540 if (isDead) { 541 // Now that ValNo is dead, remove it. 542 markValNoForDeletion(ValNo); 543 } 544 } 545 546 segments.erase(I); // Removed the whole Segment. 547 } else 548 I->start = End; 549 return; 550 } 551 552 // Otherwise if the span we are removing is at the end of the Segment, 553 // adjust the other way. 554 if (I->end == End) { 555 I->end = Start; 556 return; 557 } 558 559 // Otherwise, we are splitting the Segment into two pieces. 560 SlotIndex OldEnd = I->end; 561 I->end = Start; // Trim the old segment. 562 563 // Insert the new one. 564 segments.insert(std::next(I), Segment(End, OldEnd, ValNo)); 565 } 566 567 /// removeValNo - Remove all the segments defined by the specified value#. 568 /// Also remove the value# from value# list. 569 void LiveRange::removeValNo(VNInfo *ValNo) { 570 if (empty()) return; 571 segments.erase(std::remove_if(begin(), end(), [ValNo](const Segment &S) { 572 return S.valno == ValNo; 573 }), end()); 574 // Now that ValNo is dead, remove it. 575 markValNoForDeletion(ValNo); 576 } 577 578 void LiveRange::join(LiveRange &Other, 579 const int *LHSValNoAssignments, 580 const int *RHSValNoAssignments, 581 SmallVectorImpl<VNInfo *> &NewVNInfo) { 582 verify(); 583 584 // Determine if any of our values are mapped. This is uncommon, so we want 585 // to avoid the range scan if not. 586 bool MustMapCurValNos = false; 587 unsigned NumVals = getNumValNums(); 588 unsigned NumNewVals = NewVNInfo.size(); 589 for (unsigned i = 0; i != NumVals; ++i) { 590 unsigned LHSValID = LHSValNoAssignments[i]; 591 if (i != LHSValID || 592 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) { 593 MustMapCurValNos = true; 594 break; 595 } 596 } 597 598 // If we have to apply a mapping to our base range assignment, rewrite it now. 599 if (MustMapCurValNos && !empty()) { 600 // Map the first live range. 601 602 iterator OutIt = begin(); 603 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]]; 604 for (iterator I = std::next(OutIt), E = end(); I != E; ++I) { 605 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]]; 606 assert(nextValNo && "Huh?"); 607 608 // If this live range has the same value # as its immediate predecessor, 609 // and if they are neighbors, remove one Segment. This happens when we 610 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #. 611 if (OutIt->valno == nextValNo && OutIt->end == I->start) { 612 OutIt->end = I->end; 613 } else { 614 // Didn't merge. Move OutIt to the next segment, 615 ++OutIt; 616 OutIt->valno = nextValNo; 617 if (OutIt != I) { 618 OutIt->start = I->start; 619 OutIt->end = I->end; 620 } 621 } 622 } 623 // If we merge some segments, chop off the end. 624 ++OutIt; 625 segments.erase(OutIt, end()); 626 } 627 628 // Rewrite Other values before changing the VNInfo ids. 629 // This can leave Other in an invalid state because we're not coalescing 630 // touching segments that now have identical values. That's OK since Other is 631 // not supposed to be valid after calling join(); 632 for (Segment &S : Other.segments) 633 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]]; 634 635 // Update val# info. Renumber them and make sure they all belong to this 636 // LiveRange now. Also remove dead val#'s. 637 unsigned NumValNos = 0; 638 for (unsigned i = 0; i < NumNewVals; ++i) { 639 VNInfo *VNI = NewVNInfo[i]; 640 if (VNI) { 641 if (NumValNos >= NumVals) 642 valnos.push_back(VNI); 643 else 644 valnos[NumValNos] = VNI; 645 VNI->id = NumValNos++; // Renumber val#. 646 } 647 } 648 if (NumNewVals < NumVals) 649 valnos.resize(NumNewVals); // shrinkify 650 651 // Okay, now insert the RHS live segments into the LHS. 652 LiveRangeUpdater Updater(this); 653 for (Segment &S : Other.segments) 654 Updater.add(S); 655 } 656 657 /// Merge all of the segments in RHS into this live range as the specified 658 /// value number. The segments in RHS are allowed to overlap with segments in 659 /// the current range, but only if the overlapping segments have the 660 /// specified value number. 661 void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS, 662 VNInfo *LHSValNo) { 663 LiveRangeUpdater Updater(this); 664 for (const Segment &S : RHS.segments) 665 Updater.add(S.start, S.end, LHSValNo); 666 } 667 668 /// MergeValueInAsValue - Merge all of the live segments of a specific val# 669 /// in RHS into this live range as the specified value number. 670 /// The segments in RHS are allowed to overlap with segments in the 671 /// current range, it will replace the value numbers of the overlaped 672 /// segments with the specified value number. 673 void LiveRange::MergeValueInAsValue(const LiveRange &RHS, 674 const VNInfo *RHSValNo, 675 VNInfo *LHSValNo) { 676 LiveRangeUpdater Updater(this); 677 for (const Segment &S : RHS.segments) 678 if (S.valno == RHSValNo) 679 Updater.add(S.start, S.end, LHSValNo); 680 } 681 682 /// MergeValueNumberInto - This method is called when two value nubmers 683 /// are found to be equivalent. This eliminates V1, replacing all 684 /// segments with the V1 value number with the V2 value number. This can 685 /// cause merging of V1/V2 values numbers and compaction of the value space. 686 VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) { 687 assert(V1 != V2 && "Identical value#'s are always equivalent!"); 688 689 // This code actually merges the (numerically) larger value number into the 690 // smaller value number, which is likely to allow us to compactify the value 691 // space. The only thing we have to be careful of is to preserve the 692 // instruction that defines the result value. 693 694 // Make sure V2 is smaller than V1. 695 if (V1->id < V2->id) { 696 V1->copyFrom(*V2); 697 std::swap(V1, V2); 698 } 699 700 // Merge V1 segments into V2. 701 for (iterator I = begin(); I != end(); ) { 702 iterator S = I++; 703 if (S->valno != V1) continue; // Not a V1 Segment. 704 705 // Okay, we found a V1 live range. If it had a previous, touching, V2 live 706 // range, extend it. 707 if (S != begin()) { 708 iterator Prev = S-1; 709 if (Prev->valno == V2 && Prev->end == S->start) { 710 Prev->end = S->end; 711 712 // Erase this live-range. 713 segments.erase(S); 714 I = Prev+1; 715 S = Prev; 716 } 717 } 718 719 // Okay, now we have a V1 or V2 live range that is maximally merged forward. 720 // Ensure that it is a V2 live-range. 721 S->valno = V2; 722 723 // If we can merge it into later V2 segments, do so now. We ignore any 724 // following V1 segments, as they will be merged in subsequent iterations 725 // of the loop. 726 if (I != end()) { 727 if (I->start == S->end && I->valno == V2) { 728 S->end = I->end; 729 segments.erase(I); 730 I = S+1; 731 } 732 } 733 } 734 735 // Now that V1 is dead, remove it. 736 markValNoForDeletion(V1); 737 738 return V2; 739 } 740 741 void LiveRange::flushSegmentSet() { 742 assert(segmentSet != nullptr && "segment set must have been created"); 743 assert( 744 segments.empty() && 745 "segment set can be used only initially before switching to the array"); 746 segments.append(segmentSet->begin(), segmentSet->end()); 747 segmentSet = nullptr; 748 verify(); 749 } 750 751 bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const { 752 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin(); 753 ArrayRef<SlotIndex>::iterator SlotE = Slots.end(); 754 755 // If there are no regmask slots, we have nothing to search. 756 if (SlotI == SlotE) 757 return false; 758 759 // Start our search at the first segment that ends after the first slot. 760 const_iterator SegmentI = find(*SlotI); 761 const_iterator SegmentE = end(); 762 763 // If there are no segments that end after the first slot, we're done. 764 if (SegmentI == SegmentE) 765 return false; 766 767 // Look for each slot in the live range. 768 for ( ; SlotI != SlotE; ++SlotI) { 769 // Go to the next segment that ends after the current slot. 770 // The slot may be within a hole in the range. 771 SegmentI = advanceTo(SegmentI, *SlotI); 772 if (SegmentI == SegmentE) 773 return false; 774 775 // If this segment contains the slot, we're done. 776 if (SegmentI->contains(*SlotI)) 777 return true; 778 // Otherwise, look for the next slot. 779 } 780 781 // We didn't find a segment containing any of the slots. 782 return false; 783 } 784 785 void LiveInterval::freeSubRange(SubRange *S) { 786 S->~SubRange(); 787 // Memory was allocated with BumpPtr allocator and is not freed here. 788 } 789 790 void LiveInterval::removeEmptySubRanges() { 791 SubRange **NextPtr = &SubRanges; 792 SubRange *I = *NextPtr; 793 while (I != nullptr) { 794 if (!I->empty()) { 795 NextPtr = &I->Next; 796 I = *NextPtr; 797 continue; 798 } 799 // Skip empty subranges until we find the first nonempty one. 800 do { 801 SubRange *Next = I->Next; 802 freeSubRange(I); 803 I = Next; 804 } while (I != nullptr && I->empty()); 805 *NextPtr = I; 806 } 807 } 808 809 void LiveInterval::clearSubRanges() { 810 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) { 811 Next = I->Next; 812 freeSubRange(I); 813 } 814 SubRanges = nullptr; 815 } 816 817 /// Helper function for constructMainRangeFromSubranges(): Search the CFG 818 /// backwards until we find a place covered by a LiveRange segment that actually 819 /// has a valno set. 820 static VNInfo *searchForVNI(const SlotIndexes &Indexes, LiveRange &LR, 821 const MachineBasicBlock *MBB, 822 SmallPtrSetImpl<const MachineBasicBlock*> &Visited) { 823 // We start the search at the end of MBB. 824 SlotIndex EndIdx = Indexes.getMBBEndIdx(MBB); 825 // In our use case we can't live the area covered by the live segments without 826 // finding an actual VNI def. 827 LiveRange::iterator I = LR.find(EndIdx.getPrevSlot()); 828 assert(I != LR.end()); 829 LiveRange::Segment &S = *I; 830 if (S.valno != nullptr) 831 return S.valno; 832 833 VNInfo *VNI = nullptr; 834 // Continue at predecessors (we could even go to idom with domtree available). 835 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 836 // Avoid going in circles. 837 if (!Visited.insert(Pred).second) 838 continue; 839 840 VNI = searchForVNI(Indexes, LR, Pred, Visited); 841 if (VNI != nullptr) { 842 S.valno = VNI; 843 break; 844 } 845 } 846 847 return VNI; 848 } 849 850 static void determineMissingVNIs(const SlotIndexes &Indexes, LiveInterval &LI) { 851 SmallPtrSet<const MachineBasicBlock*, 5> Visited; 852 853 LiveRange::iterator OutIt; 854 VNInfo *PrevValNo = nullptr; 855 for (LiveRange::iterator I = LI.begin(), E = LI.end(); I != E; ++I) { 856 LiveRange::Segment &S = *I; 857 // Determine final VNI if necessary. 858 if (S.valno == nullptr) { 859 // This can only happen at the begin of a basic block. 860 assert(S.start.isBlock() && "valno should only be missing at block begin"); 861 862 Visited.clear(); 863 const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(S.start); 864 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 865 VNInfo *VNI = searchForVNI(Indexes, LI, Pred, Visited); 866 if (VNI != nullptr) { 867 S.valno = VNI; 868 break; 869 } 870 } 871 assert(S.valno != nullptr && "could not determine valno"); 872 } 873 // Merge with previous segment if it has the same VNI. 874 if (PrevValNo == S.valno && OutIt->end == S.start) { 875 OutIt->end = S.end; 876 } else { 877 // Didn't merge. Move OutIt to next segment. 878 if (PrevValNo == nullptr) 879 OutIt = LI.begin(); 880 else 881 ++OutIt; 882 883 if (OutIt != I) 884 *OutIt = *I; 885 PrevValNo = S.valno; 886 } 887 } 888 // If we merged some segments chop off the end. 889 ++OutIt; 890 LI.segments.erase(OutIt, LI.end()); 891 } 892 893 void LiveInterval::constructMainRangeFromSubranges( 894 const SlotIndexes &Indexes, VNInfo::Allocator &VNIAllocator) { 895 // The basic observations on which this algorithm is based: 896 // - Each Def/ValNo in a subrange must have a corresponding def on the main 897 // range, but not further defs/valnos are necessary. 898 // - If any of the subranges is live at a point the main liverange has to be 899 // live too, conversily if no subrange is live the main range mustn't be 900 // live either. 901 // We do this by scanning through all the subranges simultaneously creating new 902 // segments in the main range as segments start/ends come up in the subranges. 903 assert(hasSubRanges() && "expected subranges to be present"); 904 assert(segments.empty() && valnos.empty() && "expected empty main range"); 905 906 // Collect subrange, iterator pairs for the walk and determine first and last 907 // SlotIndex involved. 908 SmallVector<std::pair<const SubRange*, const_iterator>, 4> SRs; 909 SlotIndex First; 910 SlotIndex Last; 911 for (const SubRange &SR : subranges()) { 912 if (SR.empty()) 913 continue; 914 SRs.push_back(std::make_pair(&SR, SR.begin())); 915 if (!First.isValid() || SR.segments.front().start < First) 916 First = SR.segments.front().start; 917 if (!Last.isValid() || SR.segments.back().end > Last) 918 Last = SR.segments.back().end; 919 } 920 921 // Walk over all subranges simultaneously. 922 Segment CurrentSegment; 923 bool ConstructingSegment = false; 924 bool NeedVNIFixup = false; 925 LaneBitmask ActiveMask = 0; 926 SlotIndex Pos = First; 927 while (true) { 928 SlotIndex NextPos = Last; 929 enum { 930 NOTHING, 931 BEGIN_SEGMENT, 932 END_SEGMENT, 933 } Event = NOTHING; 934 // Which subregister lanes are affected by the current event. 935 LaneBitmask EventMask = 0; 936 // Whether a BEGIN_SEGMENT is also a valno definition point. 937 bool IsDef = false; 938 // Find the next begin or end of a subrange segment. Combine masks if we 939 // have multiple begins/ends at the same position. Ends take precedence over 940 // Begins. 941 for (auto &SRP : SRs) { 942 const SubRange &SR = *SRP.first; 943 const_iterator &I = SRP.second; 944 // Advance iterator of subrange to a segment involving Pos; the earlier 945 // segments are already merged at this point. 946 while (I != SR.end() && 947 (I->end < Pos || 948 (I->end == Pos && (ActiveMask & SR.LaneMask) == 0))) 949 ++I; 950 if (I == SR.end()) 951 continue; 952 if ((ActiveMask & SR.LaneMask) == 0 && 953 Pos <= I->start && I->start <= NextPos) { 954 // Merge multiple begins at the same position. 955 if (I->start == NextPos && Event == BEGIN_SEGMENT) { 956 EventMask |= SR.LaneMask; 957 IsDef |= I->valno->def == I->start; 958 } else if (I->start < NextPos || Event != END_SEGMENT) { 959 Event = BEGIN_SEGMENT; 960 NextPos = I->start; 961 EventMask = SR.LaneMask; 962 IsDef = I->valno->def == I->start; 963 } 964 } 965 if ((ActiveMask & SR.LaneMask) != 0 && 966 Pos <= I->end && I->end <= NextPos) { 967 // Merge multiple ends at the same position. 968 if (I->end == NextPos && Event == END_SEGMENT) 969 EventMask |= SR.LaneMask; 970 else { 971 Event = END_SEGMENT; 972 NextPos = I->end; 973 EventMask = SR.LaneMask; 974 } 975 } 976 } 977 978 // Advance scan position. 979 Pos = NextPos; 980 if (Event == BEGIN_SEGMENT) { 981 if (ConstructingSegment && IsDef) { 982 // Finish previous segment because we have to start a new one. 983 CurrentSegment.end = Pos; 984 append(CurrentSegment); 985 ConstructingSegment = false; 986 } 987 988 // Start a new segment if necessary. 989 if (!ConstructingSegment) { 990 // Determine value number for the segment. 991 VNInfo *VNI; 992 if (IsDef) { 993 VNI = getNextValue(Pos, VNIAllocator); 994 } else { 995 // We have to reuse an existing value number, if we are lucky 996 // then we already passed one of the predecessor blocks and determined 997 // its value number (with blocks in reverse postorder this would be 998 // always true but we have no such guarantee). 999 assert(Pos.isBlock()); 1000 const MachineBasicBlock *MBB = Indexes.getMBBFromIndex(Pos); 1001 // See if any of the predecessor blocks has a lower number and a VNI 1002 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 1003 SlotIndex PredEnd = Indexes.getMBBEndIdx(Pred); 1004 VNI = getVNInfoBefore(PredEnd); 1005 if (VNI != nullptr) 1006 break; 1007 } 1008 // Def will come later: We have to do an extra fixup pass. 1009 if (VNI == nullptr) 1010 NeedVNIFixup = true; 1011 } 1012 1013 // In rare cases we can produce adjacent segments with the same value 1014 // number (if they come from different subranges, but happen to have 1015 // the same defining instruction). VNIFixup will fix those cases. 1016 if (!empty() && segments.back().end == Pos && 1017 segments.back().valno == VNI) 1018 NeedVNIFixup = true; 1019 CurrentSegment.start = Pos; 1020 CurrentSegment.valno = VNI; 1021 ConstructingSegment = true; 1022 } 1023 ActiveMask |= EventMask; 1024 } else if (Event == END_SEGMENT) { 1025 assert(ConstructingSegment); 1026 // Finish segment if no lane is active anymore. 1027 ActiveMask &= ~EventMask; 1028 if (ActiveMask == 0) { 1029 CurrentSegment.end = Pos; 1030 append(CurrentSegment); 1031 ConstructingSegment = false; 1032 } 1033 } else { 1034 // We reached the end of the last subranges and can stop. 1035 assert(Event == NOTHING); 1036 break; 1037 } 1038 } 1039 1040 // We might not be able to assign new valnos for all segments if the basic 1041 // block containing the definition comes after a segment using the valno. 1042 // Do a fixup pass for this uncommon case. 1043 if (NeedVNIFixup) 1044 determineMissingVNIs(Indexes, *this); 1045 1046 assert(ActiveMask == 0 && !ConstructingSegment && "all segments ended"); 1047 verify(); 1048 } 1049 1050 unsigned LiveInterval::getSize() const { 1051 unsigned Sum = 0; 1052 for (const Segment &S : segments) 1053 Sum += S.start.distance(S.end); 1054 return Sum; 1055 } 1056 1057 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange::Segment &S) { 1058 return os << '[' << S.start << ',' << S.end << ':' << S.valno->id << ")"; 1059 } 1060 1061 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1062 void LiveRange::Segment::dump() const { 1063 dbgs() << *this << "\n"; 1064 } 1065 #endif 1066 1067 void LiveRange::print(raw_ostream &OS) const { 1068 if (empty()) 1069 OS << "EMPTY"; 1070 else { 1071 for (const Segment &S : segments) { 1072 OS << S; 1073 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo"); 1074 } 1075 } 1076 1077 // Print value number info. 1078 if (getNumValNums()) { 1079 OS << " "; 1080 unsigned vnum = 0; 1081 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e; 1082 ++i, ++vnum) { 1083 const VNInfo *vni = *i; 1084 if (vnum) OS << " "; 1085 OS << vnum << "@"; 1086 if (vni->isUnused()) { 1087 OS << "x"; 1088 } else { 1089 OS << vni->def; 1090 if (vni->isPHIDef()) 1091 OS << "-phi"; 1092 } 1093 } 1094 } 1095 } 1096 1097 void LiveInterval::print(raw_ostream &OS) const { 1098 OS << PrintReg(reg) << ' '; 1099 super::print(OS); 1100 // Print subranges 1101 for (const SubRange &SR : subranges()) { 1102 OS << " L" << PrintLaneMask(SR.LaneMask) << ' ' << SR; 1103 } 1104 } 1105 1106 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1107 void LiveRange::dump() const { 1108 dbgs() << *this << "\n"; 1109 } 1110 1111 void LiveInterval::dump() const { 1112 dbgs() << *this << "\n"; 1113 } 1114 #endif 1115 1116 #ifndef NDEBUG 1117 void LiveRange::verify() const { 1118 for (const_iterator I = begin(), E = end(); I != E; ++I) { 1119 assert(I->start.isValid()); 1120 assert(I->end.isValid()); 1121 assert(I->start < I->end); 1122 assert(I->valno != nullptr); 1123 assert(I->valno->id < valnos.size()); 1124 assert(I->valno == valnos[I->valno->id]); 1125 if (std::next(I) != E) { 1126 assert(I->end <= std::next(I)->start); 1127 if (I->end == std::next(I)->start) 1128 assert(I->valno != std::next(I)->valno); 1129 } 1130 } 1131 } 1132 1133 void LiveInterval::verify(const MachineRegisterInfo *MRI) const { 1134 super::verify(); 1135 1136 // Make sure SubRanges are fine and LaneMasks are disjunct. 1137 LaneBitmask Mask = 0; 1138 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg) : ~0u; 1139 for (const SubRange &SR : subranges()) { 1140 // Subrange lanemask should be disjunct to any previous subrange masks. 1141 assert((Mask & SR.LaneMask) == 0); 1142 Mask |= SR.LaneMask; 1143 1144 // subrange mask should not contained in maximum lane mask for the vreg. 1145 assert((Mask & ~MaxMask) == 0); 1146 // empty subranges must be removed. 1147 assert(!SR.empty()); 1148 1149 SR.verify(); 1150 // Main liverange should cover subrange. 1151 assert(covers(SR)); 1152 } 1153 } 1154 #endif 1155 1156 1157 //===----------------------------------------------------------------------===// 1158 // LiveRangeUpdater class 1159 //===----------------------------------------------------------------------===// 1160 // 1161 // The LiveRangeUpdater class always maintains these invariants: 1162 // 1163 // - When LastStart is invalid, Spills is empty and the iterators are invalid. 1164 // This is the initial state, and the state created by flush(). 1165 // In this state, isDirty() returns false. 1166 // 1167 // Otherwise, segments are kept in three separate areas: 1168 // 1169 // 1. [begin; WriteI) at the front of LR. 1170 // 2. [ReadI; end) at the back of LR. 1171 // 3. Spills. 1172 // 1173 // - LR.begin() <= WriteI <= ReadI <= LR.end(). 1174 // - Segments in all three areas are fully ordered and coalesced. 1175 // - Segments in area 1 precede and can't coalesce with segments in area 2. 1176 // - Segments in Spills precede and can't coalesce with segments in area 2. 1177 // - No coalescing is possible between segments in Spills and segments in area 1178 // 1, and there are no overlapping segments. 1179 // 1180 // The segments in Spills are not ordered with respect to the segments in area 1181 // 1. They need to be merged. 1182 // 1183 // When they exist, Spills.back().start <= LastStart, 1184 // and WriteI[-1].start <= LastStart. 1185 1186 void LiveRangeUpdater::print(raw_ostream &OS) const { 1187 if (!isDirty()) { 1188 if (LR) 1189 OS << "Clean updater: " << *LR << '\n'; 1190 else 1191 OS << "Null updater.\n"; 1192 return; 1193 } 1194 assert(LR && "Can't have null LR in dirty updater."); 1195 OS << " updater with gap = " << (ReadI - WriteI) 1196 << ", last start = " << LastStart 1197 << ":\n Area 1:"; 1198 for (const auto &S : make_range(LR->begin(), WriteI)) 1199 OS << ' ' << S; 1200 OS << "\n Spills:"; 1201 for (unsigned I = 0, E = Spills.size(); I != E; ++I) 1202 OS << ' ' << Spills[I]; 1203 OS << "\n Area 2:"; 1204 for (const auto &S : make_range(ReadI, LR->end())) 1205 OS << ' ' << S; 1206 OS << '\n'; 1207 } 1208 1209 void LiveRangeUpdater::dump() const 1210 { 1211 print(errs()); 1212 } 1213 1214 // Determine if A and B should be coalesced. 1215 static inline bool coalescable(const LiveRange::Segment &A, 1216 const LiveRange::Segment &B) { 1217 assert(A.start <= B.start && "Unordered live segments."); 1218 if (A.end == B.start) 1219 return A.valno == B.valno; 1220 if (A.end < B.start) 1221 return false; 1222 assert(A.valno == B.valno && "Cannot overlap different values"); 1223 return true; 1224 } 1225 1226 void LiveRangeUpdater::add(LiveRange::Segment Seg) { 1227 assert(LR && "Cannot add to a null destination"); 1228 1229 // Fall back to the regular add method if the live range 1230 // is using the segment set instead of the segment vector. 1231 if (LR->segmentSet != nullptr) { 1232 LR->addSegmentToSet(Seg); 1233 return; 1234 } 1235 1236 // Flush the state if Start moves backwards. 1237 if (!LastStart.isValid() || LastStart > Seg.start) { 1238 if (isDirty()) 1239 flush(); 1240 // This brings us to an uninitialized state. Reinitialize. 1241 assert(Spills.empty() && "Leftover spilled segments"); 1242 WriteI = ReadI = LR->begin(); 1243 } 1244 1245 // Remember start for next time. 1246 LastStart = Seg.start; 1247 1248 // Advance ReadI until it ends after Seg.start. 1249 LiveRange::iterator E = LR->end(); 1250 if (ReadI != E && ReadI->end <= Seg.start) { 1251 // First try to close the gap between WriteI and ReadI with spills. 1252 if (ReadI != WriteI) 1253 mergeSpills(); 1254 // Then advance ReadI. 1255 if (ReadI == WriteI) 1256 ReadI = WriteI = LR->find(Seg.start); 1257 else 1258 while (ReadI != E && ReadI->end <= Seg.start) 1259 *WriteI++ = *ReadI++; 1260 } 1261 1262 assert(ReadI == E || ReadI->end > Seg.start); 1263 1264 // Check if the ReadI segment begins early. 1265 if (ReadI != E && ReadI->start <= Seg.start) { 1266 assert(ReadI->valno == Seg.valno && "Cannot overlap different values"); 1267 // Bail if Seg is completely contained in ReadI. 1268 if (ReadI->end >= Seg.end) 1269 return; 1270 // Coalesce into Seg. 1271 Seg.start = ReadI->start; 1272 ++ReadI; 1273 } 1274 1275 // Coalesce as much as possible from ReadI into Seg. 1276 while (ReadI != E && coalescable(Seg, *ReadI)) { 1277 Seg.end = std::max(Seg.end, ReadI->end); 1278 ++ReadI; 1279 } 1280 1281 // Try coalescing Spills.back() into Seg. 1282 if (!Spills.empty() && coalescable(Spills.back(), Seg)) { 1283 Seg.start = Spills.back().start; 1284 Seg.end = std::max(Spills.back().end, Seg.end); 1285 Spills.pop_back(); 1286 } 1287 1288 // Try coalescing Seg into WriteI[-1]. 1289 if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) { 1290 WriteI[-1].end = std::max(WriteI[-1].end, Seg.end); 1291 return; 1292 } 1293 1294 // Seg doesn't coalesce with anything, and needs to be inserted somewhere. 1295 if (WriteI != ReadI) { 1296 *WriteI++ = Seg; 1297 return; 1298 } 1299 1300 // Finally, append to LR or Spills. 1301 if (WriteI == E) { 1302 LR->segments.push_back(Seg); 1303 WriteI = ReadI = LR->end(); 1304 } else 1305 Spills.push_back(Seg); 1306 } 1307 1308 // Merge as many spilled segments as possible into the gap between WriteI 1309 // and ReadI. Advance WriteI to reflect the inserted instructions. 1310 void LiveRangeUpdater::mergeSpills() { 1311 // Perform a backwards merge of Spills and [SpillI;WriteI). 1312 size_t GapSize = ReadI - WriteI; 1313 size_t NumMoved = std::min(Spills.size(), GapSize); 1314 LiveRange::iterator Src = WriteI; 1315 LiveRange::iterator Dst = Src + NumMoved; 1316 LiveRange::iterator SpillSrc = Spills.end(); 1317 LiveRange::iterator B = LR->begin(); 1318 1319 // This is the new WriteI position after merging spills. 1320 WriteI = Dst; 1321 1322 // Now merge Src and Spills backwards. 1323 while (Src != Dst) { 1324 if (Src != B && Src[-1].start > SpillSrc[-1].start) 1325 *--Dst = *--Src; 1326 else 1327 *--Dst = *--SpillSrc; 1328 } 1329 assert(NumMoved == size_t(Spills.end() - SpillSrc)); 1330 Spills.erase(SpillSrc, Spills.end()); 1331 } 1332 1333 void LiveRangeUpdater::flush() { 1334 if (!isDirty()) 1335 return; 1336 // Clear the dirty state. 1337 LastStart = SlotIndex(); 1338 1339 assert(LR && "Cannot add to a null destination"); 1340 1341 // Nothing to merge? 1342 if (Spills.empty()) { 1343 LR->segments.erase(WriteI, ReadI); 1344 LR->verify(); 1345 return; 1346 } 1347 1348 // Resize the WriteI - ReadI gap to match Spills. 1349 size_t GapSize = ReadI - WriteI; 1350 if (GapSize < Spills.size()) { 1351 // The gap is too small. Make some room. 1352 size_t WritePos = WriteI - LR->begin(); 1353 LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment()); 1354 // This also invalidated ReadI, but it is recomputed below. 1355 WriteI = LR->begin() + WritePos; 1356 } else { 1357 // Shrink the gap if necessary. 1358 LR->segments.erase(WriteI + Spills.size(), ReadI); 1359 } 1360 ReadI = WriteI + Spills.size(); 1361 mergeSpills(); 1362 LR->verify(); 1363 } 1364 1365 unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) { 1366 // Create initial equivalence classes. 1367 EqClass.clear(); 1368 EqClass.grow(LR.getNumValNums()); 1369 1370 const VNInfo *used = nullptr, *unused = nullptr; 1371 1372 // Determine connections. 1373 for (const VNInfo *VNI : LR.valnos) { 1374 // Group all unused values into one class. 1375 if (VNI->isUnused()) { 1376 if (unused) 1377 EqClass.join(unused->id, VNI->id); 1378 unused = VNI; 1379 continue; 1380 } 1381 used = VNI; 1382 if (VNI->isPHIDef()) { 1383 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 1384 assert(MBB && "Phi-def has no defining MBB"); 1385 // Connect to values live out of predecessors. 1386 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), 1387 PE = MBB->pred_end(); PI != PE; ++PI) 1388 if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(*PI))) 1389 EqClass.join(VNI->id, PVNI->id); 1390 } else { 1391 // Normal value defined by an instruction. Check for two-addr redef. 1392 // FIXME: This could be coincidental. Should we really check for a tied 1393 // operand constraint? 1394 // Note that VNI->def may be a use slot for an early clobber def. 1395 if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def)) 1396 EqClass.join(VNI->id, UVNI->id); 1397 } 1398 } 1399 1400 // Lump all the unused values in with the last used value. 1401 if (used && unused) 1402 EqClass.join(used->id, unused->id); 1403 1404 EqClass.compress(); 1405 return EqClass.getNumClasses(); 1406 } 1407 1408 template<typename LiveRangeT, typename EqClassesT> 1409 static void DistributeRange(LiveRangeT &LR, LiveRangeT *SplitLRs[], 1410 EqClassesT VNIClasses) { 1411 // Move segments to new intervals. 1412 LiveRange::iterator J = LR.begin(), E = LR.end(); 1413 while (J != E && VNIClasses[J->valno->id] == 0) 1414 ++J; 1415 for (LiveRange::iterator I = J; I != E; ++I) { 1416 if (unsigned eq = VNIClasses[I->valno->id]) { 1417 assert((SplitLRs[eq-1]->empty() || SplitLRs[eq-1]->expiredAt(I->start)) && 1418 "New intervals should be empty"); 1419 SplitLRs[eq-1]->segments.push_back(*I); 1420 } else 1421 *J++ = *I; 1422 } 1423 LR.segments.erase(J, E); 1424 1425 // Transfer VNInfos to their new owners and renumber them. 1426 unsigned j = 0, e = LR.getNumValNums(); 1427 while (j != e && VNIClasses[j] == 0) 1428 ++j; 1429 for (unsigned i = j; i != e; ++i) { 1430 VNInfo *VNI = LR.getValNumInfo(i); 1431 if (unsigned eq = VNIClasses[i]) { 1432 VNI->id = SplitLRs[eq-1]->getNumValNums(); 1433 SplitLRs[eq-1]->valnos.push_back(VNI); 1434 } else { 1435 VNI->id = j; 1436 LR.valnos[j++] = VNI; 1437 } 1438 } 1439 LR.valnos.resize(j); 1440 } 1441 1442 void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[], 1443 MachineRegisterInfo &MRI) { 1444 // Rewrite instructions. 1445 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg), 1446 RE = MRI.reg_end(); RI != RE;) { 1447 MachineOperand &MO = *RI; 1448 MachineInstr *MI = RI->getParent(); 1449 ++RI; 1450 // DBG_VALUE instructions don't have slot indexes, so get the index of the 1451 // instruction before them. 1452 // Normally, DBG_VALUE instructions are removed before this function is 1453 // called, but it is not a requirement. 1454 SlotIndex Idx; 1455 if (MI->isDebugValue()) 1456 Idx = LIS.getSlotIndexes()->getIndexBefore(MI); 1457 else 1458 Idx = LIS.getInstructionIndex(MI); 1459 LiveQueryResult LRQ = LI.Query(Idx); 1460 const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined(); 1461 // In the case of an <undef> use that isn't tied to any def, VNI will be 1462 // NULL. If the use is tied to a def, VNI will be the defined value. 1463 if (!VNI) 1464 continue; 1465 if (unsigned EqClass = getEqClass(VNI)) 1466 MO.setReg(LIV[EqClass-1]->reg); 1467 } 1468 1469 // Distribute subregister liveranges. 1470 if (LI.hasSubRanges()) { 1471 unsigned NumComponents = EqClass.getNumClasses(); 1472 SmallVector<unsigned, 8> VNIMapping; 1473 SmallVector<LiveInterval::SubRange*, 8> SubRanges; 1474 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator(); 1475 for (LiveInterval::SubRange &SR : LI.subranges()) { 1476 // Create new subranges in the split intervals and construct a mapping 1477 // for the VNInfos in the subrange. 1478 unsigned NumValNos = SR.valnos.size(); 1479 VNIMapping.clear(); 1480 VNIMapping.reserve(NumValNos); 1481 SubRanges.clear(); 1482 SubRanges.resize(NumComponents-1, nullptr); 1483 for (unsigned I = 0; I < NumValNos; ++I) { 1484 const VNInfo &VNI = *SR.valnos[I]; 1485 const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def); 1486 assert(MainRangeVNI != nullptr 1487 && "SubRange def must have corresponding main range def"); 1488 unsigned ComponentNum = getEqClass(MainRangeVNI); 1489 VNIMapping.push_back(ComponentNum); 1490 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) { 1491 SubRanges[ComponentNum-1] 1492 = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask); 1493 } 1494 } 1495 DistributeRange(SR, SubRanges.data(), VNIMapping); 1496 } 1497 LI.removeEmptySubRanges(); 1498 } 1499 1500 // Distribute main liverange. 1501 DistributeRange(LI, LIV, EqClass); 1502 } 1503