IntervalMap.h 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file implements a coalescing interval map for small objects.
  15. //
  16. // KeyT objects are mapped to ValT objects. Intervals of keys that map to the
  17. // same value are represented in a compressed form.
  18. //
  19. // Iterators provide ordered access to the compressed intervals rather than the
  20. // individual keys, and insert and erase operations use key intervals as well.
  21. //
  22. // Like SmallVector, IntervalMap will store the first N intervals in the map
  23. // object itself without any allocations. When space is exhausted it switches to
  24. // a B+-tree representation with very small overhead for small key and value
  25. // objects.
  26. //
  27. // A Traits class specifies how keys are compared. It also allows IntervalMap to
  28. // work with both closed and half-open intervals.
  29. //
  30. // Keys and values are not stored next to each other in a std::pair, so we don't
  31. // provide such a value_type. Dereferencing iterators only returns the mapped
  32. // value. The interval bounds are accessible through the start() and stop()
  33. // iterator methods.
  34. //
  35. // IntervalMap is optimized for small key and value objects, 4 or 8 bytes each
  36. // is the optimal size. For large objects use std::map instead.
  37. //
  38. //===----------------------------------------------------------------------===//
  39. //
  40. // Synopsis:
  41. //
  42. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  43. // class IntervalMap {
  44. // public:
  45. // typedef KeyT key_type;
  46. // typedef ValT mapped_type;
  47. // typedef RecyclingAllocator<...> Allocator;
  48. // class iterator;
  49. // class const_iterator;
  50. //
  51. // explicit IntervalMap(Allocator&);
  52. // ~IntervalMap():
  53. //
  54. // bool empty() const;
  55. // KeyT start() const;
  56. // KeyT stop() const;
  57. // ValT lookup(KeyT x, Value NotFound = Value()) const;
  58. //
  59. // const_iterator begin() const;
  60. // const_iterator end() const;
  61. // iterator begin();
  62. // iterator end();
  63. // const_iterator find(KeyT x) const;
  64. // iterator find(KeyT x);
  65. //
  66. // void insert(KeyT a, KeyT b, ValT y);
  67. // void clear();
  68. // };
  69. //
  70. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  71. // class IntervalMap::const_iterator :
  72. // public std::iterator<std::bidirectional_iterator_tag, ValT> {
  73. // public:
  74. // bool operator==(const const_iterator &) const;
  75. // bool operator!=(const const_iterator &) const;
  76. // bool valid() const;
  77. //
  78. // const KeyT &start() const;
  79. // const KeyT &stop() const;
  80. // const ValT &value() const;
  81. // const ValT &operator*() const;
  82. // const ValT *operator->() const;
  83. //
  84. // const_iterator &operator++();
  85. // const_iterator &operator++(int);
  86. // const_iterator &operator--();
  87. // const_iterator &operator--(int);
  88. // void goToBegin();
  89. // void goToEnd();
  90. // void find(KeyT x);
  91. // void advanceTo(KeyT x);
  92. // };
  93. //
  94. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  95. // class IntervalMap::iterator : public const_iterator {
  96. // public:
  97. // void insert(KeyT a, KeyT b, Value y);
  98. // void erase();
  99. // };
  100. //
  101. //===----------------------------------------------------------------------===//
  102. #ifndef LLVM_ADT_INTERVALMAP_H
  103. #define LLVM_ADT_INTERVALMAP_H
  104. #include "llvm/ADT/PointerIntPair.h"
  105. #include "llvm/ADT/SmallVector.h"
  106. #include "llvm/ADT/bit.h"
  107. #include "llvm/Support/AlignOf.h"
  108. #include "llvm/Support/Allocator.h"
  109. #include "llvm/Support/RecyclingAllocator.h"
  110. #include <algorithm>
  111. #include <cassert>
  112. #include <cstdint>
  113. #include <iterator>
  114. #include <new>
  115. #include <utility>
  116. namespace llvm {
  117. //===----------------------------------------------------------------------===//
  118. //--- Key traits ---//
  119. //===----------------------------------------------------------------------===//
  120. //
  121. // The IntervalMap works with closed or half-open intervals.
  122. // Adjacent intervals that map to the same value are coalesced.
  123. //
  124. // The IntervalMapInfo traits class is used to determine if a key is contained
  125. // in an interval, and if two intervals are adjacent so they can be coalesced.
  126. // The provided implementation works for closed integer intervals, other keys
  127. // probably need a specialized version.
  128. //
  129. // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
  130. //
  131. // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
  132. // allowed. This is so that stopLess(a, b) can be used to determine if two
  133. // intervals overlap.
  134. //
  135. //===----------------------------------------------------------------------===//
  136. template <typename T>
  137. struct IntervalMapInfo {
  138. /// startLess - Return true if x is not in [a;b].
  139. /// This is x < a both for closed intervals and for [a;b) half-open intervals.
  140. static inline bool startLess(const T &x, const T &a) {
  141. return x < a;
  142. }
  143. /// stopLess - Return true if x is not in [a;b].
  144. /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
  145. static inline bool stopLess(const T &b, const T &x) {
  146. return b < x;
  147. }
  148. /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
  149. /// This is a+1 == b for closed intervals, a == b for half-open intervals.
  150. static inline bool adjacent(const T &a, const T &b) {
  151. return a+1 == b;
  152. }
  153. /// nonEmpty - Return true if [a;b] is non-empty.
  154. /// This is a <= b for a closed interval, a < b for [a;b) half-open intervals.
  155. static inline bool nonEmpty(const T &a, const T &b) {
  156. return a <= b;
  157. }
  158. };
  159. template <typename T>
  160. struct IntervalMapHalfOpenInfo {
  161. /// startLess - Return true if x is not in [a;b).
  162. static inline bool startLess(const T &x, const T &a) {
  163. return x < a;
  164. }
  165. /// stopLess - Return true if x is not in [a;b).
  166. static inline bool stopLess(const T &b, const T &x) {
  167. return b <= x;
  168. }
  169. /// adjacent - Return true when the intervals [x;a) and [b;y) can coalesce.
  170. static inline bool adjacent(const T &a, const T &b) {
  171. return a == b;
  172. }
  173. /// nonEmpty - Return true if [a;b) is non-empty.
  174. static inline bool nonEmpty(const T &a, const T &b) {
  175. return a < b;
  176. }
  177. };
  178. /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
  179. /// It should be considered private to the implementation.
  180. namespace IntervalMapImpl {
  181. using IdxPair = std::pair<unsigned,unsigned>;
  182. //===----------------------------------------------------------------------===//
  183. //--- IntervalMapImpl::NodeBase ---//
  184. //===----------------------------------------------------------------------===//
  185. //
  186. // Both leaf and branch nodes store vectors of pairs.
  187. // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT).
  188. //
  189. // Keys and values are stored in separate arrays to avoid padding caused by
  190. // different object alignments. This also helps improve locality of reference
  191. // when searching the keys.
  192. //
  193. // The nodes don't know how many elements they contain - that information is
  194. // stored elsewhere. Omitting the size field prevents padding and allows a node
  195. // to fill the allocated cache lines completely.
  196. //
  197. // These are typical key and value sizes, the node branching factor (N), and
  198. // wasted space when nodes are sized to fit in three cache lines (192 bytes):
  199. //
  200. // T1 T2 N Waste Used by
  201. // 4 4 24 0 Branch<4> (32-bit pointers)
  202. // 8 4 16 0 Leaf<4,4>, Branch<4>
  203. // 8 8 12 0 Leaf<4,8>, Branch<8>
  204. // 16 4 9 12 Leaf<8,4>
  205. // 16 8 8 0 Leaf<8,8>
  206. //
  207. //===----------------------------------------------------------------------===//
  208. template <typename T1, typename T2, unsigned N>
  209. class NodeBase {
  210. public:
  211. enum { Capacity = N };
  212. T1 first[N];
  213. T2 second[N];
  214. /// copy - Copy elements from another node.
  215. /// @param Other Node elements are copied from.
  216. /// @param i Beginning of the source range in other.
  217. /// @param j Beginning of the destination range in this.
  218. /// @param Count Number of elements to copy.
  219. template <unsigned M>
  220. void copy(const NodeBase<T1, T2, M> &Other, unsigned i,
  221. unsigned j, unsigned Count) {
  222. assert(i + Count <= M && "Invalid source range");
  223. assert(j + Count <= N && "Invalid dest range");
  224. for (unsigned e = i + Count; i != e; ++i, ++j) {
  225. first[j] = Other.first[i];
  226. second[j] = Other.second[i];
  227. }
  228. }
  229. /// moveLeft - Move elements to the left.
  230. /// @param i Beginning of the source range.
  231. /// @param j Beginning of the destination range.
  232. /// @param Count Number of elements to copy.
  233. void moveLeft(unsigned i, unsigned j, unsigned Count) {
  234. assert(j <= i && "Use moveRight shift elements right");
  235. copy(*this, i, j, Count);
  236. }
  237. /// moveRight - Move elements to the right.
  238. /// @param i Beginning of the source range.
  239. /// @param j Beginning of the destination range.
  240. /// @param Count Number of elements to copy.
  241. void moveRight(unsigned i, unsigned j, unsigned Count) {
  242. assert(i <= j && "Use moveLeft shift elements left");
  243. assert(j + Count <= N && "Invalid range");
  244. while (Count--) {
  245. first[j + Count] = first[i + Count];
  246. second[j + Count] = second[i + Count];
  247. }
  248. }
  249. /// erase - Erase elements [i;j).
  250. /// @param i Beginning of the range to erase.
  251. /// @param j End of the range. (Exclusive).
  252. /// @param Size Number of elements in node.
  253. void erase(unsigned i, unsigned j, unsigned Size) {
  254. moveLeft(j, i, Size - j);
  255. }
  256. /// erase - Erase element at i.
  257. /// @param i Index of element to erase.
  258. /// @param Size Number of elements in node.
  259. void erase(unsigned i, unsigned Size) {
  260. erase(i, i+1, Size);
  261. }
  262. /// shift - Shift elements [i;size) 1 position to the right.
  263. /// @param i Beginning of the range to move.
  264. /// @param Size Number of elements in node.
  265. void shift(unsigned i, unsigned Size) {
  266. moveRight(i, i + 1, Size - i);
  267. }
  268. /// transferToLeftSib - Transfer elements to a left sibling node.
  269. /// @param Size Number of elements in this.
  270. /// @param Sib Left sibling node.
  271. /// @param SSize Number of elements in sib.
  272. /// @param Count Number of elements to transfer.
  273. void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize,
  274. unsigned Count) {
  275. Sib.copy(*this, 0, SSize, Count);
  276. erase(0, Count, Size);
  277. }
  278. /// transferToRightSib - Transfer elements to a right sibling node.
  279. /// @param Size Number of elements in this.
  280. /// @param Sib Right sibling node.
  281. /// @param SSize Number of elements in sib.
  282. /// @param Count Number of elements to transfer.
  283. void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize,
  284. unsigned Count) {
  285. Sib.moveRight(0, Count, SSize);
  286. Sib.copy(*this, Size-Count, 0, Count);
  287. }
  288. /// adjustFromLeftSib - Adjust the number if elements in this node by moving
  289. /// elements to or from a left sibling node.
  290. /// @param Size Number of elements in this.
  291. /// @param Sib Right sibling node.
  292. /// @param SSize Number of elements in sib.
  293. /// @param Add The number of elements to add to this node, possibly < 0.
  294. /// @return Number of elements added to this node, possibly negative.
  295. int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
  296. if (Add > 0) {
  297. // We want to grow, copy from sib.
  298. unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
  299. Sib.transferToRightSib(SSize, *this, Size, Count);
  300. return Count;
  301. } else {
  302. // We want to shrink, copy to sib.
  303. unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
  304. transferToLeftSib(Size, Sib, SSize, Count);
  305. return -Count;
  306. }
  307. }
  308. };
  309. /// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes.
  310. /// @param Node Array of pointers to sibling nodes.
  311. /// @param Nodes Number of nodes.
  312. /// @param CurSize Array of current node sizes, will be overwritten.
  313. /// @param NewSize Array of desired node sizes.
  314. template <typename NodeT>
  315. void adjustSiblingSizes(NodeT *Node[], unsigned Nodes,
  316. unsigned CurSize[], const unsigned NewSize[]) {
  317. // Move elements right.
  318. for (int n = Nodes - 1; n; --n) {
  319. if (CurSize[n] == NewSize[n])
  320. continue;
  321. for (int m = n - 1; m != -1; --m) {
  322. int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m],
  323. NewSize[n] - CurSize[n]);
  324. CurSize[m] -= d;
  325. CurSize[n] += d;
  326. // Keep going if the current node was exhausted.
  327. if (CurSize[n] >= NewSize[n])
  328. break;
  329. }
  330. }
  331. if (Nodes == 0)
  332. return;
  333. // Move elements left.
  334. for (unsigned n = 0; n != Nodes - 1; ++n) {
  335. if (CurSize[n] == NewSize[n])
  336. continue;
  337. for (unsigned m = n + 1; m != Nodes; ++m) {
  338. int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n],
  339. CurSize[n] - NewSize[n]);
  340. CurSize[m] += d;
  341. CurSize[n] -= d;
  342. // Keep going if the current node was exhausted.
  343. if (CurSize[n] >= NewSize[n])
  344. break;
  345. }
  346. }
  347. #ifndef NDEBUG
  348. for (unsigned n = 0; n != Nodes; n++)
  349. assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
  350. #endif
  351. }
  352. /// IntervalMapImpl::distribute - Compute a new distribution of node elements
  353. /// after an overflow or underflow. Reserve space for a new element at Position,
  354. /// and compute the node that will hold Position after redistributing node
  355. /// elements.
  356. ///
  357. /// It is required that
  358. ///
  359. /// Elements == sum(CurSize), and
  360. /// Elements + Grow <= Nodes * Capacity.
  361. ///
  362. /// NewSize[] will be filled in such that:
  363. ///
  364. /// sum(NewSize) == Elements, and
  365. /// NewSize[i] <= Capacity.
  366. ///
  367. /// The returned index is the node where Position will go, so:
  368. ///
  369. /// sum(NewSize[0..idx-1]) <= Position
  370. /// sum(NewSize[0..idx]) >= Position
  371. ///
  372. /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
  373. /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
  374. /// before the one holding the Position'th element where there is room for an
  375. /// insertion.
  376. ///
  377. /// @param Nodes The number of nodes.
  378. /// @param Elements Total elements in all nodes.
  379. /// @param Capacity The capacity of each node.
  380. /// @param CurSize Array[Nodes] of current node sizes, or NULL.
  381. /// @param NewSize Array[Nodes] to receive the new node sizes.
  382. /// @param Position Insert position.
  383. /// @param Grow Reserve space for a new element at Position.
  384. /// @return (node, offset) for Position.
  385. IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
  386. const unsigned *CurSize, unsigned NewSize[],
  387. unsigned Position, bool Grow);
  388. //===----------------------------------------------------------------------===//
  389. //--- IntervalMapImpl::NodeSizer ---//
  390. //===----------------------------------------------------------------------===//
  391. //
  392. // Compute node sizes from key and value types.
  393. //
  394. // The branching factors are chosen to make nodes fit in three cache lines.
  395. // This may not be possible if keys or values are very large. Such large objects
  396. // are handled correctly, but a std::map would probably give better performance.
  397. //
  398. //===----------------------------------------------------------------------===//
  399. enum {
  400. // Cache line size. Most architectures have 32 or 64 byte cache lines.
  401. // We use 64 bytes here because it provides good branching factors.
  402. Log2CacheLine = 6,
  403. CacheLineBytes = 1 << Log2CacheLine,
  404. DesiredNodeBytes = 3 * CacheLineBytes
  405. };
  406. template <typename KeyT, typename ValT>
  407. struct NodeSizer {
  408. enum {
  409. // Compute the leaf node branching factor that makes a node fit in three
  410. // cache lines. The branching factor must be at least 3, or some B+-tree
  411. // balancing algorithms won't work.
  412. // LeafSize can't be larger than CacheLineBytes. This is required by the
  413. // PointerIntPair used by NodeRef.
  414. DesiredLeafSize = DesiredNodeBytes /
  415. static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
  416. MinLeafSize = 3,
  417. LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
  418. };
  419. using LeafBase = NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize>;
  420. enum {
  421. // Now that we have the leaf branching factor, compute the actual allocation
  422. // unit size by rounding up to a whole number of cache lines.
  423. AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
  424. // Determine the branching factor for branch nodes.
  425. BranchSize = AllocBytes /
  426. static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
  427. };
  428. /// Allocator - The recycling allocator used for both branch and leaf nodes.
  429. /// This typedef is very likely to be identical for all IntervalMaps with
  430. /// reasonably sized entries, so the same allocator can be shared among
  431. /// different kinds of maps.
  432. using Allocator =
  433. RecyclingAllocator<BumpPtrAllocator, char, AllocBytes, CacheLineBytes>;
  434. };
  435. //===----------------------------------------------------------------------===//
  436. //--- IntervalMapImpl::NodeRef ---//
  437. //===----------------------------------------------------------------------===//
  438. //
  439. // B+-tree nodes can be leaves or branches, so we need a polymorphic node
  440. // pointer that can point to both kinds.
  441. //
  442. // All nodes are cache line aligned and the low 6 bits of a node pointer are
  443. // always 0. These bits are used to store the number of elements in the
  444. // referenced node. Besides saving space, placing node sizes in the parents
  445. // allow tree balancing algorithms to run without faulting cache lines for nodes
  446. // that may not need to be modified.
  447. //
  448. // A NodeRef doesn't know whether it references a leaf node or a branch node.
  449. // It is the responsibility of the caller to use the correct types.
  450. //
  451. // Nodes are never supposed to be empty, and it is invalid to store a node size
  452. // of 0 in a NodeRef. The valid range of sizes is 1-64.
  453. //
  454. //===----------------------------------------------------------------------===//
  455. class NodeRef {
  456. struct CacheAlignedPointerTraits {
  457. static inline void *getAsVoidPointer(void *P) { return P; }
  458. static inline void *getFromVoidPointer(void *P) { return P; }
  459. static constexpr int NumLowBitsAvailable = Log2CacheLine;
  460. };
  461. PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
  462. public:
  463. /// NodeRef - Create a null ref.
  464. NodeRef() = default;
  465. /// operator bool - Detect a null ref.
  466. explicit operator bool() const { return pip.getOpaqueValue(); }
  467. /// NodeRef - Create a reference to the node p with n elements.
  468. template <typename NodeT>
  469. NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) {
  470. assert(n <= NodeT::Capacity && "Size too big for node");
  471. }
  472. /// size - Return the number of elements in the referenced node.
  473. unsigned size() const { return pip.getInt() + 1; }
  474. /// setSize - Update the node size.
  475. void setSize(unsigned n) { pip.setInt(n - 1); }
  476. /// subtree - Access the i'th subtree reference in a branch node.
  477. /// This depends on branch nodes storing the NodeRef array as their first
  478. /// member.
  479. NodeRef &subtree(unsigned i) const {
  480. return reinterpret_cast<NodeRef*>(pip.getPointer())[i];
  481. }
  482. /// get - Dereference as a NodeT reference.
  483. template <typename NodeT>
  484. NodeT &get() const {
  485. return *reinterpret_cast<NodeT*>(pip.getPointer());
  486. }
  487. bool operator==(const NodeRef &RHS) const {
  488. if (pip == RHS.pip)
  489. return true;
  490. assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
  491. return false;
  492. }
  493. bool operator!=(const NodeRef &RHS) const {
  494. return !operator==(RHS);
  495. }
  496. };
  497. //===----------------------------------------------------------------------===//
  498. //--- IntervalMapImpl::LeafNode ---//
  499. //===----------------------------------------------------------------------===//
  500. //
  501. // Leaf nodes store up to N disjoint intervals with corresponding values.
  502. //
  503. // The intervals are kept sorted and fully coalesced so there are no adjacent
  504. // intervals mapping to the same value.
  505. //
  506. // These constraints are always satisfied:
  507. //
  508. // - Traits::stopLess(start(i), stop(i)) - Non-empty, sane intervals.
  509. //
  510. // - Traits::stopLess(stop(i), start(i + 1) - Sorted.
  511. //
  512. // - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1))
  513. // - Fully coalesced.
  514. //
  515. //===----------------------------------------------------------------------===//
  516. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  517. class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
  518. public:
  519. const KeyT &start(unsigned i) const { return this->first[i].first; }
  520. const KeyT &stop(unsigned i) const { return this->first[i].second; }
  521. const ValT &value(unsigned i) const { return this->second[i]; }
  522. KeyT &start(unsigned i) { return this->first[i].first; }
  523. KeyT &stop(unsigned i) { return this->first[i].second; }
  524. ValT &value(unsigned i) { return this->second[i]; }
  525. /// findFrom - Find the first interval after i that may contain x.
  526. /// @param i Starting index for the search.
  527. /// @param Size Number of elements in node.
  528. /// @param x Key to search for.
  529. /// @return First index with !stopLess(key[i].stop, x), or size.
  530. /// This is the first interval that can possibly contain x.
  531. unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
  532. assert(i <= Size && Size <= N && "Bad indices");
  533. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  534. "Index is past the needed point");
  535. while (i != Size && Traits::stopLess(stop(i), x)) ++i;
  536. return i;
  537. }
  538. /// safeFind - Find an interval that is known to exist. This is the same as
  539. /// findFrom except is it assumed that x is at least within range of the last
  540. /// interval.
  541. /// @param i Starting index for the search.
  542. /// @param x Key to search for.
  543. /// @return First index with !stopLess(key[i].stop, x), never size.
  544. /// This is the first interval that can possibly contain x.
  545. unsigned safeFind(unsigned i, KeyT x) const {
  546. assert(i < N && "Bad index");
  547. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  548. "Index is past the needed point");
  549. while (Traits::stopLess(stop(i), x)) ++i;
  550. assert(i < N && "Unsafe intervals");
  551. return i;
  552. }
  553. /// safeLookup - Lookup mapped value for a safe key.
  554. /// It is assumed that x is within range of the last entry.
  555. /// @param x Key to search for.
  556. /// @param NotFound Value to return if x is not in any interval.
  557. /// @return The mapped value at x or NotFound.
  558. ValT safeLookup(KeyT x, ValT NotFound) const {
  559. unsigned i = safeFind(0, x);
  560. return Traits::startLess(x, start(i)) ? NotFound : value(i);
  561. }
  562. unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y);
  563. };
  564. /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
  565. /// possible. This may cause the node to grow by 1, or it may cause the node
  566. /// to shrink because of coalescing.
  567. /// @param Pos Starting index = insertFrom(0, size, a)
  568. /// @param Size Number of elements in node.
  569. /// @param a Interval start.
  570. /// @param b Interval stop.
  571. /// @param y Value be mapped.
  572. /// @return (insert position, new size), or (i, Capacity+1) on overflow.
  573. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  574. unsigned LeafNode<KeyT, ValT, N, Traits>::
  575. insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) {
  576. unsigned i = Pos;
  577. assert(i <= Size && Size <= N && "Invalid index");
  578. assert(!Traits::stopLess(b, a) && "Invalid interval");
  579. // Verify the findFrom invariant.
  580. assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
  581. assert((i == Size || !Traits::stopLess(stop(i), a)));
  582. assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert");
  583. // Coalesce with previous interval.
  584. if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) {
  585. Pos = i - 1;
  586. // Also coalesce with next interval?
  587. if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) {
  588. stop(i - 1) = stop(i);
  589. this->erase(i, Size);
  590. return Size - 1;
  591. }
  592. stop(i - 1) = b;
  593. return Size;
  594. }
  595. // Detect overflow.
  596. if (i == N)
  597. return N + 1;
  598. // Add new interval at end.
  599. if (i == Size) {
  600. start(i) = a;
  601. stop(i) = b;
  602. value(i) = y;
  603. return Size + 1;
  604. }
  605. // Try to coalesce with following interval.
  606. if (value(i) == y && Traits::adjacent(b, start(i))) {
  607. start(i) = a;
  608. return Size;
  609. }
  610. // We must insert before i. Detect overflow.
  611. if (Size == N)
  612. return N + 1;
  613. // Insert before i.
  614. this->shift(i, Size);
  615. start(i) = a;
  616. stop(i) = b;
  617. value(i) = y;
  618. return Size + 1;
  619. }
  620. //===----------------------------------------------------------------------===//
  621. //--- IntervalMapImpl::BranchNode ---//
  622. //===----------------------------------------------------------------------===//
  623. //
  624. // A branch node stores references to 1--N subtrees all of the same height.
  625. //
  626. // The key array in a branch node holds the rightmost stop key of each subtree.
  627. // It is redundant to store the last stop key since it can be found in the
  628. // parent node, but doing so makes tree balancing a lot simpler.
  629. //
  630. // It is unusual for a branch node to only have one subtree, but it can happen
  631. // in the root node if it is smaller than the normal nodes.
  632. //
  633. // When all of the leaf nodes from all the subtrees are concatenated, they must
  634. // satisfy the same constraints as a single leaf node. They must be sorted,
  635. // sane, and fully coalesced.
  636. //
  637. //===----------------------------------------------------------------------===//
  638. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  639. class BranchNode : public NodeBase<NodeRef, KeyT, N> {
  640. public:
  641. const KeyT &stop(unsigned i) const { return this->second[i]; }
  642. const NodeRef &subtree(unsigned i) const { return this->first[i]; }
  643. KeyT &stop(unsigned i) { return this->second[i]; }
  644. NodeRef &subtree(unsigned i) { return this->first[i]; }
  645. /// findFrom - Find the first subtree after i that may contain x.
  646. /// @param i Starting index for the search.
  647. /// @param Size Number of elements in node.
  648. /// @param x Key to search for.
  649. /// @return First index with !stopLess(key[i], x), or size.
  650. /// This is the first subtree that can possibly contain x.
  651. unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
  652. assert(i <= Size && Size <= N && "Bad indices");
  653. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  654. "Index to findFrom is past the needed point");
  655. while (i != Size && Traits::stopLess(stop(i), x)) ++i;
  656. return i;
  657. }
  658. /// safeFind - Find a subtree that is known to exist. This is the same as
  659. /// findFrom except is it assumed that x is in range.
  660. /// @param i Starting index for the search.
  661. /// @param x Key to search for.
  662. /// @return First index with !stopLess(key[i], x), never size.
  663. /// This is the first subtree that can possibly contain x.
  664. unsigned safeFind(unsigned i, KeyT x) const {
  665. assert(i < N && "Bad index");
  666. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  667. "Index is past the needed point");
  668. while (Traits::stopLess(stop(i), x)) ++i;
  669. assert(i < N && "Unsafe intervals");
  670. return i;
  671. }
  672. /// safeLookup - Get the subtree containing x, Assuming that x is in range.
  673. /// @param x Key to search for.
  674. /// @return Subtree containing x
  675. NodeRef safeLookup(KeyT x) const {
  676. return subtree(safeFind(0, x));
  677. }
  678. /// insert - Insert a new (subtree, stop) pair.
  679. /// @param i Insert position, following entries will be shifted.
  680. /// @param Size Number of elements in node.
  681. /// @param Node Subtree to insert.
  682. /// @param Stop Last key in subtree.
  683. void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) {
  684. assert(Size < N && "branch node overflow");
  685. assert(i <= Size && "Bad insert position");
  686. this->shift(i, Size);
  687. subtree(i) = Node;
  688. stop(i) = Stop;
  689. }
  690. };
  691. //===----------------------------------------------------------------------===//
  692. //--- IntervalMapImpl::Path ---//
  693. //===----------------------------------------------------------------------===//
  694. //
  695. // A Path is used by iterators to represent a position in a B+-tree, and the
  696. // path to get there from the root.
  697. //
  698. // The Path class also contains the tree navigation code that doesn't have to
  699. // be templatized.
  700. //
  701. //===----------------------------------------------------------------------===//
  702. class Path {
  703. /// Entry - Each step in the path is a node pointer and an offset into that
  704. /// node.
  705. struct Entry {
  706. void *node;
  707. unsigned size;
  708. unsigned offset;
  709. Entry(void *Node, unsigned Size, unsigned Offset)
  710. : node(Node), size(Size), offset(Offset) {}
  711. Entry(NodeRef Node, unsigned Offset)
  712. : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {}
  713. NodeRef &subtree(unsigned i) const {
  714. return reinterpret_cast<NodeRef*>(node)[i];
  715. }
  716. };
  717. /// path - The path entries, path[0] is the root node, path.back() is a leaf.
  718. SmallVector<Entry, 4> path;
  719. public:
  720. // Node accessors.
  721. template <typename NodeT> NodeT &node(unsigned Level) const {
  722. return *reinterpret_cast<NodeT*>(path[Level].node);
  723. }
  724. unsigned size(unsigned Level) const { return path[Level].size; }
  725. unsigned offset(unsigned Level) const { return path[Level].offset; }
  726. unsigned &offset(unsigned Level) { return path[Level].offset; }
  727. // Leaf accessors.
  728. template <typename NodeT> NodeT &leaf() const {
  729. return *reinterpret_cast<NodeT*>(path.back().node);
  730. }
  731. unsigned leafSize() const { return path.back().size; }
  732. unsigned leafOffset() const { return path.back().offset; }
  733. unsigned &leafOffset() { return path.back().offset; }
  734. /// valid - Return true if path is at a valid node, not at end().
  735. bool valid() const {
  736. return !path.empty() && path.front().offset < path.front().size;
  737. }
  738. /// height - Return the height of the tree corresponding to this path.
  739. /// This matches map->height in a full path.
  740. unsigned height() const { return path.size() - 1; }
  741. /// subtree - Get the subtree referenced from Level. When the path is
  742. /// consistent, node(Level + 1) == subtree(Level).
  743. /// @param Level 0..height-1. The leaves have no subtrees.
  744. NodeRef &subtree(unsigned Level) const {
  745. return path[Level].subtree(path[Level].offset);
  746. }
  747. /// reset - Reset cached information about node(Level) from subtree(Level -1).
  748. /// @param Level 1..height. The node to update after parent node changed.
  749. void reset(unsigned Level) {
  750. path[Level] = Entry(subtree(Level - 1), offset(Level));
  751. }
  752. /// push - Add entry to path.
  753. /// @param Node Node to add, should be subtree(path.size()-1).
  754. /// @param Offset Offset into Node.
  755. void push(NodeRef Node, unsigned Offset) {
  756. path.push_back(Entry(Node, Offset));
  757. }
  758. /// pop - Remove the last path entry.
  759. void pop() {
  760. path.pop_back();
  761. }
  762. /// setSize - Set the size of a node both in the path and in the tree.
  763. /// @param Level 0..height. Note that setting the root size won't change
  764. /// map->rootSize.
  765. /// @param Size New node size.
  766. void setSize(unsigned Level, unsigned Size) {
  767. path[Level].size = Size;
  768. if (Level)
  769. subtree(Level - 1).setSize(Size);
  770. }
  771. /// setRoot - Clear the path and set a new root node.
  772. /// @param Node New root node.
  773. /// @param Size New root size.
  774. /// @param Offset Offset into root node.
  775. void setRoot(void *Node, unsigned Size, unsigned Offset) {
  776. path.clear();
  777. path.push_back(Entry(Node, Size, Offset));
  778. }
  779. /// replaceRoot - Replace the current root node with two new entries after the
  780. /// tree height has increased.
  781. /// @param Root The new root node.
  782. /// @param Size Number of entries in the new root.
  783. /// @param Offsets Offsets into the root and first branch nodes.
  784. void replaceRoot(void *Root, unsigned Size, IdxPair Offsets);
  785. /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
  786. /// @param Level Get the sibling to node(Level).
  787. /// @return Left sibling, or NodeRef().
  788. NodeRef getLeftSibling(unsigned Level) const;
  789. /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level
  790. /// unaltered.
  791. /// @param Level Move node(Level).
  792. void moveLeft(unsigned Level);
  793. /// fillLeft - Grow path to Height by taking leftmost branches.
  794. /// @param Height The target height.
  795. void fillLeft(unsigned Height) {
  796. while (height() < Height)
  797. push(subtree(height()), 0);
  798. }
  799. /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
  800. /// @param Level Get the sibling to node(Level).
  801. /// @return Left sibling, or NodeRef().
  802. NodeRef getRightSibling(unsigned Level) const;
  803. /// moveRight - Move path to the left sibling at Level. Leave nodes below
  804. /// Level unaltered.
  805. /// @param Level Move node(Level).
  806. void moveRight(unsigned Level);
  807. /// atBegin - Return true if path is at begin().
  808. bool atBegin() const {
  809. for (unsigned i = 0, e = path.size(); i != e; ++i)
  810. if (path[i].offset != 0)
  811. return false;
  812. return true;
  813. }
  814. /// atLastEntry - Return true if the path is at the last entry of the node at
  815. /// Level.
  816. /// @param Level Node to examine.
  817. bool atLastEntry(unsigned Level) const {
  818. return path[Level].offset == path[Level].size - 1;
  819. }
  820. /// legalizeForInsert - Prepare the path for an insertion at Level. When the
  821. /// path is at end(), node(Level) may not be a legal node. legalizeForInsert
  822. /// ensures that node(Level) is real by moving back to the last node at Level,
  823. /// and setting offset(Level) to size(Level) if required.
  824. /// @param Level The level where an insertion is about to take place.
  825. void legalizeForInsert(unsigned Level) {
  826. if (valid())
  827. return;
  828. moveLeft(Level);
  829. ++path[Level].offset;
  830. }
  831. };
  832. } // end namespace IntervalMapImpl
  833. //===----------------------------------------------------------------------===//
  834. //--- IntervalMap ----//
  835. //===----------------------------------------------------------------------===//
  836. template <typename KeyT, typename ValT,
  837. unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
  838. typename Traits = IntervalMapInfo<KeyT>>
  839. class IntervalMap {
  840. using Sizer = IntervalMapImpl::NodeSizer<KeyT, ValT>;
  841. using Leaf = IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits>;
  842. using Branch =
  843. IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>;
  844. using RootLeaf = IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits>;
  845. using IdxPair = IntervalMapImpl::IdxPair;
  846. // The RootLeaf capacity is given as a template parameter. We must compute the
  847. // corresponding RootBranch capacity.
  848. enum {
  849. DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
  850. (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)),
  851. RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
  852. };
  853. using RootBranch =
  854. IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>;
  855. // When branched, we store a global start key as well as the branch node.
  856. struct RootBranchData {
  857. KeyT start;
  858. RootBranch node;
  859. };
  860. public:
  861. using Allocator = typename Sizer::Allocator;
  862. using KeyType = KeyT;
  863. using ValueType = ValT;
  864. using KeyTraits = Traits;
  865. private:
  866. // The root data is either a RootLeaf or a RootBranchData instance.
  867. AlignedCharArrayUnion<RootLeaf, RootBranchData> data;
  868. // Tree height.
  869. // 0: Leaves in root.
  870. // 1: Root points to leaf.
  871. // 2: root->branch->leaf ...
  872. unsigned height;
  873. // Number of entries in the root node.
  874. unsigned rootSize;
  875. // Allocator used for creating external nodes.
  876. Allocator &allocator;
  877. /// Represent data as a node type without breaking aliasing rules.
  878. template <typename T> T &dataAs() const { return *llvm::bit_cast<T *>(&data); }
  879. const RootLeaf &rootLeaf() const {
  880. assert(!branched() && "Cannot acces leaf data in branched root");
  881. return dataAs<RootLeaf>();
  882. }
  883. RootLeaf &rootLeaf() {
  884. assert(!branched() && "Cannot acces leaf data in branched root");
  885. return dataAs<RootLeaf>();
  886. }
  887. RootBranchData &rootBranchData() const {
  888. assert(branched() && "Cannot access branch data in non-branched root");
  889. return dataAs<RootBranchData>();
  890. }
  891. RootBranchData &rootBranchData() {
  892. assert(branched() && "Cannot access branch data in non-branched root");
  893. return dataAs<RootBranchData>();
  894. }
  895. const RootBranch &rootBranch() const { return rootBranchData().node; }
  896. RootBranch &rootBranch() { return rootBranchData().node; }
  897. KeyT rootBranchStart() const { return rootBranchData().start; }
  898. KeyT &rootBranchStart() { return rootBranchData().start; }
  899. template <typename NodeT> NodeT *newNode() {
  900. return new(allocator.template Allocate<NodeT>()) NodeT();
  901. }
  902. template <typename NodeT> void deleteNode(NodeT *P) {
  903. P->~NodeT();
  904. allocator.Deallocate(P);
  905. }
  906. IdxPair branchRoot(unsigned Position);
  907. IdxPair splitRoot(unsigned Position);
  908. void switchRootToBranch() {
  909. rootLeaf().~RootLeaf();
  910. height = 1;
  911. new (&rootBranchData()) RootBranchData();
  912. }
  913. void switchRootToLeaf() {
  914. rootBranchData().~RootBranchData();
  915. height = 0;
  916. new(&rootLeaf()) RootLeaf();
  917. }
  918. bool branched() const { return height > 0; }
  919. ValT treeSafeLookup(KeyT x, ValT NotFound) const;
  920. void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef,
  921. unsigned Level));
  922. void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level);
  923. public:
  924. explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
  925. assert((uintptr_t(&data) & (alignof(RootLeaf) - 1)) == 0 &&
  926. "Insufficient alignment");
  927. new(&rootLeaf()) RootLeaf();
  928. }
  929. ~IntervalMap() {
  930. clear();
  931. rootLeaf().~RootLeaf();
  932. }
  933. /// empty - Return true when no intervals are mapped.
  934. bool empty() const {
  935. return rootSize == 0;
  936. }
  937. /// start - Return the smallest mapped key in a non-empty map.
  938. KeyT start() const {
  939. assert(!empty() && "Empty IntervalMap has no start");
  940. return !branched() ? rootLeaf().start(0) : rootBranchStart();
  941. }
  942. /// stop - Return the largest mapped key in a non-empty map.
  943. KeyT stop() const {
  944. assert(!empty() && "Empty IntervalMap has no stop");
  945. return !branched() ? rootLeaf().stop(rootSize - 1) :
  946. rootBranch().stop(rootSize - 1);
  947. }
  948. /// lookup - Return the mapped value at x or NotFound.
  949. ValT lookup(KeyT x, ValT NotFound = ValT()) const {
  950. if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
  951. return NotFound;
  952. return branched() ? treeSafeLookup(x, NotFound) :
  953. rootLeaf().safeLookup(x, NotFound);
  954. }
  955. /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
  956. /// It is assumed that no key in the interval is mapped to another value, but
  957. /// overlapping intervals already mapped to y will be coalesced.
  958. void insert(KeyT a, KeyT b, ValT y) {
  959. if (branched() || rootSize == RootLeaf::Capacity)
  960. return find(a).insert(a, b, y);
  961. // Easy insert into root leaf.
  962. unsigned p = rootLeaf().findFrom(0, rootSize, a);
  963. rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y);
  964. }
  965. /// clear - Remove all entries.
  966. void clear();
  967. class const_iterator;
  968. class iterator;
  969. friend class const_iterator;
  970. friend class iterator;
  971. const_iterator begin() const {
  972. const_iterator I(*this);
  973. I.goToBegin();
  974. return I;
  975. }
  976. iterator begin() {
  977. iterator I(*this);
  978. I.goToBegin();
  979. return I;
  980. }
  981. const_iterator end() const {
  982. const_iterator I(*this);
  983. I.goToEnd();
  984. return I;
  985. }
  986. iterator end() {
  987. iterator I(*this);
  988. I.goToEnd();
  989. return I;
  990. }
  991. /// find - Return an iterator pointing to the first interval ending at or
  992. /// after x, or end().
  993. const_iterator find(KeyT x) const {
  994. const_iterator I(*this);
  995. I.find(x);
  996. return I;
  997. }
  998. iterator find(KeyT x) {
  999. iterator I(*this);
  1000. I.find(x);
  1001. return I;
  1002. }
  1003. /// overlaps(a, b) - Return true if the intervals in this map overlap with the
  1004. /// interval [a;b].
  1005. bool overlaps(KeyT a, KeyT b) {
  1006. assert(Traits::nonEmpty(a, b));
  1007. const_iterator I = find(a);
  1008. if (!I.valid())
  1009. return false;
  1010. // [a;b] and [x;y] overlap iff x<=b and a<=y. The find() call guarantees the
  1011. // second part (y = find(a).stop()), so it is sufficient to check the first
  1012. // one.
  1013. return !Traits::stopLess(b, I.start());
  1014. }
  1015. };
  1016. /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
  1017. /// branched root.
  1018. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1019. ValT IntervalMap<KeyT, ValT, N, Traits>::
  1020. treeSafeLookup(KeyT x, ValT NotFound) const {
  1021. assert(branched() && "treeLookup assumes a branched root");
  1022. IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x);
  1023. for (unsigned h = height-1; h; --h)
  1024. NR = NR.get<Branch>().safeLookup(x);
  1025. return NR.get<Leaf>().safeLookup(x, NotFound);
  1026. }
  1027. // branchRoot - Switch from a leaf root to a branched root.
  1028. // Return the new (root offset, node offset) corresponding to Position.
  1029. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1030. IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
  1031. branchRoot(unsigned Position) {
  1032. using namespace IntervalMapImpl;
  1033. // How many external leaf nodes to hold RootLeaf+1?
  1034. const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
  1035. // Compute element distribution among new nodes.
  1036. unsigned size[Nodes];
  1037. IdxPair NewOffset(0, Position);
  1038. // Is is very common for the root node to be smaller than external nodes.
  1039. if (Nodes == 1)
  1040. size[0] = rootSize;
  1041. else
  1042. NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, size,
  1043. Position, true);
  1044. // Allocate new nodes.
  1045. unsigned pos = 0;
  1046. NodeRef node[Nodes];
  1047. for (unsigned n = 0; n != Nodes; ++n) {
  1048. Leaf *L = newNode<Leaf>();
  1049. L->copy(rootLeaf(), pos, 0, size[n]);
  1050. node[n] = NodeRef(L, size[n]);
  1051. pos += size[n];
  1052. }
  1053. // Destroy the old leaf node, construct branch node instead.
  1054. switchRootToBranch();
  1055. for (unsigned n = 0; n != Nodes; ++n) {
  1056. rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1);
  1057. rootBranch().subtree(n) = node[n];
  1058. }
  1059. rootBranchStart() = node[0].template get<Leaf>().start(0);
  1060. rootSize = Nodes;
  1061. return NewOffset;
  1062. }
  1063. // splitRoot - Split the current BranchRoot into multiple Branch nodes.
  1064. // Return the new (root offset, node offset) corresponding to Position.
  1065. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1066. IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
  1067. splitRoot(unsigned Position) {
  1068. using namespace IntervalMapImpl;
  1069. // How many external leaf nodes to hold RootBranch+1?
  1070. const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
  1071. // Compute element distribution among new nodes.
  1072. unsigned Size[Nodes];
  1073. IdxPair NewOffset(0, Position);
  1074. // Is is very common for the root node to be smaller than external nodes.
  1075. if (Nodes == 1)
  1076. Size[0] = rootSize;
  1077. else
  1078. NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, Size,
  1079. Position, true);
  1080. // Allocate new nodes.
  1081. unsigned Pos = 0;
  1082. NodeRef Node[Nodes];
  1083. for (unsigned n = 0; n != Nodes; ++n) {
  1084. Branch *B = newNode<Branch>();
  1085. B->copy(rootBranch(), Pos, 0, Size[n]);
  1086. Node[n] = NodeRef(B, Size[n]);
  1087. Pos += Size[n];
  1088. }
  1089. for (unsigned n = 0; n != Nodes; ++n) {
  1090. rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1);
  1091. rootBranch().subtree(n) = Node[n];
  1092. }
  1093. rootSize = Nodes;
  1094. ++height;
  1095. return NewOffset;
  1096. }
  1097. /// visitNodes - Visit each external node.
  1098. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1099. void IntervalMap<KeyT, ValT, N, Traits>::
  1100. visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) {
  1101. if (!branched())
  1102. return;
  1103. SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs;
  1104. // Collect level 0 nodes from the root.
  1105. for (unsigned i = 0; i != rootSize; ++i)
  1106. Refs.push_back(rootBranch().subtree(i));
  1107. // Visit all branch nodes.
  1108. for (unsigned h = height - 1; h; --h) {
  1109. for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
  1110. for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
  1111. NextRefs.push_back(Refs[i].subtree(j));
  1112. (this->*f)(Refs[i], h);
  1113. }
  1114. Refs.clear();
  1115. Refs.swap(NextRefs);
  1116. }
  1117. // Visit all leaf nodes.
  1118. for (unsigned i = 0, e = Refs.size(); i != e; ++i)
  1119. (this->*f)(Refs[i], 0);
  1120. }
  1121. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1122. void IntervalMap<KeyT, ValT, N, Traits>::
  1123. deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) {
  1124. if (Level)
  1125. deleteNode(&Node.get<Branch>());
  1126. else
  1127. deleteNode(&Node.get<Leaf>());
  1128. }
  1129. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1130. void IntervalMap<KeyT, ValT, N, Traits>::
  1131. clear() {
  1132. if (branched()) {
  1133. visitNodes(&IntervalMap::deleteNode);
  1134. switchRootToLeaf();
  1135. }
  1136. rootSize = 0;
  1137. }
  1138. //===----------------------------------------------------------------------===//
  1139. //--- IntervalMap::const_iterator ----//
  1140. //===----------------------------------------------------------------------===//
  1141. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1142. class IntervalMap<KeyT, ValT, N, Traits>::const_iterator :
  1143. public std::iterator<std::bidirectional_iterator_tag, ValT> {
  1144. protected:
  1145. friend class IntervalMap;
  1146. // The map referred to.
  1147. IntervalMap *map = nullptr;
  1148. // We store a full path from the root to the current position.
  1149. // The path may be partially filled, but never between iterator calls.
  1150. IntervalMapImpl::Path path;
  1151. explicit const_iterator(const IntervalMap &map) :
  1152. map(const_cast<IntervalMap*>(&map)) {}
  1153. bool branched() const {
  1154. assert(map && "Invalid iterator");
  1155. return map->branched();
  1156. }
  1157. void setRoot(unsigned Offset) {
  1158. if (branched())
  1159. path.setRoot(&map->rootBranch(), map->rootSize, Offset);
  1160. else
  1161. path.setRoot(&map->rootLeaf(), map->rootSize, Offset);
  1162. }
  1163. void pathFillFind(KeyT x);
  1164. void treeFind(KeyT x);
  1165. void treeAdvanceTo(KeyT x);
  1166. /// unsafeStart - Writable access to start() for iterator.
  1167. KeyT &unsafeStart() const {
  1168. assert(valid() && "Cannot access invalid iterator");
  1169. return branched() ? path.leaf<Leaf>().start(path.leafOffset()) :
  1170. path.leaf<RootLeaf>().start(path.leafOffset());
  1171. }
  1172. /// unsafeStop - Writable access to stop() for iterator.
  1173. KeyT &unsafeStop() const {
  1174. assert(valid() && "Cannot access invalid iterator");
  1175. return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) :
  1176. path.leaf<RootLeaf>().stop(path.leafOffset());
  1177. }
  1178. /// unsafeValue - Writable access to value() for iterator.
  1179. ValT &unsafeValue() const {
  1180. assert(valid() && "Cannot access invalid iterator");
  1181. return branched() ? path.leaf<Leaf>().value(path.leafOffset()) :
  1182. path.leaf<RootLeaf>().value(path.leafOffset());
  1183. }
  1184. public:
  1185. /// const_iterator - Create an iterator that isn't pointing anywhere.
  1186. const_iterator() = default;
  1187. /// setMap - Change the map iterated over. This call must be followed by a
  1188. /// call to goToBegin(), goToEnd(), or find()
  1189. void setMap(const IntervalMap &m) { map = const_cast<IntervalMap*>(&m); }
  1190. /// valid - Return true if the current position is valid, false for end().
  1191. bool valid() const { return path.valid(); }
  1192. /// atBegin - Return true if the current position is the first map entry.
  1193. bool atBegin() const { return path.atBegin(); }
  1194. /// start - Return the beginning of the current interval.
  1195. const KeyT &start() const { return unsafeStart(); }
  1196. /// stop - Return the end of the current interval.
  1197. const KeyT &stop() const { return unsafeStop(); }
  1198. /// value - Return the mapped value at the current interval.
  1199. const ValT &value() const { return unsafeValue(); }
  1200. const ValT &operator*() const { return value(); }
  1201. bool operator==(const const_iterator &RHS) const {
  1202. assert(map == RHS.map && "Cannot compare iterators from different maps");
  1203. if (!valid())
  1204. return !RHS.valid();
  1205. if (path.leafOffset() != RHS.path.leafOffset())
  1206. return false;
  1207. return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>();
  1208. }
  1209. bool operator!=(const const_iterator &RHS) const {
  1210. return !operator==(RHS);
  1211. }
  1212. /// goToBegin - Move to the first interval in map.
  1213. void goToBegin() {
  1214. setRoot(0);
  1215. if (branched())
  1216. path.fillLeft(map->height);
  1217. }
  1218. /// goToEnd - Move beyond the last interval in map.
  1219. void goToEnd() {
  1220. setRoot(map->rootSize);
  1221. }
  1222. /// preincrement - Move to the next interval.
  1223. const_iterator &operator++() {
  1224. assert(valid() && "Cannot increment end()");
  1225. if (++path.leafOffset() == path.leafSize() && branched())
  1226. path.moveRight(map->height);
  1227. return *this;
  1228. }
  1229. /// postincrement - Don't do that!
  1230. const_iterator operator++(int) {
  1231. const_iterator tmp = *this;
  1232. operator++();
  1233. return tmp;
  1234. }
  1235. /// predecrement - Move to the previous interval.
  1236. const_iterator &operator--() {
  1237. if (path.leafOffset() && (valid() || !branched()))
  1238. --path.leafOffset();
  1239. else
  1240. path.moveLeft(map->height);
  1241. return *this;
  1242. }
  1243. /// postdecrement - Don't do that!
  1244. const_iterator operator--(int) {
  1245. const_iterator tmp = *this;
  1246. operator--();
  1247. return tmp;
  1248. }
  1249. /// find - Move to the first interval with stop >= x, or end().
  1250. /// This is a full search from the root, the current position is ignored.
  1251. void find(KeyT x) {
  1252. if (branched())
  1253. treeFind(x);
  1254. else
  1255. setRoot(map->rootLeaf().findFrom(0, map->rootSize, x));
  1256. }
  1257. /// advanceTo - Move to the first interval with stop >= x, or end().
  1258. /// The search is started from the current position, and no earlier positions
  1259. /// can be found. This is much faster than find() for small moves.
  1260. void advanceTo(KeyT x) {
  1261. if (!valid())
  1262. return;
  1263. if (branched())
  1264. treeAdvanceTo(x);
  1265. else
  1266. path.leafOffset() =
  1267. map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x);
  1268. }
  1269. };
  1270. /// pathFillFind - Complete path by searching for x.
  1271. /// @param x Key to search for.
  1272. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1273. void IntervalMap<KeyT, ValT, N, Traits>::
  1274. const_iterator::pathFillFind(KeyT x) {
  1275. IntervalMapImpl::NodeRef NR = path.subtree(path.height());
  1276. for (unsigned i = map->height - path.height() - 1; i; --i) {
  1277. unsigned p = NR.get<Branch>().safeFind(0, x);
  1278. path.push(NR, p);
  1279. NR = NR.subtree(p);
  1280. }
  1281. path.push(NR, NR.get<Leaf>().safeFind(0, x));
  1282. }
  1283. /// treeFind - Find in a branched tree.
  1284. /// @param x Key to search for.
  1285. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1286. void IntervalMap<KeyT, ValT, N, Traits>::
  1287. const_iterator::treeFind(KeyT x) {
  1288. setRoot(map->rootBranch().findFrom(0, map->rootSize, x));
  1289. if (valid())
  1290. pathFillFind(x);
  1291. }
  1292. /// treeAdvanceTo - Find position after the current one.
  1293. /// @param x Key to search for.
  1294. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1295. void IntervalMap<KeyT, ValT, N, Traits>::
  1296. const_iterator::treeAdvanceTo(KeyT x) {
  1297. // Can we stay on the same leaf node?
  1298. if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) {
  1299. path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x);
  1300. return;
  1301. }
  1302. // Drop the current leaf.
  1303. path.pop();
  1304. // Search towards the root for a usable subtree.
  1305. if (path.height()) {
  1306. for (unsigned l = path.height() - 1; l; --l) {
  1307. if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) {
  1308. // The branch node at l+1 is usable
  1309. path.offset(l + 1) =
  1310. path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x);
  1311. return pathFillFind(x);
  1312. }
  1313. path.pop();
  1314. }
  1315. // Is the level-1 Branch usable?
  1316. if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) {
  1317. path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x);
  1318. return pathFillFind(x);
  1319. }
  1320. }
  1321. // We reached the root.
  1322. setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x));
  1323. if (valid())
  1324. pathFillFind(x);
  1325. }
  1326. //===----------------------------------------------------------------------===//
  1327. //--- IntervalMap::iterator ----//
  1328. //===----------------------------------------------------------------------===//
  1329. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1330. class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
  1331. friend class IntervalMap;
  1332. using IdxPair = IntervalMapImpl::IdxPair;
  1333. explicit iterator(IntervalMap &map) : const_iterator(map) {}
  1334. void setNodeStop(unsigned Level, KeyT Stop);
  1335. bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop);
  1336. template <typename NodeT> bool overflow(unsigned Level);
  1337. void treeInsert(KeyT a, KeyT b, ValT y);
  1338. void eraseNode(unsigned Level);
  1339. void treeErase(bool UpdateRoot = true);
  1340. bool canCoalesceLeft(KeyT Start, ValT x);
  1341. bool canCoalesceRight(KeyT Stop, ValT x);
  1342. public:
  1343. /// iterator - Create null iterator.
  1344. iterator() = default;
  1345. /// setStart - Move the start of the current interval.
  1346. /// This may cause coalescing with the previous interval.
  1347. /// @param a New start key, must not overlap the previous interval.
  1348. void setStart(KeyT a);
  1349. /// setStop - Move the end of the current interval.
  1350. /// This may cause coalescing with the following interval.
  1351. /// @param b New stop key, must not overlap the following interval.
  1352. void setStop(KeyT b);
  1353. /// setValue - Change the mapped value of the current interval.
  1354. /// This may cause coalescing with the previous and following intervals.
  1355. /// @param x New value.
  1356. void setValue(ValT x);
  1357. /// setStartUnchecked - Move the start of the current interval without
  1358. /// checking for coalescing or overlaps.
  1359. /// This should only be used when it is known that coalescing is not required.
  1360. /// @param a New start key.
  1361. void setStartUnchecked(KeyT a) { this->unsafeStart() = a; }
  1362. /// setStopUnchecked - Move the end of the current interval without checking
  1363. /// for coalescing or overlaps.
  1364. /// This should only be used when it is known that coalescing is not required.
  1365. /// @param b New stop key.
  1366. void setStopUnchecked(KeyT b) {
  1367. this->unsafeStop() = b;
  1368. // Update keys in branch nodes as well.
  1369. if (this->path.atLastEntry(this->path.height()))
  1370. setNodeStop(this->path.height(), b);
  1371. }
  1372. /// setValueUnchecked - Change the mapped value of the current interval
  1373. /// without checking for coalescing.
  1374. /// @param x New value.
  1375. void setValueUnchecked(ValT x) { this->unsafeValue() = x; }
  1376. /// insert - Insert mapping [a;b] -> y before the current position.
  1377. void insert(KeyT a, KeyT b, ValT y);
  1378. /// erase - Erase the current interval.
  1379. void erase();
  1380. iterator &operator++() {
  1381. const_iterator::operator++();
  1382. return *this;
  1383. }
  1384. iterator operator++(int) {
  1385. iterator tmp = *this;
  1386. operator++();
  1387. return tmp;
  1388. }
  1389. iterator &operator--() {
  1390. const_iterator::operator--();
  1391. return *this;
  1392. }
  1393. iterator operator--(int) {
  1394. iterator tmp = *this;
  1395. operator--();
  1396. return tmp;
  1397. }
  1398. };
  1399. /// canCoalesceLeft - Can the current interval coalesce to the left after
  1400. /// changing start or value?
  1401. /// @param Start New start of current interval.
  1402. /// @param Value New value for current interval.
  1403. /// @return True when updating the current interval would enable coalescing.
  1404. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1405. bool IntervalMap<KeyT, ValT, N, Traits>::
  1406. iterator::canCoalesceLeft(KeyT Start, ValT Value) {
  1407. using namespace IntervalMapImpl;
  1408. Path &P = this->path;
  1409. if (!this->branched()) {
  1410. unsigned i = P.leafOffset();
  1411. RootLeaf &Node = P.leaf<RootLeaf>();
  1412. return i && Node.value(i-1) == Value &&
  1413. Traits::adjacent(Node.stop(i-1), Start);
  1414. }
  1415. // Branched.
  1416. if (unsigned i = P.leafOffset()) {
  1417. Leaf &Node = P.leaf<Leaf>();
  1418. return Node.value(i-1) == Value && Traits::adjacent(Node.stop(i-1), Start);
  1419. } else if (NodeRef NR = P.getLeftSibling(P.height())) {
  1420. unsigned i = NR.size() - 1;
  1421. Leaf &Node = NR.get<Leaf>();
  1422. return Node.value(i) == Value && Traits::adjacent(Node.stop(i), Start);
  1423. }
  1424. return false;
  1425. }
  1426. /// canCoalesceRight - Can the current interval coalesce to the right after
  1427. /// changing stop or value?
  1428. /// @param Stop New stop of current interval.
  1429. /// @param Value New value for current interval.
  1430. /// @return True when updating the current interval would enable coalescing.
  1431. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1432. bool IntervalMap<KeyT, ValT, N, Traits>::
  1433. iterator::canCoalesceRight(KeyT Stop, ValT Value) {
  1434. using namespace IntervalMapImpl;
  1435. Path &P = this->path;
  1436. unsigned i = P.leafOffset() + 1;
  1437. if (!this->branched()) {
  1438. if (i >= P.leafSize())
  1439. return false;
  1440. RootLeaf &Node = P.leaf<RootLeaf>();
  1441. return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
  1442. }
  1443. // Branched.
  1444. if (i < P.leafSize()) {
  1445. Leaf &Node = P.leaf<Leaf>();
  1446. return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
  1447. } else if (NodeRef NR = P.getRightSibling(P.height())) {
  1448. Leaf &Node = NR.get<Leaf>();
  1449. return Node.value(0) == Value && Traits::adjacent(Stop, Node.start(0));
  1450. }
  1451. return false;
  1452. }
  1453. /// setNodeStop - Update the stop key of the current node at level and above.
  1454. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1455. void IntervalMap<KeyT, ValT, N, Traits>::
  1456. iterator::setNodeStop(unsigned Level, KeyT Stop) {
  1457. // There are no references to the root node, so nothing to update.
  1458. if (!Level)
  1459. return;
  1460. IntervalMapImpl::Path &P = this->path;
  1461. // Update nodes pointing to the current node.
  1462. while (--Level) {
  1463. P.node<Branch>(Level).stop(P.offset(Level)) = Stop;
  1464. if (!P.atLastEntry(Level))
  1465. return;
  1466. }
  1467. // Update root separately since it has a different layout.
  1468. P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop;
  1469. }
  1470. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1471. void IntervalMap<KeyT, ValT, N, Traits>::
  1472. iterator::setStart(KeyT a) {
  1473. assert(Traits::nonEmpty(a, this->stop()) && "Cannot move start beyond stop");
  1474. KeyT &CurStart = this->unsafeStart();
  1475. if (!Traits::startLess(a, CurStart) || !canCoalesceLeft(a, this->value())) {
  1476. CurStart = a;
  1477. return;
  1478. }
  1479. // Coalesce with the interval to the left.
  1480. --*this;
  1481. a = this->start();
  1482. erase();
  1483. setStartUnchecked(a);
  1484. }
  1485. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1486. void IntervalMap<KeyT, ValT, N, Traits>::
  1487. iterator::setStop(KeyT b) {
  1488. assert(Traits::nonEmpty(this->start(), b) && "Cannot move stop beyond start");
  1489. if (Traits::startLess(b, this->stop()) ||
  1490. !canCoalesceRight(b, this->value())) {
  1491. setStopUnchecked(b);
  1492. return;
  1493. }
  1494. // Coalesce with interval to the right.
  1495. KeyT a = this->start();
  1496. erase();
  1497. setStartUnchecked(a);
  1498. }
  1499. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1500. void IntervalMap<KeyT, ValT, N, Traits>::
  1501. iterator::setValue(ValT x) {
  1502. setValueUnchecked(x);
  1503. if (canCoalesceRight(this->stop(), x)) {
  1504. KeyT a = this->start();
  1505. erase();
  1506. setStartUnchecked(a);
  1507. }
  1508. if (canCoalesceLeft(this->start(), x)) {
  1509. --*this;
  1510. KeyT a = this->start();
  1511. erase();
  1512. setStartUnchecked(a);
  1513. }
  1514. }
  1515. /// insertNode - insert a node before the current path at level.
  1516. /// Leave the current path pointing at the new node.
  1517. /// @param Level path index of the node to be inserted.
  1518. /// @param Node The node to be inserted.
  1519. /// @param Stop The last index in the new node.
  1520. /// @return True if the tree height was increased.
  1521. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1522. bool IntervalMap<KeyT, ValT, N, Traits>::
  1523. iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) {
  1524. assert(Level && "Cannot insert next to the root");
  1525. bool SplitRoot = false;
  1526. IntervalMap &IM = *this->map;
  1527. IntervalMapImpl::Path &P = this->path;
  1528. if (Level == 1) {
  1529. // Insert into the root branch node.
  1530. if (IM.rootSize < RootBranch::Capacity) {
  1531. IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop);
  1532. P.setSize(0, ++IM.rootSize);
  1533. P.reset(Level);
  1534. return SplitRoot;
  1535. }
  1536. // We need to split the root while keeping our position.
  1537. SplitRoot = true;
  1538. IdxPair Offset = IM.splitRoot(P.offset(0));
  1539. P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
  1540. // Fall through to insert at the new higher level.
  1541. ++Level;
  1542. }
  1543. // When inserting before end(), make sure we have a valid path.
  1544. P.legalizeForInsert(--Level);
  1545. // Insert into the branch node at Level-1.
  1546. if (P.size(Level) == Branch::Capacity) {
  1547. // Branch node is full, handle handle the overflow.
  1548. assert(!SplitRoot && "Cannot overflow after splitting the root");
  1549. SplitRoot = overflow<Branch>(Level);
  1550. Level += SplitRoot;
  1551. }
  1552. P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop);
  1553. P.setSize(Level, P.size(Level) + 1);
  1554. if (P.atLastEntry(Level))
  1555. setNodeStop(Level, Stop);
  1556. P.reset(Level + 1);
  1557. return SplitRoot;
  1558. }
  1559. // insert
  1560. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1561. void IntervalMap<KeyT, ValT, N, Traits>::
  1562. iterator::insert(KeyT a, KeyT b, ValT y) {
  1563. if (this->branched())
  1564. return treeInsert(a, b, y);
  1565. IntervalMap &IM = *this->map;
  1566. IntervalMapImpl::Path &P = this->path;
  1567. // Try simple root leaf insert.
  1568. unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y);
  1569. // Was the root node insert successful?
  1570. if (Size <= RootLeaf::Capacity) {
  1571. P.setSize(0, IM.rootSize = Size);
  1572. return;
  1573. }
  1574. // Root leaf node is full, we must branch.
  1575. IdxPair Offset = IM.branchRoot(P.leafOffset());
  1576. P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
  1577. // Now it fits in the new leaf.
  1578. treeInsert(a, b, y);
  1579. }
  1580. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1581. void IntervalMap<KeyT, ValT, N, Traits>::
  1582. iterator::treeInsert(KeyT a, KeyT b, ValT y) {
  1583. using namespace IntervalMapImpl;
  1584. Path &P = this->path;
  1585. if (!P.valid())
  1586. P.legalizeForInsert(this->map->height);
  1587. // Check if this insertion will extend the node to the left.
  1588. if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) {
  1589. // Node is growing to the left, will it affect a left sibling node?
  1590. if (NodeRef Sib = P.getLeftSibling(P.height())) {
  1591. Leaf &SibLeaf = Sib.get<Leaf>();
  1592. unsigned SibOfs = Sib.size() - 1;
  1593. if (SibLeaf.value(SibOfs) == y &&
  1594. Traits::adjacent(SibLeaf.stop(SibOfs), a)) {
  1595. // This insertion will coalesce with the last entry in SibLeaf. We can
  1596. // handle it in two ways:
  1597. // 1. Extend SibLeaf.stop to b and be done, or
  1598. // 2. Extend a to SibLeaf, erase the SibLeaf entry and continue.
  1599. // We prefer 1., but need 2 when coalescing to the right as well.
  1600. Leaf &CurLeaf = P.leaf<Leaf>();
  1601. P.moveLeft(P.height());
  1602. if (Traits::stopLess(b, CurLeaf.start(0)) &&
  1603. (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) {
  1604. // Easy, just extend SibLeaf and we're done.
  1605. setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b);
  1606. return;
  1607. } else {
  1608. // We have both left and right coalescing. Erase the old SibLeaf entry
  1609. // and continue inserting the larger interval.
  1610. a = SibLeaf.start(SibOfs);
  1611. treeErase(/* UpdateRoot= */false);
  1612. }
  1613. }
  1614. } else {
  1615. // No left sibling means we are at begin(). Update cached bound.
  1616. this->map->rootBranchStart() = a;
  1617. }
  1618. }
  1619. // When we are inserting at the end of a leaf node, we must update stops.
  1620. unsigned Size = P.leafSize();
  1621. bool Grow = P.leafOffset() == Size;
  1622. Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y);
  1623. // Leaf insertion unsuccessful? Overflow and try again.
  1624. if (Size > Leaf::Capacity) {
  1625. overflow<Leaf>(P.height());
  1626. Grow = P.leafOffset() == P.leafSize();
  1627. Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y);
  1628. assert(Size <= Leaf::Capacity && "overflow() didn't make room");
  1629. }
  1630. // Inserted, update offset and leaf size.
  1631. P.setSize(P.height(), Size);
  1632. // Insert was the last node entry, update stops.
  1633. if (Grow)
  1634. setNodeStop(P.height(), b);
  1635. }
  1636. /// erase - erase the current interval and move to the next position.
  1637. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1638. void IntervalMap<KeyT, ValT, N, Traits>::
  1639. iterator::erase() {
  1640. IntervalMap &IM = *this->map;
  1641. IntervalMapImpl::Path &P = this->path;
  1642. assert(P.valid() && "Cannot erase end()");
  1643. if (this->branched())
  1644. return treeErase();
  1645. IM.rootLeaf().erase(P.leafOffset(), IM.rootSize);
  1646. P.setSize(0, --IM.rootSize);
  1647. }
  1648. /// treeErase - erase() for a branched tree.
  1649. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1650. void IntervalMap<KeyT, ValT, N, Traits>::
  1651. iterator::treeErase(bool UpdateRoot) {
  1652. IntervalMap &IM = *this->map;
  1653. IntervalMapImpl::Path &P = this->path;
  1654. Leaf &Node = P.leaf<Leaf>();
  1655. // Nodes are not allowed to become empty.
  1656. if (P.leafSize() == 1) {
  1657. IM.deleteNode(&Node);
  1658. eraseNode(IM.height);
  1659. // Update rootBranchStart if we erased begin().
  1660. if (UpdateRoot && IM.branched() && P.valid() && P.atBegin())
  1661. IM.rootBranchStart() = P.leaf<Leaf>().start(0);
  1662. return;
  1663. }
  1664. // Erase current entry.
  1665. Node.erase(P.leafOffset(), P.leafSize());
  1666. unsigned NewSize = P.leafSize() - 1;
  1667. P.setSize(IM.height, NewSize);
  1668. // When we erase the last entry, update stop and move to a legal position.
  1669. if (P.leafOffset() == NewSize) {
  1670. setNodeStop(IM.height, Node.stop(NewSize - 1));
  1671. P.moveRight(IM.height);
  1672. } else if (UpdateRoot && P.atBegin())
  1673. IM.rootBranchStart() = P.leaf<Leaf>().start(0);
  1674. }
  1675. /// eraseNode - Erase the current node at Level from its parent and move path to
  1676. /// the first entry of the next sibling node.
  1677. /// The node must be deallocated by the caller.
  1678. /// @param Level 1..height, the root node cannot be erased.
  1679. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1680. void IntervalMap<KeyT, ValT, N, Traits>::
  1681. iterator::eraseNode(unsigned Level) {
  1682. assert(Level && "Cannot erase root node");
  1683. IntervalMap &IM = *this->map;
  1684. IntervalMapImpl::Path &P = this->path;
  1685. if (--Level == 0) {
  1686. IM.rootBranch().erase(P.offset(0), IM.rootSize);
  1687. P.setSize(0, --IM.rootSize);
  1688. // If this cleared the root, switch to height=0.
  1689. if (IM.empty()) {
  1690. IM.switchRootToLeaf();
  1691. this->setRoot(0);
  1692. return;
  1693. }
  1694. } else {
  1695. // Remove node ref from branch node at Level.
  1696. Branch &Parent = P.node<Branch>(Level);
  1697. if (P.size(Level) == 1) {
  1698. // Branch node became empty, remove it recursively.
  1699. IM.deleteNode(&Parent);
  1700. eraseNode(Level);
  1701. } else {
  1702. // Branch node won't become empty.
  1703. Parent.erase(P.offset(Level), P.size(Level));
  1704. unsigned NewSize = P.size(Level) - 1;
  1705. P.setSize(Level, NewSize);
  1706. // If we removed the last branch, update stop and move to a legal pos.
  1707. if (P.offset(Level) == NewSize) {
  1708. setNodeStop(Level, Parent.stop(NewSize - 1));
  1709. P.moveRight(Level);
  1710. }
  1711. }
  1712. }
  1713. // Update path cache for the new right sibling position.
  1714. if (P.valid()) {
  1715. P.reset(Level + 1);
  1716. P.offset(Level + 1) = 0;
  1717. }
  1718. }
  1719. /// overflow - Distribute entries of the current node evenly among
  1720. /// its siblings and ensure that the current node is not full.
  1721. /// This may require allocating a new node.
  1722. /// @tparam NodeT The type of node at Level (Leaf or Branch).
  1723. /// @param Level path index of the overflowing node.
  1724. /// @return True when the tree height was changed.
  1725. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1726. template <typename NodeT>
  1727. bool IntervalMap<KeyT, ValT, N, Traits>::
  1728. iterator::overflow(unsigned Level) {
  1729. using namespace IntervalMapImpl;
  1730. Path &P = this->path;
  1731. unsigned CurSize[4];
  1732. NodeT *Node[4];
  1733. unsigned Nodes = 0;
  1734. unsigned Elements = 0;
  1735. unsigned Offset = P.offset(Level);
  1736. // Do we have a left sibling?
  1737. NodeRef LeftSib = P.getLeftSibling(Level);
  1738. if (LeftSib) {
  1739. Offset += Elements = CurSize[Nodes] = LeftSib.size();
  1740. Node[Nodes++] = &LeftSib.get<NodeT>();
  1741. }
  1742. // Current node.
  1743. Elements += CurSize[Nodes] = P.size(Level);
  1744. Node[Nodes++] = &P.node<NodeT>(Level);
  1745. // Do we have a right sibling?
  1746. NodeRef RightSib = P.getRightSibling(Level);
  1747. if (RightSib) {
  1748. Elements += CurSize[Nodes] = RightSib.size();
  1749. Node[Nodes++] = &RightSib.get<NodeT>();
  1750. }
  1751. // Do we need to allocate a new node?
  1752. unsigned NewNode = 0;
  1753. if (Elements + 1 > Nodes * NodeT::Capacity) {
  1754. // Insert NewNode at the penultimate position, or after a single node.
  1755. NewNode = Nodes == 1 ? 1 : Nodes - 1;
  1756. CurSize[Nodes] = CurSize[NewNode];
  1757. Node[Nodes] = Node[NewNode];
  1758. CurSize[NewNode] = 0;
  1759. Node[NewNode] = this->map->template newNode<NodeT>();
  1760. ++Nodes;
  1761. }
  1762. // Compute the new element distribution.
  1763. unsigned NewSize[4];
  1764. IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity,
  1765. CurSize, NewSize, Offset, true);
  1766. adjustSiblingSizes(Node, Nodes, CurSize, NewSize);
  1767. // Move current location to the leftmost node.
  1768. if (LeftSib)
  1769. P.moveLeft(Level);
  1770. // Elements have been rearranged, now update node sizes and stops.
  1771. bool SplitRoot = false;
  1772. unsigned Pos = 0;
  1773. while (true) {
  1774. KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
  1775. if (NewNode && Pos == NewNode) {
  1776. SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop);
  1777. Level += SplitRoot;
  1778. } else {
  1779. P.setSize(Level, NewSize[Pos]);
  1780. setNodeStop(Level, Stop);
  1781. }
  1782. if (Pos + 1 == Nodes)
  1783. break;
  1784. P.moveRight(Level);
  1785. ++Pos;
  1786. }
  1787. // Where was I? Find NewOffset.
  1788. while(Pos != NewOffset.first) {
  1789. P.moveLeft(Level);
  1790. --Pos;
  1791. }
  1792. P.offset(Level) = NewOffset.second;
  1793. return SplitRoot;
  1794. }
  1795. //===----------------------------------------------------------------------===//
  1796. //--- IntervalMapOverlaps ----//
  1797. //===----------------------------------------------------------------------===//
  1798. /// IntervalMapOverlaps - Iterate over the overlaps of mapped intervals in two
  1799. /// IntervalMaps. The maps may be different, but the KeyT and Traits types
  1800. /// should be the same.
  1801. ///
  1802. /// Typical uses:
  1803. ///
  1804. /// 1. Test for overlap:
  1805. /// bool overlap = IntervalMapOverlaps(a, b).valid();
  1806. ///
  1807. /// 2. Enumerate overlaps:
  1808. /// for (IntervalMapOverlaps I(a, b); I.valid() ; ++I) { ... }
  1809. ///
  1810. template <typename MapA, typename MapB>
  1811. class IntervalMapOverlaps {
  1812. using KeyType = typename MapA::KeyType;
  1813. using Traits = typename MapA::KeyTraits;
  1814. typename MapA::const_iterator posA;
  1815. typename MapB::const_iterator posB;
  1816. /// advance - Move posA and posB forward until reaching an overlap, or until
  1817. /// either meets end.
  1818. /// Don't move the iterators if they are already overlapping.
  1819. void advance() {
  1820. if (!valid())
  1821. return;
  1822. if (Traits::stopLess(posA.stop(), posB.start())) {
  1823. // A ends before B begins. Catch up.
  1824. posA.advanceTo(posB.start());
  1825. if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
  1826. return;
  1827. } else if (Traits::stopLess(posB.stop(), posA.start())) {
  1828. // B ends before A begins. Catch up.
  1829. posB.advanceTo(posA.start());
  1830. if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
  1831. return;
  1832. } else
  1833. // Already overlapping.
  1834. return;
  1835. while (true) {
  1836. // Make a.end > b.start.
  1837. posA.advanceTo(posB.start());
  1838. if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
  1839. return;
  1840. // Make b.end > a.start.
  1841. posB.advanceTo(posA.start());
  1842. if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
  1843. return;
  1844. }
  1845. }
  1846. public:
  1847. /// IntervalMapOverlaps - Create an iterator for the overlaps of a and b.
  1848. IntervalMapOverlaps(const MapA &a, const MapB &b)
  1849. : posA(b.empty() ? a.end() : a.find(b.start())),
  1850. posB(posA.valid() ? b.find(posA.start()) : b.end()) { advance(); }
  1851. /// valid - Return true if iterator is at an overlap.
  1852. bool valid() const {
  1853. return posA.valid() && posB.valid();
  1854. }
  1855. /// a - access the left hand side in the overlap.
  1856. const typename MapA::const_iterator &a() const { return posA; }
  1857. /// b - access the right hand side in the overlap.
  1858. const typename MapB::const_iterator &b() const { return posB; }
  1859. /// start - Beginning of the overlapping interval.
  1860. KeyType start() const {
  1861. KeyType ak = a().start();
  1862. KeyType bk = b().start();
  1863. return Traits::startLess(ak, bk) ? bk : ak;
  1864. }
  1865. /// stop - End of the overlapping interval.
  1866. KeyType stop() const {
  1867. KeyType ak = a().stop();
  1868. KeyType bk = b().stop();
  1869. return Traits::startLess(ak, bk) ? ak : bk;
  1870. }
  1871. /// skipA - Move to the next overlap that doesn't involve a().
  1872. void skipA() {
  1873. ++posA;
  1874. advance();
  1875. }
  1876. /// skipB - Move to the next overlap that doesn't involve b().
  1877. void skipB() {
  1878. ++posB;
  1879. advance();
  1880. }
  1881. /// Preincrement - Move to the next overlap.
  1882. IntervalMapOverlaps &operator++() {
  1883. // Bump the iterator that ends first. The other one may have more overlaps.
  1884. if (Traits::startLess(posB.stop(), posA.stop()))
  1885. skipB();
  1886. else
  1887. skipA();
  1888. return *this;
  1889. }
  1890. /// advanceTo - Move to the first overlapping interval with
  1891. /// stopLess(x, stop()).
  1892. void advanceTo(KeyType x) {
  1893. if (!valid())
  1894. return;
  1895. // Make sure advanceTo sees monotonic keys.
  1896. if (Traits::stopLess(posA.stop(), x))
  1897. posA.advanceTo(x);
  1898. if (Traits::stopLess(posB.stop(), x))
  1899. posB.advanceTo(x);
  1900. advance();
  1901. }
  1902. };
  1903. } // end namespace llvm
  1904. #endif // LLVM_ADT_INTERVALMAP_H
  1905. #ifdef __GNUC__
  1906. #pragma GCC diagnostic pop
  1907. #endif