LiveInterval.cpp 46 KB

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