IntervalMap.h 73 KB

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