LLVM API Documentation

LiveInterval.cpp
Go to the documentation of this file.
00001 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LiveRange and LiveInterval classes.  Given some
00011 // numbering of each the machine instructions an interval [i, j) is said to be a
00012 // live range for register v if there is no instruction with number j' >= j
00013 // such that v is live at j' and there is no instruction with number i' < i such
00014 // that v is live at i'. In this implementation ranges can have holes,
00015 // i.e. a range might look like [1,20), [50,65), [1000,1001).  Each
00016 // individual segment is represented as an instance of LiveRange::Segment,
00017 // and the whole range is represented as an instance of LiveRange.
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #include "llvm/CodeGen/LiveInterval.h"
00022 #include "RegisterCoalescer.h"
00023 #include "llvm/ADT/DenseMap.h"
00024 #include "llvm/ADT/STLExtras.h"
00025 #include "llvm/ADT/SmallSet.h"
00026 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetRegisterInfo.h"
00031 #include <algorithm>
00032 using namespace llvm;
00033 
00034 LiveRange::iterator LiveRange::find(SlotIndex Pos) {
00035   // This algorithm is basically std::upper_bound.
00036   // Unfortunately, std::upper_bound cannot be used with mixed types until we
00037   // adopt C++0x. Many libraries can do it, but not all.
00038   if (empty() || Pos >= endIndex())
00039     return end();
00040   iterator I = begin();
00041   size_t Len = size();
00042   do {
00043     size_t Mid = Len >> 1;
00044     if (Pos < I[Mid].end)
00045       Len = Mid;
00046     else
00047       I += Mid + 1, Len -= Mid + 1;
00048   } while (Len);
00049   return I;
00050 }
00051 
00052 VNInfo *LiveRange::createDeadDef(SlotIndex Def,
00053                                   VNInfo::Allocator &VNInfoAllocator) {
00054   assert(!Def.isDead() && "Cannot define a value at the dead slot");
00055   iterator I = find(Def);
00056   if (I == end()) {
00057     VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
00058     segments.push_back(Segment(Def, Def.getDeadSlot(), VNI));
00059     return VNI;
00060   }
00061   if (SlotIndex::isSameInstr(Def, I->start)) {
00062     assert(I->valno->def == I->start && "Inconsistent existing value def");
00063 
00064     // It is possible to have both normal and early-clobber defs of the same
00065     // register on an instruction. It doesn't make a lot of sense, but it is
00066     // possible to specify in inline assembly.
00067     //
00068     // Just convert everything to early-clobber.
00069     Def = std::min(Def, I->start);
00070     if (Def != I->start)
00071       I->start = I->valno->def = Def;
00072     return I->valno;
00073   }
00074   assert(SlotIndex::isEarlierInstr(Def, I->start) && "Already live at def");
00075   VNInfo *VNI = getNextValue(Def, VNInfoAllocator);
00076   segments.insert(I, Segment(Def, Def.getDeadSlot(), VNI));
00077   return VNI;
00078 }
00079 
00080 // overlaps - Return true if the intersection of the two live ranges is
00081 // not empty.
00082 //
00083 // An example for overlaps():
00084 //
00085 // 0: A = ...
00086 // 4: B = ...
00087 // 8: C = A + B ;; last use of A
00088 //
00089 // The live ranges should look like:
00090 //
00091 // A = [3, 11)
00092 // B = [7, x)
00093 // C = [11, y)
00094 //
00095 // A->overlaps(C) should return false since we want to be able to join
00096 // A and C.
00097 //
00098 bool LiveRange::overlapsFrom(const LiveRange& other,
00099                              const_iterator StartPos) const {
00100   assert(!empty() && "empty range");
00101   const_iterator i = begin();
00102   const_iterator ie = end();
00103   const_iterator j = StartPos;
00104   const_iterator je = other.end();
00105 
00106   assert((StartPos->start <= i->start || StartPos == other.begin()) &&
00107          StartPos != other.end() && "Bogus start position hint!");
00108 
00109   if (i->start < j->start) {
00110     i = std::upper_bound(i, ie, j->start);
00111     if (i != begin()) --i;
00112   } else if (j->start < i->start) {
00113     ++StartPos;
00114     if (StartPos != other.end() && StartPos->start <= i->start) {
00115       assert(StartPos < other.end() && i < end());
00116       j = std::upper_bound(j, je, i->start);
00117       if (j != other.begin()) --j;
00118     }
00119   } else {
00120     return true;
00121   }
00122 
00123   if (j == je) return false;
00124 
00125   while (i != ie) {
00126     if (i->start > j->start) {
00127       std::swap(i, j);
00128       std::swap(ie, je);
00129     }
00130 
00131     if (i->end > j->start)
00132       return true;
00133     ++i;
00134   }
00135 
00136   return false;
00137 }
00138 
00139 bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
00140                          const SlotIndexes &Indexes) const {
00141   assert(!empty() && "empty range");
00142   if (Other.empty())
00143     return false;
00144 
00145   // Use binary searches to find initial positions.
00146   const_iterator I = find(Other.beginIndex());
00147   const_iterator IE = end();
00148   if (I == IE)
00149     return false;
00150   const_iterator J = Other.find(I->start);
00151   const_iterator JE = Other.end();
00152   if (J == JE)
00153     return false;
00154 
00155   for (;;) {
00156     // J has just been advanced to satisfy:
00157     assert(J->end >= I->start);
00158     // Check for an overlap.
00159     if (J->start < I->end) {
00160       // I and J are overlapping. Find the later start.
00161       SlotIndex Def = std::max(I->start, J->start);
00162       // Allow the overlap if Def is a coalescable copy.
00163       if (Def.isBlock() ||
00164           !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
00165         return true;
00166     }
00167     // Advance the iterator that ends first to check for more overlaps.
00168     if (J->end > I->end) {
00169       std::swap(I, J);
00170       std::swap(IE, JE);
00171     }
00172     // Advance J until J->end >= I->start.
00173     do
00174       if (++J == JE)
00175         return false;
00176     while (J->end < I->start);
00177   }
00178 }
00179 
00180 /// overlaps - Return true if the live range overlaps an interval specified
00181 /// by [Start, End).
00182 bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
00183   assert(Start < End && "Invalid range");
00184   const_iterator I = std::lower_bound(begin(), end(), End);
00185   return I != begin() && (--I)->end > Start;
00186 }
00187 
00188 
00189 /// ValNo is dead, remove it.  If it is the largest value number, just nuke it
00190 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
00191 /// it can be nuked later.
00192 void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
00193   if (ValNo->id == getNumValNums()-1) {
00194     do {
00195       valnos.pop_back();
00196     } while (!valnos.empty() && valnos.back()->isUnused());
00197   } else {
00198     ValNo->markUnused();
00199   }
00200 }
00201 
00202 /// RenumberValues - Renumber all values in order of appearance and delete the
00203 /// remaining unused values.
00204 void LiveRange::RenumberValues() {
00205   SmallPtrSet<VNInfo*, 8> Seen;
00206   valnos.clear();
00207   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00208     VNInfo *VNI = I->valno;
00209     if (!Seen.insert(VNI))
00210       continue;
00211     assert(!VNI->isUnused() && "Unused valno used by live segment");
00212     VNI->id = (unsigned)valnos.size();
00213     valnos.push_back(VNI);
00214   }
00215 }
00216 
00217 /// This method is used when we want to extend the segment specified by I to end
00218 /// at the specified endpoint.  To do this, we should merge and eliminate all
00219 /// segments that this will overlap with.  The iterator is not invalidated.
00220 void LiveRange::extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
00221   assert(I != end() && "Not a valid segment!");
00222   VNInfo *ValNo = I->valno;
00223 
00224   // Search for the first segment that we can't merge with.
00225   iterator MergeTo = std::next(I);
00226   for (; MergeTo != end() && NewEnd >= MergeTo->end; ++MergeTo) {
00227     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
00228   }
00229 
00230   // If NewEnd was in the middle of a segment, make sure to get its endpoint.
00231   I->end = std::max(NewEnd, std::prev(MergeTo)->end);
00232 
00233   // If the newly formed segment now touches the segment after it and if they
00234   // have the same value number, merge the two segments into one segment.
00235   if (MergeTo != end() && MergeTo->start <= I->end &&
00236       MergeTo->valno == ValNo) {
00237     I->end = MergeTo->end;
00238     ++MergeTo;
00239   }
00240 
00241   // Erase any dead segments.
00242   segments.erase(std::next(I), MergeTo);
00243 }
00244 
00245 
00246 /// This method is used when we want to extend the segment specified by I to
00247 /// start at the specified endpoint.  To do this, we should merge and eliminate
00248 /// all segments that this will overlap with.
00249 LiveRange::iterator
00250 LiveRange::extendSegmentStartTo(iterator I, SlotIndex NewStart) {
00251   assert(I != end() && "Not a valid segment!");
00252   VNInfo *ValNo = I->valno;
00253 
00254   // Search for the first segment that we can't merge with.
00255   iterator MergeTo = I;
00256   do {
00257     if (MergeTo == begin()) {
00258       I->start = NewStart;
00259       segments.erase(MergeTo, I);
00260       return I;
00261     }
00262     assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
00263     --MergeTo;
00264   } while (NewStart <= MergeTo->start);
00265 
00266   // If we start in the middle of another segment, just delete a range and
00267   // extend that segment.
00268   if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
00269     MergeTo->end = I->end;
00270   } else {
00271     // Otherwise, extend the segment right after.
00272     ++MergeTo;
00273     MergeTo->start = NewStart;
00274     MergeTo->end = I->end;
00275   }
00276 
00277   segments.erase(std::next(MergeTo), std::next(I));
00278   return MergeTo;
00279 }
00280 
00281 LiveRange::iterator LiveRange::addSegmentFrom(Segment S, iterator From) {
00282   SlotIndex Start = S.start, End = S.end;
00283   iterator it = std::upper_bound(From, end(), Start);
00284 
00285   // If the inserted segment starts in the middle or right at the end of
00286   // another segment, just extend that segment to contain the segment of S.
00287   if (it != begin()) {
00288     iterator B = std::prev(it);
00289     if (S.valno == B->valno) {
00290       if (B->start <= Start && B->end >= Start) {
00291         extendSegmentEndTo(B, End);
00292         return B;
00293       }
00294     } else {
00295       // Check to make sure that we are not overlapping two live segments with
00296       // different valno's.
00297       assert(B->end <= Start &&
00298              "Cannot overlap two segments with differing ValID's"
00299              " (did you def the same reg twice in a MachineInstr?)");
00300     }
00301   }
00302 
00303   // Otherwise, if this segment ends in the middle of, or right next to, another
00304   // segment, merge it into that segment.
00305   if (it != end()) {
00306     if (S.valno == it->valno) {
00307       if (it->start <= End) {
00308         it = extendSegmentStartTo(it, Start);
00309 
00310         // If S is a complete superset of a segment, we may need to grow its
00311         // endpoint as well.
00312         if (End > it->end)
00313           extendSegmentEndTo(it, End);
00314         return it;
00315       }
00316     } else {
00317       // Check to make sure that we are not overlapping two live segments with
00318       // different valno's.
00319       assert(it->start >= End &&
00320              "Cannot overlap two segments with differing ValID's");
00321     }
00322   }
00323 
00324   // Otherwise, this is just a new segment that doesn't interact with anything.
00325   // Insert it.
00326   return segments.insert(it, S);
00327 }
00328 
00329 /// extendInBlock - If this range is live before Kill in the basic
00330 /// block that starts at StartIdx, extend it to be live up to Kill and return
00331 /// the value. If there is no live range before Kill, return NULL.
00332 VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
00333   if (empty())
00334     return nullptr;
00335   iterator I = std::upper_bound(begin(), end(), Kill.getPrevSlot());
00336   if (I == begin())
00337     return nullptr;
00338   --I;
00339   if (I->end <= StartIdx)
00340     return nullptr;
00341   if (I->end < Kill)
00342     extendSegmentEndTo(I, Kill);
00343   return I->valno;
00344 }
00345 
00346 /// Remove the specified segment from this range.  Note that the segment must
00347 /// be in a single Segment in its entirety.
00348 void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
00349                               bool RemoveDeadValNo) {
00350   // Find the Segment containing this span.
00351   iterator I = find(Start);
00352   assert(I != end() && "Segment is not in range!");
00353   assert(I->containsInterval(Start, End)
00354          && "Segment is not entirely in range!");
00355 
00356   // If the span we are removing is at the start of the Segment, adjust it.
00357   VNInfo *ValNo = I->valno;
00358   if (I->start == Start) {
00359     if (I->end == End) {
00360       if (RemoveDeadValNo) {
00361         // Check if val# is dead.
00362         bool isDead = true;
00363         for (const_iterator II = begin(), EE = end(); II != EE; ++II)
00364           if (II != I && II->valno == ValNo) {
00365             isDead = false;
00366             break;
00367           }
00368         if (isDead) {
00369           // Now that ValNo is dead, remove it.
00370           markValNoForDeletion(ValNo);
00371         }
00372       }
00373 
00374       segments.erase(I);  // Removed the whole Segment.
00375     } else
00376       I->start = End;
00377     return;
00378   }
00379 
00380   // Otherwise if the span we are removing is at the end of the Segment,
00381   // adjust the other way.
00382   if (I->end == End) {
00383     I->end = Start;
00384     return;
00385   }
00386 
00387   // Otherwise, we are splitting the Segment into two pieces.
00388   SlotIndex OldEnd = I->end;
00389   I->end = Start;   // Trim the old segment.
00390 
00391   // Insert the new one.
00392   segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
00393 }
00394 
00395 /// removeValNo - Remove all the segments defined by the specified value#.
00396 /// Also remove the value# from value# list.
00397 void LiveRange::removeValNo(VNInfo *ValNo) {
00398   if (empty()) return;
00399   iterator I = end();
00400   iterator E = begin();
00401   do {
00402     --I;
00403     if (I->valno == ValNo)
00404       segments.erase(I);
00405   } while (I != E);
00406   // Now that ValNo is dead, remove it.
00407   markValNoForDeletion(ValNo);
00408 }
00409 
00410 void LiveRange::join(LiveRange &Other,
00411                      const int *LHSValNoAssignments,
00412                      const int *RHSValNoAssignments,
00413                      SmallVectorImpl<VNInfo *> &NewVNInfo) {
00414   verify();
00415 
00416   // Determine if any of our values are mapped.  This is uncommon, so we want
00417   // to avoid the range scan if not.
00418   bool MustMapCurValNos = false;
00419   unsigned NumVals = getNumValNums();
00420   unsigned NumNewVals = NewVNInfo.size();
00421   for (unsigned i = 0; i != NumVals; ++i) {
00422     unsigned LHSValID = LHSValNoAssignments[i];
00423     if (i != LHSValID ||
00424         (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
00425       MustMapCurValNos = true;
00426       break;
00427     }
00428   }
00429 
00430   // If we have to apply a mapping to our base range assignment, rewrite it now.
00431   if (MustMapCurValNos && !empty()) {
00432     // Map the first live range.
00433 
00434     iterator OutIt = begin();
00435     OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
00436     for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
00437       VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
00438       assert(nextValNo && "Huh?");
00439 
00440       // If this live range has the same value # as its immediate predecessor,
00441       // and if they are neighbors, remove one Segment.  This happens when we
00442       // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
00443       if (OutIt->valno == nextValNo && OutIt->end == I->start) {
00444         OutIt->end = I->end;
00445       } else {
00446         // Didn't merge. Move OutIt to the next segment,
00447         ++OutIt;
00448         OutIt->valno = nextValNo;
00449         if (OutIt != I) {
00450           OutIt->start = I->start;
00451           OutIt->end = I->end;
00452         }
00453       }
00454     }
00455     // If we merge some segments, chop off the end.
00456     ++OutIt;
00457     segments.erase(OutIt, end());
00458   }
00459 
00460   // Rewrite Other values before changing the VNInfo ids.
00461   // This can leave Other in an invalid state because we're not coalescing
00462   // touching segments that now have identical values. That's OK since Other is
00463   // not supposed to be valid after calling join();
00464   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
00465     I->valno = NewVNInfo[RHSValNoAssignments[I->valno->id]];
00466 
00467   // Update val# info. Renumber them and make sure they all belong to this
00468   // LiveRange now. Also remove dead val#'s.
00469   unsigned NumValNos = 0;
00470   for (unsigned i = 0; i < NumNewVals; ++i) {
00471     VNInfo *VNI = NewVNInfo[i];
00472     if (VNI) {
00473       if (NumValNos >= NumVals)
00474         valnos.push_back(VNI);
00475       else
00476         valnos[NumValNos] = VNI;
00477       VNI->id = NumValNos++;  // Renumber val#.
00478     }
00479   }
00480   if (NumNewVals < NumVals)
00481     valnos.resize(NumNewVals);  // shrinkify
00482 
00483   // Okay, now insert the RHS live segments into the LHS.
00484   LiveRangeUpdater Updater(this);
00485   for (iterator I = Other.begin(), E = Other.end(); I != E; ++I)
00486     Updater.add(*I);
00487 }
00488 
00489 /// Merge all of the segments in RHS into this live range as the specified
00490 /// value number.  The segments in RHS are allowed to overlap with segments in
00491 /// the current range, but only if the overlapping segments have the
00492 /// specified value number.
00493 void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
00494                                        VNInfo *LHSValNo) {
00495   LiveRangeUpdater Updater(this);
00496   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
00497     Updater.add(I->start, I->end, LHSValNo);
00498 }
00499 
00500 /// MergeValueInAsValue - Merge all of the live segments of a specific val#
00501 /// in RHS into this live range as the specified value number.
00502 /// The segments in RHS are allowed to overlap with segments in the
00503 /// current range, it will replace the value numbers of the overlaped
00504 /// segments with the specified value number.
00505 void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
00506                                     const VNInfo *RHSValNo,
00507                                     VNInfo *LHSValNo) {
00508   LiveRangeUpdater Updater(this);
00509   for (const_iterator I = RHS.begin(), E = RHS.end(); I != E; ++I)
00510     if (I->valno == RHSValNo)
00511       Updater.add(I->start, I->end, LHSValNo);
00512 }
00513 
00514 /// MergeValueNumberInto - This method is called when two value nubmers
00515 /// are found to be equivalent.  This eliminates V1, replacing all
00516 /// segments with the V1 value number with the V2 value number.  This can
00517 /// cause merging of V1/V2 values numbers and compaction of the value space.
00518 VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
00519   assert(V1 != V2 && "Identical value#'s are always equivalent!");
00520 
00521   // This code actually merges the (numerically) larger value number into the
00522   // smaller value number, which is likely to allow us to compactify the value
00523   // space.  The only thing we have to be careful of is to preserve the
00524   // instruction that defines the result value.
00525 
00526   // Make sure V2 is smaller than V1.
00527   if (V1->id < V2->id) {
00528     V1->copyFrom(*V2);
00529     std::swap(V1, V2);
00530   }
00531 
00532   // Merge V1 segments into V2.
00533   for (iterator I = begin(); I != end(); ) {
00534     iterator S = I++;
00535     if (S->valno != V1) continue;  // Not a V1 Segment.
00536 
00537     // Okay, we found a V1 live range.  If it had a previous, touching, V2 live
00538     // range, extend it.
00539     if (S != begin()) {
00540       iterator Prev = S-1;
00541       if (Prev->valno == V2 && Prev->end == S->start) {
00542         Prev->end = S->end;
00543 
00544         // Erase this live-range.
00545         segments.erase(S);
00546         I = Prev+1;
00547         S = Prev;
00548       }
00549     }
00550 
00551     // Okay, now we have a V1 or V2 live range that is maximally merged forward.
00552     // Ensure that it is a V2 live-range.
00553     S->valno = V2;
00554 
00555     // If we can merge it into later V2 segments, do so now.  We ignore any
00556     // following V1 segments, as they will be merged in subsequent iterations
00557     // of the loop.
00558     if (I != end()) {
00559       if (I->start == S->end && I->valno == V2) {
00560         S->end = I->end;
00561         segments.erase(I);
00562         I = S+1;
00563       }
00564     }
00565   }
00566 
00567   // Now that V1 is dead, remove it.
00568   markValNoForDeletion(V1);
00569 
00570   return V2;
00571 }
00572 
00573 unsigned LiveInterval::getSize() const {
00574   unsigned Sum = 0;
00575   for (const_iterator I = begin(), E = end(); I != E; ++I)
00576     Sum += I->start.distance(I->end);
00577   return Sum;
00578 }
00579 
00580 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange::Segment &S) {
00581   return os << '[' << S.start << ',' << S.end << ':' << S.valno->id << ")";
00582 }
00583 
00584 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00585 void LiveRange::Segment::dump() const {
00586   dbgs() << *this << "\n";
00587 }
00588 #endif
00589 
00590 void LiveRange::print(raw_ostream &OS) const {
00591   if (empty())
00592     OS << "EMPTY";
00593   else {
00594     for (const_iterator I = begin(), E = end(); I != E; ++I) {
00595       OS << *I;
00596       assert(I->valno == getValNumInfo(I->valno->id) && "Bad VNInfo");
00597     }
00598   }
00599 
00600   // Print value number info.
00601   if (getNumValNums()) {
00602     OS << "  ";
00603     unsigned vnum = 0;
00604     for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
00605          ++i, ++vnum) {
00606       const VNInfo *vni = *i;
00607       if (vnum) OS << " ";
00608       OS << vnum << "@";
00609       if (vni->isUnused()) {
00610         OS << "x";
00611       } else {
00612         OS << vni->def;
00613         if (vni->isPHIDef())
00614           OS << "-phi";
00615       }
00616     }
00617   }
00618 }
00619 
00620 void LiveInterval::print(raw_ostream &OS) const {
00621   OS << PrintReg(reg) << ' ';
00622   super::print(OS);
00623 }
00624 
00625 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00626 void LiveRange::dump() const {
00627   dbgs() << *this << "\n";
00628 }
00629 
00630 void LiveInterval::dump() const {
00631   dbgs() << *this << "\n";
00632 }
00633 #endif
00634 
00635 #ifndef NDEBUG
00636 void LiveRange::verify() const {
00637   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00638     assert(I->start.isValid());
00639     assert(I->end.isValid());
00640     assert(I->start < I->end);
00641     assert(I->valno != nullptr);
00642     assert(I->valno->id < valnos.size());
00643     assert(I->valno == valnos[I->valno->id]);
00644     if (std::next(I) != E) {
00645       assert(I->end <= std::next(I)->start);
00646       if (I->end == std::next(I)->start)
00647         assert(I->valno != std::next(I)->valno);
00648     }
00649   }
00650 }
00651 #endif
00652 
00653 
00654 //===----------------------------------------------------------------------===//
00655 //                           LiveRangeUpdater class
00656 //===----------------------------------------------------------------------===//
00657 //
00658 // The LiveRangeUpdater class always maintains these invariants:
00659 //
00660 // - When LastStart is invalid, Spills is empty and the iterators are invalid.
00661 //   This is the initial state, and the state created by flush().
00662 //   In this state, isDirty() returns false.
00663 //
00664 // Otherwise, segments are kept in three separate areas:
00665 //
00666 // 1. [begin; WriteI) at the front of LR.
00667 // 2. [ReadI; end) at the back of LR.
00668 // 3. Spills.
00669 //
00670 // - LR.begin() <= WriteI <= ReadI <= LR.end().
00671 // - Segments in all three areas are fully ordered and coalesced.
00672 // - Segments in area 1 precede and can't coalesce with segments in area 2.
00673 // - Segments in Spills precede and can't coalesce with segments in area 2.
00674 // - No coalescing is possible between segments in Spills and segments in area
00675 //   1, and there are no overlapping segments.
00676 //
00677 // The segments in Spills are not ordered with respect to the segments in area
00678 // 1. They need to be merged.
00679 //
00680 // When they exist, Spills.back().start <= LastStart,
00681 //                 and WriteI[-1].start <= LastStart.
00682 
00683 void LiveRangeUpdater::print(raw_ostream &OS) const {
00684   if (!isDirty()) {
00685     if (LR)
00686       OS << "Clean updater: " << *LR << '\n';
00687     else
00688       OS << "Null updater.\n";
00689     return;
00690   }
00691   assert(LR && "Can't have null LR in dirty updater.");
00692   OS << " updater with gap = " << (ReadI - WriteI)
00693      << ", last start = " << LastStart
00694      << ":\n  Area 1:";
00695   for (LiveRange::const_iterator I = LR->begin(); I != WriteI; ++I)
00696     OS << ' ' << *I;
00697   OS << "\n  Spills:";
00698   for (unsigned I = 0, E = Spills.size(); I != E; ++I)
00699     OS << ' ' << Spills[I];
00700   OS << "\n  Area 2:";
00701   for (LiveRange::const_iterator I = ReadI, E = LR->end(); I != E; ++I)
00702     OS << ' ' << *I;
00703   OS << '\n';
00704 }
00705 
00706 void LiveRangeUpdater::dump() const
00707 {
00708   print(errs());
00709 }
00710 
00711 // Determine if A and B should be coalesced.
00712 static inline bool coalescable(const LiveRange::Segment &A,
00713                                const LiveRange::Segment &B) {
00714   assert(A.start <= B.start && "Unordered live segments.");
00715   if (A.end == B.start)
00716     return A.valno == B.valno;
00717   if (A.end < B.start)
00718     return false;
00719   assert(A.valno == B.valno && "Cannot overlap different values");
00720   return true;
00721 }
00722 
00723 void LiveRangeUpdater::add(LiveRange::Segment Seg) {
00724   assert(LR && "Cannot add to a null destination");
00725 
00726   // Flush the state if Start moves backwards.
00727   if (!LastStart.isValid() || LastStart > Seg.start) {
00728     if (isDirty())
00729       flush();
00730     // This brings us to an uninitialized state. Reinitialize.
00731     assert(Spills.empty() && "Leftover spilled segments");
00732     WriteI = ReadI = LR->begin();
00733   }
00734 
00735   // Remember start for next time.
00736   LastStart = Seg.start;
00737 
00738   // Advance ReadI until it ends after Seg.start.
00739   LiveRange::iterator E = LR->end();
00740   if (ReadI != E && ReadI->end <= Seg.start) {
00741     // First try to close the gap between WriteI and ReadI with spills.
00742     if (ReadI != WriteI)
00743       mergeSpills();
00744     // Then advance ReadI.
00745     if (ReadI == WriteI)
00746       ReadI = WriteI = LR->find(Seg.start);
00747     else
00748       while (ReadI != E && ReadI->end <= Seg.start)
00749         *WriteI++ = *ReadI++;
00750   }
00751 
00752   assert(ReadI == E || ReadI->end > Seg.start);
00753 
00754   // Check if the ReadI segment begins early.
00755   if (ReadI != E && ReadI->start <= Seg.start) {
00756     assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
00757     // Bail if Seg is completely contained in ReadI.
00758     if (ReadI->end >= Seg.end)
00759       return;
00760     // Coalesce into Seg.
00761     Seg.start = ReadI->start;
00762     ++ReadI;
00763   }
00764 
00765   // Coalesce as much as possible from ReadI into Seg.
00766   while (ReadI != E && coalescable(Seg, *ReadI)) {
00767     Seg.end = std::max(Seg.end, ReadI->end);
00768     ++ReadI;
00769   }
00770 
00771   // Try coalescing Spills.back() into Seg.
00772   if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
00773     Seg.start = Spills.back().start;
00774     Seg.end = std::max(Spills.back().end, Seg.end);
00775     Spills.pop_back();
00776   }
00777 
00778   // Try coalescing Seg into WriteI[-1].
00779   if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
00780     WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
00781     return;
00782   }
00783 
00784   // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
00785   if (WriteI != ReadI) {
00786     *WriteI++ = Seg;
00787     return;
00788   }
00789 
00790   // Finally, append to LR or Spills.
00791   if (WriteI == E) {
00792     LR->segments.push_back(Seg);
00793     WriteI = ReadI = LR->end();
00794   } else
00795     Spills.push_back(Seg);
00796 }
00797 
00798 // Merge as many spilled segments as possible into the gap between WriteI
00799 // and ReadI. Advance WriteI to reflect the inserted instructions.
00800 void LiveRangeUpdater::mergeSpills() {
00801   // Perform a backwards merge of Spills and [SpillI;WriteI).
00802   size_t GapSize = ReadI - WriteI;
00803   size_t NumMoved = std::min(Spills.size(), GapSize);
00804   LiveRange::iterator Src = WriteI;
00805   LiveRange::iterator Dst = Src + NumMoved;
00806   LiveRange::iterator SpillSrc = Spills.end();
00807   LiveRange::iterator B = LR->begin();
00808 
00809   // This is the new WriteI position after merging spills.
00810   WriteI = Dst;
00811 
00812   // Now merge Src and Spills backwards.
00813   while (Src != Dst) {
00814     if (Src != B && Src[-1].start > SpillSrc[-1].start)
00815       *--Dst = *--Src;
00816     else
00817       *--Dst = *--SpillSrc;
00818   }
00819   assert(NumMoved == size_t(Spills.end() - SpillSrc));
00820   Spills.erase(SpillSrc, Spills.end());
00821 }
00822 
00823 void LiveRangeUpdater::flush() {
00824   if (!isDirty())
00825     return;
00826   // Clear the dirty state.
00827   LastStart = SlotIndex();
00828 
00829   assert(LR && "Cannot add to a null destination");
00830 
00831   // Nothing to merge?
00832   if (Spills.empty()) {
00833     LR->segments.erase(WriteI, ReadI);
00834     LR->verify();
00835     return;
00836   }
00837 
00838   // Resize the WriteI - ReadI gap to match Spills.
00839   size_t GapSize = ReadI - WriteI;
00840   if (GapSize < Spills.size()) {
00841     // The gap is too small. Make some room.
00842     size_t WritePos = WriteI - LR->begin();
00843     LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
00844     // This also invalidated ReadI, but it is recomputed below.
00845     WriteI = LR->begin() + WritePos;
00846   } else {
00847     // Shrink the gap if necessary.
00848     LR->segments.erase(WriteI + Spills.size(), ReadI);
00849   }
00850   ReadI = WriteI + Spills.size();
00851   mergeSpills();
00852   LR->verify();
00853 }
00854 
00855 unsigned ConnectedVNInfoEqClasses::Classify(const LiveInterval *LI) {
00856   // Create initial equivalence classes.
00857   EqClass.clear();
00858   EqClass.grow(LI->getNumValNums());
00859 
00860   const VNInfo *used = nullptr, *unused = nullptr;
00861 
00862   // Determine connections.
00863   for (LiveInterval::const_vni_iterator I = LI->vni_begin(), E = LI->vni_end();
00864        I != E; ++I) {
00865     const VNInfo *VNI = *I;
00866     // Group all unused values into one class.
00867     if (VNI->isUnused()) {
00868       if (unused)
00869         EqClass.join(unused->id, VNI->id);
00870       unused = VNI;
00871       continue;
00872     }
00873     used = VNI;
00874     if (VNI->isPHIDef()) {
00875       const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
00876       assert(MBB && "Phi-def has no defining MBB");
00877       // Connect to values live out of predecessors.
00878       for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
00879            PE = MBB->pred_end(); PI != PE; ++PI)
00880         if (const VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
00881           EqClass.join(VNI->id, PVNI->id);
00882     } else {
00883       // Normal value defined by an instruction. Check for two-addr redef.
00884       // FIXME: This could be coincidental. Should we really check for a tied
00885       // operand constraint?
00886       // Note that VNI->def may be a use slot for an early clobber def.
00887       if (const VNInfo *UVNI = LI->getVNInfoBefore(VNI->def))
00888         EqClass.join(VNI->id, UVNI->id);
00889     }
00890   }
00891 
00892   // Lump all the unused values in with the last used value.
00893   if (used && unused)
00894     EqClass.join(used->id, unused->id);
00895 
00896   EqClass.compress();
00897   return EqClass.getNumClasses();
00898 }
00899 
00900 void ConnectedVNInfoEqClasses::Distribute(LiveInterval *LIV[],
00901                                           MachineRegisterInfo &MRI) {
00902   assert(LIV[0] && "LIV[0] must be set");
00903   LiveInterval &LI = *LIV[0];
00904 
00905   // Rewrite instructions.
00906   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
00907        RE = MRI.reg_end(); RI != RE;) {
00908     MachineOperand &MO = *RI;
00909     MachineInstr *MI = RI->getParent();
00910     ++RI;
00911     // DBG_VALUE instructions don't have slot indexes, so get the index of the
00912     // instruction before them.
00913     // Normally, DBG_VALUE instructions are removed before this function is
00914     // called, but it is not a requirement.
00915     SlotIndex Idx;
00916     if (MI->isDebugValue())
00917       Idx = LIS.getSlotIndexes()->getIndexBefore(MI);
00918     else
00919       Idx = LIS.getInstructionIndex(MI);
00920     LiveQueryResult LRQ = LI.Query(Idx);
00921     const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
00922     // In the case of an <undef> use that isn't tied to any def, VNI will be
00923     // NULL. If the use is tied to a def, VNI will be the defined value.
00924     if (!VNI)
00925       continue;
00926     MO.setReg(LIV[getEqClass(VNI)]->reg);
00927   }
00928 
00929   // Move runs to new intervals.
00930   LiveInterval::iterator J = LI.begin(), E = LI.end();
00931   while (J != E && EqClass[J->valno->id] == 0)
00932     ++J;
00933   for (LiveInterval::iterator I = J; I != E; ++I) {
00934     if (unsigned eq = EqClass[I->valno->id]) {
00935       assert((LIV[eq]->empty() || LIV[eq]->expiredAt(I->start)) &&
00936              "New intervals should be empty");
00937       LIV[eq]->segments.push_back(*I);
00938     } else
00939       *J++ = *I;
00940   }
00941   LI.segments.erase(J, E);
00942 
00943   // Transfer VNInfos to their new owners and renumber them.
00944   unsigned j = 0, e = LI.getNumValNums();
00945   while (j != e && EqClass[j] == 0)
00946     ++j;
00947   for (unsigned i = j; i != e; ++i) {
00948     VNInfo *VNI = LI.getValNumInfo(i);
00949     if (unsigned eq = EqClass[i]) {
00950       VNI->id = LIV[eq]->getNumValNums();
00951       LIV[eq]->valnos.push_back(VNI);
00952     } else {
00953       VNI->id = j;
00954       LI.valnos[j++] = VNI;
00955     }
00956   }
00957   LI.valnos.resize(j);
00958 }