1 //===- LiveInterval.cpp - Live Interval Representation --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the LiveRange and LiveInterval classes. Given some 10 // numbering of each the machine instructions an interval [i, j) is said to be a 11 // live range for register v if there is no instruction with number j' >= j 12 // such that v is live at j' and there is no instruction with number i' < i such 13 // that v is live at i'. In this implementation ranges can have holes, 14 // i.e. a range might look like [1,20), [50,65), [1000,1001). Each 15 // individual segment is represented as an instance of LiveRange::Segment, 16 // and the whole range is represented as an instance of LiveRange. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/CodeGen/LiveInterval.h" 21 #include "LiveRangeUtils.h" 22 #include "RegisterCoalescer.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/iterator_range.h" 28 #include "llvm/CodeGen/LiveIntervals.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineOperand.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/SlotIndexes.h" 34 #include "llvm/CodeGen/TargetRegisterInfo.h" 35 #include "llvm/Config/llvm-config.h" 36 #include "llvm/MC/LaneBitmask.h" 37 #include "llvm/Support/Compiler.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/raw_ostream.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 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 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 iterator I = impl().find(Def); 93 if (I == segments().end()) { 94 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator); 95 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI)); 96 return VNI; 97 } 98 99 Segment *S = segmentAt(I); 100 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 Def = std::min(Def, S->start); 110 if (Def != S->start) 111 S->start = S->valno->def = Def; 112 return S->valno; 113 } 114 assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def"); 115 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator); 116 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI)); 117 return VNI; 118 } 119 120 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) { 121 if (segments().empty()) 122 return nullptr; 123 iterator I = 124 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr)); 125 if (I == segments().begin()) 126 return nullptr; 127 --I; 128 if (I->end <= StartIdx) 129 return nullptr; 130 if (I->end < Use) 131 extendSegmentEndTo(I, Use); 132 return I->valno; 133 } 134 135 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs, 136 SlotIndex StartIdx, SlotIndex Use) { 137 if (segments().empty()) 138 return std::make_pair(nullptr, false); 139 SlotIndex BeforeUse = Use.getPrevSlot(); 140 iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr)); 141 if (I == segments().begin()) 142 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse)); 143 --I; 144 if (I->end <= StartIdx) 145 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse)); 146 if (I->end < Use) { 147 if (LR->isUndefIn(Undefs, I->end, BeforeUse)) 148 return std::make_pair(nullptr, true); 149 extendSegmentEndTo(I, Use); 150 } 151 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 void extendSegmentEndTo(iterator I, SlotIndex NewEnd) { 159 assert(I != segments().end() && "Not a valid segment!"); 160 Segment *S = segmentAt(I); 161 VNInfo *ValNo = I->valno; 162 163 // Search for the first segment that we can't merge with. 164 iterator MergeTo = std::next(I); 165 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 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 if (MergeTo != segments().end() && MergeTo->start <= I->end && 174 MergeTo->valno == ValNo) { 175 S->end = MergeTo->end; 176 ++MergeTo; 177 } 178 179 // Erase any dead segments. 180 segments().erase(std::next(I), MergeTo); 181 } 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 iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) { 187 assert(I != segments().end() && "Not a valid segment!"); 188 Segment *S = segmentAt(I); 189 VNInfo *ValNo = I->valno; 190 191 // Search for the first segment that we can't merge with. 192 iterator MergeTo = I; 193 do { 194 if (MergeTo == segments().begin()) { 195 S->start = NewStart; 196 segments().erase(MergeTo, I); 197 return I; 198 } 199 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!"); 200 --MergeTo; 201 } 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 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) { 206 segmentAt(MergeTo)->end = S->end; 207 } else { 208 // Otherwise, extend the segment right after. 209 ++MergeTo; 210 Segment *MergeToSeg = segmentAt(MergeTo); 211 MergeToSeg->start = NewStart; 212 MergeToSeg->end = S->end; 213 } 214 215 segments().erase(std::next(MergeTo), std::next(I)); 216 return MergeTo; 217 } 218 219 iterator addSegment(Segment S) { 220 SlotIndex Start = S.start, End = S.end; 221 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 if (I != segments().begin()) { 226 iterator B = std::prev(I); 227 if (S.valno == B->valno) { 228 if (B->start <= Start && B->end >= Start) { 229 extendSegmentEndTo(B, End); 230 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 if (I != segments().end()) { 244 if (S.valno == I->valno) { 245 if (I->start <= End) { 246 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 if (End > I->end) 251 extendSegmentEndTo(I, End); 252 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 return segments().insert(I, S); 266 } 267 268 private: 269 ImplT &impl() { return *static_cast<ImplT *>(this); } 270 271 CollectionT &segments() { return impl().segmentsColl(); } 272 273 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 CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {} 289 290 private: 291 friend CalcLiveRangeUtilVectorBase; 292 293 LiveRange::Segments &segmentsColl() { return LR->segments; } 294 295 void insertAtEnd(const Segment &S) { LR->segments.push_back(S); } 296 297 iterator find(SlotIndex Pos) { return LR->find(Pos); } 298 299 iterator findInsertPos(Segment S) { return llvm::upper_bound(*LR, S.start); } 300 }; 301 302 //===----------------------------------------------------------------------===// 303 // Instantiation of the methods for calculation of live ranges 304 // based on a segment set. 305 //===----------------------------------------------------------------------===// 306 307 class CalcLiveRangeUtilSet; 308 using CalcLiveRangeUtilSetBase = 309 CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator, 310 LiveRange::SegmentSet>; 311 312 class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase { 313 public: 314 CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {} 315 316 private: 317 friend CalcLiveRangeUtilSetBase; 318 319 LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; } 320 321 void insertAtEnd(const Segment &S) { 322 LR->segmentSet->insert(LR->segmentSet->end(), S); 323 } 324 325 iterator find(SlotIndex Pos) { 326 iterator I = 327 LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr)); 328 if (I == LR->segmentSet->begin()) 329 return I; 330 iterator PrevI = std::prev(I); 331 if (Pos < (*PrevI).end) 332 return PrevI; 333 return I; 334 } 335 336 iterator findInsertPos(Segment S) { 337 iterator I = LR->segmentSet->upper_bound(S); 338 if (I != LR->segmentSet->end() && !(S.start < *I)) 339 ++I; 340 return I; 341 } 342 }; 343 344 } // end anonymous namespace 345 346 //===----------------------------------------------------------------------===// 347 // LiveRange methods 348 //===----------------------------------------------------------------------===// 349 350 LiveRange::iterator LiveRange::find(SlotIndex Pos) { 351 return llvm::partition(*this, [&](const Segment &X) { return X.end <= Pos; }); 352 } 353 354 VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) { 355 // Use the segment set, if it is available. 356 if (segmentSet != nullptr) 357 return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr); 358 // Otherwise use the segment vector. 359 return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr); 360 } 361 362 VNInfo *LiveRange::createDeadDef(VNInfo *VNI) { 363 // Use the segment set, if it is available. 364 if (segmentSet != nullptr) 365 return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI); 366 // Otherwise use the segment vector. 367 return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI); 368 } 369 370 // overlaps - Return true if the intersection of the two live ranges is 371 // not empty. 372 // 373 // An example for overlaps(): 374 // 375 // 0: A = ... 376 // 4: B = ... 377 // 8: C = A + B ;; last use of A 378 // 379 // The live ranges should look like: 380 // 381 // A = [3, 11) 382 // B = [7, x) 383 // C = [11, y) 384 // 385 // A->overlaps(C) should return false since we want to be able to join 386 // A and C. 387 // 388 bool LiveRange::overlapsFrom(const LiveRange& other, 389 const_iterator StartPos) const { 390 assert(!empty() && "empty range"); 391 const_iterator i = begin(); 392 const_iterator ie = end(); 393 const_iterator j = StartPos; 394 const_iterator je = other.end(); 395 396 assert((StartPos->start <= i->start || StartPos == other.begin()) && 397 StartPos != other.end() && "Bogus start position hint!"); 398 399 if (i->start < j->start) { 400 i = std::upper_bound(i, ie, j->start); 401 if (i != begin()) --i; 402 } else if (j->start < i->start) { 403 ++StartPos; 404 if (StartPos != other.end() && StartPos->start <= i->start) { 405 assert(StartPos < other.end() && i < end()); 406 j = std::upper_bound(j, je, i->start); 407 if (j != other.begin()) --j; 408 } 409 } else { 410 return true; 411 } 412 413 if (j == je) return false; 414 415 while (i != ie) { 416 if (i->start > j->start) { 417 std::swap(i, j); 418 std::swap(ie, je); 419 } 420 421 if (i->end > j->start) 422 return true; 423 ++i; 424 } 425 426 return false; 427 } 428 429 bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP, 430 const SlotIndexes &Indexes) const { 431 assert(!empty() && "empty range"); 432 if (Other.empty()) 433 return false; 434 435 // Use binary searches to find initial positions. 436 const_iterator I = find(Other.beginIndex()); 437 const_iterator IE = end(); 438 if (I == IE) 439 return false; 440 const_iterator J = Other.find(I->start); 441 const_iterator JE = Other.end(); 442 if (J == JE) 443 return false; 444 445 while (true) { 446 // J has just been advanced to satisfy: 447 assert(J->end >= I->start); 448 // Check for an overlap. 449 if (J->start < I->end) { 450 // I and J are overlapping. Find the later start. 451 SlotIndex Def = std::max(I->start, J->start); 452 // Allow the overlap if Def is a coalescable copy. 453 if (Def.isBlock() || 454 !CP.isCoalescable(Indexes.getInstructionFromIndex(Def))) 455 return true; 456 } 457 // Advance the iterator that ends first to check for more overlaps. 458 if (J->end > I->end) { 459 std::swap(I, J); 460 std::swap(IE, JE); 461 } 462 // Advance J until J->end >= I->start. 463 do 464 if (++J == JE) 465 return false; 466 while (J->end < I->start); 467 } 468 } 469 470 /// overlaps - Return true if the live range overlaps an interval specified 471 /// by [Start, End). 472 bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const { 473 assert(Start < End && "Invalid range"); 474 const_iterator I = lower_bound(*this, End); 475 return I != begin() && (--I)->end > Start; 476 } 477 478 bool LiveRange::covers(const LiveRange &Other) const { 479 if (empty()) 480 return Other.empty(); 481 482 const_iterator I = begin(); 483 for (const Segment &O : Other.segments) { 484 I = advanceTo(I, O.start); 485 if (I == end() || I->start > O.start) 486 return false; 487 488 // Check adjacent live segments and see if we can get behind O.end. 489 while (I->end < O.end) { 490 const_iterator Last = I; 491 // Get next segment and abort if it was not adjacent. 492 ++I; 493 if (I == end() || Last->end != I->start) 494 return false; 495 } 496 } 497 return true; 498 } 499 500 /// ValNo is dead, remove it. If it is the largest value number, just nuke it 501 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so 502 /// it can be nuked later. 503 void LiveRange::markValNoForDeletion(VNInfo *ValNo) { 504 if (ValNo->id == getNumValNums()-1) { 505 do { 506 valnos.pop_back(); 507 } while (!valnos.empty() && valnos.back()->isUnused()); 508 } else { 509 ValNo->markUnused(); 510 } 511 } 512 513 /// RenumberValues - Renumber all values in order of appearance and delete the 514 /// remaining unused values. 515 void LiveRange::RenumberValues() { 516 SmallPtrSet<VNInfo*, 8> Seen; 517 valnos.clear(); 518 for (const Segment &S : segments) { 519 VNInfo *VNI = S.valno; 520 if (!Seen.insert(VNI).second) 521 continue; 522 assert(!VNI->isUnused() && "Unused valno used by live segment"); 523 VNI->id = (unsigned)valnos.size(); 524 valnos.push_back(VNI); 525 } 526 } 527 528 void LiveRange::addSegmentToSet(Segment S) { 529 CalcLiveRangeUtilSet(this).addSegment(S); 530 } 531 532 LiveRange::iterator LiveRange::addSegment(Segment S) { 533 // Use the segment set, if it is available. 534 if (segmentSet != nullptr) { 535 addSegmentToSet(S); 536 return end(); 537 } 538 // Otherwise use the segment vector. 539 return CalcLiveRangeUtilVector(this).addSegment(S); 540 } 541 542 void LiveRange::append(const Segment S) { 543 // Check that the segment belongs to the back of the list. 544 assert(segments.empty() || segments.back().end <= S.start); 545 segments.push_back(S); 546 } 547 548 std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs, 549 SlotIndex StartIdx, SlotIndex Kill) { 550 // Use the segment set, if it is available. 551 if (segmentSet != nullptr) 552 return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill); 553 // Otherwise use the segment vector. 554 return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill); 555 } 556 557 VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) { 558 // Use the segment set, if it is available. 559 if (segmentSet != nullptr) 560 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill); 561 // Otherwise use the segment vector. 562 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill); 563 } 564 565 /// Remove the specified segment from this range. Note that the segment must 566 /// be in a single Segment in its entirety. 567 void LiveRange::removeSegment(SlotIndex Start, SlotIndex End, 568 bool RemoveDeadValNo) { 569 // Find the Segment containing this span. 570 iterator I = find(Start); 571 assert(I != end() && "Segment is not in range!"); 572 assert(I->containsInterval(Start, End) 573 && "Segment is not entirely in range!"); 574 575 // If the span we are removing is at the start of the Segment, adjust it. 576 VNInfo *ValNo = I->valno; 577 if (I->start == Start) { 578 if (I->end == End) { 579 segments.erase(I); // Removed the whole Segment. 580 581 if (RemoveDeadValNo) 582 removeValNoIfDead(ValNo); 583 } else 584 I->start = End; 585 return; 586 } 587 588 // Otherwise if the span we are removing is at the end of the Segment, 589 // adjust the other way. 590 if (I->end == End) { 591 I->end = Start; 592 return; 593 } 594 595 // Otherwise, we are splitting the Segment into two pieces. 596 SlotIndex OldEnd = I->end; 597 I->end = Start; // Trim the old segment. 598 599 // Insert the new one. 600 segments.insert(std::next(I), Segment(End, OldEnd, ValNo)); 601 } 602 603 LiveRange::iterator LiveRange::removeSegment(iterator I, bool RemoveDeadValNo) { 604 VNInfo *ValNo = I->valno; 605 I = segments.erase(I); 606 if (RemoveDeadValNo) 607 removeValNoIfDead(ValNo); 608 return I; 609 } 610 611 void LiveRange::removeValNoIfDead(VNInfo *ValNo) { 612 if (none_of(*this, [=](const Segment &S) { return S.valno == ValNo; })) 613 markValNoForDeletion(ValNo); 614 } 615 616 /// removeValNo - Remove all the segments defined by the specified value#. 617 /// Also remove the value# from value# list. 618 void LiveRange::removeValNo(VNInfo *ValNo) { 619 if (empty()) return; 620 llvm::erase_if(segments, 621 [ValNo](const Segment &S) { return S.valno == ValNo; }); 622 // Now that ValNo is dead, remove it. 623 markValNoForDeletion(ValNo); 624 } 625 626 void LiveRange::join(LiveRange &Other, 627 const int *LHSValNoAssignments, 628 const int *RHSValNoAssignments, 629 SmallVectorImpl<VNInfo *> &NewVNInfo) { 630 verify(); 631 632 // Determine if any of our values are mapped. This is uncommon, so we want 633 // to avoid the range scan if not. 634 bool MustMapCurValNos = false; 635 unsigned NumVals = getNumValNums(); 636 unsigned NumNewVals = NewVNInfo.size(); 637 for (unsigned i = 0; i != NumVals; ++i) { 638 unsigned LHSValID = LHSValNoAssignments[i]; 639 if (i != LHSValID || 640 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) { 641 MustMapCurValNos = true; 642 break; 643 } 644 } 645 646 // If we have to apply a mapping to our base range assignment, rewrite it now. 647 if (MustMapCurValNos && !empty()) { 648 // Map the first live range. 649 650 iterator OutIt = begin(); 651 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]]; 652 for (iterator I = std::next(OutIt), E = end(); I != E; ++I) { 653 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]]; 654 assert(nextValNo && "Huh?"); 655 656 // If this live range has the same value # as its immediate predecessor, 657 // and if they are neighbors, remove one Segment. This happens when we 658 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #. 659 if (OutIt->valno == nextValNo && OutIt->end == I->start) { 660 OutIt->end = I->end; 661 } else { 662 // Didn't merge. Move OutIt to the next segment, 663 ++OutIt; 664 OutIt->valno = nextValNo; 665 if (OutIt != I) { 666 OutIt->start = I->start; 667 OutIt->end = I->end; 668 } 669 } 670 } 671 // If we merge some segments, chop off the end. 672 ++OutIt; 673 segments.erase(OutIt, end()); 674 } 675 676 // Rewrite Other values before changing the VNInfo ids. 677 // This can leave Other in an invalid state because we're not coalescing 678 // touching segments that now have identical values. That's OK since Other is 679 // not supposed to be valid after calling join(); 680 for (Segment &S : Other.segments) 681 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]]; 682 683 // Update val# info. Renumber them and make sure they all belong to this 684 // LiveRange now. Also remove dead val#'s. 685 unsigned NumValNos = 0; 686 for (unsigned i = 0; i < NumNewVals; ++i) { 687 VNInfo *VNI = NewVNInfo[i]; 688 if (VNI) { 689 if (NumValNos >= NumVals) 690 valnos.push_back(VNI); 691 else 692 valnos[NumValNos] = VNI; 693 VNI->id = NumValNos++; // Renumber val#. 694 } 695 } 696 if (NumNewVals < NumVals) 697 valnos.resize(NumNewVals); // shrinkify 698 699 // Okay, now insert the RHS live segments into the LHS. 700 LiveRangeUpdater Updater(this); 701 for (Segment &S : Other.segments) 702 Updater.add(S); 703 } 704 705 /// Merge all of the segments in RHS into this live range as the specified 706 /// value number. The segments in RHS are allowed to overlap with segments in 707 /// the current range, but only if the overlapping segments have the 708 /// specified value number. 709 void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS, 710 VNInfo *LHSValNo) { 711 LiveRangeUpdater Updater(this); 712 for (const Segment &S : RHS.segments) 713 Updater.add(S.start, S.end, LHSValNo); 714 } 715 716 /// MergeValueInAsValue - Merge all of the live segments of a specific val# 717 /// in RHS into this live range as the specified value number. 718 /// The segments in RHS are allowed to overlap with segments in the 719 /// current range, it will replace the value numbers of the overlaped 720 /// segments with the specified value number. 721 void LiveRange::MergeValueInAsValue(const LiveRange &RHS, 722 const VNInfo *RHSValNo, 723 VNInfo *LHSValNo) { 724 LiveRangeUpdater Updater(this); 725 for (const Segment &S : RHS.segments) 726 if (S.valno == RHSValNo) 727 Updater.add(S.start, S.end, LHSValNo); 728 } 729 730 /// MergeValueNumberInto - This method is called when two value nubmers 731 /// are found to be equivalent. This eliminates V1, replacing all 732 /// segments with the V1 value number with the V2 value number. This can 733 /// cause merging of V1/V2 values numbers and compaction of the value space. 734 VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) { 735 assert(V1 != V2 && "Identical value#'s are always equivalent!"); 736 737 // This code actually merges the (numerically) larger value number into the 738 // smaller value number, which is likely to allow us to compactify the value 739 // space. The only thing we have to be careful of is to preserve the 740 // instruction that defines the result value. 741 742 // Make sure V2 is smaller than V1. 743 if (V1->id < V2->id) { 744 V1->copyFrom(*V2); 745 std::swap(V1, V2); 746 } 747 748 // Merge V1 segments into V2. 749 for (iterator I = begin(); I != end(); ) { 750 iterator S = I++; 751 if (S->valno != V1) continue; // Not a V1 Segment. 752 753 // Okay, we found a V1 live range. If it had a previous, touching, V2 live 754 // range, extend it. 755 if (S != begin()) { 756 iterator Prev = S-1; 757 if (Prev->valno == V2 && Prev->end == S->start) { 758 Prev->end = S->end; 759 760 // Erase this live-range. 761 segments.erase(S); 762 I = Prev+1; 763 S = Prev; 764 } 765 } 766 767 // Okay, now we have a V1 or V2 live range that is maximally merged forward. 768 // Ensure that it is a V2 live-range. 769 S->valno = V2; 770 771 // If we can merge it into later V2 segments, do so now. We ignore any 772 // following V1 segments, as they will be merged in subsequent iterations 773 // of the loop. 774 if (I != end()) { 775 if (I->start == S->end && I->valno == V2) { 776 S->end = I->end; 777 segments.erase(I); 778 I = S+1; 779 } 780 } 781 } 782 783 // Now that V1 is dead, remove it. 784 markValNoForDeletion(V1); 785 786 return V2; 787 } 788 789 void LiveRange::flushSegmentSet() { 790 assert(segmentSet != nullptr && "segment set must have been created"); 791 assert( 792 segments.empty() && 793 "segment set can be used only initially before switching to the array"); 794 segments.append(segmentSet->begin(), segmentSet->end()); 795 segmentSet = nullptr; 796 verify(); 797 } 798 799 bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const { 800 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin(); 801 ArrayRef<SlotIndex>::iterator SlotE = Slots.end(); 802 803 // If there are no regmask slots, we have nothing to search. 804 if (SlotI == SlotE) 805 return false; 806 807 // Start our search at the first segment that ends after the first slot. 808 const_iterator SegmentI = find(*SlotI); 809 const_iterator SegmentE = end(); 810 811 // If there are no segments that end after the first slot, we're done. 812 if (SegmentI == SegmentE) 813 return false; 814 815 // Look for each slot in the live range. 816 for ( ; SlotI != SlotE; ++SlotI) { 817 // Go to the next segment that ends after the current slot. 818 // The slot may be within a hole in the range. 819 SegmentI = advanceTo(SegmentI, *SlotI); 820 if (SegmentI == SegmentE) 821 return false; 822 823 // If this segment contains the slot, we're done. 824 if (SegmentI->contains(*SlotI)) 825 return true; 826 // Otherwise, look for the next slot. 827 } 828 829 // We didn't find a segment containing any of the slots. 830 return false; 831 } 832 833 void LiveInterval::freeSubRange(SubRange *S) { 834 S->~SubRange(); 835 // Memory was allocated with BumpPtr allocator and is not freed here. 836 } 837 838 void LiveInterval::removeEmptySubRanges() { 839 SubRange **NextPtr = &SubRanges; 840 SubRange *I = *NextPtr; 841 while (I != nullptr) { 842 if (!I->empty()) { 843 NextPtr = &I->Next; 844 I = *NextPtr; 845 continue; 846 } 847 // Skip empty subranges until we find the first nonempty one. 848 do { 849 SubRange *Next = I->Next; 850 freeSubRange(I); 851 I = Next; 852 } while (I != nullptr && I->empty()); 853 *NextPtr = I; 854 } 855 } 856 857 void LiveInterval::clearSubRanges() { 858 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) { 859 Next = I->Next; 860 freeSubRange(I); 861 } 862 SubRanges = nullptr; 863 } 864 865 /// For each VNI in \p SR, check whether or not that value defines part 866 /// of the mask describe by \p LaneMask and if not, remove that value 867 /// from \p SR. 868 static void stripValuesNotDefiningMask(unsigned Reg, LiveInterval::SubRange &SR, 869 LaneBitmask LaneMask, 870 const SlotIndexes &Indexes, 871 const TargetRegisterInfo &TRI, 872 unsigned ComposeSubRegIdx) { 873 // Phys reg should not be tracked at subreg level. 874 // Same for noreg (Reg == 0). 875 if (!Register::isVirtualRegister(Reg) || !Reg) 876 return; 877 // Remove the values that don't define those lanes. 878 SmallVector<VNInfo *, 8> ToBeRemoved; 879 for (VNInfo *VNI : SR.valnos) { 880 if (VNI->isUnused()) 881 continue; 882 // PHI definitions don't have MI attached, so there is nothing 883 // we can use to strip the VNI. 884 if (VNI->isPHIDef()) 885 continue; 886 const MachineInstr *MI = Indexes.getInstructionFromIndex(VNI->def); 887 assert(MI && "Cannot find the definition of a value"); 888 bool hasDef = false; 889 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) { 890 if (!MOI->isReg() || !MOI->isDef()) 891 continue; 892 if (MOI->getReg() != Reg) 893 continue; 894 LaneBitmask OrigMask = TRI.getSubRegIndexLaneMask(MOI->getSubReg()); 895 LaneBitmask ExpectedDefMask = 896 ComposeSubRegIdx 897 ? TRI.composeSubRegIndexLaneMask(ComposeSubRegIdx, OrigMask) 898 : OrigMask; 899 if ((ExpectedDefMask & LaneMask).none()) 900 continue; 901 hasDef = true; 902 break; 903 } 904 905 if (!hasDef) 906 ToBeRemoved.push_back(VNI); 907 } 908 for (VNInfo *VNI : ToBeRemoved) 909 SR.removeValNo(VNI); 910 911 // If the subrange is empty at this point, the MIR is invalid. Do not assert 912 // and let the verifier catch this case. 913 } 914 915 void LiveInterval::refineSubRanges( 916 BumpPtrAllocator &Allocator, LaneBitmask LaneMask, 917 std::function<void(LiveInterval::SubRange &)> Apply, 918 const SlotIndexes &Indexes, const TargetRegisterInfo &TRI, 919 unsigned ComposeSubRegIdx) { 920 LaneBitmask ToApply = LaneMask; 921 for (SubRange &SR : subranges()) { 922 LaneBitmask SRMask = SR.LaneMask; 923 LaneBitmask Matching = SRMask & LaneMask; 924 if (Matching.none()) 925 continue; 926 927 SubRange *MatchingRange; 928 if (SRMask == Matching) { 929 // The subrange fits (it does not cover bits outside \p LaneMask). 930 MatchingRange = &SR; 931 } else { 932 // We have to split the subrange into a matching and non-matching part. 933 // Reduce lanemask of existing lane to non-matching part. 934 SR.LaneMask = SRMask & ~Matching; 935 // Create a new subrange for the matching part 936 MatchingRange = createSubRangeFrom(Allocator, Matching, SR); 937 // Now that the subrange is split in half, make sure we 938 // only keep in the subranges the VNIs that touch the related half. 939 stripValuesNotDefiningMask(reg(), *MatchingRange, Matching, Indexes, TRI, 940 ComposeSubRegIdx); 941 stripValuesNotDefiningMask(reg(), SR, SR.LaneMask, Indexes, TRI, 942 ComposeSubRegIdx); 943 } 944 Apply(*MatchingRange); 945 ToApply &= ~Matching; 946 } 947 // Create a new subrange if there are uncovered bits left. 948 if (ToApply.any()) { 949 SubRange *NewRange = createSubRange(Allocator, ToApply); 950 Apply(*NewRange); 951 } 952 } 953 954 unsigned LiveInterval::getSize() const { 955 unsigned Sum = 0; 956 for (const Segment &S : segments) 957 Sum += S.start.distance(S.end); 958 return Sum; 959 } 960 961 void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs, 962 LaneBitmask LaneMask, 963 const MachineRegisterInfo &MRI, 964 const SlotIndexes &Indexes) const { 965 assert(Register::isVirtualRegister(reg())); 966 LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg()); 967 assert((VRegMask & LaneMask).any()); 968 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 969 for (const MachineOperand &MO : MRI.def_operands(reg())) { 970 if (!MO.isUndef()) 971 continue; 972 unsigned SubReg = MO.getSubReg(); 973 assert(SubReg != 0 && "Undef should only be set on subreg defs"); 974 LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg); 975 LaneBitmask UndefMask = VRegMask & ~DefMask; 976 if ((UndefMask & LaneMask).any()) { 977 const MachineInstr &MI = *MO.getParent(); 978 bool EarlyClobber = MO.isEarlyClobber(); 979 SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber); 980 Undefs.push_back(Pos); 981 } 982 } 983 } 984 985 raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) { 986 return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')'; 987 } 988 989 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 990 LLVM_DUMP_METHOD void LiveRange::Segment::dump() const { 991 dbgs() << *this << '\n'; 992 } 993 #endif 994 995 void LiveRange::print(raw_ostream &OS) const { 996 if (empty()) 997 OS << "EMPTY"; 998 else { 999 for (const Segment &S : segments) { 1000 OS << S; 1001 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo"); 1002 } 1003 } 1004 1005 // Print value number info. 1006 if (getNumValNums()) { 1007 OS << ' '; 1008 unsigned vnum = 0; 1009 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e; 1010 ++i, ++vnum) { 1011 const VNInfo *vni = *i; 1012 if (vnum) OS << ' '; 1013 OS << vnum << '@'; 1014 if (vni->isUnused()) { 1015 OS << 'x'; 1016 } else { 1017 OS << vni->def; 1018 if (vni->isPHIDef()) 1019 OS << "-phi"; 1020 } 1021 } 1022 } 1023 } 1024 1025 void LiveInterval::SubRange::print(raw_ostream &OS) const { 1026 OS << " L" << PrintLaneMask(LaneMask) << ' ' 1027 << static_cast<const LiveRange &>(*this); 1028 } 1029 1030 void LiveInterval::print(raw_ostream &OS) const { 1031 OS << printReg(reg()) << ' '; 1032 super::print(OS); 1033 // Print subranges 1034 for (const SubRange &SR : subranges()) 1035 OS << SR; 1036 OS << " weight:" << Weight; 1037 } 1038 1039 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1040 LLVM_DUMP_METHOD void LiveRange::dump() const { 1041 dbgs() << *this << '\n'; 1042 } 1043 1044 LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const { 1045 dbgs() << *this << '\n'; 1046 } 1047 1048 LLVM_DUMP_METHOD void LiveInterval::dump() const { 1049 dbgs() << *this << '\n'; 1050 } 1051 #endif 1052 1053 #ifndef NDEBUG 1054 void LiveRange::verify() const { 1055 for (const_iterator I = begin(), E = end(); I != E; ++I) { 1056 assert(I->start.isValid()); 1057 assert(I->end.isValid()); 1058 assert(I->start < I->end); 1059 assert(I->valno != nullptr); 1060 assert(I->valno->id < valnos.size()); 1061 assert(I->valno == valnos[I->valno->id]); 1062 if (std::next(I) != E) { 1063 assert(I->end <= std::next(I)->start); 1064 if (I->end == std::next(I)->start) 1065 assert(I->valno != std::next(I)->valno); 1066 } 1067 } 1068 } 1069 1070 void LiveInterval::verify(const MachineRegisterInfo *MRI) const { 1071 super::verify(); 1072 1073 // Make sure SubRanges are fine and LaneMasks are disjunct. 1074 LaneBitmask Mask; 1075 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg()) 1076 : LaneBitmask::getAll(); 1077 for (const SubRange &SR : subranges()) { 1078 // Subrange lanemask should be disjunct to any previous subrange masks. 1079 assert((Mask & SR.LaneMask).none()); 1080 Mask |= SR.LaneMask; 1081 1082 // subrange mask should not contained in maximum lane mask for the vreg. 1083 assert((Mask & ~MaxMask).none()); 1084 // empty subranges must be removed. 1085 assert(!SR.empty()); 1086 1087 SR.verify(); 1088 // Main liverange should cover subrange. 1089 assert(covers(SR)); 1090 } 1091 } 1092 #endif 1093 1094 //===----------------------------------------------------------------------===// 1095 // LiveRangeUpdater class 1096 //===----------------------------------------------------------------------===// 1097 // 1098 // The LiveRangeUpdater class always maintains these invariants: 1099 // 1100 // - When LastStart is invalid, Spills is empty and the iterators are invalid. 1101 // This is the initial state, and the state created by flush(). 1102 // In this state, isDirty() returns false. 1103 // 1104 // Otherwise, segments are kept in three separate areas: 1105 // 1106 // 1. [begin; WriteI) at the front of LR. 1107 // 2. [ReadI; end) at the back of LR. 1108 // 3. Spills. 1109 // 1110 // - LR.begin() <= WriteI <= ReadI <= LR.end(). 1111 // - Segments in all three areas are fully ordered and coalesced. 1112 // - Segments in area 1 precede and can't coalesce with segments in area 2. 1113 // - Segments in Spills precede and can't coalesce with segments in area 2. 1114 // - No coalescing is possible between segments in Spills and segments in area 1115 // 1, and there are no overlapping segments. 1116 // 1117 // The segments in Spills are not ordered with respect to the segments in area 1118 // 1. They need to be merged. 1119 // 1120 // When they exist, Spills.back().start <= LastStart, 1121 // and WriteI[-1].start <= LastStart. 1122 1123 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1124 void LiveRangeUpdater::print(raw_ostream &OS) const { 1125 if (!isDirty()) { 1126 if (LR) 1127 OS << "Clean updater: " << *LR << '\n'; 1128 else 1129 OS << "Null updater.\n"; 1130 return; 1131 } 1132 assert(LR && "Can't have null LR in dirty updater."); 1133 OS << " updater with gap = " << (ReadI - WriteI) 1134 << ", last start = " << LastStart 1135 << ":\n Area 1:"; 1136 for (const auto &S : make_range(LR->begin(), WriteI)) 1137 OS << ' ' << S; 1138 OS << "\n Spills:"; 1139 for (unsigned I = 0, E = Spills.size(); I != E; ++I) 1140 OS << ' ' << Spills[I]; 1141 OS << "\n Area 2:"; 1142 for (const auto &S : make_range(ReadI, LR->end())) 1143 OS << ' ' << S; 1144 OS << '\n'; 1145 } 1146 1147 LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const { 1148 print(errs()); 1149 } 1150 #endif 1151 1152 // Determine if A and B should be coalesced. 1153 static inline bool coalescable(const LiveRange::Segment &A, 1154 const LiveRange::Segment &B) { 1155 assert(A.start <= B.start && "Unordered live segments."); 1156 if (A.end == B.start) 1157 return A.valno == B.valno; 1158 if (A.end < B.start) 1159 return false; 1160 assert(A.valno == B.valno && "Cannot overlap different values"); 1161 return true; 1162 } 1163 1164 void LiveRangeUpdater::add(LiveRange::Segment Seg) { 1165 assert(LR && "Cannot add to a null destination"); 1166 1167 // Fall back to the regular add method if the live range 1168 // is using the segment set instead of the segment vector. 1169 if (LR->segmentSet != nullptr) { 1170 LR->addSegmentToSet(Seg); 1171 return; 1172 } 1173 1174 // Flush the state if Start moves backwards. 1175 if (!LastStart.isValid() || LastStart > Seg.start) { 1176 if (isDirty()) 1177 flush(); 1178 // This brings us to an uninitialized state. Reinitialize. 1179 assert(Spills.empty() && "Leftover spilled segments"); 1180 WriteI = ReadI = LR->begin(); 1181 } 1182 1183 // Remember start for next time. 1184 LastStart = Seg.start; 1185 1186 // Advance ReadI until it ends after Seg.start. 1187 LiveRange::iterator E = LR->end(); 1188 if (ReadI != E && ReadI->end <= Seg.start) { 1189 // First try to close the gap between WriteI and ReadI with spills. 1190 if (ReadI != WriteI) 1191 mergeSpills(); 1192 // Then advance ReadI. 1193 if (ReadI == WriteI) 1194 ReadI = WriteI = LR->find(Seg.start); 1195 else 1196 while (ReadI != E && ReadI->end <= Seg.start) 1197 *WriteI++ = *ReadI++; 1198 } 1199 1200 assert(ReadI == E || ReadI->end > Seg.start); 1201 1202 // Check if the ReadI segment begins early. 1203 if (ReadI != E && ReadI->start <= Seg.start) { 1204 assert(ReadI->valno == Seg.valno && "Cannot overlap different values"); 1205 // Bail if Seg is completely contained in ReadI. 1206 if (ReadI->end >= Seg.end) 1207 return; 1208 // Coalesce into Seg. 1209 Seg.start = ReadI->start; 1210 ++ReadI; 1211 } 1212 1213 // Coalesce as much as possible from ReadI into Seg. 1214 while (ReadI != E && coalescable(Seg, *ReadI)) { 1215 Seg.end = std::max(Seg.end, ReadI->end); 1216 ++ReadI; 1217 } 1218 1219 // Try coalescing Spills.back() into Seg. 1220 if (!Spills.empty() && coalescable(Spills.back(), Seg)) { 1221 Seg.start = Spills.back().start; 1222 Seg.end = std::max(Spills.back().end, Seg.end); 1223 Spills.pop_back(); 1224 } 1225 1226 // Try coalescing Seg into WriteI[-1]. 1227 if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) { 1228 WriteI[-1].end = std::max(WriteI[-1].end, Seg.end); 1229 return; 1230 } 1231 1232 // Seg doesn't coalesce with anything, and needs to be inserted somewhere. 1233 if (WriteI != ReadI) { 1234 *WriteI++ = Seg; 1235 return; 1236 } 1237 1238 // Finally, append to LR or Spills. 1239 if (WriteI == E) { 1240 LR->segments.push_back(Seg); 1241 WriteI = ReadI = LR->end(); 1242 } else 1243 Spills.push_back(Seg); 1244 } 1245 1246 // Merge as many spilled segments as possible into the gap between WriteI 1247 // and ReadI. Advance WriteI to reflect the inserted instructions. 1248 void LiveRangeUpdater::mergeSpills() { 1249 // Perform a backwards merge of Spills and [SpillI;WriteI). 1250 size_t GapSize = ReadI - WriteI; 1251 size_t NumMoved = std::min(Spills.size(), GapSize); 1252 LiveRange::iterator Src = WriteI; 1253 LiveRange::iterator Dst = Src + NumMoved; 1254 LiveRange::iterator SpillSrc = Spills.end(); 1255 LiveRange::iterator B = LR->begin(); 1256 1257 // This is the new WriteI position after merging spills. 1258 WriteI = Dst; 1259 1260 // Now merge Src and Spills backwards. 1261 while (Src != Dst) { 1262 if (Src != B && Src[-1].start > SpillSrc[-1].start) 1263 *--Dst = *--Src; 1264 else 1265 *--Dst = *--SpillSrc; 1266 } 1267 assert(NumMoved == size_t(Spills.end() - SpillSrc)); 1268 Spills.erase(SpillSrc, Spills.end()); 1269 } 1270 1271 void LiveRangeUpdater::flush() { 1272 if (!isDirty()) 1273 return; 1274 // Clear the dirty state. 1275 LastStart = SlotIndex(); 1276 1277 assert(LR && "Cannot add to a null destination"); 1278 1279 // Nothing to merge? 1280 if (Spills.empty()) { 1281 LR->segments.erase(WriteI, ReadI); 1282 LR->verify(); 1283 return; 1284 } 1285 1286 // Resize the WriteI - ReadI gap to match Spills. 1287 size_t GapSize = ReadI - WriteI; 1288 if (GapSize < Spills.size()) { 1289 // The gap is too small. Make some room. 1290 size_t WritePos = WriteI - LR->begin(); 1291 LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment()); 1292 // This also invalidated ReadI, but it is recomputed below. 1293 WriteI = LR->begin() + WritePos; 1294 } else { 1295 // Shrink the gap if necessary. 1296 LR->segments.erase(WriteI + Spills.size(), ReadI); 1297 } 1298 ReadI = WriteI + Spills.size(); 1299 mergeSpills(); 1300 LR->verify(); 1301 } 1302 1303 unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) { 1304 // Create initial equivalence classes. 1305 EqClass.clear(); 1306 EqClass.grow(LR.getNumValNums()); 1307 1308 const VNInfo *used = nullptr, *unused = nullptr; 1309 1310 // Determine connections. 1311 for (const VNInfo *VNI : LR.valnos) { 1312 // Group all unused values into one class. 1313 if (VNI->isUnused()) { 1314 if (unused) 1315 EqClass.join(unused->id, VNI->id); 1316 unused = VNI; 1317 continue; 1318 } 1319 used = VNI; 1320 if (VNI->isPHIDef()) { 1321 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 1322 assert(MBB && "Phi-def has no defining MBB"); 1323 // Connect to values live out of predecessors. 1324 for (MachineBasicBlock *Pred : MBB->predecessors()) 1325 if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(Pred))) 1326 EqClass.join(VNI->id, PVNI->id); 1327 } else { 1328 // Normal value defined by an instruction. Check for two-addr redef. 1329 // FIXME: This could be coincidental. Should we really check for a tied 1330 // operand constraint? 1331 // Note that VNI->def may be a use slot for an early clobber def. 1332 if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def)) 1333 EqClass.join(VNI->id, UVNI->id); 1334 } 1335 } 1336 1337 // Lump all the unused values in with the last used value. 1338 if (used && unused) 1339 EqClass.join(used->id, unused->id); 1340 1341 EqClass.compress(); 1342 return EqClass.getNumClasses(); 1343 } 1344 1345 void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[], 1346 MachineRegisterInfo &MRI) { 1347 // Rewrite instructions. 1348 for (MachineOperand &MO : 1349 llvm::make_early_inc_range(MRI.reg_operands(LI.reg()))) { 1350 MachineInstr *MI = MO.getParent(); 1351 const VNInfo *VNI; 1352 if (MI->isDebugValue()) { 1353 // DBG_VALUE instructions don't have slot indexes, so get the index of 1354 // the instruction before them. The value is defined there too. 1355 SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI); 1356 VNI = LI.Query(Idx).valueOut(); 1357 } else { 1358 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1359 LiveQueryResult LRQ = LI.Query(Idx); 1360 VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined(); 1361 } 1362 // In the case of an <undef> use that isn't tied to any def, VNI will be 1363 // NULL. If the use is tied to a def, VNI will be the defined value. 1364 if (!VNI) 1365 continue; 1366 if (unsigned EqClass = getEqClass(VNI)) 1367 MO.setReg(LIV[EqClass - 1]->reg()); 1368 } 1369 1370 // Distribute subregister liveranges. 1371 if (LI.hasSubRanges()) { 1372 unsigned NumComponents = EqClass.getNumClasses(); 1373 SmallVector<unsigned, 8> VNIMapping; 1374 SmallVector<LiveInterval::SubRange*, 8> SubRanges; 1375 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator(); 1376 for (LiveInterval::SubRange &SR : LI.subranges()) { 1377 // Create new subranges in the split intervals and construct a mapping 1378 // for the VNInfos in the subrange. 1379 unsigned NumValNos = SR.valnos.size(); 1380 VNIMapping.clear(); 1381 VNIMapping.reserve(NumValNos); 1382 SubRanges.clear(); 1383 SubRanges.resize(NumComponents-1, nullptr); 1384 for (unsigned I = 0; I < NumValNos; ++I) { 1385 const VNInfo &VNI = *SR.valnos[I]; 1386 unsigned ComponentNum; 1387 if (VNI.isUnused()) { 1388 ComponentNum = 0; 1389 } else { 1390 const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def); 1391 assert(MainRangeVNI != nullptr 1392 && "SubRange def must have corresponding main range def"); 1393 ComponentNum = getEqClass(MainRangeVNI); 1394 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) { 1395 SubRanges[ComponentNum-1] 1396 = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask); 1397 } 1398 } 1399 VNIMapping.push_back(ComponentNum); 1400 } 1401 DistributeRange(SR, SubRanges.data(), VNIMapping); 1402 } 1403 LI.removeEmptySubRanges(); 1404 } 1405 1406 // Distribute main liverange. 1407 DistributeRange(LI, LIV, EqClass); 1408 } 1409