IntervalMap.h 72 KB

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