1 //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a coalescing interval map for small objects.
12 // KeyT objects are mapped to ValT objects. Intervals of keys that map to the
13 // same value are represented in a compressed form.
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.
18 // Like SmallVector, IntervalMap will store the first N intervals in the map
19 // object itself without any allocations. When space is exhausted it switches to
20 // a B+-tree representation with very small overhead for small key and value
23 // A Traits class specifies how keys are compared. It also allows IntervalMap to
24 // work with both closed and half-open intervals.
26 // Keys and values are not stored next to each other in a std::pair, so we don't
27 // provide such a value_type. Dereferencing iterators only returns the mapped
28 // value. The interval bounds are accessible through the start() and stop()
31 // IntervalMap is optimized for small key and value objects, 4 or 8 bytes each
32 // is the optimal size. For large objects use std::map instead.
34 //===----------------------------------------------------------------------===//
38 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
39 // class IntervalMap {
41 // typedef KeyT key_type;
42 // typedef ValT mapped_type;
43 // typedef RecyclingAllocator<...> Allocator;
45 // class const_iterator;
47 // explicit IntervalMap(Allocator&);
50 // bool empty() const;
51 // KeyT start() const;
53 // ValT lookup(KeyT x, Value NotFound = Value()) const;
55 // const_iterator begin() const;
56 // const_iterator end() const;
59 // const_iterator find(KeyT x) const;
60 // iterator find(KeyT x);
62 // void insert(KeyT a, KeyT b, ValT y);
66 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
67 // class IntervalMap::const_iterator :
68 // public std::iterator<std::bidirectional_iterator_tag, ValT> {
70 // bool operator==(const const_iterator &) const;
71 // bool operator!=(const const_iterator &) const;
72 // bool valid() const;
74 // const KeyT &start() const;
75 // const KeyT &stop() const;
76 // const ValT &value() const;
77 // const ValT &operator*() const;
78 // const ValT *operator->() const;
80 // const_iterator &operator++();
81 // const_iterator &operator++(int);
82 // const_iterator &operator--();
83 // const_iterator &operator--(int);
87 // void advanceTo(KeyT x);
90 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
91 // class IntervalMap::iterator : public const_iterator {
93 // void insert(KeyT a, KeyT b, Value y);
97 //===----------------------------------------------------------------------===//
99 #ifndef LLVM_ADT_INTERVALMAP_H
100 #define LLVM_ADT_INTERVALMAP_H
102 #include "llvm/ADT/SmallVector.h"
103 #include "llvm/ADT/PointerIntPair.h"
104 #include "llvm/Support/Allocator.h"
105 #include "llvm/Support/RecyclingAllocator.h"
109 // FIXME: Remove debugging code
111 #include "llvm/Support/raw_ostream.h"
117 //===----------------------------------------------------------------------===//
118 //--- Key traits ---//
119 //===----------------------------------------------------------------------===//
121 // The IntervalMap works with closed or half-open intervals.
122 // Adjacent intervals that map to the same value are coalesced.
124 // The IntervalMapInfo traits class is used to determine if a key is contained
125 // in an interval, and if two intervals are adjacent so they can be coalesced.
126 // The provided implementation works for closed integer intervals, other keys
127 // probably need a specialized version.
129 // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
131 // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
132 // allowed. This is so that stopLess(a, b) can be used to determine if two
133 // intervals overlap.
135 //===----------------------------------------------------------------------===//
137 template <typename T>
138 struct IntervalMapInfo {
140 /// startLess - Return true if x is not in [a;b].
141 /// This is x < a both for closed intervals and for [a;b) half-open intervals.
142 static inline bool startLess(const T &x, const T &a) {
146 /// stopLess - Return true if x is not in [a;b].
147 /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
148 static inline bool stopLess(const T &b, const T &x) {
152 /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
153 /// This is a+1 == b for closed intervals, a == b for half-open intervals.
154 static inline bool adjacent(const T &a, const T &b) {
160 /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
161 /// It should be considered private to the implementation.
162 namespace IntervalMapImpl {
164 // Forward declarations.
165 template <typename, typename, unsigned, typename> class LeafNode;
166 template <typename, typename, unsigned, typename> class BranchNode;
168 typedef std::pair<unsigned,unsigned> IdxPair;
171 //===----------------------------------------------------------------------===//
172 //--- Node Storage ---//
173 //===----------------------------------------------------------------------===//
175 // Both leaf and branch nodes store vectors of (key,value) pairs.
176 // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (KeyT, NodeRef).
178 // Keys and values are stored in separate arrays to avoid padding caused by
179 // different object alignments. This also helps improve locality of reference
180 // when searching the keys.
182 // The nodes don't know how many elements they contain - that information is
183 // stored elsewhere. Omitting the size field prevents padding and allows a node
184 // to fill the allocated cache lines completely.
186 // These are typical key and value sizes, the node branching factor (N), and
187 // wasted space when nodes are sized to fit in three cache lines (192 bytes):
189 // KT VT N Waste Used by
190 // 4 4 24 0 Branch<4> (32-bit pointers)
191 // 4 8 16 0 Branch<4>
192 // 8 4 16 0 Leaf<4,4>
193 // 8 8 12 0 Leaf<4,8>, Branch<8>
194 // 16 4 9 12 Leaf<8,4>
195 // 16 8 8 0 Leaf<8,8>
197 //===----------------------------------------------------------------------===//
199 template <typename KT, typename VT, unsigned N>
202 enum { Capacity = N };
207 /// copy - Copy elements from another node.
208 /// @param other Node elements are copied from.
209 /// @param i Beginning of the source range in other.
210 /// @param j Beginning of the destination range in this.
211 /// @param count Number of elements to copy.
212 template <unsigned M>
213 void copy(const NodeBase<KT, VT, M> &Other, unsigned i,
214 unsigned j, unsigned Count) {
215 assert(i + Count <= M && "Invalid source range");
216 assert(j + Count <= N && "Invalid dest range");
217 std::copy(Other.key + i, Other.key + i + Count, key + j);
218 std::copy(Other.val + i, Other.val + i + Count, val + j);
221 /// lmove - Move elements to the left.
222 /// @param i Beginning of the source range.
223 /// @param j Beginning of the destination range.
224 /// @param count Number of elements to copy.
225 void lmove(unsigned i, unsigned j, unsigned Count) {
226 assert(j <= i && "Use rmove shift elements right");
227 copy(*this, i, j, Count);
230 /// rmove - Move elements to the right.
231 /// @param i Beginning of the source range.
232 /// @param j Beginning of the destination range.
233 /// @param count Number of elements to copy.
234 void rmove(unsigned i, unsigned j, unsigned Count) {
235 assert(i <= j && "Use lmove shift elements left");
236 assert(j + Count <= N && "Invalid range");
237 std::copy_backward(key + i, key + i + Count, key + j + Count);
238 std::copy_backward(val + i, val + i + Count, val + j + Count);
241 /// erase - Erase elements [i;j).
242 /// @param i Beginning of the range to erase.
243 /// @param j End of the range. (Exclusive).
244 /// @param size Number of elements in node.
245 void erase(unsigned i, unsigned j, unsigned Size) {
246 lmove(j, i, Size - j);
249 /// shift - Shift elements [i;size) 1 position to the right.
250 /// @param i Beginning of the range to move.
251 /// @param size Number of elements in node.
252 void shift(unsigned i, unsigned Size) {
253 rmove(i, i + 1, Size - i);
256 /// xferLeft - Transfer elements to a left sibling node.
257 /// @param size Number of elements in this.
258 /// @param sib Left sibling node.
259 /// @param ssize Number of elements in sib.
260 /// @param count Number of elements to transfer.
261 void xferLeft(unsigned Size, NodeBase &Sib, unsigned SSize, unsigned Count) {
262 Sib.copy(*this, 0, SSize, Count);
263 erase(0, Count, Size);
266 /// xferRight - Transfer elements to a right sibling node.
267 /// @param size Number of elements in this.
268 /// @param sib Right sibling node.
269 /// @param ssize Number of elements in sib.
270 /// @param count Number of elements to transfer.
271 void xferRight(unsigned Size, NodeBase &Sib, unsigned SSize, unsigned Count) {
272 Sib.rmove(0, Count, SSize);
273 Sib.copy(*this, Size-Count, 0, Count);
276 /// adjLeftSib - Adjust the number if elements in this node by moving
277 /// elements to or from a left sibling node.
278 /// @param size Number of elements in this.
279 /// @param sib Right sibling node.
280 /// @param ssize Number of elements in sib.
281 /// @param add The number of elements to add to this node, possibly < 0.
282 /// @return Number of elements added to this node, possibly negative.
283 int adjLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
285 // We want to grow, copy from sib.
286 unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
287 Sib.xferRight(SSize, *this, Size, Count);
290 // We want to shrink, copy to sib.
291 unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
292 xferLeft(Size, Sib, SSize, Count);
299 //===----------------------------------------------------------------------===//
300 //--- NodeSizer ---//
301 //===----------------------------------------------------------------------===//
303 // Compute node sizes from key and value types.
305 // The branching factors are chosen to make nodes fit in three cache lines.
306 // This may not be possible if keys or values are very large. Such large objects
307 // are handled correctly, but a std::map would probably give better performance.
309 //===----------------------------------------------------------------------===//
312 // Cache line size. Most architectures have 32 or 64 byte cache lines.
313 // We use 64 bytes here because it provides good branching factors.
315 CacheLineBytes = 1 << Log2CacheLine,
316 DesiredNodeBytes = 3 * CacheLineBytes
319 template <typename KeyT, typename ValT>
322 // Compute the leaf node branching factor that makes a node fit in three
323 // cache lines. The branching factor must be at least 3, or some B+-tree
324 // balancing algorithms won't work.
325 // LeafSize can't be larger than CacheLineBytes. This is required by the
326 // PointerIntPair used by NodeRef.
327 DesiredLeafSize = DesiredNodeBytes /
328 static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
330 LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize,
332 // Now that we have the leaf branching factor, compute the actual allocation
333 // unit size by rounding up to a whole number of cache lines.
334 LeafBytes = sizeof(NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize>),
335 AllocBytes = (LeafBytes + CacheLineBytes-1) & ~(CacheLineBytes-1),
337 // Determine the branching factor for branch nodes.
338 BranchSize = AllocBytes /
339 static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
342 /// Allocator - The recycling allocator used for both branch and leaf nodes.
343 /// This typedef is very likely to be identical for all IntervalMaps with
344 /// reasonably sized entries, so the same allocator can be shared among
345 /// different kinds of maps.
346 typedef RecyclingAllocator<BumpPtrAllocator, char,
347 AllocBytes, CacheLineBytes> Allocator;
352 //===----------------------------------------------------------------------===//
354 //===----------------------------------------------------------------------===//
356 // B+-tree nodes can be leaves or branches, so we need a polymorphic node
357 // pointer that can point to both kinds.
359 // All nodes are cache line aligned and the low 6 bits of a node pointer are
360 // always 0. These bits are used to store the number of elements in the
361 // referenced node. Besides saving space, placing node sizes in the parents
362 // allow tree balancing algorithms to run without faulting cache lines for nodes
363 // that may not need to be modified.
365 // A NodeRef doesn't know whether it references a leaf node or a branch node.
366 // It is the responsibility of the caller to use the correct types.
368 // Nodes are never supposed to be empty, and it is invalid to store a node size
369 // of 0 in a NodeRef. The valid range of sizes is 1-64.
371 //===----------------------------------------------------------------------===//
373 struct CacheAlignedPointerTraits {
374 static inline void *getAsVoidPointer(void *P) { return P; }
375 static inline void *getFromVoidPointer(void *P) { return P; }
376 enum { NumLowBitsAvailable = Log2CacheLine };
379 template <typename KeyT, typename ValT, typename Traits>
382 typedef LeafNode<KeyT, ValT, NodeSizer<KeyT, ValT>::LeafSize, Traits> Leaf;
383 typedef BranchNode<KeyT, ValT, NodeSizer<KeyT, ValT>::BranchSize,
387 PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
390 /// NodeRef - Create a null ref.
393 /// operator bool - Detect a null ref.
394 operator bool() const { return pip.getOpaqueValue(); }
396 /// NodeRef - Create a reference to the leaf node p with n elements.
397 NodeRef(Leaf *p, unsigned n) : pip(p, n - 1) {}
399 /// NodeRef - Create a reference to the branch node p with n elements.
400 NodeRef(Branch *p, unsigned n) : pip(p, n - 1) {}
402 /// size - Return the number of elements in the referenced node.
403 unsigned size() const { return pip.getInt() + 1; }
405 /// setSize - Update the node size.
406 void setSize(unsigned n) { pip.setInt(n - 1); }
408 /// leaf - Return the referenced leaf node.
409 /// Note there are no dynamic type checks.
411 return *reinterpret_cast<Leaf*>(pip.getPointer());
414 /// branch - Return the referenced branch node.
415 /// Note there are no dynamic type checks.
416 Branch &branch() const {
417 return *reinterpret_cast<Branch*>(pip.getPointer());
420 bool operator==(const NodeRef &RHS) const {
423 assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
427 bool operator!=(const NodeRef &RHS) const {
428 return !operator==(RHS);
432 //===----------------------------------------------------------------------===//
433 //--- Leaf nodes ---//
434 //===----------------------------------------------------------------------===//
436 // Leaf nodes store up to N disjoint intervals with corresponding values.
438 // The intervals are kept sorted and fully coalesced so there are no adjacent
439 // intervals mapping to the same value.
441 // These constraints are always satisfied:
443 // - Traits::stopLess(key[i].start, key[i].stop) - Non-empty, sane intervals.
445 // - Traits::stopLess(key[i].stop, key[i + 1].start) - Sorted.
447 // - val[i] != val[i + 1] ||
448 // !Traits::adjacent(key[i].stop, key[i + 1].start) - Fully coalesced.
450 //===----------------------------------------------------------------------===//
452 template <typename KeyT, typename ValT, unsigned N, typename Traits>
453 class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
455 const KeyT &start(unsigned i) const { return this->key[i].first; }
456 const KeyT &stop(unsigned i) const { return this->key[i].second; }
457 const ValT &value(unsigned i) const { return this->val[i]; }
459 KeyT &start(unsigned i) { return this->key[i].first; }
460 KeyT &stop(unsigned i) { return this->key[i].second; }
461 ValT &value(unsigned i) { return this->val[i]; }
463 /// findFrom - Find the first interval after i that may contain x.
464 /// @param i Starting index for the search.
465 /// @param size Number of elements in node.
466 /// @param x Key to search for.
467 /// @return First index with !stopLess(key[i].stop, x), or size.
468 /// This is the first interval that can possibly contain x.
469 unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
470 assert(i <= Size && Size <= N && "Bad indices");
471 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
472 "Index is past the needed point");
473 while (i != Size && Traits::stopLess(stop(i), x)) ++i;
477 /// safeFind - Find an interval that is known to exist. This is the same as
478 /// findFrom except is it assumed that x is at least within range of the last
480 /// @param i Starting index for the search.
481 /// @param x Key to search for.
482 /// @return First index with !stopLess(key[i].stop, x), never size.
483 /// This is the first interval that can possibly contain x.
484 unsigned safeFind(unsigned i, KeyT x) const {
485 assert(i < N && "Bad index");
486 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
487 "Index is past the needed point");
488 while (Traits::stopLess(stop(i), x)) ++i;
489 assert(i < N && "Unsafe intervals");
493 /// safeLookup - Lookup mapped value for a safe key.
494 /// It is assumed that x is within range of the last entry.
495 /// @param x Key to search for.
496 /// @param NotFound Value to return if x is not in any interval.
497 /// @return The mapped value at x or NotFound.
498 ValT safeLookup(KeyT x, ValT NotFound) const {
499 unsigned i = safeFind(0, x);
500 return Traits::startLess(x, start(i)) ? NotFound : value(i);
503 IdxPair insertFrom(unsigned i, unsigned Size, KeyT a, KeyT b, ValT y);
504 unsigned extendStop(unsigned i, unsigned Size, KeyT b);
507 void dump(unsigned Size) {
508 errs() << " N" << this << " [shape=record label=\"{ " << Size << '/' << N;
509 for (unsigned i = 0; i != Size; ++i)
510 errs() << " | {" << start(i) << '-' << stop(i) << "|" << value(i) << '}';
517 /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
518 /// possible. This may cause the node to grow by 1, or it may cause the node
519 /// to shrink because of coalescing.
520 /// @param i Starting index = insertFrom(0, size, a)
521 /// @param size Number of elements in node.
522 /// @param a Interval start.
523 /// @param b Interval stop.
524 /// @param y Value be mapped.
525 /// @return (insert position, new size), or (i, Capacity+1) on overflow.
526 template <typename KeyT, typename ValT, unsigned N, typename Traits>
527 IdxPair LeafNode<KeyT, ValT, N, Traits>::
528 insertFrom(unsigned i, unsigned Size, KeyT a, KeyT b, ValT y) {
529 assert(i <= Size && Size <= N && "Invalid index");
530 assert(!Traits::stopLess(b, a) && "Invalid interval");
532 // Verify the findFrom invariant.
533 assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
534 assert((i == Size || !Traits::stopLess(stop(i), a)));
536 // Coalesce with previous interval.
537 if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a))
538 return IdxPair(i - 1, extendStop(i - 1, Size, b));
542 return IdxPair(i, N + 1);
544 // Add new interval at end.
549 return IdxPair(i, Size + 1);
552 // Overlapping intervals?
553 if (!Traits::stopLess(b, start(i))) {
554 assert(value(i) == y && "Inconsistent values in overlapping intervals");
555 if (Traits::startLess(a, start(i)))
557 return IdxPair(i, extendStop(i, Size, b));
560 // Try to coalesce with following interval.
561 if (value(i) == y && Traits::adjacent(b, start(i))) {
563 return IdxPair(i, Size);
566 // We must insert before i. Detect overflow.
568 return IdxPair(i, N + 1);
571 this->shift(i, Size);
575 return IdxPair(i, Size + 1);
578 /// extendStop - Extend stop(i) to b, coalescing with following intervals.
579 /// @param i Interval to extend.
580 /// @param size Number of elements in node.
581 /// @param b New interval end point.
582 /// @return New node size after coalescing.
583 template <typename KeyT, typename ValT, unsigned N, typename Traits>
584 unsigned LeafNode<KeyT, ValT, N, Traits>::
585 extendStop(unsigned i, unsigned Size, KeyT b) {
586 assert(i < Size && Size <= N && "Bad indices");
588 // Are we even extending the interval?
589 if (Traits::startLess(b, stop(i)))
592 // Find the first interval that may be preserved.
593 unsigned j = findFrom(i + 1, Size, b);
595 // Would key[i] overlap key[j] after the extension?
596 if (Traits::stopLess(b, start(j))) {
597 // Not overlapping. Perhaps adjacent and coalescable?
598 if (value(i) == value(j) && Traits::adjacent(b, start(j)))
601 // Overlap. Include key[j] in the new interval.
602 assert(value(i) == value(j) && "Overlapping values");
608 // Entries [i+1;j) were coalesced.
609 if (i + 1 < j && j < Size)
610 this->erase(i + 1, j, Size);
611 return Size - (j - (i + 1));
615 //===----------------------------------------------------------------------===//
616 //--- Branch nodes ---//
617 //===----------------------------------------------------------------------===//
619 // A branch node stores references to 1--N subtrees all of the same height.
621 // The key array in a branch node holds the rightmost stop key of each subtree.
622 // It is redundant to store the last stop key since it can be found in the
623 // parent node, but doing so makes tree balancing a lot simpler.
625 // It is unusual for a branch node to only have one subtree, but it can happen
626 // in the root node if it is smaller than the normal nodes.
628 // When all of the leaf nodes from all the subtrees are concatenated, they must
629 // satisfy the same constraints as a single leaf node. They must be sorted,
630 // sane, and fully coalesced.
632 //===----------------------------------------------------------------------===//
634 template <typename KeyT, typename ValT, unsigned N, typename Traits>
635 class BranchNode : public NodeBase<KeyT, NodeRef<KeyT, ValT, Traits>, N> {
636 typedef NodeRef<KeyT, ValT, Traits> NodeRefT;
638 const KeyT &stop(unsigned i) const { return this->key[i]; }
639 const NodeRefT &subtree(unsigned i) const { return this->val[i]; }
641 KeyT &stop(unsigned i) { return this->key[i]; }
642 NodeRefT &subtree(unsigned i) { return this->val[i]; }
644 /// findFrom - Find the first subtree after i that may contain x.
645 /// @param i Starting index for the search.
646 /// @param size Number of elements in node.
647 /// @param x Key to search for.
648 /// @return First index with !stopLess(key[i], x), or size.
649 /// This is the first subtree that can possibly contain x.
650 unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
651 assert(i <= Size && Size <= N && "Bad indices");
652 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
653 "Index to findFrom is past the needed point");
654 while (i != Size && Traits::stopLess(stop(i), x)) ++i;
658 /// safeFind - Find a subtree that is known to exist. This is the same as
659 /// findFrom except is it assumed that x is in range.
660 /// @param i Starting index for the search.
661 /// @param x Key to search for.
662 /// @return First index with !stopLess(key[i], x), never size.
663 /// This is the first subtree that can possibly contain x.
664 unsigned safeFind(unsigned i, KeyT x) const {
665 assert(i < N && "Bad index");
666 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
667 "Index is past the needed point");
668 while (Traits::stopLess(stop(i), x)) ++i;
669 assert(i < N && "Unsafe intervals");
673 /// safeLookup - Get the subtree containing x, Assuming that x is in range.
674 /// @param x Key to search for.
675 /// @return Subtree containing x
676 NodeRefT safeLookup(KeyT x) const {
677 return subtree(safeFind(0, x));
680 /// insert - Insert a new (subtree, stop) pair.
681 /// @param i Insert position, following entries will be shifted.
682 /// @param size Number of elements in node.
683 /// @param node Subtree to insert.
684 /// @param stp Last key in subtree.
685 void insert(unsigned i, unsigned Size, NodeRefT Node, KeyT Stop) {
686 assert(Size < N && "branch node overflow");
687 assert(i <= Size && "Bad insert position");
688 this->shift(i, Size);
694 void dump(unsigned Size) {
695 errs() << " N" << this << " [shape=record label=\"" << Size << '/' << N;
696 for (unsigned i = 0; i != Size; ++i)
697 errs() << " | <s" << i << "> " << stop(i);
699 for (unsigned i = 0; i != Size; ++i)
700 errs() << " N" << this << ":s" << i << " -> N"
701 << &subtree(i).branch() << ";\n";
707 } // namespace IntervalMapImpl
710 //===----------------------------------------------------------------------===//
711 //--- IntervalMap ----//
712 //===----------------------------------------------------------------------===//
714 template <typename KeyT, typename ValT,
715 unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
716 typename Traits = IntervalMapInfo<KeyT> >
718 typedef IntervalMapImpl::NodeRef<KeyT, ValT, Traits> NodeRef;
719 typedef IntervalMapImpl::NodeSizer<KeyT, ValT> NodeSizer;
720 typedef typename NodeRef::Leaf Leaf;
721 typedef typename NodeRef::Branch Branch;
722 typedef IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits> RootLeaf;
723 typedef IntervalMapImpl::IdxPair IdxPair;
725 // The RootLeaf capacity is given as a template parameter. We must compute the
726 // corresponding RootBranch capacity.
728 DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
729 (sizeof(KeyT) + sizeof(NodeRef)),
730 RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
733 typedef IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits> RootBranch;
735 // When branched, we store a global start key as well as the branch node.
736 struct RootBranchData {
742 RootDataSize = sizeof(RootBranchData) > sizeof(RootLeaf) ?
743 sizeof(RootBranchData) : sizeof(RootLeaf)
747 typedef typename NodeSizer::Allocator Allocator;
750 // The root data is either a RootLeaf or a RootBranchData instance.
751 // We can't put them in a union since C++03 doesn't allow non-trivial
752 // constructors in unions.
753 // Instead, we use a char array with pointer alignment. The alignment is
754 // ensured by the allocator member in the class, but still verified in the
755 // constructor. We don't support keys or values that are more aligned than a
757 char data[RootDataSize];
760 // 0: Leaves in root.
761 // 1: Root points to leaf.
762 // 2: root->branch->leaf ...
765 // Number of entries in the root node.
768 // Allocator used for creating external nodes.
769 Allocator &allocator;
771 /// dataAs - Represent data as a node type without breaking aliasing rules.
772 template <typename T>
782 const RootLeaf &rootLeaf() const {
783 assert(!branched() && "Cannot acces leaf data in branched root");
784 return dataAs<RootLeaf>();
786 RootLeaf &rootLeaf() {
787 assert(!branched() && "Cannot acces leaf data in branched root");
788 return dataAs<RootLeaf>();
790 RootBranchData &rootBranchData() const {
791 assert(branched() && "Cannot access branch data in non-branched root");
792 return dataAs<RootBranchData>();
794 RootBranchData &rootBranchData() {
795 assert(branched() && "Cannot access branch data in non-branched root");
796 return dataAs<RootBranchData>();
798 const RootBranch &rootBranch() const { return rootBranchData().node; }
799 RootBranch &rootBranch() { return rootBranchData().node; }
800 KeyT rootBranchStart() const { return rootBranchData().start; }
801 KeyT &rootBranchStart() { return rootBranchData().start; }
804 return new(allocator.template Allocate<Leaf>()) Leaf();
806 void freeLeaf(Leaf *P) {
808 allocator.Deallocate(P);
811 Branch *allocBranch() {
812 return new(allocator.template Allocate<Branch>()) Branch();
814 void freeBranch(Branch *P) {
816 allocator.Deallocate(P);
820 IdxPair branchRoot(unsigned Position);
821 IdxPair splitRoot(unsigned Position);
823 void switchRootToBranch() {
824 rootLeaf().~RootLeaf();
826 new (&rootBranchData()) RootBranchData();
829 void switchRootToLeaf() {
830 rootBranchData().~RootBranchData();
832 new(&rootLeaf()) RootLeaf();
835 bool branched() const { return height > 0; }
837 ValT treeSafeLookup(KeyT x, ValT NotFound) const;
839 void visitNodes(void (IntervalMap::*f)(NodeRef, unsigned Level));
842 explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
843 assert((uintptr_t(data) & (alignOf<RootLeaf>() - 1)) == 0 &&
844 "Insufficient alignment");
845 new(&rootLeaf()) RootLeaf();
848 /// empty - Return true when no intervals are mapped.
850 return rootSize == 0;
853 /// start - Return the smallest mapped key in a non-empty map.
855 assert(!empty() && "Empty IntervalMap has no start");
856 return !branched() ? rootLeaf().start(0) : rootBranchStart();
859 /// stop - Return the largest mapped key in a non-empty map.
861 assert(!empty() && "Empty IntervalMap has no stop");
862 return !branched() ? rootLeaf().stop(rootSize - 1) :
863 rootBranch().stop(rootSize - 1);
866 /// lookup - Return the mapped value at x or NotFound.
867 ValT lookup(KeyT x, ValT NotFound = ValT()) const {
868 if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
870 return branched() ? treeSafeLookup(x, NotFound) :
871 rootLeaf().safeLookup(x, NotFound);
874 /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
875 /// It is assumed that no key in the interval is mapped to another value, but
876 /// overlapping intervals already mapped to y will be coalesced.
877 void insert(KeyT a, KeyT b, ValT y) {
878 find(a).insert(a, b, y);
881 class const_iterator;
883 friend class const_iterator;
884 friend class iterator;
886 const_iterator begin() const {
898 const_iterator end() const {
910 /// find - Return an iterator pointing to the first interval ending at or
911 /// after x, or end().
912 const_iterator find(KeyT x) const {
918 iterator find(KeyT x) {
926 void dumpNode(NodeRef Node, unsigned Height);
930 /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
932 template <typename KeyT, typename ValT, unsigned N, typename Traits>
933 ValT IntervalMap<KeyT, ValT, N, Traits>::
934 treeSafeLookup(KeyT x, ValT NotFound) const {
935 assert(branched() && "treeLookup assumes a branched root");
937 NodeRef NR = rootBranch().safeLookup(x);
938 for (unsigned h = height-1; h; --h)
939 NR = NR.branch().safeLookup(x);
940 return NR.leaf().safeLookup(x, NotFound);
944 // branchRoot - Switch from a leaf root to a branched root.
945 // Return the new (root offset, node offset) corresponding to Position.
946 template <typename KeyT, typename ValT, unsigned N, typename Traits>
947 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
948 branchRoot(unsigned Position) {
949 // How many external leaf nodes to hold RootLeaf+1?
950 const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
952 // Compute element distribution among new nodes.
953 unsigned size[Nodes];
954 IdxPair NewOffset(0, Position);
956 // Is is very common for the root node to be smaller than external nodes.
960 NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, size,
963 // Allocate new nodes.
966 for (unsigned n = 0; n != Nodes; ++n) {
967 node[n] = NodeRef(allocLeaf(), size[n]);
968 node[n].leaf().copy(rootLeaf(), pos, 0, size[n]);
972 // Destroy the old leaf node, construct branch node instead.
973 switchRootToBranch();
974 for (unsigned n = 0; n != Nodes; ++n) {
975 rootBranch().stop(n) = node[n].leaf().stop(size[n]-1);
976 rootBranch().subtree(n) = node[n];
978 rootBranchStart() = node[0].leaf().start(0);
983 // splitRoot - Split the current BranchRoot into multiple Branch nodes.
984 // Return the new (root offset, node offset) corresponding to Position.
985 template <typename KeyT, typename ValT, unsigned N, typename Traits>
986 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
987 splitRoot(unsigned Position) {
988 // How many external leaf nodes to hold RootBranch+1?
989 const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
991 // Compute element distribution among new nodes.
992 unsigned Size[Nodes];
993 IdxPair NewOffset(0, Position);
995 // Is is very common for the root node to be smaller than external nodes.
999 NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, Size,
1002 // Allocate new nodes.
1004 NodeRef Node[Nodes];
1005 for (unsigned n = 0; n != Nodes; ++n) {
1006 Node[n] = NodeRef(allocBranch(), Size[n]);
1007 Node[n].branch().copy(rootBranch(), Pos, 0, Size[n]);
1011 for (unsigned n = 0; n != Nodes; ++n) {
1012 rootBranch().stop(n) = Node[n].branch().stop(Size[n]-1);
1013 rootBranch().subtree(n) = Node[n];
1019 /// visitNodes - Visit each external node.
1020 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1021 void IntervalMap<KeyT, ValT, N, Traits>::
1022 visitNodes(void (IntervalMap::*f)(NodeRef, unsigned Height)) {
1025 SmallVector<NodeRef, 4> Refs, NextRefs;
1027 // Collect level 0 nodes from the root.
1028 for (unsigned i = 0; i != rootSize; ++i)
1029 Refs.push_back(rootBranch().subtree(i));
1031 // Visit all branch nodes.
1032 for (unsigned h = height - 1; h; --h) {
1033 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
1034 Branch &B = Refs[i].branch();
1035 for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
1036 NextRefs.push_back(B.subtree(j));
1037 (this->*f)(Refs[i], h);
1040 Refs.swap(NextRefs);
1043 // Visit all leaf nodes.
1044 for (unsigned i = 0, e = Refs.size(); i != e; ++i)
1045 (this->*f)(Refs[i], 0);
1049 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1050 void IntervalMap<KeyT, ValT, N, Traits>::
1051 dumpNode(NodeRef Node, unsigned Height) {
1053 Node.branch().dump(Node.size());
1055 Node.leaf().dump(Node.size());
1058 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1059 void IntervalMap<KeyT, ValT, N, Traits>::
1061 errs() << "digraph {\n";
1063 rootBranch().dump(rootSize);
1065 rootLeaf().dump(rootSize);
1066 visitNodes(&IntervalMap::dumpNode);
1071 //===----------------------------------------------------------------------===//
1072 //--- const_iterator ----//
1073 //===----------------------------------------------------------------------===//
1075 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1076 class IntervalMap<KeyT, ValT, N, Traits>::const_iterator :
1077 public std::iterator<std::bidirectional_iterator_tag, ValT> {
1079 friend class IntervalMap;
1080 typedef std::pair<NodeRef, unsigned> PathEntry;
1081 typedef SmallVector<PathEntry, 4> Path;
1083 // The map referred to.
1086 // The offset into map's root node.
1087 unsigned rootOffset;
1089 // We store a full path from the root to the current position.
1091 // When rootOffset == map->rootSize, we are at end() and path() is empty.
1092 // Otherwise, when branched these conditions hold:
1094 // 1. path.front().first == rootBranch().subtree(rootOffset)
1095 // 2. path[i].first == path[i-1].first.branch().subtree(path[i-1].second)
1096 // 3. path.size() == map->height.
1098 // Thus, path.back() always refers to the current leaf node unless the root is
1101 // The path may be partially filled, but never between iterator calls.
1104 explicit const_iterator(IntervalMap &map)
1105 : map(&map), rootOffset(map.rootSize) {}
1107 bool branched() const {
1108 assert(map && "Invalid iterator");
1109 return map->branched();
1112 NodeRef pathNode(unsigned h) const { return path[h].first; }
1113 NodeRef &pathNode(unsigned h) { return path[h].first; }
1114 unsigned pathOffset(unsigned h) const { return path[h].second; }
1115 unsigned &pathOffset(unsigned h) { return path[h].second; }
1117 Leaf &treeLeaf() const {
1118 assert(branched() && path.size() == map->height);
1119 return path.back().first.leaf();
1121 unsigned treeLeafSize() const {
1122 assert(branched() && path.size() == map->height);
1123 return path.back().first.size();
1125 unsigned &treeLeafOffset() {
1126 assert(branched() && path.size() == map->height);
1127 return path.back().second;
1129 unsigned treeLeafOffset() const {
1130 assert(branched() && path.size() == map->height);
1131 return path.back().second;
1134 // Get the next node ptr for an incomplete path.
1135 NodeRef pathNextDown() {
1136 assert(path.size() < map->height && "Path is already complete");
1139 return map->rootBranch().subtree(rootOffset);
1141 return path.back().first.branch().subtree(path.back().second);
1144 void pathFillLeft();
1145 void pathFillFind(KeyT x);
1146 void pathFillRight();
1148 NodeRef leftSibling(unsigned level) const;
1149 NodeRef rightSibling(unsigned level) const;
1151 void treeIncrement();
1152 void treeDecrement();
1153 void treeFind(KeyT x);
1156 /// valid - Return true if the current position is valid, false for end().
1157 bool valid() const {
1158 assert(map && "Invalid iterator");
1159 return rootOffset < map->rootSize;
1162 /// start - Return the beginning of the current interval.
1163 const KeyT &start() const {
1164 assert(valid() && "Cannot access invalid iterator");
1165 return branched() ? treeLeaf().start(treeLeafOffset()) :
1166 map->rootLeaf().start(rootOffset);
1169 /// stop - Return the end of the current interval.
1170 const KeyT &stop() const {
1171 assert(valid() && "Cannot access invalid iterator");
1172 return branched() ? treeLeaf().stop(treeLeafOffset()) :
1173 map->rootLeaf().stop(rootOffset);
1176 /// value - Return the mapped value at the current interval.
1177 const ValT &value() const {
1178 assert(valid() && "Cannot access invalid iterator");
1179 return branched() ? treeLeaf().value(treeLeafOffset()) :
1180 map->rootLeaf().value(rootOffset);
1183 const ValT &operator*() const {
1187 bool operator==(const const_iterator &RHS) const {
1188 assert(map == RHS.map && "Cannot compare iterators from different maps");
1189 return rootOffset == RHS.rootOffset &&
1190 (!valid() || !branched() || path.back() == RHS.path.back());
1193 bool operator!=(const const_iterator &RHS) const {
1194 return !operator==(RHS);
1197 /// goToBegin - Move to the first interval in map.
1205 /// goToEnd - Move beyond the last interval in map.
1207 rootOffset = map->rootSize;
1211 /// preincrement - move to the next interval.
1212 const_iterator &operator++() {
1213 assert(valid() && "Cannot increment end()");
1216 else if (treeLeafOffset() != treeLeafSize() - 1)
1223 /// postincrement - Dont do that!
1224 const_iterator operator++(int) {
1225 const_iterator tmp = *this;
1230 /// predecrement - move to the previous interval.
1231 const_iterator &operator--() {
1233 assert(rootOffset && "Cannot decrement begin()");
1235 } else if (treeLeafOffset())
1242 /// postdecrement - Dont do that!
1243 const_iterator operator--(int) {
1244 const_iterator tmp = *this;
1249 /// find - Move to the first interval with stop >= x, or end().
1250 /// This is a full search from the root, the current position is ignored.
1255 rootOffset = map->rootLeaf().findFrom(0, map->rootSize, x);
1258 /// advanceTo - Move to the first interval with stop >= x, or end().
1259 /// The search is started from the current position, and no earlier positions
1260 /// can be found. This is much faster than find() for small moves.
1261 void advanceTo(KeyT x) {
1265 rootOffset = map->rootLeaf().findFrom(rootOffset, map->rootSize, x);
1270 // pathFillLeft - Complete path by following left-most branches.
1271 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1272 void IntervalMap<KeyT, ValT, N, Traits>::
1273 const_iterator::pathFillLeft() {
1274 NodeRef NR = pathNextDown();
1275 for (unsigned i = map->height - path.size() - 1; i; --i) {
1276 path.push_back(PathEntry(NR, 0));
1277 NR = NR.branch().subtree(0);
1279 path.push_back(PathEntry(NR, 0));
1282 // pathFillFind - Complete path by searching for x.
1283 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1284 void IntervalMap<KeyT, ValT, N, Traits>::
1285 const_iterator::pathFillFind(KeyT x) {
1286 NodeRef NR = pathNextDown();
1287 for (unsigned i = map->height - path.size() - 1; i; --i) {
1288 unsigned p = NR.branch().safeFind(0, x);
1289 path.push_back(PathEntry(NR, p));
1290 NR = NR.branch().subtree(p);
1292 path.push_back(PathEntry(NR, NR.leaf().safeFind(0, x)));
1295 // pathFillRight - Complete path by adding rightmost entries.
1296 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1297 void IntervalMap<KeyT, ValT, N, Traits>::
1298 const_iterator::pathFillRight() {
1299 NodeRef NR = pathNextDown();
1300 for (unsigned i = map->height - path.size() - 1; i; --i) {
1301 unsigned p = NR.size() - 1;
1302 path.push_back(PathEntry(NR, p));
1303 NR = NR.branch().subtree(p);
1305 path.push_back(PathEntry(NR, NR.size() - 1));
1308 /// leftSibling - find the left sibling node to path[level].
1309 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1310 /// @return The left sibling NodeRef, or NULL.
1311 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1312 typename IntervalMap<KeyT, ValT, N, Traits>::NodeRef
1313 IntervalMap<KeyT, ValT, N, Traits>::
1314 const_iterator::leftSibling(unsigned level) const {
1315 assert(branched() && "Not at a branched node");
1316 assert(level <= path.size() && "Bad level");
1318 // Go up the tree until we can go left.
1320 while (h && pathOffset(h - 1) == 0)
1323 // We are at the first leaf node, no left sibling.
1324 if (!h && rootOffset == 0)
1327 // NR is the subtree containing our left sibling.
1329 pathNode(h - 1).branch().subtree(pathOffset(h - 1) - 1) :
1330 map->rootBranch().subtree(rootOffset - 1);
1332 // Keep right all the way down.
1333 for (; h != level; ++h)
1334 NR = NR.branch().subtree(NR.size() - 1);
1338 /// rightSibling - find the right sibling node to path[level].
1339 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1340 /// @return The right sibling NodeRef, or NULL.
1341 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1342 typename IntervalMap<KeyT, ValT, N, Traits>::NodeRef
1343 IntervalMap<KeyT, ValT, N, Traits>::
1344 const_iterator::rightSibling(unsigned level) const {
1345 assert(branched() && "Not at a branched node");
1346 assert(level <= this->path.size() && "Bad level");
1348 // Go up the tree until we can go right.
1350 while (h && pathOffset(h - 1) == pathNode(h - 1).size() - 1)
1353 // We are at the last leaf node, no right sibling.
1354 if (!h && rootOffset == map->rootSize - 1)
1357 // NR is the subtree containing our right sibling.
1359 pathNode(h - 1).branch().subtree(pathOffset(h - 1) + 1) :
1360 map->rootBranch().subtree(rootOffset + 1);
1362 // Keep left all the way down.
1363 for (; h != level; ++h)
1364 NR = NR.branch().subtree(0);
1368 // treeIncrement - Move to the beginning of the next leaf node.
1369 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1370 void IntervalMap<KeyT, ValT, N, Traits>::
1371 const_iterator::treeIncrement() {
1372 assert(branched() && "treeIncrement is not for small maps");
1373 assert(path.size() == map->height && "inconsistent iterator");
1375 while (!path.empty() && path.back().second == path.back().first.size() - 1);
1381 ++path.back().second;
1385 // treeDecrement - Move to the end of the previous leaf node.
1386 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1387 void IntervalMap<KeyT, ValT, N, Traits>::
1388 const_iterator::treeDecrement() {
1389 assert(branched() && "treeDecrement is not for small maps");
1391 assert(path.size() == map->height && "inconsistent iterator");
1393 while (!path.empty() && path.back().second == 0);
1396 assert(rootOffset && "cannot treeDecrement() on begin()");
1399 --path.back().second;
1403 // treeFind - Find in a branched tree.
1404 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1405 void IntervalMap<KeyT, ValT, N, Traits>::
1406 const_iterator::treeFind(KeyT x) {
1408 rootOffset = map->rootBranch().findFrom(0, map->rootSize, x);
1414 //===----------------------------------------------------------------------===//
1415 //--- iterator ----//
1416 //===----------------------------------------------------------------------===//
1418 namespace IntervalMapImpl {
1420 /// distribute - Compute a new distribution of node elements after an overflow
1421 /// or underflow. Reserve space for a new element at Position, and compute the
1422 /// node that will hold Position after redistributing node elements.
1424 /// It is required that
1426 /// Elements == sum(CurSize), and
1427 /// Elements + Grow <= Nodes * Capacity.
1429 /// NewSize[] will be filled in such that:
1431 /// sum(NewSize) == Elements, and
1432 /// NewSize[i] <= Capacity.
1434 /// The returned index is the node where Position will go, so:
1436 /// sum(NewSize[0..idx-1]) <= Position
1437 /// sum(NewSize[0..idx]) >= Position
1439 /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
1440 /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
1441 /// before the one holding the Position'th element where there is room for an
1444 /// @param Nodes The number of nodes.
1445 /// @param Elements Total elements in all nodes.
1446 /// @param Capacity The capacity of each node.
1447 /// @param CurSize Array[Nodes] of current node sizes, or NULL.
1448 /// @param NewSize Array[Nodes] to receive the new node sizes.
1449 /// @param Position Insert position.
1450 /// @param Grow Reserve space for a new element at Position.
1451 /// @return (node, offset) for Position.
1452 IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
1453 const unsigned *CurSize, unsigned NewSize[],
1454 unsigned Position, bool Grow);
1458 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1459 class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
1460 friend class IntervalMap;
1461 typedef IntervalMapImpl::IdxPair IdxPair;
1463 explicit iterator(IntervalMap &map) : const_iterator(map) {}
1465 void setNodeSize(unsigned Level, unsigned Size);
1466 void setNodeStop(unsigned Level, KeyT Stop);
1467 void insertNode(unsigned Level, NodeRef Node, KeyT Stop);
1468 void overflowLeaf();
1469 void treeInsert(KeyT a, KeyT b, ValT y);
1472 /// insert - Insert mapping [a;b] -> y before the current position.
1473 void insert(KeyT a, KeyT b, ValT y);
1477 /// setNodeSize - Set the size of the node at path[level], updating both path
1478 /// and the real tree.
1479 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1480 /// @param size New node size.
1481 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1482 void IntervalMap<KeyT, ValT, N, Traits>::
1483 iterator::setNodeSize(unsigned Level, unsigned Size) {
1484 this->pathNode(Level).setSize(Size);
1486 this->pathNode(Level-1).branch()
1487 .subtree(this->pathOffset(Level-1)).setSize(Size);
1489 this->map->rootBranch().subtree(this->rootOffset).setSize(Size);
1492 /// setNodeStop - Update the stop key of the current node at level and above.
1493 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1494 void IntervalMap<KeyT, ValT, N, Traits>::
1495 iterator::setNodeStop(unsigned Level, KeyT Stop) {
1497 this->pathNode(Level).branch().stop(this->pathOffset(Level)) = Stop;
1498 if (this->pathOffset(Level) != this->pathNode(Level).size() - 1)
1501 this->map->rootBranch().stop(this->rootOffset) = Stop;
1504 /// insertNode - insert a node before the current path at level.
1505 /// Leave the current path pointing at the new node.
1506 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1507 void IntervalMap<KeyT, ValT, N, Traits>::
1508 iterator::insertNode(unsigned Level, NodeRef Node, KeyT Stop) {
1510 // Insert into the root branch node.
1511 IntervalMap &IM = *this->map;
1512 if (IM.rootSize < RootBranch::Capacity) {
1513 IM.rootBranch().insert(this->rootOffset, IM.rootSize, Node, Stop);
1518 // We need to split the root while keeping our position.
1519 IdxPair Offset = IM.splitRoot(this->rootOffset);
1520 this->rootOffset = Offset.first;
1521 this->path.insert(this->path.begin(),std::make_pair(
1522 this->map->rootBranch().subtree(Offset.first), Offset.second));
1526 // When inserting before end(), make sure we have a valid path.
1527 if (!this->valid()) {
1528 this->treeDecrement();
1529 ++this->pathOffset(Level-1);
1532 // Insert into the branch node at level-1.
1533 NodeRef NR = this->pathNode(Level-1);
1534 unsigned Offset = this->pathOffset(Level-1);
1535 assert(NR.size() < Branch::Capacity && "Branch overflow");
1536 NR.branch().insert(Offset, NR.size(), Node, Stop);
1537 setNodeSize(Level - 1, NR.size() + 1);
1541 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1542 void IntervalMap<KeyT, ValT, N, Traits>::
1543 iterator::insert(KeyT a, KeyT b, ValT y) {
1544 if (this->branched())
1545 return treeInsert(a, b, y);
1546 IdxPair IP = this->map->rootLeaf().insertFrom(this->rootOffset,
1547 this->map->rootSize,
1549 if (IP.second <= RootLeaf::Capacity) {
1550 this->rootOffset = IP.first;
1551 this->map->rootSize = IP.second;
1554 IdxPair Offset = this->map->branchRoot(this->rootOffset);
1555 this->rootOffset = Offset.first;
1556 this->path.push_back(std::make_pair(
1557 this->map->rootBranch().subtree(Offset.first), Offset.second));
1558 treeInsert(a, b, y);
1562 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1563 void IntervalMap<KeyT, ValT, N, Traits>::
1564 iterator::treeInsert(KeyT a, KeyT b, ValT y) {
1565 if (!this->valid()) {
1566 // end() has an empty path. Go back to the last leaf node and use an
1567 // invalid offset instead.
1568 this->treeDecrement();
1569 ++this->treeLeafOffset();
1571 IdxPair IP = this->treeLeaf().insertFrom(this->treeLeafOffset(),
1572 this->treeLeafSize(), a, b, y);
1573 this->treeLeafOffset() = IP.first;
1574 if (IP.second <= Leaf::Capacity) {
1575 setNodeSize(this->map->height - 1, IP.second);
1576 if (IP.first == IP.second - 1)
1577 setNodeStop(this->map->height - 1, this->treeLeaf().stop(IP.first));
1580 // Leaf node has no space.
1582 IP = this->treeLeaf().insertFrom(this->treeLeafOffset(),
1583 this->treeLeafSize(), a, b, y);
1584 this->treeLeafOffset() = IP.first;
1585 setNodeSize(this->map->height-1, IP.second);
1586 if (IP.first == IP.second - 1)
1587 setNodeStop(this->map->height - 1, this->treeLeaf().stop(IP.first));
1589 // FIXME: Handle cross-node coalescing.
1592 // overflowLeaf - Distribute entries of the current leaf node evenly among
1593 // its siblings and ensure that the current node is not full.
1594 // This may require allocating a new node.
1595 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1596 void IntervalMap<KeyT, ValT, N, Traits>::
1597 iterator::overflowLeaf() {
1598 unsigned CurSize[4];
1601 unsigned Elements = 0;
1602 unsigned Offset = this->treeLeafOffset();
1604 // Do we have a left sibling?
1605 NodeRef LeftSib = this->leftSibling(this->map->height-1);
1607 Offset += Elements = CurSize[Nodes] = LeftSib.size();
1608 Node[Nodes++] = &LeftSib.leaf();
1611 // Current leaf node.
1612 Elements += CurSize[Nodes] = this->treeLeafSize();
1613 Node[Nodes++] = &this->treeLeaf();
1615 // Do we have a right sibling?
1616 NodeRef RightSib = this->rightSibling(this->map->height-1);
1618 Offset += Elements = CurSize[Nodes] = RightSib.size();
1619 Node[Nodes++] = &RightSib.leaf();
1622 // Do we need to allocate a new node?
1623 unsigned NewNode = 0;
1624 if (Elements + 1 > Nodes * Leaf::Capacity) {
1625 // Insert NewNode at the penultimate position, or after a single node.
1626 NewNode = Nodes == 1 ? 1 : Nodes - 1;
1627 CurSize[Nodes] = CurSize[NewNode];
1628 Node[Nodes] = Node[NewNode];
1629 CurSize[NewNode] = 0;
1630 Node[NewNode] = this->map->allocLeaf();
1634 // Compute the new element distribution.
1635 unsigned NewSize[4];
1637 IntervalMapImpl::distribute(Nodes, Elements, Leaf::Capacity,
1638 CurSize, NewSize, Offset, true);
1640 // Move current location to the leftmost node.
1642 this->treeDecrement();
1644 // Move elements right.
1645 for (int n = Nodes - 1; n; --n) {
1646 if (CurSize[n] == NewSize[n])
1648 for (int m = n - 1; m != -1; --m) {
1649 int d = Node[n]->adjLeftSib(CurSize[n], *Node[m], CurSize[m],
1650 NewSize[n] - CurSize[n]);
1653 // Keep going if the current node was exhausted.
1654 if (CurSize[n] >= NewSize[n])
1659 // Move elements left.
1660 for (unsigned n = 0; n != Nodes - 1; ++n) {
1661 if (CurSize[n] == NewSize[n])
1663 for (unsigned m = n + 1; m != Nodes; ++m) {
1664 int d = Node[m]->adjLeftSib(CurSize[m], *Node[n], CurSize[n],
1665 CurSize[n] - NewSize[n]);
1668 // Keep going if the current node was exhausted.
1669 if (CurSize[n] >= NewSize[n])
1675 for (unsigned n = 0; n != Nodes; n++)
1676 assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
1679 // Elements have been rearranged, now update node sizes and stops.
1682 KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
1683 if (NewNode && Pos == NewNode)
1684 insertNode(this->map->height - 1, NodeRef(Node[Pos], NewSize[Pos]), Stop);
1686 setNodeSize(this->map->height - 1, NewSize[Pos]);
1687 setNodeStop(this->map->height - 1, Stop);
1689 if (Pos + 1 == Nodes)
1691 this->treeIncrement();
1695 // Where was I? Find NewOffset.
1696 while(Pos != NewOffset.first) {
1697 this->treeDecrement();
1700 this->treeLeafOffset() = NewOffset.second;