106f32e7eSjoerg //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file implements a coalescing interval map for small objects.
1006f32e7eSjoerg //
1106f32e7eSjoerg // KeyT objects are mapped to ValT objects. Intervals of keys that map to the
1206f32e7eSjoerg // same value are represented in a compressed form.
1306f32e7eSjoerg //
1406f32e7eSjoerg // Iterators provide ordered access to the compressed intervals rather than the
1506f32e7eSjoerg // individual keys, and insert and erase operations use key intervals as well.
1606f32e7eSjoerg //
1706f32e7eSjoerg // Like SmallVector, IntervalMap will store the first N intervals in the map
1806f32e7eSjoerg // object itself without any allocations. When space is exhausted it switches to
1906f32e7eSjoerg // a B+-tree representation with very small overhead for small key and value
2006f32e7eSjoerg // objects.
2106f32e7eSjoerg //
2206f32e7eSjoerg // A Traits class specifies how keys are compared. It also allows IntervalMap to
2306f32e7eSjoerg // work with both closed and half-open intervals.
2406f32e7eSjoerg //
2506f32e7eSjoerg // Keys and values are not stored next to each other in a std::pair, so we don't
2606f32e7eSjoerg // provide such a value_type. Dereferencing iterators only returns the mapped
2706f32e7eSjoerg // value. The interval bounds are accessible through the start() and stop()
2806f32e7eSjoerg // iterator methods.
2906f32e7eSjoerg //
3006f32e7eSjoerg // IntervalMap is optimized for small key and value objects, 4 or 8 bytes each
3106f32e7eSjoerg // is the optimal size. For large objects use std::map instead.
3206f32e7eSjoerg //
3306f32e7eSjoerg //===----------------------------------------------------------------------===//
3406f32e7eSjoerg //
3506f32e7eSjoerg // Synopsis:
3606f32e7eSjoerg //
3706f32e7eSjoerg // template <typename KeyT, typename ValT, unsigned N, typename Traits>
3806f32e7eSjoerg // class IntervalMap {
3906f32e7eSjoerg // public:
4006f32e7eSjoerg //   typedef KeyT key_type;
4106f32e7eSjoerg //   typedef ValT mapped_type;
4206f32e7eSjoerg //   typedef RecyclingAllocator<...> Allocator;
4306f32e7eSjoerg //   class iterator;
4406f32e7eSjoerg //   class const_iterator;
4506f32e7eSjoerg //
4606f32e7eSjoerg //   explicit IntervalMap(Allocator&);
4706f32e7eSjoerg //   ~IntervalMap():
4806f32e7eSjoerg //
4906f32e7eSjoerg //   bool empty() const;
5006f32e7eSjoerg //   KeyT start() const;
5106f32e7eSjoerg //   KeyT stop() const;
5206f32e7eSjoerg //   ValT lookup(KeyT x, Value NotFound = Value()) const;
5306f32e7eSjoerg //
5406f32e7eSjoerg //   const_iterator begin() const;
5506f32e7eSjoerg //   const_iterator end() const;
5606f32e7eSjoerg //   iterator begin();
5706f32e7eSjoerg //   iterator end();
5806f32e7eSjoerg //   const_iterator find(KeyT x) const;
5906f32e7eSjoerg //   iterator find(KeyT x);
6006f32e7eSjoerg //
6106f32e7eSjoerg //   void insert(KeyT a, KeyT b, ValT y);
6206f32e7eSjoerg //   void clear();
6306f32e7eSjoerg // };
6406f32e7eSjoerg //
6506f32e7eSjoerg // template <typename KeyT, typename ValT, unsigned N, typename Traits>
66*da58b97aSjoerg // class IntervalMap::const_iterator {
6706f32e7eSjoerg // public:
68*da58b97aSjoerg //   using iterator_category = std::bidirectional_iterator_tag;
69*da58b97aSjoerg //   using value_type = ValT;
70*da58b97aSjoerg //   using difference_type = std::ptrdiff_t;
71*da58b97aSjoerg //   using pointer = value_type *;
72*da58b97aSjoerg //   using reference = value_type &;
73*da58b97aSjoerg //
7406f32e7eSjoerg //   bool operator==(const const_iterator &) const;
7506f32e7eSjoerg //   bool operator!=(const const_iterator &) const;
7606f32e7eSjoerg //   bool valid() const;
7706f32e7eSjoerg //
7806f32e7eSjoerg //   const KeyT &start() const;
7906f32e7eSjoerg //   const KeyT &stop() const;
8006f32e7eSjoerg //   const ValT &value() const;
8106f32e7eSjoerg //   const ValT &operator*() const;
8206f32e7eSjoerg //   const ValT *operator->() const;
8306f32e7eSjoerg //
8406f32e7eSjoerg //   const_iterator &operator++();
8506f32e7eSjoerg //   const_iterator &operator++(int);
8606f32e7eSjoerg //   const_iterator &operator--();
8706f32e7eSjoerg //   const_iterator &operator--(int);
8806f32e7eSjoerg //   void goToBegin();
8906f32e7eSjoerg //   void goToEnd();
9006f32e7eSjoerg //   void find(KeyT x);
9106f32e7eSjoerg //   void advanceTo(KeyT x);
9206f32e7eSjoerg // };
9306f32e7eSjoerg //
9406f32e7eSjoerg // template <typename KeyT, typename ValT, unsigned N, typename Traits>
9506f32e7eSjoerg // class IntervalMap::iterator : public const_iterator {
9606f32e7eSjoerg // public:
9706f32e7eSjoerg //   void insert(KeyT a, KeyT b, Value y);
9806f32e7eSjoerg //   void erase();
9906f32e7eSjoerg // };
10006f32e7eSjoerg //
10106f32e7eSjoerg //===----------------------------------------------------------------------===//
10206f32e7eSjoerg 
10306f32e7eSjoerg #ifndef LLVM_ADT_INTERVALMAP_H
10406f32e7eSjoerg #define LLVM_ADT_INTERVALMAP_H
10506f32e7eSjoerg 
10606f32e7eSjoerg #include "llvm/ADT/PointerIntPair.h"
10706f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
10806f32e7eSjoerg #include "llvm/ADT/bit.h"
10906f32e7eSjoerg #include "llvm/Support/AlignOf.h"
11006f32e7eSjoerg #include "llvm/Support/Allocator.h"
11106f32e7eSjoerg #include "llvm/Support/RecyclingAllocator.h"
11206f32e7eSjoerg #include <algorithm>
11306f32e7eSjoerg #include <cassert>
11406f32e7eSjoerg #include <cstdint>
11506f32e7eSjoerg #include <iterator>
11606f32e7eSjoerg #include <new>
11706f32e7eSjoerg #include <utility>
11806f32e7eSjoerg 
11906f32e7eSjoerg namespace llvm {
12006f32e7eSjoerg 
12106f32e7eSjoerg //===----------------------------------------------------------------------===//
12206f32e7eSjoerg //---                              Key traits                              ---//
12306f32e7eSjoerg //===----------------------------------------------------------------------===//
12406f32e7eSjoerg //
12506f32e7eSjoerg // The IntervalMap works with closed or half-open intervals.
12606f32e7eSjoerg // Adjacent intervals that map to the same value are coalesced.
12706f32e7eSjoerg //
12806f32e7eSjoerg // The IntervalMapInfo traits class is used to determine if a key is contained
12906f32e7eSjoerg // in an interval, and if two intervals are adjacent so they can be coalesced.
13006f32e7eSjoerg // The provided implementation works for closed integer intervals, other keys
13106f32e7eSjoerg // probably need a specialized version.
13206f32e7eSjoerg //
13306f32e7eSjoerg // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
13406f32e7eSjoerg //
13506f32e7eSjoerg // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
13606f32e7eSjoerg // allowed. This is so that stopLess(a, b) can be used to determine if two
13706f32e7eSjoerg // intervals overlap.
13806f32e7eSjoerg //
13906f32e7eSjoerg //===----------------------------------------------------------------------===//
14006f32e7eSjoerg 
14106f32e7eSjoerg template <typename T>
14206f32e7eSjoerg struct IntervalMapInfo {
14306f32e7eSjoerg   /// startLess - Return true if x is not in [a;b].
14406f32e7eSjoerg   /// This is x < a both for closed intervals and for [a;b) half-open intervals.
startLessIntervalMapInfo14506f32e7eSjoerg   static inline bool startLess(const T &x, const T &a) {
14606f32e7eSjoerg     return x < a;
14706f32e7eSjoerg   }
14806f32e7eSjoerg 
14906f32e7eSjoerg   /// stopLess - Return true if x is not in [a;b].
15006f32e7eSjoerg   /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
stopLessIntervalMapInfo15106f32e7eSjoerg   static inline bool stopLess(const T &b, const T &x) {
15206f32e7eSjoerg     return b < x;
15306f32e7eSjoerg   }
15406f32e7eSjoerg 
15506f32e7eSjoerg   /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
15606f32e7eSjoerg   /// This is a+1 == b for closed intervals, a == b for half-open intervals.
adjacentIntervalMapInfo15706f32e7eSjoerg   static inline bool adjacent(const T &a, const T &b) {
15806f32e7eSjoerg     return a+1 == b;
15906f32e7eSjoerg   }
16006f32e7eSjoerg 
16106f32e7eSjoerg   /// nonEmpty - Return true if [a;b] is non-empty.
16206f32e7eSjoerg   /// This is a <= b for a closed interval, a < b for [a;b) half-open intervals.
nonEmptyIntervalMapInfo16306f32e7eSjoerg   static inline bool nonEmpty(const T &a, const T &b) {
16406f32e7eSjoerg     return a <= b;
16506f32e7eSjoerg   }
16606f32e7eSjoerg };
16706f32e7eSjoerg 
16806f32e7eSjoerg template <typename T>
16906f32e7eSjoerg struct IntervalMapHalfOpenInfo {
17006f32e7eSjoerg   /// startLess - Return true if x is not in [a;b).
startLessIntervalMapHalfOpenInfo17106f32e7eSjoerg   static inline bool startLess(const T &x, const T &a) {
17206f32e7eSjoerg     return x < a;
17306f32e7eSjoerg   }
17406f32e7eSjoerg 
17506f32e7eSjoerg   /// stopLess - Return true if x is not in [a;b).
stopLessIntervalMapHalfOpenInfo17606f32e7eSjoerg   static inline bool stopLess(const T &b, const T &x) {
17706f32e7eSjoerg     return b <= x;
17806f32e7eSjoerg   }
17906f32e7eSjoerg 
18006f32e7eSjoerg   /// adjacent - Return true when the intervals [x;a) and [b;y) can coalesce.
adjacentIntervalMapHalfOpenInfo18106f32e7eSjoerg   static inline bool adjacent(const T &a, const T &b) {
18206f32e7eSjoerg     return a == b;
18306f32e7eSjoerg   }
18406f32e7eSjoerg 
18506f32e7eSjoerg   /// nonEmpty - Return true if [a;b) is non-empty.
nonEmptyIntervalMapHalfOpenInfo18606f32e7eSjoerg   static inline bool nonEmpty(const T &a, const T &b) {
18706f32e7eSjoerg     return a < b;
18806f32e7eSjoerg   }
18906f32e7eSjoerg };
19006f32e7eSjoerg 
19106f32e7eSjoerg /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
19206f32e7eSjoerg /// It should be considered private to the implementation.
19306f32e7eSjoerg namespace IntervalMapImpl {
19406f32e7eSjoerg 
19506f32e7eSjoerg using IdxPair = std::pair<unsigned,unsigned>;
19606f32e7eSjoerg 
19706f32e7eSjoerg //===----------------------------------------------------------------------===//
19806f32e7eSjoerg //---                    IntervalMapImpl::NodeBase                         ---//
19906f32e7eSjoerg //===----------------------------------------------------------------------===//
20006f32e7eSjoerg //
20106f32e7eSjoerg // Both leaf and branch nodes store vectors of pairs.
20206f32e7eSjoerg // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT).
20306f32e7eSjoerg //
20406f32e7eSjoerg // Keys and values are stored in separate arrays to avoid padding caused by
20506f32e7eSjoerg // different object alignments. This also helps improve locality of reference
20606f32e7eSjoerg // when searching the keys.
20706f32e7eSjoerg //
20806f32e7eSjoerg // The nodes don't know how many elements they contain - that information is
20906f32e7eSjoerg // stored elsewhere. Omitting the size field prevents padding and allows a node
21006f32e7eSjoerg // to fill the allocated cache lines completely.
21106f32e7eSjoerg //
21206f32e7eSjoerg // These are typical key and value sizes, the node branching factor (N), and
21306f32e7eSjoerg // wasted space when nodes are sized to fit in three cache lines (192 bytes):
21406f32e7eSjoerg //
21506f32e7eSjoerg //   T1  T2   N Waste  Used by
21606f32e7eSjoerg //    4   4  24   0    Branch<4> (32-bit pointers)
21706f32e7eSjoerg //    8   4  16   0    Leaf<4,4>, Branch<4>
21806f32e7eSjoerg //    8   8  12   0    Leaf<4,8>, Branch<8>
21906f32e7eSjoerg //   16   4   9  12    Leaf<8,4>
22006f32e7eSjoerg //   16   8   8   0    Leaf<8,8>
22106f32e7eSjoerg //
22206f32e7eSjoerg //===----------------------------------------------------------------------===//
22306f32e7eSjoerg 
22406f32e7eSjoerg template <typename T1, typename T2, unsigned N>
22506f32e7eSjoerg class NodeBase {
22606f32e7eSjoerg public:
22706f32e7eSjoerg   enum { Capacity = N };
22806f32e7eSjoerg 
22906f32e7eSjoerg   T1 first[N];
23006f32e7eSjoerg   T2 second[N];
23106f32e7eSjoerg 
23206f32e7eSjoerg   /// copy - Copy elements from another node.
23306f32e7eSjoerg   /// @param Other Node elements are copied from.
23406f32e7eSjoerg   /// @param i     Beginning of the source range in other.
23506f32e7eSjoerg   /// @param j     Beginning of the destination range in this.
23606f32e7eSjoerg   /// @param Count Number of elements to copy.
23706f32e7eSjoerg   template <unsigned M>
copy(const NodeBase<T1,T2,M> & Other,unsigned i,unsigned j,unsigned Count)23806f32e7eSjoerg   void copy(const NodeBase<T1, T2, M> &Other, unsigned i,
23906f32e7eSjoerg             unsigned j, unsigned Count) {
24006f32e7eSjoerg     assert(i + Count <= M && "Invalid source range");
24106f32e7eSjoerg     assert(j + Count <= N && "Invalid dest range");
24206f32e7eSjoerg     for (unsigned e = i + Count; i != e; ++i, ++j) {
24306f32e7eSjoerg       first[j]  = Other.first[i];
24406f32e7eSjoerg       second[j] = Other.second[i];
24506f32e7eSjoerg     }
24606f32e7eSjoerg   }
24706f32e7eSjoerg 
24806f32e7eSjoerg   /// moveLeft - Move elements to the left.
24906f32e7eSjoerg   /// @param i     Beginning of the source range.
25006f32e7eSjoerg   /// @param j     Beginning of the destination range.
25106f32e7eSjoerg   /// @param Count Number of elements to copy.
moveLeft(unsigned i,unsigned j,unsigned Count)25206f32e7eSjoerg   void moveLeft(unsigned i, unsigned j, unsigned Count) {
25306f32e7eSjoerg     assert(j <= i && "Use moveRight shift elements right");
25406f32e7eSjoerg     copy(*this, i, j, Count);
25506f32e7eSjoerg   }
25606f32e7eSjoerg 
25706f32e7eSjoerg   /// moveRight - Move elements to the right.
25806f32e7eSjoerg   /// @param i     Beginning of the source range.
25906f32e7eSjoerg   /// @param j     Beginning of the destination range.
26006f32e7eSjoerg   /// @param Count Number of elements to copy.
moveRight(unsigned i,unsigned j,unsigned Count)26106f32e7eSjoerg   void moveRight(unsigned i, unsigned j, unsigned Count) {
26206f32e7eSjoerg     assert(i <= j && "Use moveLeft shift elements left");
26306f32e7eSjoerg     assert(j + Count <= N && "Invalid range");
26406f32e7eSjoerg     while (Count--) {
26506f32e7eSjoerg       first[j + Count]  = first[i + Count];
26606f32e7eSjoerg       second[j + Count] = second[i + Count];
26706f32e7eSjoerg     }
26806f32e7eSjoerg   }
26906f32e7eSjoerg 
27006f32e7eSjoerg   /// erase - Erase elements [i;j).
27106f32e7eSjoerg   /// @param i    Beginning of the range to erase.
27206f32e7eSjoerg   /// @param j    End of the range. (Exclusive).
27306f32e7eSjoerg   /// @param Size Number of elements in node.
erase(unsigned i,unsigned j,unsigned Size)27406f32e7eSjoerg   void erase(unsigned i, unsigned j, unsigned Size) {
27506f32e7eSjoerg     moveLeft(j, i, Size - j);
27606f32e7eSjoerg   }
27706f32e7eSjoerg 
27806f32e7eSjoerg   /// erase - Erase element at i.
27906f32e7eSjoerg   /// @param i    Index of element to erase.
28006f32e7eSjoerg   /// @param Size Number of elements in node.
erase(unsigned i,unsigned Size)28106f32e7eSjoerg   void erase(unsigned i, unsigned Size) {
28206f32e7eSjoerg     erase(i, i+1, Size);
28306f32e7eSjoerg   }
28406f32e7eSjoerg 
28506f32e7eSjoerg   /// shift - Shift elements [i;size) 1 position to the right.
28606f32e7eSjoerg   /// @param i    Beginning of the range to move.
28706f32e7eSjoerg   /// @param Size Number of elements in node.
shift(unsigned i,unsigned Size)28806f32e7eSjoerg   void shift(unsigned i, unsigned Size) {
28906f32e7eSjoerg     moveRight(i, i + 1, Size - i);
29006f32e7eSjoerg   }
29106f32e7eSjoerg 
29206f32e7eSjoerg   /// transferToLeftSib - Transfer elements to a left sibling node.
29306f32e7eSjoerg   /// @param Size  Number of elements in this.
29406f32e7eSjoerg   /// @param Sib   Left sibling node.
29506f32e7eSjoerg   /// @param SSize Number of elements in sib.
29606f32e7eSjoerg   /// @param Count Number of elements to transfer.
transferToLeftSib(unsigned Size,NodeBase & Sib,unsigned SSize,unsigned Count)29706f32e7eSjoerg   void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize,
29806f32e7eSjoerg                          unsigned Count) {
29906f32e7eSjoerg     Sib.copy(*this, 0, SSize, Count);
30006f32e7eSjoerg     erase(0, Count, Size);
30106f32e7eSjoerg   }
30206f32e7eSjoerg 
30306f32e7eSjoerg   /// transferToRightSib - Transfer elements to a right sibling node.
30406f32e7eSjoerg   /// @param Size  Number of elements in this.
30506f32e7eSjoerg   /// @param Sib   Right sibling node.
30606f32e7eSjoerg   /// @param SSize Number of elements in sib.
30706f32e7eSjoerg   /// @param Count Number of elements to transfer.
transferToRightSib(unsigned Size,NodeBase & Sib,unsigned SSize,unsigned Count)30806f32e7eSjoerg   void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize,
30906f32e7eSjoerg                           unsigned Count) {
31006f32e7eSjoerg     Sib.moveRight(0, Count, SSize);
31106f32e7eSjoerg     Sib.copy(*this, Size-Count, 0, Count);
31206f32e7eSjoerg   }
31306f32e7eSjoerg 
31406f32e7eSjoerg   /// adjustFromLeftSib - Adjust the number if elements in this node by moving
31506f32e7eSjoerg   /// elements to or from a left sibling node.
31606f32e7eSjoerg   /// @param Size  Number of elements in this.
31706f32e7eSjoerg   /// @param Sib   Right sibling node.
31806f32e7eSjoerg   /// @param SSize Number of elements in sib.
31906f32e7eSjoerg   /// @param Add   The number of elements to add to this node, possibly < 0.
32006f32e7eSjoerg   /// @return      Number of elements added to this node, possibly negative.
adjustFromLeftSib(unsigned Size,NodeBase & Sib,unsigned SSize,int Add)32106f32e7eSjoerg   int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
32206f32e7eSjoerg     if (Add > 0) {
32306f32e7eSjoerg       // We want to grow, copy from sib.
32406f32e7eSjoerg       unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
32506f32e7eSjoerg       Sib.transferToRightSib(SSize, *this, Size, Count);
32606f32e7eSjoerg       return Count;
32706f32e7eSjoerg     } else {
32806f32e7eSjoerg       // We want to shrink, copy to sib.
32906f32e7eSjoerg       unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
33006f32e7eSjoerg       transferToLeftSib(Size, Sib, SSize, Count);
33106f32e7eSjoerg       return -Count;
33206f32e7eSjoerg     }
33306f32e7eSjoerg   }
33406f32e7eSjoerg };
33506f32e7eSjoerg 
33606f32e7eSjoerg /// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes.
33706f32e7eSjoerg /// @param Node  Array of pointers to sibling nodes.
33806f32e7eSjoerg /// @param Nodes Number of nodes.
33906f32e7eSjoerg /// @param CurSize Array of current node sizes, will be overwritten.
34006f32e7eSjoerg /// @param NewSize Array of desired node sizes.
34106f32e7eSjoerg template <typename NodeT>
adjustSiblingSizes(NodeT * Node[],unsigned Nodes,unsigned CurSize[],const unsigned NewSize[])34206f32e7eSjoerg void adjustSiblingSizes(NodeT *Node[], unsigned Nodes,
34306f32e7eSjoerg                         unsigned CurSize[], const unsigned NewSize[]) {
34406f32e7eSjoerg   // Move elements right.
34506f32e7eSjoerg   for (int n = Nodes - 1; n; --n) {
34606f32e7eSjoerg     if (CurSize[n] == NewSize[n])
34706f32e7eSjoerg       continue;
34806f32e7eSjoerg     for (int m = n - 1; m != -1; --m) {
34906f32e7eSjoerg       int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m],
35006f32e7eSjoerg                                          NewSize[n] - CurSize[n]);
35106f32e7eSjoerg       CurSize[m] -= d;
35206f32e7eSjoerg       CurSize[n] += d;
35306f32e7eSjoerg       // Keep going if the current node was exhausted.
35406f32e7eSjoerg       if (CurSize[n] >= NewSize[n])
35506f32e7eSjoerg           break;
35606f32e7eSjoerg     }
35706f32e7eSjoerg   }
35806f32e7eSjoerg 
35906f32e7eSjoerg   if (Nodes == 0)
36006f32e7eSjoerg     return;
36106f32e7eSjoerg 
36206f32e7eSjoerg   // Move elements left.
36306f32e7eSjoerg   for (unsigned n = 0; n != Nodes - 1; ++n) {
36406f32e7eSjoerg     if (CurSize[n] == NewSize[n])
36506f32e7eSjoerg       continue;
36606f32e7eSjoerg     for (unsigned m = n + 1; m != Nodes; ++m) {
36706f32e7eSjoerg       int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n],
36806f32e7eSjoerg                                         CurSize[n] -  NewSize[n]);
36906f32e7eSjoerg       CurSize[m] += d;
37006f32e7eSjoerg       CurSize[n] -= d;
37106f32e7eSjoerg       // Keep going if the current node was exhausted.
37206f32e7eSjoerg       if (CurSize[n] >= NewSize[n])
37306f32e7eSjoerg           break;
37406f32e7eSjoerg     }
37506f32e7eSjoerg   }
37606f32e7eSjoerg 
37706f32e7eSjoerg #ifndef NDEBUG
37806f32e7eSjoerg   for (unsigned n = 0; n != Nodes; n++)
37906f32e7eSjoerg     assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
38006f32e7eSjoerg #endif
38106f32e7eSjoerg }
38206f32e7eSjoerg 
38306f32e7eSjoerg /// IntervalMapImpl::distribute - Compute a new distribution of node elements
38406f32e7eSjoerg /// after an overflow or underflow. Reserve space for a new element at Position,
38506f32e7eSjoerg /// and compute the node that will hold Position after redistributing node
38606f32e7eSjoerg /// elements.
38706f32e7eSjoerg ///
38806f32e7eSjoerg /// It is required that
38906f32e7eSjoerg ///
39006f32e7eSjoerg ///   Elements == sum(CurSize), and
39106f32e7eSjoerg ///   Elements + Grow <= Nodes * Capacity.
39206f32e7eSjoerg ///
39306f32e7eSjoerg /// NewSize[] will be filled in such that:
39406f32e7eSjoerg ///
39506f32e7eSjoerg ///   sum(NewSize) == Elements, and
39606f32e7eSjoerg ///   NewSize[i] <= Capacity.
39706f32e7eSjoerg ///
39806f32e7eSjoerg /// The returned index is the node where Position will go, so:
39906f32e7eSjoerg ///
40006f32e7eSjoerg ///   sum(NewSize[0..idx-1]) <= Position
40106f32e7eSjoerg ///   sum(NewSize[0..idx])   >= Position
40206f32e7eSjoerg ///
40306f32e7eSjoerg /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
40406f32e7eSjoerg /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
40506f32e7eSjoerg /// before the one holding the Position'th element where there is room for an
40606f32e7eSjoerg /// insertion.
40706f32e7eSjoerg ///
40806f32e7eSjoerg /// @param Nodes    The number of nodes.
40906f32e7eSjoerg /// @param Elements Total elements in all nodes.
41006f32e7eSjoerg /// @param Capacity The capacity of each node.
41106f32e7eSjoerg /// @param CurSize  Array[Nodes] of current node sizes, or NULL.
41206f32e7eSjoerg /// @param NewSize  Array[Nodes] to receive the new node sizes.
41306f32e7eSjoerg /// @param Position Insert position.
41406f32e7eSjoerg /// @param Grow     Reserve space for a new element at Position.
41506f32e7eSjoerg /// @return         (node, offset) for Position.
41606f32e7eSjoerg IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
41706f32e7eSjoerg                    const unsigned *CurSize, unsigned NewSize[],
41806f32e7eSjoerg                    unsigned Position, bool Grow);
41906f32e7eSjoerg 
42006f32e7eSjoerg //===----------------------------------------------------------------------===//
42106f32e7eSjoerg //---                   IntervalMapImpl::NodeSizer                         ---//
42206f32e7eSjoerg //===----------------------------------------------------------------------===//
42306f32e7eSjoerg //
42406f32e7eSjoerg // Compute node sizes from key and value types.
42506f32e7eSjoerg //
42606f32e7eSjoerg // The branching factors are chosen to make nodes fit in three cache lines.
42706f32e7eSjoerg // This may not be possible if keys or values are very large. Such large objects
42806f32e7eSjoerg // are handled correctly, but a std::map would probably give better performance.
42906f32e7eSjoerg //
43006f32e7eSjoerg //===----------------------------------------------------------------------===//
43106f32e7eSjoerg 
43206f32e7eSjoerg enum {
43306f32e7eSjoerg   // Cache line size. Most architectures have 32 or 64 byte cache lines.
43406f32e7eSjoerg   // We use 64 bytes here because it provides good branching factors.
43506f32e7eSjoerg   Log2CacheLine = 6,
43606f32e7eSjoerg   CacheLineBytes = 1 << Log2CacheLine,
43706f32e7eSjoerg   DesiredNodeBytes = 3 * CacheLineBytes
43806f32e7eSjoerg };
43906f32e7eSjoerg 
44006f32e7eSjoerg template <typename KeyT, typename ValT>
44106f32e7eSjoerg struct NodeSizer {
44206f32e7eSjoerg   enum {
44306f32e7eSjoerg     // Compute the leaf node branching factor that makes a node fit in three
44406f32e7eSjoerg     // cache lines. The branching factor must be at least 3, or some B+-tree
44506f32e7eSjoerg     // balancing algorithms won't work.
44606f32e7eSjoerg     // LeafSize can't be larger than CacheLineBytes. This is required by the
44706f32e7eSjoerg     // PointerIntPair used by NodeRef.
44806f32e7eSjoerg     DesiredLeafSize = DesiredNodeBytes /
44906f32e7eSjoerg       static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
45006f32e7eSjoerg     MinLeafSize = 3,
45106f32e7eSjoerg     LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
45206f32e7eSjoerg   };
45306f32e7eSjoerg 
45406f32e7eSjoerg   using LeafBase = NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize>;
45506f32e7eSjoerg 
45606f32e7eSjoerg   enum {
45706f32e7eSjoerg     // Now that we have the leaf branching factor, compute the actual allocation
45806f32e7eSjoerg     // unit size by rounding up to a whole number of cache lines.
45906f32e7eSjoerg     AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
46006f32e7eSjoerg 
46106f32e7eSjoerg     // Determine the branching factor for branch nodes.
46206f32e7eSjoerg     BranchSize = AllocBytes /
46306f32e7eSjoerg       static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
46406f32e7eSjoerg   };
46506f32e7eSjoerg 
46606f32e7eSjoerg   /// Allocator - The recycling allocator used for both branch and leaf nodes.
46706f32e7eSjoerg   /// This typedef is very likely to be identical for all IntervalMaps with
46806f32e7eSjoerg   /// reasonably sized entries, so the same allocator can be shared among
46906f32e7eSjoerg   /// different kinds of maps.
47006f32e7eSjoerg   using Allocator =
47106f32e7eSjoerg       RecyclingAllocator<BumpPtrAllocator, char, AllocBytes, CacheLineBytes>;
47206f32e7eSjoerg };
47306f32e7eSjoerg 
47406f32e7eSjoerg //===----------------------------------------------------------------------===//
47506f32e7eSjoerg //---                     IntervalMapImpl::NodeRef                         ---//
47606f32e7eSjoerg //===----------------------------------------------------------------------===//
47706f32e7eSjoerg //
47806f32e7eSjoerg // B+-tree nodes can be leaves or branches, so we need a polymorphic node
47906f32e7eSjoerg // pointer that can point to both kinds.
48006f32e7eSjoerg //
48106f32e7eSjoerg // All nodes are cache line aligned and the low 6 bits of a node pointer are
48206f32e7eSjoerg // always 0. These bits are used to store the number of elements in the
48306f32e7eSjoerg // referenced node. Besides saving space, placing node sizes in the parents
48406f32e7eSjoerg // allow tree balancing algorithms to run without faulting cache lines for nodes
48506f32e7eSjoerg // that may not need to be modified.
48606f32e7eSjoerg //
48706f32e7eSjoerg // A NodeRef doesn't know whether it references a leaf node or a branch node.
48806f32e7eSjoerg // It is the responsibility of the caller to use the correct types.
48906f32e7eSjoerg //
49006f32e7eSjoerg // Nodes are never supposed to be empty, and it is invalid to store a node size
49106f32e7eSjoerg // of 0 in a NodeRef. The valid range of sizes is 1-64.
49206f32e7eSjoerg //
49306f32e7eSjoerg //===----------------------------------------------------------------------===//
49406f32e7eSjoerg 
49506f32e7eSjoerg class NodeRef {
49606f32e7eSjoerg   struct CacheAlignedPointerTraits {
getAsVoidPointerCacheAlignedPointerTraits49706f32e7eSjoerg     static inline void *getAsVoidPointer(void *P) { return P; }
getFromVoidPointerCacheAlignedPointerTraits49806f32e7eSjoerg     static inline void *getFromVoidPointer(void *P) { return P; }
499*da58b97aSjoerg     static constexpr int NumLowBitsAvailable = Log2CacheLine;
50006f32e7eSjoerg   };
50106f32e7eSjoerg   PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
50206f32e7eSjoerg 
50306f32e7eSjoerg public:
50406f32e7eSjoerg   /// NodeRef - Create a null ref.
50506f32e7eSjoerg   NodeRef() = default;
50606f32e7eSjoerg 
50706f32e7eSjoerg   /// operator bool - Detect a null ref.
50806f32e7eSjoerg   explicit operator bool() const { return pip.getOpaqueValue(); }
50906f32e7eSjoerg 
51006f32e7eSjoerg   /// NodeRef - Create a reference to the node p with n elements.
51106f32e7eSjoerg   template <typename NodeT>
NodeRef(NodeT * p,unsigned n)51206f32e7eSjoerg   NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) {
51306f32e7eSjoerg     assert(n <= NodeT::Capacity && "Size too big for node");
51406f32e7eSjoerg   }
51506f32e7eSjoerg 
51606f32e7eSjoerg   /// size - Return the number of elements in the referenced node.
size()51706f32e7eSjoerg   unsigned size() const { return pip.getInt() + 1; }
51806f32e7eSjoerg 
51906f32e7eSjoerg   /// setSize - Update the node size.
setSize(unsigned n)52006f32e7eSjoerg   void setSize(unsigned n) { pip.setInt(n - 1); }
52106f32e7eSjoerg 
52206f32e7eSjoerg   /// subtree - Access the i'th subtree reference in a branch node.
52306f32e7eSjoerg   /// This depends on branch nodes storing the NodeRef array as their first
52406f32e7eSjoerg   /// member.
subtree(unsigned i)52506f32e7eSjoerg   NodeRef &subtree(unsigned i) const {
52606f32e7eSjoerg     return reinterpret_cast<NodeRef*>(pip.getPointer())[i];
52706f32e7eSjoerg   }
52806f32e7eSjoerg 
52906f32e7eSjoerg   /// get - Dereference as a NodeT reference.
53006f32e7eSjoerg   template <typename NodeT>
get()53106f32e7eSjoerg   NodeT &get() const {
53206f32e7eSjoerg     return *reinterpret_cast<NodeT*>(pip.getPointer());
53306f32e7eSjoerg   }
53406f32e7eSjoerg 
53506f32e7eSjoerg   bool operator==(const NodeRef &RHS) const {
53606f32e7eSjoerg     if (pip == RHS.pip)
53706f32e7eSjoerg       return true;
53806f32e7eSjoerg     assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
53906f32e7eSjoerg     return false;
54006f32e7eSjoerg   }
54106f32e7eSjoerg 
54206f32e7eSjoerg   bool operator!=(const NodeRef &RHS) const {
54306f32e7eSjoerg     return !operator==(RHS);
54406f32e7eSjoerg   }
54506f32e7eSjoerg };
54606f32e7eSjoerg 
54706f32e7eSjoerg //===----------------------------------------------------------------------===//
54806f32e7eSjoerg //---                      IntervalMapImpl::LeafNode                       ---//
54906f32e7eSjoerg //===----------------------------------------------------------------------===//
55006f32e7eSjoerg //
55106f32e7eSjoerg // Leaf nodes store up to N disjoint intervals with corresponding values.
55206f32e7eSjoerg //
55306f32e7eSjoerg // The intervals are kept sorted and fully coalesced so there are no adjacent
55406f32e7eSjoerg // intervals mapping to the same value.
55506f32e7eSjoerg //
55606f32e7eSjoerg // These constraints are always satisfied:
55706f32e7eSjoerg //
55806f32e7eSjoerg // - Traits::stopLess(start(i), stop(i))    - Non-empty, sane intervals.
55906f32e7eSjoerg //
56006f32e7eSjoerg // - Traits::stopLess(stop(i), start(i + 1) - Sorted.
56106f32e7eSjoerg //
56206f32e7eSjoerg // - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1))
56306f32e7eSjoerg //                                          - Fully coalesced.
56406f32e7eSjoerg //
56506f32e7eSjoerg //===----------------------------------------------------------------------===//
56606f32e7eSjoerg 
56706f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
56806f32e7eSjoerg class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
56906f32e7eSjoerg public:
start(unsigned i)57006f32e7eSjoerg   const KeyT &start(unsigned i) const { return this->first[i].first; }
stop(unsigned i)57106f32e7eSjoerg   const KeyT &stop(unsigned i) const { return this->first[i].second; }
value(unsigned i)57206f32e7eSjoerg   const ValT &value(unsigned i) const { return this->second[i]; }
57306f32e7eSjoerg 
start(unsigned i)57406f32e7eSjoerg   KeyT &start(unsigned i) { return this->first[i].first; }
stop(unsigned i)57506f32e7eSjoerg   KeyT &stop(unsigned i) { return this->first[i].second; }
value(unsigned i)57606f32e7eSjoerg   ValT &value(unsigned i) { return this->second[i]; }
57706f32e7eSjoerg 
57806f32e7eSjoerg   /// findFrom - Find the first interval after i that may contain x.
57906f32e7eSjoerg   /// @param i    Starting index for the search.
58006f32e7eSjoerg   /// @param Size Number of elements in node.
58106f32e7eSjoerg   /// @param x    Key to search for.
58206f32e7eSjoerg   /// @return     First index with !stopLess(key[i].stop, x), or size.
58306f32e7eSjoerg   ///             This is the first interval that can possibly contain x.
findFrom(unsigned i,unsigned Size,KeyT x)58406f32e7eSjoerg   unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
58506f32e7eSjoerg     assert(i <= Size && Size <= N && "Bad indices");
58606f32e7eSjoerg     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
58706f32e7eSjoerg            "Index is past the needed point");
58806f32e7eSjoerg     while (i != Size && Traits::stopLess(stop(i), x)) ++i;
58906f32e7eSjoerg     return i;
59006f32e7eSjoerg   }
59106f32e7eSjoerg 
59206f32e7eSjoerg   /// safeFind - Find an interval that is known to exist. This is the same as
59306f32e7eSjoerg   /// findFrom except is it assumed that x is at least within range of the last
59406f32e7eSjoerg   /// interval.
59506f32e7eSjoerg   /// @param i Starting index for the search.
59606f32e7eSjoerg   /// @param x Key to search for.
59706f32e7eSjoerg   /// @return  First index with !stopLess(key[i].stop, x), never size.
59806f32e7eSjoerg   ///          This is the first interval that can possibly contain x.
safeFind(unsigned i,KeyT x)59906f32e7eSjoerg   unsigned safeFind(unsigned i, KeyT x) const {
60006f32e7eSjoerg     assert(i < N && "Bad index");
60106f32e7eSjoerg     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
60206f32e7eSjoerg            "Index is past the needed point");
60306f32e7eSjoerg     while (Traits::stopLess(stop(i), x)) ++i;
60406f32e7eSjoerg     assert(i < N && "Unsafe intervals");
60506f32e7eSjoerg     return i;
60606f32e7eSjoerg   }
60706f32e7eSjoerg 
60806f32e7eSjoerg   /// safeLookup - Lookup mapped value for a safe key.
60906f32e7eSjoerg   /// It is assumed that x is within range of the last entry.
61006f32e7eSjoerg   /// @param x        Key to search for.
61106f32e7eSjoerg   /// @param NotFound Value to return if x is not in any interval.
61206f32e7eSjoerg   /// @return         The mapped value at x or NotFound.
safeLookup(KeyT x,ValT NotFound)61306f32e7eSjoerg   ValT safeLookup(KeyT x, ValT NotFound) const {
61406f32e7eSjoerg     unsigned i = safeFind(0, x);
61506f32e7eSjoerg     return Traits::startLess(x, start(i)) ? NotFound : value(i);
61606f32e7eSjoerg   }
61706f32e7eSjoerg 
61806f32e7eSjoerg   unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y);
61906f32e7eSjoerg };
62006f32e7eSjoerg 
62106f32e7eSjoerg /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
62206f32e7eSjoerg /// possible. This may cause the node to grow by 1, or it may cause the node
62306f32e7eSjoerg /// to shrink because of coalescing.
62406f32e7eSjoerg /// @param Pos  Starting index = insertFrom(0, size, a)
62506f32e7eSjoerg /// @param Size Number of elements in node.
62606f32e7eSjoerg /// @param a    Interval start.
62706f32e7eSjoerg /// @param b    Interval stop.
62806f32e7eSjoerg /// @param y    Value be mapped.
62906f32e7eSjoerg /// @return     (insert position, new size), or (i, Capacity+1) on overflow.
63006f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
63106f32e7eSjoerg unsigned LeafNode<KeyT, ValT, N, Traits>::
insertFrom(unsigned & Pos,unsigned Size,KeyT a,KeyT b,ValT y)63206f32e7eSjoerg insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) {
63306f32e7eSjoerg   unsigned i = Pos;
63406f32e7eSjoerg   assert(i <= Size && Size <= N && "Invalid index");
63506f32e7eSjoerg   assert(!Traits::stopLess(b, a) && "Invalid interval");
63606f32e7eSjoerg 
63706f32e7eSjoerg   // Verify the findFrom invariant.
63806f32e7eSjoerg   assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
63906f32e7eSjoerg   assert((i == Size || !Traits::stopLess(stop(i), a)));
64006f32e7eSjoerg   assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert");
64106f32e7eSjoerg 
64206f32e7eSjoerg   // Coalesce with previous interval.
64306f32e7eSjoerg   if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) {
64406f32e7eSjoerg     Pos = i - 1;
64506f32e7eSjoerg     // Also coalesce with next interval?
64606f32e7eSjoerg     if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) {
64706f32e7eSjoerg       stop(i - 1) = stop(i);
64806f32e7eSjoerg       this->erase(i, Size);
64906f32e7eSjoerg       return Size - 1;
65006f32e7eSjoerg     }
65106f32e7eSjoerg     stop(i - 1) = b;
65206f32e7eSjoerg     return Size;
65306f32e7eSjoerg   }
65406f32e7eSjoerg 
65506f32e7eSjoerg   // Detect overflow.
65606f32e7eSjoerg   if (i == N)
65706f32e7eSjoerg     return N + 1;
65806f32e7eSjoerg 
65906f32e7eSjoerg   // Add new interval at end.
66006f32e7eSjoerg   if (i == Size) {
66106f32e7eSjoerg     start(i) = a;
66206f32e7eSjoerg     stop(i) = b;
66306f32e7eSjoerg     value(i) = y;
66406f32e7eSjoerg     return Size + 1;
66506f32e7eSjoerg   }
66606f32e7eSjoerg 
66706f32e7eSjoerg   // Try to coalesce with following interval.
66806f32e7eSjoerg   if (value(i) == y && Traits::adjacent(b, start(i))) {
66906f32e7eSjoerg     start(i) = a;
67006f32e7eSjoerg     return Size;
67106f32e7eSjoerg   }
67206f32e7eSjoerg 
67306f32e7eSjoerg   // We must insert before i. Detect overflow.
67406f32e7eSjoerg   if (Size == N)
67506f32e7eSjoerg     return N + 1;
67606f32e7eSjoerg 
67706f32e7eSjoerg   // Insert before i.
67806f32e7eSjoerg   this->shift(i, Size);
67906f32e7eSjoerg   start(i) = a;
68006f32e7eSjoerg   stop(i) = b;
68106f32e7eSjoerg   value(i) = y;
68206f32e7eSjoerg   return Size + 1;
68306f32e7eSjoerg }
68406f32e7eSjoerg 
68506f32e7eSjoerg //===----------------------------------------------------------------------===//
68606f32e7eSjoerg //---                   IntervalMapImpl::BranchNode                        ---//
68706f32e7eSjoerg //===----------------------------------------------------------------------===//
68806f32e7eSjoerg //
68906f32e7eSjoerg // A branch node stores references to 1--N subtrees all of the same height.
69006f32e7eSjoerg //
69106f32e7eSjoerg // The key array in a branch node holds the rightmost stop key of each subtree.
69206f32e7eSjoerg // It is redundant to store the last stop key since it can be found in the
69306f32e7eSjoerg // parent node, but doing so makes tree balancing a lot simpler.
69406f32e7eSjoerg //
69506f32e7eSjoerg // It is unusual for a branch node to only have one subtree, but it can happen
69606f32e7eSjoerg // in the root node if it is smaller than the normal nodes.
69706f32e7eSjoerg //
69806f32e7eSjoerg // When all of the leaf nodes from all the subtrees are concatenated, they must
69906f32e7eSjoerg // satisfy the same constraints as a single leaf node. They must be sorted,
70006f32e7eSjoerg // sane, and fully coalesced.
70106f32e7eSjoerg //
70206f32e7eSjoerg //===----------------------------------------------------------------------===//
70306f32e7eSjoerg 
70406f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
70506f32e7eSjoerg class BranchNode : public NodeBase<NodeRef, KeyT, N> {
70606f32e7eSjoerg public:
stop(unsigned i)70706f32e7eSjoerg   const KeyT &stop(unsigned i) const { return this->second[i]; }
subtree(unsigned i)70806f32e7eSjoerg   const NodeRef &subtree(unsigned i) const { return this->first[i]; }
70906f32e7eSjoerg 
stop(unsigned i)71006f32e7eSjoerg   KeyT &stop(unsigned i) { return this->second[i]; }
subtree(unsigned i)71106f32e7eSjoerg   NodeRef &subtree(unsigned i) { return this->first[i]; }
71206f32e7eSjoerg 
71306f32e7eSjoerg   /// findFrom - Find the first subtree after i that may contain x.
71406f32e7eSjoerg   /// @param i    Starting index for the search.
71506f32e7eSjoerg   /// @param Size Number of elements in node.
71606f32e7eSjoerg   /// @param x    Key to search for.
71706f32e7eSjoerg   /// @return     First index with !stopLess(key[i], x), or size.
71806f32e7eSjoerg   ///             This is the first subtree that can possibly contain x.
findFrom(unsigned i,unsigned Size,KeyT x)71906f32e7eSjoerg   unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
72006f32e7eSjoerg     assert(i <= Size && Size <= N && "Bad indices");
72106f32e7eSjoerg     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
72206f32e7eSjoerg            "Index to findFrom is past the needed point");
72306f32e7eSjoerg     while (i != Size && Traits::stopLess(stop(i), x)) ++i;
72406f32e7eSjoerg     return i;
72506f32e7eSjoerg   }
72606f32e7eSjoerg 
72706f32e7eSjoerg   /// safeFind - Find a subtree that is known to exist. This is the same as
72806f32e7eSjoerg   /// findFrom except is it assumed that x is in range.
72906f32e7eSjoerg   /// @param i Starting index for the search.
73006f32e7eSjoerg   /// @param x Key to search for.
73106f32e7eSjoerg   /// @return  First index with !stopLess(key[i], x), never size.
73206f32e7eSjoerg   ///          This is the first subtree that can possibly contain x.
safeFind(unsigned i,KeyT x)73306f32e7eSjoerg   unsigned safeFind(unsigned i, KeyT x) const {
73406f32e7eSjoerg     assert(i < N && "Bad index");
73506f32e7eSjoerg     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
73606f32e7eSjoerg            "Index is past the needed point");
73706f32e7eSjoerg     while (Traits::stopLess(stop(i), x)) ++i;
73806f32e7eSjoerg     assert(i < N && "Unsafe intervals");
73906f32e7eSjoerg     return i;
74006f32e7eSjoerg   }
74106f32e7eSjoerg 
74206f32e7eSjoerg   /// safeLookup - Get the subtree containing x, Assuming that x is in range.
74306f32e7eSjoerg   /// @param x Key to search for.
74406f32e7eSjoerg   /// @return  Subtree containing x
safeLookup(KeyT x)74506f32e7eSjoerg   NodeRef safeLookup(KeyT x) const {
74606f32e7eSjoerg     return subtree(safeFind(0, x));
74706f32e7eSjoerg   }
74806f32e7eSjoerg 
74906f32e7eSjoerg   /// insert - Insert a new (subtree, stop) pair.
75006f32e7eSjoerg   /// @param i    Insert position, following entries will be shifted.
75106f32e7eSjoerg   /// @param Size Number of elements in node.
75206f32e7eSjoerg   /// @param Node Subtree to insert.
75306f32e7eSjoerg   /// @param Stop Last key in subtree.
insert(unsigned i,unsigned Size,NodeRef Node,KeyT Stop)75406f32e7eSjoerg   void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) {
75506f32e7eSjoerg     assert(Size < N && "branch node overflow");
75606f32e7eSjoerg     assert(i <= Size && "Bad insert position");
75706f32e7eSjoerg     this->shift(i, Size);
75806f32e7eSjoerg     subtree(i) = Node;
75906f32e7eSjoerg     stop(i) = Stop;
76006f32e7eSjoerg   }
76106f32e7eSjoerg };
76206f32e7eSjoerg 
76306f32e7eSjoerg //===----------------------------------------------------------------------===//
76406f32e7eSjoerg //---                         IntervalMapImpl::Path                        ---//
76506f32e7eSjoerg //===----------------------------------------------------------------------===//
76606f32e7eSjoerg //
76706f32e7eSjoerg // A Path is used by iterators to represent a position in a B+-tree, and the
76806f32e7eSjoerg // path to get there from the root.
76906f32e7eSjoerg //
77006f32e7eSjoerg // The Path class also contains the tree navigation code that doesn't have to
77106f32e7eSjoerg // be templatized.
77206f32e7eSjoerg //
77306f32e7eSjoerg //===----------------------------------------------------------------------===//
77406f32e7eSjoerg 
77506f32e7eSjoerg class Path {
77606f32e7eSjoerg   /// Entry - Each step in the path is a node pointer and an offset into that
77706f32e7eSjoerg   /// node.
77806f32e7eSjoerg   struct Entry {
77906f32e7eSjoerg     void *node;
78006f32e7eSjoerg     unsigned size;
78106f32e7eSjoerg     unsigned offset;
78206f32e7eSjoerg 
EntryEntry78306f32e7eSjoerg     Entry(void *Node, unsigned Size, unsigned Offset)
78406f32e7eSjoerg       : node(Node), size(Size), offset(Offset) {}
78506f32e7eSjoerg 
EntryEntry78606f32e7eSjoerg     Entry(NodeRef Node, unsigned Offset)
78706f32e7eSjoerg       : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {}
78806f32e7eSjoerg 
subtreeEntry78906f32e7eSjoerg     NodeRef &subtree(unsigned i) const {
79006f32e7eSjoerg       return reinterpret_cast<NodeRef*>(node)[i];
79106f32e7eSjoerg     }
79206f32e7eSjoerg   };
79306f32e7eSjoerg 
79406f32e7eSjoerg   /// path - The path entries, path[0] is the root node, path.back() is a leaf.
79506f32e7eSjoerg   SmallVector<Entry, 4> path;
79606f32e7eSjoerg 
79706f32e7eSjoerg public:
79806f32e7eSjoerg   // Node accessors.
node(unsigned Level)79906f32e7eSjoerg   template <typename NodeT> NodeT &node(unsigned Level) const {
80006f32e7eSjoerg     return *reinterpret_cast<NodeT*>(path[Level].node);
80106f32e7eSjoerg   }
size(unsigned Level)80206f32e7eSjoerg   unsigned size(unsigned Level) const { return path[Level].size; }
offset(unsigned Level)80306f32e7eSjoerg   unsigned offset(unsigned Level) const { return path[Level].offset; }
offset(unsigned Level)80406f32e7eSjoerg   unsigned &offset(unsigned Level) { return path[Level].offset; }
80506f32e7eSjoerg 
80606f32e7eSjoerg   // Leaf accessors.
leaf()80706f32e7eSjoerg   template <typename NodeT> NodeT &leaf() const {
80806f32e7eSjoerg     return *reinterpret_cast<NodeT*>(path.back().node);
80906f32e7eSjoerg   }
leafSize()81006f32e7eSjoerg   unsigned leafSize() const { return path.back().size; }
leafOffset()81106f32e7eSjoerg   unsigned leafOffset() const { return path.back().offset; }
leafOffset()81206f32e7eSjoerg   unsigned &leafOffset() { return path.back().offset; }
81306f32e7eSjoerg 
81406f32e7eSjoerg   /// valid - Return true if path is at a valid node, not at end().
valid()81506f32e7eSjoerg   bool valid() const {
81606f32e7eSjoerg     return !path.empty() && path.front().offset < path.front().size;
81706f32e7eSjoerg   }
81806f32e7eSjoerg 
81906f32e7eSjoerg   /// height - Return the height of the tree corresponding to this path.
82006f32e7eSjoerg   /// This matches map->height in a full path.
height()82106f32e7eSjoerg   unsigned height() const { return path.size() - 1; }
82206f32e7eSjoerg 
82306f32e7eSjoerg   /// subtree - Get the subtree referenced from Level. When the path is
82406f32e7eSjoerg   /// consistent, node(Level + 1) == subtree(Level).
82506f32e7eSjoerg   /// @param Level 0..height-1. The leaves have no subtrees.
subtree(unsigned Level)82606f32e7eSjoerg   NodeRef &subtree(unsigned Level) const {
82706f32e7eSjoerg     return path[Level].subtree(path[Level].offset);
82806f32e7eSjoerg   }
82906f32e7eSjoerg 
83006f32e7eSjoerg   /// reset - Reset cached information about node(Level) from subtree(Level -1).
831*da58b97aSjoerg   /// @param Level 1..height. The node to update after parent node changed.
reset(unsigned Level)83206f32e7eSjoerg   void reset(unsigned Level) {
83306f32e7eSjoerg     path[Level] = Entry(subtree(Level - 1), offset(Level));
83406f32e7eSjoerg   }
83506f32e7eSjoerg 
83606f32e7eSjoerg   /// push - Add entry to path.
83706f32e7eSjoerg   /// @param Node Node to add, should be subtree(path.size()-1).
83806f32e7eSjoerg   /// @param Offset Offset into Node.
push(NodeRef Node,unsigned Offset)83906f32e7eSjoerg   void push(NodeRef Node, unsigned Offset) {
84006f32e7eSjoerg     path.push_back(Entry(Node, Offset));
84106f32e7eSjoerg   }
84206f32e7eSjoerg 
84306f32e7eSjoerg   /// pop - Remove the last path entry.
pop()84406f32e7eSjoerg   void pop() {
84506f32e7eSjoerg     path.pop_back();
84606f32e7eSjoerg   }
84706f32e7eSjoerg 
84806f32e7eSjoerg   /// setSize - Set the size of a node both in the path and in the tree.
84906f32e7eSjoerg   /// @param Level 0..height. Note that setting the root size won't change
85006f32e7eSjoerg   ///              map->rootSize.
85106f32e7eSjoerg   /// @param Size New node size.
setSize(unsigned Level,unsigned Size)85206f32e7eSjoerg   void setSize(unsigned Level, unsigned Size) {
85306f32e7eSjoerg     path[Level].size = Size;
85406f32e7eSjoerg     if (Level)
85506f32e7eSjoerg       subtree(Level - 1).setSize(Size);
85606f32e7eSjoerg   }
85706f32e7eSjoerg 
85806f32e7eSjoerg   /// setRoot - Clear the path and set a new root node.
85906f32e7eSjoerg   /// @param Node New root node.
86006f32e7eSjoerg   /// @param Size New root size.
86106f32e7eSjoerg   /// @param Offset Offset into root node.
setRoot(void * Node,unsigned Size,unsigned Offset)86206f32e7eSjoerg   void setRoot(void *Node, unsigned Size, unsigned Offset) {
86306f32e7eSjoerg     path.clear();
86406f32e7eSjoerg     path.push_back(Entry(Node, Size, Offset));
86506f32e7eSjoerg   }
86606f32e7eSjoerg 
86706f32e7eSjoerg   /// replaceRoot - Replace the current root node with two new entries after the
86806f32e7eSjoerg   /// tree height has increased.
86906f32e7eSjoerg   /// @param Root The new root node.
87006f32e7eSjoerg   /// @param Size Number of entries in the new root.
87106f32e7eSjoerg   /// @param Offsets Offsets into the root and first branch nodes.
87206f32e7eSjoerg   void replaceRoot(void *Root, unsigned Size, IdxPair Offsets);
87306f32e7eSjoerg 
87406f32e7eSjoerg   /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
87506f32e7eSjoerg   /// @param Level Get the sibling to node(Level).
87606f32e7eSjoerg   /// @return Left sibling, or NodeRef().
87706f32e7eSjoerg   NodeRef getLeftSibling(unsigned Level) const;
87806f32e7eSjoerg 
87906f32e7eSjoerg   /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level
88006f32e7eSjoerg   /// unaltered.
88106f32e7eSjoerg   /// @param Level Move node(Level).
88206f32e7eSjoerg   void moveLeft(unsigned Level);
88306f32e7eSjoerg 
88406f32e7eSjoerg   /// fillLeft - Grow path to Height by taking leftmost branches.
88506f32e7eSjoerg   /// @param Height The target height.
fillLeft(unsigned Height)88606f32e7eSjoerg   void fillLeft(unsigned Height) {
88706f32e7eSjoerg     while (height() < Height)
88806f32e7eSjoerg       push(subtree(height()), 0);
88906f32e7eSjoerg   }
89006f32e7eSjoerg 
89106f32e7eSjoerg   /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
892*da58b97aSjoerg   /// @param Level Get the sibling to node(Level).
89306f32e7eSjoerg   /// @return Left sibling, or NodeRef().
89406f32e7eSjoerg   NodeRef getRightSibling(unsigned Level) const;
89506f32e7eSjoerg 
89606f32e7eSjoerg   /// moveRight - Move path to the left sibling at Level. Leave nodes below
89706f32e7eSjoerg   /// Level unaltered.
89806f32e7eSjoerg   /// @param Level Move node(Level).
89906f32e7eSjoerg   void moveRight(unsigned Level);
90006f32e7eSjoerg 
90106f32e7eSjoerg   /// atBegin - Return true if path is at begin().
atBegin()90206f32e7eSjoerg   bool atBegin() const {
90306f32e7eSjoerg     for (unsigned i = 0, e = path.size(); i != e; ++i)
90406f32e7eSjoerg       if (path[i].offset != 0)
90506f32e7eSjoerg         return false;
90606f32e7eSjoerg     return true;
90706f32e7eSjoerg   }
90806f32e7eSjoerg 
90906f32e7eSjoerg   /// atLastEntry - Return true if the path is at the last entry of the node at
91006f32e7eSjoerg   /// Level.
91106f32e7eSjoerg   /// @param Level Node to examine.
atLastEntry(unsigned Level)91206f32e7eSjoerg   bool atLastEntry(unsigned Level) const {
91306f32e7eSjoerg     return path[Level].offset == path[Level].size - 1;
91406f32e7eSjoerg   }
91506f32e7eSjoerg 
91606f32e7eSjoerg   /// legalizeForInsert - Prepare the path for an insertion at Level. When the
91706f32e7eSjoerg   /// path is at end(), node(Level) may not be a legal node. legalizeForInsert
91806f32e7eSjoerg   /// ensures that node(Level) is real by moving back to the last node at Level,
91906f32e7eSjoerg   /// and setting offset(Level) to size(Level) if required.
92006f32e7eSjoerg   /// @param Level The level where an insertion is about to take place.
legalizeForInsert(unsigned Level)92106f32e7eSjoerg   void legalizeForInsert(unsigned Level) {
92206f32e7eSjoerg     if (valid())
92306f32e7eSjoerg       return;
92406f32e7eSjoerg     moveLeft(Level);
92506f32e7eSjoerg     ++path[Level].offset;
92606f32e7eSjoerg   }
92706f32e7eSjoerg };
92806f32e7eSjoerg 
92906f32e7eSjoerg } // end namespace IntervalMapImpl
93006f32e7eSjoerg 
93106f32e7eSjoerg //===----------------------------------------------------------------------===//
93206f32e7eSjoerg //---                          IntervalMap                                ----//
93306f32e7eSjoerg //===----------------------------------------------------------------------===//
93406f32e7eSjoerg 
93506f32e7eSjoerg template <typename KeyT, typename ValT,
93606f32e7eSjoerg           unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
93706f32e7eSjoerg           typename Traits = IntervalMapInfo<KeyT>>
93806f32e7eSjoerg class IntervalMap {
93906f32e7eSjoerg   using Sizer = IntervalMapImpl::NodeSizer<KeyT, ValT>;
94006f32e7eSjoerg   using Leaf = IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits>;
94106f32e7eSjoerg   using Branch =
94206f32e7eSjoerg       IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>;
94306f32e7eSjoerg   using RootLeaf = IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits>;
94406f32e7eSjoerg   using IdxPair = IntervalMapImpl::IdxPair;
94506f32e7eSjoerg 
94606f32e7eSjoerg   // The RootLeaf capacity is given as a template parameter. We must compute the
94706f32e7eSjoerg   // corresponding RootBranch capacity.
94806f32e7eSjoerg   enum {
94906f32e7eSjoerg     DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
95006f32e7eSjoerg       (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)),
95106f32e7eSjoerg     RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
95206f32e7eSjoerg   };
95306f32e7eSjoerg 
95406f32e7eSjoerg   using RootBranch =
95506f32e7eSjoerg       IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>;
95606f32e7eSjoerg 
95706f32e7eSjoerg   // When branched, we store a global start key as well as the branch node.
95806f32e7eSjoerg   struct RootBranchData {
95906f32e7eSjoerg     KeyT start;
96006f32e7eSjoerg     RootBranch node;
96106f32e7eSjoerg   };
96206f32e7eSjoerg 
96306f32e7eSjoerg public:
96406f32e7eSjoerg   using Allocator = typename Sizer::Allocator;
96506f32e7eSjoerg   using KeyType = KeyT;
96606f32e7eSjoerg   using ValueType = ValT;
96706f32e7eSjoerg   using KeyTraits = Traits;
96806f32e7eSjoerg 
96906f32e7eSjoerg private:
97006f32e7eSjoerg   // The root data is either a RootLeaf or a RootBranchData instance.
97106f32e7eSjoerg   AlignedCharArrayUnion<RootLeaf, RootBranchData> data;
97206f32e7eSjoerg 
97306f32e7eSjoerg   // Tree height.
97406f32e7eSjoerg   // 0: Leaves in root.
97506f32e7eSjoerg   // 1: Root points to leaf.
97606f32e7eSjoerg   // 2: root->branch->leaf ...
97706f32e7eSjoerg   unsigned height;
97806f32e7eSjoerg 
97906f32e7eSjoerg   // Number of entries in the root node.
98006f32e7eSjoerg   unsigned rootSize;
98106f32e7eSjoerg 
98206f32e7eSjoerg   // Allocator used for creating external nodes.
98306f32e7eSjoerg   Allocator &allocator;
98406f32e7eSjoerg 
98506f32e7eSjoerg   /// Represent data as a node type without breaking aliasing rules.
dataAs()986*da58b97aSjoerg   template <typename T> T &dataAs() const { return *bit_cast<T *>(&data); }
98706f32e7eSjoerg 
rootLeaf()98806f32e7eSjoerg   const RootLeaf &rootLeaf() const {
98906f32e7eSjoerg     assert(!branched() && "Cannot acces leaf data in branched root");
99006f32e7eSjoerg     return dataAs<RootLeaf>();
99106f32e7eSjoerg   }
rootLeaf()99206f32e7eSjoerg   RootLeaf &rootLeaf() {
99306f32e7eSjoerg     assert(!branched() && "Cannot acces leaf data in branched root");
99406f32e7eSjoerg     return dataAs<RootLeaf>();
99506f32e7eSjoerg   }
99606f32e7eSjoerg 
rootBranchData()99706f32e7eSjoerg   RootBranchData &rootBranchData() const {
99806f32e7eSjoerg     assert(branched() && "Cannot access branch data in non-branched root");
99906f32e7eSjoerg     return dataAs<RootBranchData>();
100006f32e7eSjoerg   }
rootBranchData()100106f32e7eSjoerg   RootBranchData &rootBranchData() {
100206f32e7eSjoerg     assert(branched() && "Cannot access branch data in non-branched root");
100306f32e7eSjoerg     return dataAs<RootBranchData>();
100406f32e7eSjoerg   }
100506f32e7eSjoerg 
rootBranch()100606f32e7eSjoerg   const RootBranch &rootBranch() const { return rootBranchData().node; }
rootBranch()100706f32e7eSjoerg   RootBranch &rootBranch()             { return rootBranchData().node; }
rootBranchStart()100806f32e7eSjoerg   KeyT rootBranchStart() const { return rootBranchData().start; }
rootBranchStart()100906f32e7eSjoerg   KeyT &rootBranchStart()      { return rootBranchData().start; }
101006f32e7eSjoerg 
newNode()101106f32e7eSjoerg   template <typename NodeT> NodeT *newNode() {
101206f32e7eSjoerg     return new(allocator.template Allocate<NodeT>()) NodeT();
101306f32e7eSjoerg   }
101406f32e7eSjoerg 
deleteNode(NodeT * P)101506f32e7eSjoerg   template <typename NodeT> void deleteNode(NodeT *P) {
101606f32e7eSjoerg     P->~NodeT();
101706f32e7eSjoerg     allocator.Deallocate(P);
101806f32e7eSjoerg   }
101906f32e7eSjoerg 
102006f32e7eSjoerg   IdxPair branchRoot(unsigned Position);
102106f32e7eSjoerg   IdxPair splitRoot(unsigned Position);
102206f32e7eSjoerg 
switchRootToBranch()102306f32e7eSjoerg   void switchRootToBranch() {
102406f32e7eSjoerg     rootLeaf().~RootLeaf();
102506f32e7eSjoerg     height = 1;
102606f32e7eSjoerg     new (&rootBranchData()) RootBranchData();
102706f32e7eSjoerg   }
102806f32e7eSjoerg 
switchRootToLeaf()102906f32e7eSjoerg   void switchRootToLeaf() {
103006f32e7eSjoerg     rootBranchData().~RootBranchData();
103106f32e7eSjoerg     height = 0;
103206f32e7eSjoerg     new(&rootLeaf()) RootLeaf();
103306f32e7eSjoerg   }
103406f32e7eSjoerg 
branched()103506f32e7eSjoerg   bool branched() const { return height > 0; }
103606f32e7eSjoerg 
103706f32e7eSjoerg   ValT treeSafeLookup(KeyT x, ValT NotFound) const;
103806f32e7eSjoerg   void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef,
103906f32e7eSjoerg                   unsigned Level));
104006f32e7eSjoerg   void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level);
104106f32e7eSjoerg 
104206f32e7eSjoerg public:
IntervalMap(Allocator & a)104306f32e7eSjoerg   explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
1044*da58b97aSjoerg     assert((uintptr_t(&data) & (alignof(RootLeaf) - 1)) == 0 &&
104506f32e7eSjoerg            "Insufficient alignment");
104606f32e7eSjoerg     new(&rootLeaf()) RootLeaf();
104706f32e7eSjoerg   }
104806f32e7eSjoerg 
~IntervalMap()104906f32e7eSjoerg   ~IntervalMap() {
105006f32e7eSjoerg     clear();
105106f32e7eSjoerg     rootLeaf().~RootLeaf();
105206f32e7eSjoerg   }
105306f32e7eSjoerg 
105406f32e7eSjoerg   /// empty -  Return true when no intervals are mapped.
empty()105506f32e7eSjoerg   bool empty() const {
105606f32e7eSjoerg     return rootSize == 0;
105706f32e7eSjoerg   }
105806f32e7eSjoerg 
105906f32e7eSjoerg   /// start - Return the smallest mapped key in a non-empty map.
start()106006f32e7eSjoerg   KeyT start() const {
106106f32e7eSjoerg     assert(!empty() && "Empty IntervalMap has no start");
106206f32e7eSjoerg     return !branched() ? rootLeaf().start(0) : rootBranchStart();
106306f32e7eSjoerg   }
106406f32e7eSjoerg 
106506f32e7eSjoerg   /// stop - Return the largest mapped key in a non-empty map.
stop()106606f32e7eSjoerg   KeyT stop() const {
106706f32e7eSjoerg     assert(!empty() && "Empty IntervalMap has no stop");
106806f32e7eSjoerg     return !branched() ? rootLeaf().stop(rootSize - 1) :
106906f32e7eSjoerg                          rootBranch().stop(rootSize - 1);
107006f32e7eSjoerg   }
107106f32e7eSjoerg 
107206f32e7eSjoerg   /// lookup - Return the mapped value at x or NotFound.
107306f32e7eSjoerg   ValT lookup(KeyT x, ValT NotFound = ValT()) const {
107406f32e7eSjoerg     if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
107506f32e7eSjoerg       return NotFound;
107606f32e7eSjoerg     return branched() ? treeSafeLookup(x, NotFound) :
107706f32e7eSjoerg                         rootLeaf().safeLookup(x, NotFound);
107806f32e7eSjoerg   }
107906f32e7eSjoerg 
108006f32e7eSjoerg   /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
108106f32e7eSjoerg   /// It is assumed that no key in the interval is mapped to another value, but
108206f32e7eSjoerg   /// overlapping intervals already mapped to y will be coalesced.
insert(KeyT a,KeyT b,ValT y)108306f32e7eSjoerg   void insert(KeyT a, KeyT b, ValT y) {
108406f32e7eSjoerg     if (branched() || rootSize == RootLeaf::Capacity)
108506f32e7eSjoerg       return find(a).insert(a, b, y);
108606f32e7eSjoerg 
108706f32e7eSjoerg     // Easy insert into root leaf.
108806f32e7eSjoerg     unsigned p = rootLeaf().findFrom(0, rootSize, a);
108906f32e7eSjoerg     rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y);
109006f32e7eSjoerg   }
109106f32e7eSjoerg 
109206f32e7eSjoerg   /// clear - Remove all entries.
109306f32e7eSjoerg   void clear();
109406f32e7eSjoerg 
109506f32e7eSjoerg   class const_iterator;
109606f32e7eSjoerg   class iterator;
109706f32e7eSjoerg   friend class const_iterator;
109806f32e7eSjoerg   friend class iterator;
109906f32e7eSjoerg 
begin()110006f32e7eSjoerg   const_iterator begin() const {
110106f32e7eSjoerg     const_iterator I(*this);
110206f32e7eSjoerg     I.goToBegin();
110306f32e7eSjoerg     return I;
110406f32e7eSjoerg   }
110506f32e7eSjoerg 
begin()110606f32e7eSjoerg   iterator begin() {
110706f32e7eSjoerg     iterator I(*this);
110806f32e7eSjoerg     I.goToBegin();
110906f32e7eSjoerg     return I;
111006f32e7eSjoerg   }
111106f32e7eSjoerg 
end()111206f32e7eSjoerg   const_iterator end() const {
111306f32e7eSjoerg     const_iterator I(*this);
111406f32e7eSjoerg     I.goToEnd();
111506f32e7eSjoerg     return I;
111606f32e7eSjoerg   }
111706f32e7eSjoerg 
end()111806f32e7eSjoerg   iterator end() {
111906f32e7eSjoerg     iterator I(*this);
112006f32e7eSjoerg     I.goToEnd();
112106f32e7eSjoerg     return I;
112206f32e7eSjoerg   }
112306f32e7eSjoerg 
112406f32e7eSjoerg   /// find - Return an iterator pointing to the first interval ending at or
112506f32e7eSjoerg   /// after x, or end().
find(KeyT x)112606f32e7eSjoerg   const_iterator find(KeyT x) const {
112706f32e7eSjoerg     const_iterator I(*this);
112806f32e7eSjoerg     I.find(x);
112906f32e7eSjoerg     return I;
113006f32e7eSjoerg   }
113106f32e7eSjoerg 
find(KeyT x)113206f32e7eSjoerg   iterator find(KeyT x) {
113306f32e7eSjoerg     iterator I(*this);
113406f32e7eSjoerg     I.find(x);
113506f32e7eSjoerg     return I;
113606f32e7eSjoerg   }
113706f32e7eSjoerg 
113806f32e7eSjoerg   /// overlaps(a, b) - Return true if the intervals in this map overlap with the
113906f32e7eSjoerg   /// interval [a;b].
overlaps(KeyT a,KeyT b)114006f32e7eSjoerg   bool overlaps(KeyT a, KeyT b) {
114106f32e7eSjoerg     assert(Traits::nonEmpty(a, b));
114206f32e7eSjoerg     const_iterator I = find(a);
114306f32e7eSjoerg     if (!I.valid())
114406f32e7eSjoerg       return false;
114506f32e7eSjoerg     // [a;b] and [x;y] overlap iff x<=b and a<=y. The find() call guarantees the
114606f32e7eSjoerg     // second part (y = find(a).stop()), so it is sufficient to check the first
114706f32e7eSjoerg     // one.
114806f32e7eSjoerg     return !Traits::stopLess(b, I.start());
114906f32e7eSjoerg   }
115006f32e7eSjoerg };
115106f32e7eSjoerg 
115206f32e7eSjoerg /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
115306f32e7eSjoerg /// branched root.
115406f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
115506f32e7eSjoerg ValT IntervalMap<KeyT, ValT, N, Traits>::
treeSafeLookup(KeyT x,ValT NotFound)115606f32e7eSjoerg treeSafeLookup(KeyT x, ValT NotFound) const {
115706f32e7eSjoerg   assert(branched() && "treeLookup assumes a branched root");
115806f32e7eSjoerg 
115906f32e7eSjoerg   IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x);
116006f32e7eSjoerg   for (unsigned h = height-1; h; --h)
116106f32e7eSjoerg     NR = NR.get<Branch>().safeLookup(x);
116206f32e7eSjoerg   return NR.get<Leaf>().safeLookup(x, NotFound);
116306f32e7eSjoerg }
116406f32e7eSjoerg 
116506f32e7eSjoerg // branchRoot - Switch from a leaf root to a branched root.
116606f32e7eSjoerg // Return the new (root offset, node offset) corresponding to Position.
116706f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
116806f32e7eSjoerg IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
branchRoot(unsigned Position)116906f32e7eSjoerg branchRoot(unsigned Position) {
117006f32e7eSjoerg   using namespace IntervalMapImpl;
117106f32e7eSjoerg   // How many external leaf nodes to hold RootLeaf+1?
117206f32e7eSjoerg   const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
117306f32e7eSjoerg 
117406f32e7eSjoerg   // Compute element distribution among new nodes.
117506f32e7eSjoerg   unsigned size[Nodes];
117606f32e7eSjoerg   IdxPair NewOffset(0, Position);
117706f32e7eSjoerg 
117806f32e7eSjoerg   // Is is very common for the root node to be smaller than external nodes.
117906f32e7eSjoerg   if (Nodes == 1)
118006f32e7eSjoerg     size[0] = rootSize;
118106f32e7eSjoerg   else
118206f32e7eSjoerg     NewOffset = distribute(Nodes, rootSize, Leaf::Capacity,  nullptr, size,
118306f32e7eSjoerg                            Position, true);
118406f32e7eSjoerg 
118506f32e7eSjoerg   // Allocate new nodes.
118606f32e7eSjoerg   unsigned pos = 0;
118706f32e7eSjoerg   NodeRef node[Nodes];
118806f32e7eSjoerg   for (unsigned n = 0; n != Nodes; ++n) {
118906f32e7eSjoerg     Leaf *L = newNode<Leaf>();
119006f32e7eSjoerg     L->copy(rootLeaf(), pos, 0, size[n]);
119106f32e7eSjoerg     node[n] = NodeRef(L, size[n]);
119206f32e7eSjoerg     pos += size[n];
119306f32e7eSjoerg   }
119406f32e7eSjoerg 
119506f32e7eSjoerg   // Destroy the old leaf node, construct branch node instead.
119606f32e7eSjoerg   switchRootToBranch();
119706f32e7eSjoerg   for (unsigned n = 0; n != Nodes; ++n) {
119806f32e7eSjoerg     rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1);
119906f32e7eSjoerg     rootBranch().subtree(n) = node[n];
120006f32e7eSjoerg   }
120106f32e7eSjoerg   rootBranchStart() = node[0].template get<Leaf>().start(0);
120206f32e7eSjoerg   rootSize = Nodes;
120306f32e7eSjoerg   return NewOffset;
120406f32e7eSjoerg }
120506f32e7eSjoerg 
120606f32e7eSjoerg // splitRoot - Split the current BranchRoot into multiple Branch nodes.
120706f32e7eSjoerg // Return the new (root offset, node offset) corresponding to Position.
120806f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
120906f32e7eSjoerg IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
splitRoot(unsigned Position)121006f32e7eSjoerg splitRoot(unsigned Position) {
121106f32e7eSjoerg   using namespace IntervalMapImpl;
121206f32e7eSjoerg   // How many external leaf nodes to hold RootBranch+1?
121306f32e7eSjoerg   const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
121406f32e7eSjoerg 
121506f32e7eSjoerg   // Compute element distribution among new nodes.
121606f32e7eSjoerg   unsigned Size[Nodes];
121706f32e7eSjoerg   IdxPair NewOffset(0, Position);
121806f32e7eSjoerg 
121906f32e7eSjoerg   // Is is very common for the root node to be smaller than external nodes.
122006f32e7eSjoerg   if (Nodes == 1)
122106f32e7eSjoerg     Size[0] = rootSize;
122206f32e7eSjoerg   else
122306f32e7eSjoerg     NewOffset = distribute(Nodes, rootSize, Leaf::Capacity,  nullptr, Size,
122406f32e7eSjoerg                            Position, true);
122506f32e7eSjoerg 
122606f32e7eSjoerg   // Allocate new nodes.
122706f32e7eSjoerg   unsigned Pos = 0;
122806f32e7eSjoerg   NodeRef Node[Nodes];
122906f32e7eSjoerg   for (unsigned n = 0; n != Nodes; ++n) {
123006f32e7eSjoerg     Branch *B = newNode<Branch>();
123106f32e7eSjoerg     B->copy(rootBranch(), Pos, 0, Size[n]);
123206f32e7eSjoerg     Node[n] = NodeRef(B, Size[n]);
123306f32e7eSjoerg     Pos += Size[n];
123406f32e7eSjoerg   }
123506f32e7eSjoerg 
123606f32e7eSjoerg   for (unsigned n = 0; n != Nodes; ++n) {
123706f32e7eSjoerg     rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1);
123806f32e7eSjoerg     rootBranch().subtree(n) = Node[n];
123906f32e7eSjoerg   }
124006f32e7eSjoerg   rootSize = Nodes;
124106f32e7eSjoerg   ++height;
124206f32e7eSjoerg   return NewOffset;
124306f32e7eSjoerg }
124406f32e7eSjoerg 
124506f32e7eSjoerg /// visitNodes - Visit each external node.
124606f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
124706f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
visitNodes(void (IntervalMap::* f)(IntervalMapImpl::NodeRef,unsigned Height))124806f32e7eSjoerg visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) {
124906f32e7eSjoerg   if (!branched())
125006f32e7eSjoerg     return;
125106f32e7eSjoerg   SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs;
125206f32e7eSjoerg 
125306f32e7eSjoerg   // Collect level 0 nodes from the root.
125406f32e7eSjoerg   for (unsigned i = 0; i != rootSize; ++i)
125506f32e7eSjoerg     Refs.push_back(rootBranch().subtree(i));
125606f32e7eSjoerg 
125706f32e7eSjoerg   // Visit all branch nodes.
125806f32e7eSjoerg   for (unsigned h = height - 1; h; --h) {
125906f32e7eSjoerg     for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
126006f32e7eSjoerg       for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
126106f32e7eSjoerg         NextRefs.push_back(Refs[i].subtree(j));
126206f32e7eSjoerg       (this->*f)(Refs[i], h);
126306f32e7eSjoerg     }
126406f32e7eSjoerg     Refs.clear();
126506f32e7eSjoerg     Refs.swap(NextRefs);
126606f32e7eSjoerg   }
126706f32e7eSjoerg 
126806f32e7eSjoerg   // Visit all leaf nodes.
126906f32e7eSjoerg   for (unsigned i = 0, e = Refs.size(); i != e; ++i)
127006f32e7eSjoerg     (this->*f)(Refs[i], 0);
127106f32e7eSjoerg }
127206f32e7eSjoerg 
127306f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
127406f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
deleteNode(IntervalMapImpl::NodeRef Node,unsigned Level)127506f32e7eSjoerg deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) {
127606f32e7eSjoerg   if (Level)
127706f32e7eSjoerg     deleteNode(&Node.get<Branch>());
127806f32e7eSjoerg   else
127906f32e7eSjoerg     deleteNode(&Node.get<Leaf>());
128006f32e7eSjoerg }
128106f32e7eSjoerg 
128206f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
128306f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
clear()128406f32e7eSjoerg clear() {
128506f32e7eSjoerg   if (branched()) {
128606f32e7eSjoerg     visitNodes(&IntervalMap::deleteNode);
128706f32e7eSjoerg     switchRootToLeaf();
128806f32e7eSjoerg   }
128906f32e7eSjoerg   rootSize = 0;
129006f32e7eSjoerg }
129106f32e7eSjoerg 
129206f32e7eSjoerg //===----------------------------------------------------------------------===//
129306f32e7eSjoerg //---                   IntervalMap::const_iterator                       ----//
129406f32e7eSjoerg //===----------------------------------------------------------------------===//
129506f32e7eSjoerg 
129606f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
1297*da58b97aSjoerg class IntervalMap<KeyT, ValT, N, Traits>::const_iterator {
129806f32e7eSjoerg   friend class IntervalMap;
129906f32e7eSjoerg 
1300*da58b97aSjoerg public:
1301*da58b97aSjoerg   using iterator_category = std::bidirectional_iterator_tag;
1302*da58b97aSjoerg   using value_type = ValT;
1303*da58b97aSjoerg   using difference_type = std::ptrdiff_t;
1304*da58b97aSjoerg   using pointer = value_type *;
1305*da58b97aSjoerg   using reference = value_type &;
1306*da58b97aSjoerg 
1307*da58b97aSjoerg protected:
130806f32e7eSjoerg   // The map referred to.
130906f32e7eSjoerg   IntervalMap *map = nullptr;
131006f32e7eSjoerg 
131106f32e7eSjoerg   // We store a full path from the root to the current position.
131206f32e7eSjoerg   // The path may be partially filled, but never between iterator calls.
131306f32e7eSjoerg   IntervalMapImpl::Path path;
131406f32e7eSjoerg 
const_iterator(const IntervalMap & map)131506f32e7eSjoerg   explicit const_iterator(const IntervalMap &map) :
131606f32e7eSjoerg     map(const_cast<IntervalMap*>(&map)) {}
131706f32e7eSjoerg 
branched()131806f32e7eSjoerg   bool branched() const {
131906f32e7eSjoerg     assert(map && "Invalid iterator");
132006f32e7eSjoerg     return map->branched();
132106f32e7eSjoerg   }
132206f32e7eSjoerg 
setRoot(unsigned Offset)132306f32e7eSjoerg   void setRoot(unsigned Offset) {
132406f32e7eSjoerg     if (branched())
132506f32e7eSjoerg       path.setRoot(&map->rootBranch(), map->rootSize, Offset);
132606f32e7eSjoerg     else
132706f32e7eSjoerg       path.setRoot(&map->rootLeaf(), map->rootSize, Offset);
132806f32e7eSjoerg   }
132906f32e7eSjoerg 
133006f32e7eSjoerg   void pathFillFind(KeyT x);
133106f32e7eSjoerg   void treeFind(KeyT x);
133206f32e7eSjoerg   void treeAdvanceTo(KeyT x);
133306f32e7eSjoerg 
133406f32e7eSjoerg   /// unsafeStart - Writable access to start() for iterator.
unsafeStart()133506f32e7eSjoerg   KeyT &unsafeStart() const {
133606f32e7eSjoerg     assert(valid() && "Cannot access invalid iterator");
133706f32e7eSjoerg     return branched() ? path.leaf<Leaf>().start(path.leafOffset()) :
133806f32e7eSjoerg                         path.leaf<RootLeaf>().start(path.leafOffset());
133906f32e7eSjoerg   }
134006f32e7eSjoerg 
134106f32e7eSjoerg   /// unsafeStop - Writable access to stop() for iterator.
unsafeStop()134206f32e7eSjoerg   KeyT &unsafeStop() const {
134306f32e7eSjoerg     assert(valid() && "Cannot access invalid iterator");
134406f32e7eSjoerg     return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) :
134506f32e7eSjoerg                         path.leaf<RootLeaf>().stop(path.leafOffset());
134606f32e7eSjoerg   }
134706f32e7eSjoerg 
134806f32e7eSjoerg   /// unsafeValue - Writable access to value() for iterator.
unsafeValue()134906f32e7eSjoerg   ValT &unsafeValue() const {
135006f32e7eSjoerg     assert(valid() && "Cannot access invalid iterator");
135106f32e7eSjoerg     return branched() ? path.leaf<Leaf>().value(path.leafOffset()) :
135206f32e7eSjoerg                         path.leaf<RootLeaf>().value(path.leafOffset());
135306f32e7eSjoerg   }
135406f32e7eSjoerg 
135506f32e7eSjoerg public:
135606f32e7eSjoerg   /// const_iterator - Create an iterator that isn't pointing anywhere.
135706f32e7eSjoerg   const_iterator() = default;
135806f32e7eSjoerg 
135906f32e7eSjoerg   /// setMap - Change the map iterated over. This call must be followed by a
136006f32e7eSjoerg   /// call to goToBegin(), goToEnd(), or find()
setMap(const IntervalMap & m)136106f32e7eSjoerg   void setMap(const IntervalMap &m) { map = const_cast<IntervalMap*>(&m); }
136206f32e7eSjoerg 
136306f32e7eSjoerg   /// valid - Return true if the current position is valid, false for end().
valid()136406f32e7eSjoerg   bool valid() const { return path.valid(); }
136506f32e7eSjoerg 
136606f32e7eSjoerg   /// atBegin - Return true if the current position is the first map entry.
atBegin()136706f32e7eSjoerg   bool atBegin() const { return path.atBegin(); }
136806f32e7eSjoerg 
136906f32e7eSjoerg   /// start - Return the beginning of the current interval.
start()137006f32e7eSjoerg   const KeyT &start() const { return unsafeStart(); }
137106f32e7eSjoerg 
137206f32e7eSjoerg   /// stop - Return the end of the current interval.
stop()137306f32e7eSjoerg   const KeyT &stop() const { return unsafeStop(); }
137406f32e7eSjoerg 
137506f32e7eSjoerg   /// value - Return the mapped value at the current interval.
value()137606f32e7eSjoerg   const ValT &value() const { return unsafeValue(); }
137706f32e7eSjoerg 
137806f32e7eSjoerg   const ValT &operator*() const { return value(); }
137906f32e7eSjoerg 
138006f32e7eSjoerg   bool operator==(const const_iterator &RHS) const {
138106f32e7eSjoerg     assert(map == RHS.map && "Cannot compare iterators from different maps");
138206f32e7eSjoerg     if (!valid())
138306f32e7eSjoerg       return !RHS.valid();
138406f32e7eSjoerg     if (path.leafOffset() != RHS.path.leafOffset())
138506f32e7eSjoerg       return false;
138606f32e7eSjoerg     return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>();
138706f32e7eSjoerg   }
138806f32e7eSjoerg 
138906f32e7eSjoerg   bool operator!=(const const_iterator &RHS) const {
139006f32e7eSjoerg     return !operator==(RHS);
139106f32e7eSjoerg   }
139206f32e7eSjoerg 
139306f32e7eSjoerg   /// goToBegin - Move to the first interval in map.
goToBegin()139406f32e7eSjoerg   void goToBegin() {
139506f32e7eSjoerg     setRoot(0);
139606f32e7eSjoerg     if (branched())
139706f32e7eSjoerg       path.fillLeft(map->height);
139806f32e7eSjoerg   }
139906f32e7eSjoerg 
140006f32e7eSjoerg   /// goToEnd - Move beyond the last interval in map.
goToEnd()140106f32e7eSjoerg   void goToEnd() {
140206f32e7eSjoerg     setRoot(map->rootSize);
140306f32e7eSjoerg   }
140406f32e7eSjoerg 
1405*da58b97aSjoerg   /// preincrement - Move to the next interval.
140606f32e7eSjoerg   const_iterator &operator++() {
140706f32e7eSjoerg     assert(valid() && "Cannot increment end()");
140806f32e7eSjoerg     if (++path.leafOffset() == path.leafSize() && branched())
140906f32e7eSjoerg       path.moveRight(map->height);
141006f32e7eSjoerg     return *this;
141106f32e7eSjoerg   }
141206f32e7eSjoerg 
1413*da58b97aSjoerg   /// postincrement - Don't do that!
141406f32e7eSjoerg   const_iterator operator++(int) {
141506f32e7eSjoerg     const_iterator tmp = *this;
141606f32e7eSjoerg     operator++();
141706f32e7eSjoerg     return tmp;
141806f32e7eSjoerg   }
141906f32e7eSjoerg 
1420*da58b97aSjoerg   /// predecrement - Move to the previous interval.
142106f32e7eSjoerg   const_iterator &operator--() {
142206f32e7eSjoerg     if (path.leafOffset() && (valid() || !branched()))
142306f32e7eSjoerg       --path.leafOffset();
142406f32e7eSjoerg     else
142506f32e7eSjoerg       path.moveLeft(map->height);
142606f32e7eSjoerg     return *this;
142706f32e7eSjoerg   }
142806f32e7eSjoerg 
1429*da58b97aSjoerg   /// postdecrement - Don't do that!
143006f32e7eSjoerg   const_iterator operator--(int) {
143106f32e7eSjoerg     const_iterator tmp = *this;
143206f32e7eSjoerg     operator--();
143306f32e7eSjoerg     return tmp;
143406f32e7eSjoerg   }
143506f32e7eSjoerg 
143606f32e7eSjoerg   /// find - Move to the first interval with stop >= x, or end().
143706f32e7eSjoerg   /// This is a full search from the root, the current position is ignored.
find(KeyT x)143806f32e7eSjoerg   void find(KeyT x) {
143906f32e7eSjoerg     if (branched())
144006f32e7eSjoerg       treeFind(x);
144106f32e7eSjoerg     else
144206f32e7eSjoerg       setRoot(map->rootLeaf().findFrom(0, map->rootSize, x));
144306f32e7eSjoerg   }
144406f32e7eSjoerg 
144506f32e7eSjoerg   /// advanceTo - Move to the first interval with stop >= x, or end().
144606f32e7eSjoerg   /// The search is started from the current position, and no earlier positions
144706f32e7eSjoerg   /// can be found. This is much faster than find() for small moves.
advanceTo(KeyT x)144806f32e7eSjoerg   void advanceTo(KeyT x) {
144906f32e7eSjoerg     if (!valid())
145006f32e7eSjoerg       return;
145106f32e7eSjoerg     if (branched())
145206f32e7eSjoerg       treeAdvanceTo(x);
145306f32e7eSjoerg     else
145406f32e7eSjoerg       path.leafOffset() =
145506f32e7eSjoerg         map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x);
145606f32e7eSjoerg   }
145706f32e7eSjoerg };
145806f32e7eSjoerg 
145906f32e7eSjoerg /// pathFillFind - Complete path by searching for x.
146006f32e7eSjoerg /// @param x Key to search for.
146106f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
146206f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
pathFillFind(KeyT x)146306f32e7eSjoerg const_iterator::pathFillFind(KeyT x) {
146406f32e7eSjoerg   IntervalMapImpl::NodeRef NR = path.subtree(path.height());
146506f32e7eSjoerg   for (unsigned i = map->height - path.height() - 1; i; --i) {
146606f32e7eSjoerg     unsigned p = NR.get<Branch>().safeFind(0, x);
146706f32e7eSjoerg     path.push(NR, p);
146806f32e7eSjoerg     NR = NR.subtree(p);
146906f32e7eSjoerg   }
147006f32e7eSjoerg   path.push(NR, NR.get<Leaf>().safeFind(0, x));
147106f32e7eSjoerg }
147206f32e7eSjoerg 
147306f32e7eSjoerg /// treeFind - Find in a branched tree.
147406f32e7eSjoerg /// @param x Key to search for.
147506f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
147606f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
treeFind(KeyT x)147706f32e7eSjoerg const_iterator::treeFind(KeyT x) {
147806f32e7eSjoerg   setRoot(map->rootBranch().findFrom(0, map->rootSize, x));
147906f32e7eSjoerg   if (valid())
148006f32e7eSjoerg     pathFillFind(x);
148106f32e7eSjoerg }
148206f32e7eSjoerg 
148306f32e7eSjoerg /// treeAdvanceTo - Find position after the current one.
148406f32e7eSjoerg /// @param x Key to search for.
148506f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
148606f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
treeAdvanceTo(KeyT x)148706f32e7eSjoerg const_iterator::treeAdvanceTo(KeyT x) {
148806f32e7eSjoerg   // Can we stay on the same leaf node?
148906f32e7eSjoerg   if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) {
149006f32e7eSjoerg     path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x);
149106f32e7eSjoerg     return;
149206f32e7eSjoerg   }
149306f32e7eSjoerg 
149406f32e7eSjoerg   // Drop the current leaf.
149506f32e7eSjoerg   path.pop();
149606f32e7eSjoerg 
149706f32e7eSjoerg   // Search towards the root for a usable subtree.
149806f32e7eSjoerg   if (path.height()) {
149906f32e7eSjoerg     for (unsigned l = path.height() - 1; l; --l) {
150006f32e7eSjoerg       if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) {
150106f32e7eSjoerg         // The branch node at l+1 is usable
150206f32e7eSjoerg         path.offset(l + 1) =
150306f32e7eSjoerg           path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x);
150406f32e7eSjoerg         return pathFillFind(x);
150506f32e7eSjoerg       }
150606f32e7eSjoerg       path.pop();
150706f32e7eSjoerg     }
150806f32e7eSjoerg     // Is the level-1 Branch usable?
150906f32e7eSjoerg     if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) {
151006f32e7eSjoerg       path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x);
151106f32e7eSjoerg       return pathFillFind(x);
151206f32e7eSjoerg     }
151306f32e7eSjoerg   }
151406f32e7eSjoerg 
151506f32e7eSjoerg   // We reached the root.
151606f32e7eSjoerg   setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x));
151706f32e7eSjoerg   if (valid())
151806f32e7eSjoerg     pathFillFind(x);
151906f32e7eSjoerg }
152006f32e7eSjoerg 
152106f32e7eSjoerg //===----------------------------------------------------------------------===//
152206f32e7eSjoerg //---                       IntervalMap::iterator                         ----//
152306f32e7eSjoerg //===----------------------------------------------------------------------===//
152406f32e7eSjoerg 
152506f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
152606f32e7eSjoerg class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
152706f32e7eSjoerg   friend class IntervalMap;
152806f32e7eSjoerg 
152906f32e7eSjoerg   using IdxPair = IntervalMapImpl::IdxPair;
153006f32e7eSjoerg 
iterator(IntervalMap & map)153106f32e7eSjoerg   explicit iterator(IntervalMap &map) : const_iterator(map) {}
153206f32e7eSjoerg 
153306f32e7eSjoerg   void setNodeStop(unsigned Level, KeyT Stop);
153406f32e7eSjoerg   bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop);
153506f32e7eSjoerg   template <typename NodeT> bool overflow(unsigned Level);
153606f32e7eSjoerg   void treeInsert(KeyT a, KeyT b, ValT y);
153706f32e7eSjoerg   void eraseNode(unsigned Level);
153806f32e7eSjoerg   void treeErase(bool UpdateRoot = true);
153906f32e7eSjoerg   bool canCoalesceLeft(KeyT Start, ValT x);
154006f32e7eSjoerg   bool canCoalesceRight(KeyT Stop, ValT x);
154106f32e7eSjoerg 
154206f32e7eSjoerg public:
154306f32e7eSjoerg   /// iterator - Create null iterator.
154406f32e7eSjoerg   iterator() = default;
154506f32e7eSjoerg 
154606f32e7eSjoerg   /// setStart - Move the start of the current interval.
154706f32e7eSjoerg   /// This may cause coalescing with the previous interval.
154806f32e7eSjoerg   /// @param a New start key, must not overlap the previous interval.
154906f32e7eSjoerg   void setStart(KeyT a);
155006f32e7eSjoerg 
155106f32e7eSjoerg   /// setStop - Move the end of the current interval.
155206f32e7eSjoerg   /// This may cause coalescing with the following interval.
155306f32e7eSjoerg   /// @param b New stop key, must not overlap the following interval.
155406f32e7eSjoerg   void setStop(KeyT b);
155506f32e7eSjoerg 
155606f32e7eSjoerg   /// setValue - Change the mapped value of the current interval.
155706f32e7eSjoerg   /// This may cause coalescing with the previous and following intervals.
155806f32e7eSjoerg   /// @param x New value.
155906f32e7eSjoerg   void setValue(ValT x);
156006f32e7eSjoerg 
156106f32e7eSjoerg   /// setStartUnchecked - Move the start of the current interval without
156206f32e7eSjoerg   /// checking for coalescing or overlaps.
156306f32e7eSjoerg   /// This should only be used when it is known that coalescing is not required.
156406f32e7eSjoerg   /// @param a New start key.
setStartUnchecked(KeyT a)156506f32e7eSjoerg   void setStartUnchecked(KeyT a) { this->unsafeStart() = a; }
156606f32e7eSjoerg 
156706f32e7eSjoerg   /// setStopUnchecked - Move the end of the current interval without checking
156806f32e7eSjoerg   /// for coalescing or overlaps.
156906f32e7eSjoerg   /// This should only be used when it is known that coalescing is not required.
157006f32e7eSjoerg   /// @param b New stop key.
setStopUnchecked(KeyT b)157106f32e7eSjoerg   void setStopUnchecked(KeyT b) {
157206f32e7eSjoerg     this->unsafeStop() = b;
157306f32e7eSjoerg     // Update keys in branch nodes as well.
157406f32e7eSjoerg     if (this->path.atLastEntry(this->path.height()))
157506f32e7eSjoerg       setNodeStop(this->path.height(), b);
157606f32e7eSjoerg   }
157706f32e7eSjoerg 
157806f32e7eSjoerg   /// setValueUnchecked - Change the mapped value of the current interval
157906f32e7eSjoerg   /// without checking for coalescing.
158006f32e7eSjoerg   /// @param x New value.
setValueUnchecked(ValT x)158106f32e7eSjoerg   void setValueUnchecked(ValT x) { this->unsafeValue() = x; }
158206f32e7eSjoerg 
158306f32e7eSjoerg   /// insert - Insert mapping [a;b] -> y before the current position.
158406f32e7eSjoerg   void insert(KeyT a, KeyT b, ValT y);
158506f32e7eSjoerg 
158606f32e7eSjoerg   /// erase - Erase the current interval.
158706f32e7eSjoerg   void erase();
158806f32e7eSjoerg 
158906f32e7eSjoerg   iterator &operator++() {
159006f32e7eSjoerg     const_iterator::operator++();
159106f32e7eSjoerg     return *this;
159206f32e7eSjoerg   }
159306f32e7eSjoerg 
159406f32e7eSjoerg   iterator operator++(int) {
159506f32e7eSjoerg     iterator tmp = *this;
159606f32e7eSjoerg     operator++();
159706f32e7eSjoerg     return tmp;
159806f32e7eSjoerg   }
159906f32e7eSjoerg 
160006f32e7eSjoerg   iterator &operator--() {
160106f32e7eSjoerg     const_iterator::operator--();
160206f32e7eSjoerg     return *this;
160306f32e7eSjoerg   }
160406f32e7eSjoerg 
160506f32e7eSjoerg   iterator operator--(int) {
160606f32e7eSjoerg     iterator tmp = *this;
160706f32e7eSjoerg     operator--();
160806f32e7eSjoerg     return tmp;
160906f32e7eSjoerg   }
161006f32e7eSjoerg };
161106f32e7eSjoerg 
161206f32e7eSjoerg /// canCoalesceLeft - Can the current interval coalesce to the left after
161306f32e7eSjoerg /// changing start or value?
161406f32e7eSjoerg /// @param Start New start of current interval.
161506f32e7eSjoerg /// @param Value New value for current interval.
161606f32e7eSjoerg /// @return True when updating the current interval would enable coalescing.
161706f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
161806f32e7eSjoerg bool IntervalMap<KeyT, ValT, N, Traits>::
canCoalesceLeft(KeyT Start,ValT Value)161906f32e7eSjoerg iterator::canCoalesceLeft(KeyT Start, ValT Value) {
162006f32e7eSjoerg   using namespace IntervalMapImpl;
162106f32e7eSjoerg   Path &P = this->path;
162206f32e7eSjoerg   if (!this->branched()) {
162306f32e7eSjoerg     unsigned i = P.leafOffset();
162406f32e7eSjoerg     RootLeaf &Node = P.leaf<RootLeaf>();
162506f32e7eSjoerg     return i && Node.value(i-1) == Value &&
162606f32e7eSjoerg                 Traits::adjacent(Node.stop(i-1), Start);
162706f32e7eSjoerg   }
162806f32e7eSjoerg   // Branched.
162906f32e7eSjoerg   if (unsigned i = P.leafOffset()) {
163006f32e7eSjoerg     Leaf &Node = P.leaf<Leaf>();
163106f32e7eSjoerg     return Node.value(i-1) == Value && Traits::adjacent(Node.stop(i-1), Start);
163206f32e7eSjoerg   } else if (NodeRef NR = P.getLeftSibling(P.height())) {
163306f32e7eSjoerg     unsigned i = NR.size() - 1;
163406f32e7eSjoerg     Leaf &Node = NR.get<Leaf>();
163506f32e7eSjoerg     return Node.value(i) == Value && Traits::adjacent(Node.stop(i), Start);
163606f32e7eSjoerg   }
163706f32e7eSjoerg   return false;
163806f32e7eSjoerg }
163906f32e7eSjoerg 
164006f32e7eSjoerg /// canCoalesceRight - Can the current interval coalesce to the right after
164106f32e7eSjoerg /// changing stop or value?
164206f32e7eSjoerg /// @param Stop New stop of current interval.
164306f32e7eSjoerg /// @param Value New value for current interval.
164406f32e7eSjoerg /// @return True when updating the current interval would enable coalescing.
164506f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
164606f32e7eSjoerg bool IntervalMap<KeyT, ValT, N, Traits>::
canCoalesceRight(KeyT Stop,ValT Value)164706f32e7eSjoerg iterator::canCoalesceRight(KeyT Stop, ValT Value) {
164806f32e7eSjoerg   using namespace IntervalMapImpl;
164906f32e7eSjoerg   Path &P = this->path;
165006f32e7eSjoerg   unsigned i = P.leafOffset() + 1;
165106f32e7eSjoerg   if (!this->branched()) {
165206f32e7eSjoerg     if (i >= P.leafSize())
165306f32e7eSjoerg       return false;
165406f32e7eSjoerg     RootLeaf &Node = P.leaf<RootLeaf>();
165506f32e7eSjoerg     return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
165606f32e7eSjoerg   }
165706f32e7eSjoerg   // Branched.
165806f32e7eSjoerg   if (i < P.leafSize()) {
165906f32e7eSjoerg     Leaf &Node = P.leaf<Leaf>();
166006f32e7eSjoerg     return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
166106f32e7eSjoerg   } else if (NodeRef NR = P.getRightSibling(P.height())) {
166206f32e7eSjoerg     Leaf &Node = NR.get<Leaf>();
166306f32e7eSjoerg     return Node.value(0) == Value && Traits::adjacent(Stop, Node.start(0));
166406f32e7eSjoerg   }
166506f32e7eSjoerg   return false;
166606f32e7eSjoerg }
166706f32e7eSjoerg 
166806f32e7eSjoerg /// setNodeStop - Update the stop key of the current node at level and above.
166906f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
167006f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
setNodeStop(unsigned Level,KeyT Stop)167106f32e7eSjoerg iterator::setNodeStop(unsigned Level, KeyT Stop) {
167206f32e7eSjoerg   // There are no references to the root node, so nothing to update.
167306f32e7eSjoerg   if (!Level)
167406f32e7eSjoerg     return;
167506f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
167606f32e7eSjoerg   // Update nodes pointing to the current node.
167706f32e7eSjoerg   while (--Level) {
167806f32e7eSjoerg     P.node<Branch>(Level).stop(P.offset(Level)) = Stop;
167906f32e7eSjoerg     if (!P.atLastEntry(Level))
168006f32e7eSjoerg       return;
168106f32e7eSjoerg   }
168206f32e7eSjoerg   // Update root separately since it has a different layout.
168306f32e7eSjoerg   P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop;
168406f32e7eSjoerg }
168506f32e7eSjoerg 
168606f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
168706f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
setStart(KeyT a)168806f32e7eSjoerg iterator::setStart(KeyT a) {
168906f32e7eSjoerg   assert(Traits::nonEmpty(a, this->stop()) && "Cannot move start beyond stop");
169006f32e7eSjoerg   KeyT &CurStart = this->unsafeStart();
169106f32e7eSjoerg   if (!Traits::startLess(a, CurStart) || !canCoalesceLeft(a, this->value())) {
169206f32e7eSjoerg     CurStart = a;
169306f32e7eSjoerg     return;
169406f32e7eSjoerg   }
169506f32e7eSjoerg   // Coalesce with the interval to the left.
169606f32e7eSjoerg   --*this;
169706f32e7eSjoerg   a = this->start();
169806f32e7eSjoerg   erase();
169906f32e7eSjoerg   setStartUnchecked(a);
170006f32e7eSjoerg }
170106f32e7eSjoerg 
170206f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
170306f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
setStop(KeyT b)170406f32e7eSjoerg iterator::setStop(KeyT b) {
170506f32e7eSjoerg   assert(Traits::nonEmpty(this->start(), b) && "Cannot move stop beyond start");
170606f32e7eSjoerg   if (Traits::startLess(b, this->stop()) ||
170706f32e7eSjoerg       !canCoalesceRight(b, this->value())) {
170806f32e7eSjoerg     setStopUnchecked(b);
170906f32e7eSjoerg     return;
171006f32e7eSjoerg   }
171106f32e7eSjoerg   // Coalesce with interval to the right.
171206f32e7eSjoerg   KeyT a = this->start();
171306f32e7eSjoerg   erase();
171406f32e7eSjoerg   setStartUnchecked(a);
171506f32e7eSjoerg }
171606f32e7eSjoerg 
171706f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
171806f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
setValue(ValT x)171906f32e7eSjoerg iterator::setValue(ValT x) {
172006f32e7eSjoerg   setValueUnchecked(x);
172106f32e7eSjoerg   if (canCoalesceRight(this->stop(), x)) {
172206f32e7eSjoerg     KeyT a = this->start();
172306f32e7eSjoerg     erase();
172406f32e7eSjoerg     setStartUnchecked(a);
172506f32e7eSjoerg   }
172606f32e7eSjoerg   if (canCoalesceLeft(this->start(), x)) {
172706f32e7eSjoerg     --*this;
172806f32e7eSjoerg     KeyT a = this->start();
172906f32e7eSjoerg     erase();
173006f32e7eSjoerg     setStartUnchecked(a);
173106f32e7eSjoerg   }
173206f32e7eSjoerg }
173306f32e7eSjoerg 
173406f32e7eSjoerg /// insertNode - insert a node before the current path at level.
173506f32e7eSjoerg /// Leave the current path pointing at the new node.
173606f32e7eSjoerg /// @param Level path index of the node to be inserted.
173706f32e7eSjoerg /// @param Node The node to be inserted.
173806f32e7eSjoerg /// @param Stop The last index in the new node.
173906f32e7eSjoerg /// @return True if the tree height was increased.
174006f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
174106f32e7eSjoerg bool IntervalMap<KeyT, ValT, N, Traits>::
insertNode(unsigned Level,IntervalMapImpl::NodeRef Node,KeyT Stop)174206f32e7eSjoerg iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) {
174306f32e7eSjoerg   assert(Level && "Cannot insert next to the root");
174406f32e7eSjoerg   bool SplitRoot = false;
174506f32e7eSjoerg   IntervalMap &IM = *this->map;
174606f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
174706f32e7eSjoerg 
174806f32e7eSjoerg   if (Level == 1) {
174906f32e7eSjoerg     // Insert into the root branch node.
175006f32e7eSjoerg     if (IM.rootSize < RootBranch::Capacity) {
175106f32e7eSjoerg       IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop);
175206f32e7eSjoerg       P.setSize(0, ++IM.rootSize);
175306f32e7eSjoerg       P.reset(Level);
175406f32e7eSjoerg       return SplitRoot;
175506f32e7eSjoerg     }
175606f32e7eSjoerg 
175706f32e7eSjoerg     // We need to split the root while keeping our position.
175806f32e7eSjoerg     SplitRoot = true;
175906f32e7eSjoerg     IdxPair Offset = IM.splitRoot(P.offset(0));
176006f32e7eSjoerg     P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
176106f32e7eSjoerg 
176206f32e7eSjoerg     // Fall through to insert at the new higher level.
176306f32e7eSjoerg     ++Level;
176406f32e7eSjoerg   }
176506f32e7eSjoerg 
176606f32e7eSjoerg   // When inserting before end(), make sure we have a valid path.
176706f32e7eSjoerg   P.legalizeForInsert(--Level);
176806f32e7eSjoerg 
176906f32e7eSjoerg   // Insert into the branch node at Level-1.
177006f32e7eSjoerg   if (P.size(Level) == Branch::Capacity) {
177106f32e7eSjoerg     // Branch node is full, handle handle the overflow.
177206f32e7eSjoerg     assert(!SplitRoot && "Cannot overflow after splitting the root");
177306f32e7eSjoerg     SplitRoot = overflow<Branch>(Level);
177406f32e7eSjoerg     Level += SplitRoot;
177506f32e7eSjoerg   }
177606f32e7eSjoerg   P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop);
177706f32e7eSjoerg   P.setSize(Level, P.size(Level) + 1);
177806f32e7eSjoerg   if (P.atLastEntry(Level))
177906f32e7eSjoerg     setNodeStop(Level, Stop);
178006f32e7eSjoerg   P.reset(Level + 1);
178106f32e7eSjoerg   return SplitRoot;
178206f32e7eSjoerg }
178306f32e7eSjoerg 
178406f32e7eSjoerg // insert
178506f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
178606f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
insert(KeyT a,KeyT b,ValT y)178706f32e7eSjoerg iterator::insert(KeyT a, KeyT b, ValT y) {
178806f32e7eSjoerg   if (this->branched())
178906f32e7eSjoerg     return treeInsert(a, b, y);
179006f32e7eSjoerg   IntervalMap &IM = *this->map;
179106f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
179206f32e7eSjoerg 
179306f32e7eSjoerg   // Try simple root leaf insert.
179406f32e7eSjoerg   unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y);
179506f32e7eSjoerg 
179606f32e7eSjoerg   // Was the root node insert successful?
179706f32e7eSjoerg   if (Size <= RootLeaf::Capacity) {
179806f32e7eSjoerg     P.setSize(0, IM.rootSize = Size);
179906f32e7eSjoerg     return;
180006f32e7eSjoerg   }
180106f32e7eSjoerg 
180206f32e7eSjoerg   // Root leaf node is full, we must branch.
180306f32e7eSjoerg   IdxPair Offset = IM.branchRoot(P.leafOffset());
180406f32e7eSjoerg   P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
180506f32e7eSjoerg 
180606f32e7eSjoerg   // Now it fits in the new leaf.
180706f32e7eSjoerg   treeInsert(a, b, y);
180806f32e7eSjoerg }
180906f32e7eSjoerg 
181006f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
181106f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
treeInsert(KeyT a,KeyT b,ValT y)181206f32e7eSjoerg iterator::treeInsert(KeyT a, KeyT b, ValT y) {
181306f32e7eSjoerg   using namespace IntervalMapImpl;
181406f32e7eSjoerg   Path &P = this->path;
181506f32e7eSjoerg 
181606f32e7eSjoerg   if (!P.valid())
181706f32e7eSjoerg     P.legalizeForInsert(this->map->height);
181806f32e7eSjoerg 
181906f32e7eSjoerg   // Check if this insertion will extend the node to the left.
182006f32e7eSjoerg   if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) {
182106f32e7eSjoerg     // Node is growing to the left, will it affect a left sibling node?
182206f32e7eSjoerg     if (NodeRef Sib = P.getLeftSibling(P.height())) {
182306f32e7eSjoerg       Leaf &SibLeaf = Sib.get<Leaf>();
182406f32e7eSjoerg       unsigned SibOfs = Sib.size() - 1;
182506f32e7eSjoerg       if (SibLeaf.value(SibOfs) == y &&
182606f32e7eSjoerg           Traits::adjacent(SibLeaf.stop(SibOfs), a)) {
182706f32e7eSjoerg         // This insertion will coalesce with the last entry in SibLeaf. We can
182806f32e7eSjoerg         // handle it in two ways:
182906f32e7eSjoerg         //  1. Extend SibLeaf.stop to b and be done, or
183006f32e7eSjoerg         //  2. Extend a to SibLeaf, erase the SibLeaf entry and continue.
183106f32e7eSjoerg         // We prefer 1., but need 2 when coalescing to the right as well.
183206f32e7eSjoerg         Leaf &CurLeaf = P.leaf<Leaf>();
183306f32e7eSjoerg         P.moveLeft(P.height());
183406f32e7eSjoerg         if (Traits::stopLess(b, CurLeaf.start(0)) &&
183506f32e7eSjoerg             (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) {
183606f32e7eSjoerg           // Easy, just extend SibLeaf and we're done.
183706f32e7eSjoerg           setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b);
183806f32e7eSjoerg           return;
183906f32e7eSjoerg         } else {
184006f32e7eSjoerg           // We have both left and right coalescing. Erase the old SibLeaf entry
184106f32e7eSjoerg           // and continue inserting the larger interval.
184206f32e7eSjoerg           a = SibLeaf.start(SibOfs);
184306f32e7eSjoerg           treeErase(/* UpdateRoot= */false);
184406f32e7eSjoerg         }
184506f32e7eSjoerg       }
184606f32e7eSjoerg     } else {
184706f32e7eSjoerg       // No left sibling means we are at begin(). Update cached bound.
184806f32e7eSjoerg       this->map->rootBranchStart() = a;
184906f32e7eSjoerg     }
185006f32e7eSjoerg   }
185106f32e7eSjoerg 
185206f32e7eSjoerg   // When we are inserting at the end of a leaf node, we must update stops.
185306f32e7eSjoerg   unsigned Size = P.leafSize();
185406f32e7eSjoerg   bool Grow = P.leafOffset() == Size;
185506f32e7eSjoerg   Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y);
185606f32e7eSjoerg 
185706f32e7eSjoerg   // Leaf insertion unsuccessful? Overflow and try again.
185806f32e7eSjoerg   if (Size > Leaf::Capacity) {
185906f32e7eSjoerg     overflow<Leaf>(P.height());
186006f32e7eSjoerg     Grow = P.leafOffset() == P.leafSize();
186106f32e7eSjoerg     Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y);
186206f32e7eSjoerg     assert(Size <= Leaf::Capacity && "overflow() didn't make room");
186306f32e7eSjoerg   }
186406f32e7eSjoerg 
186506f32e7eSjoerg   // Inserted, update offset and leaf size.
186606f32e7eSjoerg   P.setSize(P.height(), Size);
186706f32e7eSjoerg 
186806f32e7eSjoerg   // Insert was the last node entry, update stops.
186906f32e7eSjoerg   if (Grow)
187006f32e7eSjoerg     setNodeStop(P.height(), b);
187106f32e7eSjoerg }
187206f32e7eSjoerg 
187306f32e7eSjoerg /// erase - erase the current interval and move to the next position.
187406f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
187506f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
erase()187606f32e7eSjoerg iterator::erase() {
187706f32e7eSjoerg   IntervalMap &IM = *this->map;
187806f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
187906f32e7eSjoerg   assert(P.valid() && "Cannot erase end()");
188006f32e7eSjoerg   if (this->branched())
188106f32e7eSjoerg     return treeErase();
188206f32e7eSjoerg   IM.rootLeaf().erase(P.leafOffset(), IM.rootSize);
188306f32e7eSjoerg   P.setSize(0, --IM.rootSize);
188406f32e7eSjoerg }
188506f32e7eSjoerg 
188606f32e7eSjoerg /// treeErase - erase() for a branched tree.
188706f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
188806f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
treeErase(bool UpdateRoot)188906f32e7eSjoerg iterator::treeErase(bool UpdateRoot) {
189006f32e7eSjoerg   IntervalMap &IM = *this->map;
189106f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
189206f32e7eSjoerg   Leaf &Node = P.leaf<Leaf>();
189306f32e7eSjoerg 
189406f32e7eSjoerg   // Nodes are not allowed to become empty.
189506f32e7eSjoerg   if (P.leafSize() == 1) {
189606f32e7eSjoerg     IM.deleteNode(&Node);
189706f32e7eSjoerg     eraseNode(IM.height);
189806f32e7eSjoerg     // Update rootBranchStart if we erased begin().
189906f32e7eSjoerg     if (UpdateRoot && IM.branched() && P.valid() && P.atBegin())
190006f32e7eSjoerg       IM.rootBranchStart() = P.leaf<Leaf>().start(0);
190106f32e7eSjoerg     return;
190206f32e7eSjoerg   }
190306f32e7eSjoerg 
190406f32e7eSjoerg   // Erase current entry.
190506f32e7eSjoerg   Node.erase(P.leafOffset(), P.leafSize());
190606f32e7eSjoerg   unsigned NewSize = P.leafSize() - 1;
190706f32e7eSjoerg   P.setSize(IM.height, NewSize);
190806f32e7eSjoerg   // When we erase the last entry, update stop and move to a legal position.
190906f32e7eSjoerg   if (P.leafOffset() == NewSize) {
191006f32e7eSjoerg     setNodeStop(IM.height, Node.stop(NewSize - 1));
191106f32e7eSjoerg     P.moveRight(IM.height);
191206f32e7eSjoerg   } else if (UpdateRoot && P.atBegin())
191306f32e7eSjoerg     IM.rootBranchStart() = P.leaf<Leaf>().start(0);
191406f32e7eSjoerg }
191506f32e7eSjoerg 
191606f32e7eSjoerg /// eraseNode - Erase the current node at Level from its parent and move path to
191706f32e7eSjoerg /// the first entry of the next sibling node.
191806f32e7eSjoerg /// The node must be deallocated by the caller.
191906f32e7eSjoerg /// @param Level 1..height, the root node cannot be erased.
192006f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
192106f32e7eSjoerg void IntervalMap<KeyT, ValT, N, Traits>::
eraseNode(unsigned Level)192206f32e7eSjoerg iterator::eraseNode(unsigned Level) {
192306f32e7eSjoerg   assert(Level && "Cannot erase root node");
192406f32e7eSjoerg   IntervalMap &IM = *this->map;
192506f32e7eSjoerg   IntervalMapImpl::Path &P = this->path;
192606f32e7eSjoerg 
192706f32e7eSjoerg   if (--Level == 0) {
192806f32e7eSjoerg     IM.rootBranch().erase(P.offset(0), IM.rootSize);
192906f32e7eSjoerg     P.setSize(0, --IM.rootSize);
193006f32e7eSjoerg     // If this cleared the root, switch to height=0.
193106f32e7eSjoerg     if (IM.empty()) {
193206f32e7eSjoerg       IM.switchRootToLeaf();
193306f32e7eSjoerg       this->setRoot(0);
193406f32e7eSjoerg       return;
193506f32e7eSjoerg     }
193606f32e7eSjoerg   } else {
193706f32e7eSjoerg     // Remove node ref from branch node at Level.
193806f32e7eSjoerg     Branch &Parent = P.node<Branch>(Level);
193906f32e7eSjoerg     if (P.size(Level) == 1) {
194006f32e7eSjoerg       // Branch node became empty, remove it recursively.
194106f32e7eSjoerg       IM.deleteNode(&Parent);
194206f32e7eSjoerg       eraseNode(Level);
194306f32e7eSjoerg     } else {
194406f32e7eSjoerg       // Branch node won't become empty.
194506f32e7eSjoerg       Parent.erase(P.offset(Level), P.size(Level));
194606f32e7eSjoerg       unsigned NewSize = P.size(Level) - 1;
194706f32e7eSjoerg       P.setSize(Level, NewSize);
194806f32e7eSjoerg       // If we removed the last branch, update stop and move to a legal pos.
194906f32e7eSjoerg       if (P.offset(Level) == NewSize) {
195006f32e7eSjoerg         setNodeStop(Level, Parent.stop(NewSize - 1));
195106f32e7eSjoerg         P.moveRight(Level);
195206f32e7eSjoerg       }
195306f32e7eSjoerg     }
195406f32e7eSjoerg   }
195506f32e7eSjoerg   // Update path cache for the new right sibling position.
195606f32e7eSjoerg   if (P.valid()) {
195706f32e7eSjoerg     P.reset(Level + 1);
195806f32e7eSjoerg     P.offset(Level + 1) = 0;
195906f32e7eSjoerg   }
196006f32e7eSjoerg }
196106f32e7eSjoerg 
196206f32e7eSjoerg /// overflow - Distribute entries of the current node evenly among
196306f32e7eSjoerg /// its siblings and ensure that the current node is not full.
196406f32e7eSjoerg /// This may require allocating a new node.
196506f32e7eSjoerg /// @tparam NodeT The type of node at Level (Leaf or Branch).
196606f32e7eSjoerg /// @param Level path index of the overflowing node.
196706f32e7eSjoerg /// @return True when the tree height was changed.
196806f32e7eSjoerg template <typename KeyT, typename ValT, unsigned N, typename Traits>
196906f32e7eSjoerg template <typename NodeT>
197006f32e7eSjoerg bool IntervalMap<KeyT, ValT, N, Traits>::
overflow(unsigned Level)197106f32e7eSjoerg iterator::overflow(unsigned Level) {
197206f32e7eSjoerg   using namespace IntervalMapImpl;
197306f32e7eSjoerg   Path &P = this->path;
197406f32e7eSjoerg   unsigned CurSize[4];
197506f32e7eSjoerg   NodeT *Node[4];
197606f32e7eSjoerg   unsigned Nodes = 0;
197706f32e7eSjoerg   unsigned Elements = 0;
197806f32e7eSjoerg   unsigned Offset = P.offset(Level);
197906f32e7eSjoerg 
198006f32e7eSjoerg   // Do we have a left sibling?
198106f32e7eSjoerg   NodeRef LeftSib = P.getLeftSibling(Level);
198206f32e7eSjoerg   if (LeftSib) {
198306f32e7eSjoerg     Offset += Elements = CurSize[Nodes] = LeftSib.size();
198406f32e7eSjoerg     Node[Nodes++] = &LeftSib.get<NodeT>();
198506f32e7eSjoerg   }
198606f32e7eSjoerg 
198706f32e7eSjoerg   // Current node.
198806f32e7eSjoerg   Elements += CurSize[Nodes] = P.size(Level);
198906f32e7eSjoerg   Node[Nodes++] = &P.node<NodeT>(Level);
199006f32e7eSjoerg 
199106f32e7eSjoerg   // Do we have a right sibling?
199206f32e7eSjoerg   NodeRef RightSib = P.getRightSibling(Level);
199306f32e7eSjoerg   if (RightSib) {
199406f32e7eSjoerg     Elements += CurSize[Nodes] = RightSib.size();
199506f32e7eSjoerg     Node[Nodes++] = &RightSib.get<NodeT>();
199606f32e7eSjoerg   }
199706f32e7eSjoerg 
199806f32e7eSjoerg   // Do we need to allocate a new node?
199906f32e7eSjoerg   unsigned NewNode = 0;
200006f32e7eSjoerg   if (Elements + 1 > Nodes * NodeT::Capacity) {
200106f32e7eSjoerg     // Insert NewNode at the penultimate position, or after a single node.
200206f32e7eSjoerg     NewNode = Nodes == 1 ? 1 : Nodes - 1;
200306f32e7eSjoerg     CurSize[Nodes] = CurSize[NewNode];
200406f32e7eSjoerg     Node[Nodes] = Node[NewNode];
200506f32e7eSjoerg     CurSize[NewNode] = 0;
200606f32e7eSjoerg     Node[NewNode] = this->map->template newNode<NodeT>();
200706f32e7eSjoerg     ++Nodes;
200806f32e7eSjoerg   }
200906f32e7eSjoerg 
201006f32e7eSjoerg   // Compute the new element distribution.
201106f32e7eSjoerg   unsigned NewSize[4];
201206f32e7eSjoerg   IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity,
201306f32e7eSjoerg                                  CurSize, NewSize, Offset, true);
201406f32e7eSjoerg   adjustSiblingSizes(Node, Nodes, CurSize, NewSize);
201506f32e7eSjoerg 
201606f32e7eSjoerg   // Move current location to the leftmost node.
201706f32e7eSjoerg   if (LeftSib)
201806f32e7eSjoerg     P.moveLeft(Level);
201906f32e7eSjoerg 
202006f32e7eSjoerg   // Elements have been rearranged, now update node sizes and stops.
202106f32e7eSjoerg   bool SplitRoot = false;
202206f32e7eSjoerg   unsigned Pos = 0;
202306f32e7eSjoerg   while (true) {
202406f32e7eSjoerg     KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
202506f32e7eSjoerg     if (NewNode && Pos == NewNode) {
202606f32e7eSjoerg       SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop);
202706f32e7eSjoerg       Level += SplitRoot;
202806f32e7eSjoerg     } else {
202906f32e7eSjoerg       P.setSize(Level, NewSize[Pos]);
203006f32e7eSjoerg       setNodeStop(Level, Stop);
203106f32e7eSjoerg     }
203206f32e7eSjoerg     if (Pos + 1 == Nodes)
203306f32e7eSjoerg       break;
203406f32e7eSjoerg     P.moveRight(Level);
203506f32e7eSjoerg     ++Pos;
203606f32e7eSjoerg   }
203706f32e7eSjoerg 
203806f32e7eSjoerg   // Where was I? Find NewOffset.
203906f32e7eSjoerg   while(Pos != NewOffset.first) {
204006f32e7eSjoerg     P.moveLeft(Level);
204106f32e7eSjoerg     --Pos;
204206f32e7eSjoerg   }
204306f32e7eSjoerg   P.offset(Level) = NewOffset.second;
204406f32e7eSjoerg   return SplitRoot;
204506f32e7eSjoerg }
204606f32e7eSjoerg 
204706f32e7eSjoerg //===----------------------------------------------------------------------===//
204806f32e7eSjoerg //---                       IntervalMapOverlaps                           ----//
204906f32e7eSjoerg //===----------------------------------------------------------------------===//
205006f32e7eSjoerg 
205106f32e7eSjoerg /// IntervalMapOverlaps - Iterate over the overlaps of mapped intervals in two
205206f32e7eSjoerg /// IntervalMaps. The maps may be different, but the KeyT and Traits types
205306f32e7eSjoerg /// should be the same.
205406f32e7eSjoerg ///
205506f32e7eSjoerg /// Typical uses:
205606f32e7eSjoerg ///
205706f32e7eSjoerg /// 1. Test for overlap:
205806f32e7eSjoerg ///    bool overlap = IntervalMapOverlaps(a, b).valid();
205906f32e7eSjoerg ///
206006f32e7eSjoerg /// 2. Enumerate overlaps:
206106f32e7eSjoerg ///    for (IntervalMapOverlaps I(a, b); I.valid() ; ++I) { ... }
206206f32e7eSjoerg ///
206306f32e7eSjoerg template <typename MapA, typename MapB>
206406f32e7eSjoerg class IntervalMapOverlaps {
206506f32e7eSjoerg   using KeyType = typename MapA::KeyType;
206606f32e7eSjoerg   using Traits = typename MapA::KeyTraits;
206706f32e7eSjoerg 
206806f32e7eSjoerg   typename MapA::const_iterator posA;
206906f32e7eSjoerg   typename MapB::const_iterator posB;
207006f32e7eSjoerg 
207106f32e7eSjoerg   /// advance - Move posA and posB forward until reaching an overlap, or until
207206f32e7eSjoerg   /// either meets end.
207306f32e7eSjoerg   /// Don't move the iterators if they are already overlapping.
advance()207406f32e7eSjoerg   void advance() {
207506f32e7eSjoerg     if (!valid())
207606f32e7eSjoerg       return;
207706f32e7eSjoerg 
207806f32e7eSjoerg     if (Traits::stopLess(posA.stop(), posB.start())) {
207906f32e7eSjoerg       // A ends before B begins. Catch up.
208006f32e7eSjoerg       posA.advanceTo(posB.start());
208106f32e7eSjoerg       if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
208206f32e7eSjoerg         return;
208306f32e7eSjoerg     } else if (Traits::stopLess(posB.stop(), posA.start())) {
208406f32e7eSjoerg       // B ends before A begins. Catch up.
208506f32e7eSjoerg       posB.advanceTo(posA.start());
208606f32e7eSjoerg       if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
208706f32e7eSjoerg         return;
208806f32e7eSjoerg     } else
208906f32e7eSjoerg       // Already overlapping.
209006f32e7eSjoerg       return;
209106f32e7eSjoerg 
209206f32e7eSjoerg     while (true) {
209306f32e7eSjoerg       // Make a.end > b.start.
209406f32e7eSjoerg       posA.advanceTo(posB.start());
209506f32e7eSjoerg       if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
209606f32e7eSjoerg         return;
209706f32e7eSjoerg       // Make b.end > a.start.
209806f32e7eSjoerg       posB.advanceTo(posA.start());
209906f32e7eSjoerg       if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
210006f32e7eSjoerg         return;
210106f32e7eSjoerg     }
210206f32e7eSjoerg   }
210306f32e7eSjoerg 
210406f32e7eSjoerg public:
210506f32e7eSjoerg   /// IntervalMapOverlaps - Create an iterator for the overlaps of a and b.
IntervalMapOverlaps(const MapA & a,const MapB & b)210606f32e7eSjoerg   IntervalMapOverlaps(const MapA &a, const MapB &b)
210706f32e7eSjoerg     : posA(b.empty() ? a.end() : a.find(b.start())),
210806f32e7eSjoerg       posB(posA.valid() ? b.find(posA.start()) : b.end()) { advance(); }
210906f32e7eSjoerg 
211006f32e7eSjoerg   /// valid - Return true if iterator is at an overlap.
valid()211106f32e7eSjoerg   bool valid() const {
211206f32e7eSjoerg     return posA.valid() && posB.valid();
211306f32e7eSjoerg   }
211406f32e7eSjoerg 
211506f32e7eSjoerg   /// a - access the left hand side in the overlap.
a()211606f32e7eSjoerg   const typename MapA::const_iterator &a() const { return posA; }
211706f32e7eSjoerg 
211806f32e7eSjoerg   /// b - access the right hand side in the overlap.
b()211906f32e7eSjoerg   const typename MapB::const_iterator &b() const { return posB; }
212006f32e7eSjoerg 
212106f32e7eSjoerg   /// start - Beginning of the overlapping interval.
start()212206f32e7eSjoerg   KeyType start() const {
212306f32e7eSjoerg     KeyType ak = a().start();
212406f32e7eSjoerg     KeyType bk = b().start();
212506f32e7eSjoerg     return Traits::startLess(ak, bk) ? bk : ak;
212606f32e7eSjoerg   }
212706f32e7eSjoerg 
212806f32e7eSjoerg   /// stop - End of the overlapping interval.
stop()212906f32e7eSjoerg   KeyType stop() const {
213006f32e7eSjoerg     KeyType ak = a().stop();
213106f32e7eSjoerg     KeyType bk = b().stop();
213206f32e7eSjoerg     return Traits::startLess(ak, bk) ? ak : bk;
213306f32e7eSjoerg   }
213406f32e7eSjoerg 
213506f32e7eSjoerg   /// skipA - Move to the next overlap that doesn't involve a().
skipA()213606f32e7eSjoerg   void skipA() {
213706f32e7eSjoerg     ++posA;
213806f32e7eSjoerg     advance();
213906f32e7eSjoerg   }
214006f32e7eSjoerg 
214106f32e7eSjoerg   /// skipB - Move to the next overlap that doesn't involve b().
skipB()214206f32e7eSjoerg   void skipB() {
214306f32e7eSjoerg     ++posB;
214406f32e7eSjoerg     advance();
214506f32e7eSjoerg   }
214606f32e7eSjoerg 
214706f32e7eSjoerg   /// Preincrement - Move to the next overlap.
214806f32e7eSjoerg   IntervalMapOverlaps &operator++() {
214906f32e7eSjoerg     // Bump the iterator that ends first. The other one may have more overlaps.
215006f32e7eSjoerg     if (Traits::startLess(posB.stop(), posA.stop()))
215106f32e7eSjoerg       skipB();
215206f32e7eSjoerg     else
215306f32e7eSjoerg       skipA();
215406f32e7eSjoerg     return *this;
215506f32e7eSjoerg   }
215606f32e7eSjoerg 
215706f32e7eSjoerg   /// advanceTo - Move to the first overlapping interval with
215806f32e7eSjoerg   /// stopLess(x, stop()).
advanceTo(KeyType x)215906f32e7eSjoerg   void advanceTo(KeyType x) {
216006f32e7eSjoerg     if (!valid())
216106f32e7eSjoerg       return;
216206f32e7eSjoerg     // Make sure advanceTo sees monotonic keys.
216306f32e7eSjoerg     if (Traits::stopLess(posA.stop(), x))
216406f32e7eSjoerg       posA.advanceTo(x);
216506f32e7eSjoerg     if (Traits::stopLess(posB.stop(), x))
216606f32e7eSjoerg       posB.advanceTo(x);
216706f32e7eSjoerg     advance();
216806f32e7eSjoerg   }
216906f32e7eSjoerg };
217006f32e7eSjoerg 
217106f32e7eSjoerg } // end namespace llvm
217206f32e7eSjoerg 
217306f32e7eSjoerg #endif // LLVM_ADT_INTERVALMAP_H
2174