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