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.
110 #include "llvm/Support/raw_ostream.h"
115 //===----------------------------------------------------------------------===//
116 //--- Key traits ---//
117 //===----------------------------------------------------------------------===//
119 // The IntervalMap works with closed or half-open intervals.
120 // Adjacent intervals that map to the same value are coalesced.
122 // The IntervalMapInfo traits class is used to determine if a key is contained
123 // in an interval, and if two intervals are adjacent so they can be coalesced.
124 // The provided implementation works for closed integer intervals, other keys
125 // probably need a specialized version.
127 // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
129 // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
130 // allowed. This is so that stopLess(a, b) can be used to determine if two
131 // intervals overlap.
133 //===----------------------------------------------------------------------===//
135 template <typename T>
136 struct IntervalMapInfo {
138 /// startLess - Return true if x is not in [a;b].
139 /// This is x < a both for closed intervals and for [a;b) half-open intervals.
140 static inline bool startLess(const T &x, const T &a) {
144 /// stopLess - Return true if x is not in [a;b].
145 /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
146 static inline bool stopLess(const T &b, const T &x) {
150 /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
151 /// This is a+1 == b for closed intervals, a == b for half-open intervals.
152 static inline bool adjacent(const T &a, const T &b) {
158 /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
159 /// It should be considered private to the implementation.
160 namespace IntervalMapImpl {
162 // Forward declarations.
163 template <typename, typename, unsigned, typename> class LeafNode;
164 template <typename, typename, unsigned, typename> class BranchNode;
166 typedef std::pair<unsigned,unsigned> IdxPair;
169 //===----------------------------------------------------------------------===//
170 //--- IntervalMapImpl::NodeBase ---//
171 //===----------------------------------------------------------------------===//
173 // Both leaf and branch nodes store vectors of pairs.
174 // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT).
176 // Keys and values are stored in separate arrays to avoid padding caused by
177 // different object alignments. This also helps improve locality of reference
178 // when searching the keys.
180 // The nodes don't know how many elements they contain - that information is
181 // stored elsewhere. Omitting the size field prevents padding and allows a node
182 // to fill the allocated cache lines completely.
184 // These are typical key and value sizes, the node branching factor (N), and
185 // wasted space when nodes are sized to fit in three cache lines (192 bytes):
187 // T1 T2 N Waste Used by
188 // 4 4 24 0 Branch<4> (32-bit pointers)
189 // 8 4 16 0 Leaf<4,4>, Branch<4>
190 // 8 8 12 0 Leaf<4,8>, Branch<8>
191 // 16 4 9 12 Leaf<8,4>
192 // 16 8 8 0 Leaf<8,8>
194 //===----------------------------------------------------------------------===//
196 template <typename T1, typename T2, unsigned N>
199 enum { Capacity = N };
204 /// copy - Copy elements from another node.
205 /// @param Other Node elements are copied from.
206 /// @param i Beginning of the source range in other.
207 /// @param j Beginning of the destination range in this.
208 /// @param Count Number of elements to copy.
209 template <unsigned M>
210 void copy(const NodeBase<T1, T2, M> &Other, unsigned i,
211 unsigned j, unsigned Count) {
212 assert(i + Count <= M && "Invalid source range");
213 assert(j + Count <= N && "Invalid dest range");
214 std::copy(Other.first + i, Other.first + i + Count, first + j);
215 std::copy(Other.second + i, Other.second + i + Count, second + j);
218 /// moveLeft - Move elements to the left.
219 /// @param i Beginning of the source range.
220 /// @param j Beginning of the destination range.
221 /// @param Count Number of elements to copy.
222 void moveLeft(unsigned i, unsigned j, unsigned Count) {
223 assert(j <= i && "Use moveRight shift elements right");
224 copy(*this, i, j, Count);
227 /// moveRight - Move elements to the right.
228 /// @param i Beginning of the source range.
229 /// @param j Beginning of the destination range.
230 /// @param Count Number of elements to copy.
231 void moveRight(unsigned i, unsigned j, unsigned Count) {
232 assert(i <= j && "Use moveLeft shift elements left");
233 assert(j + Count <= N && "Invalid range");
234 std::copy_backward(first + i, first + i + Count, first + j + Count);
235 std::copy_backward(second + i, second + i + Count, second + j + Count);
238 /// erase - Erase elements [i;j).
239 /// @param i Beginning of the range to erase.
240 /// @param j End of the range. (Exclusive).
241 /// @param Size Number of elements in node.
242 void erase(unsigned i, unsigned j, unsigned Size) {
243 moveLeft(j, i, Size - j);
246 /// erase - Erase element at i.
247 /// @param i Index of element to erase.
248 /// @param Size Number of elements in node.
249 void erase(unsigned i, unsigned Size) {
253 /// shift - Shift elements [i;size) 1 position to the right.
254 /// @param i Beginning of the range to move.
255 /// @param Size Number of elements in node.
256 void shift(unsigned i, unsigned Size) {
257 moveRight(i, i + 1, Size - i);
260 /// transferToLeftSib - Transfer elements to a left sibling node.
261 /// @param Size Number of elements in this.
262 /// @param Sib Left sibling node.
263 /// @param SSize Number of elements in sib.
264 /// @param Count Number of elements to transfer.
265 void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize,
267 Sib.copy(*this, 0, SSize, Count);
268 erase(0, Count, Size);
271 /// transferToRightSib - Transfer elements to a right sibling node.
272 /// @param Size Number of elements in this.
273 /// @param Sib Right sibling node.
274 /// @param SSize Number of elements in sib.
275 /// @param Count Number of elements to transfer.
276 void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize,
278 Sib.moveRight(0, Count, SSize);
279 Sib.copy(*this, Size-Count, 0, Count);
282 /// adjustFromLeftSib - Adjust the number if elements in this node by moving
283 /// elements to or from a left sibling node.
284 /// @param Size Number of elements in this.
285 /// @param Sib Right sibling node.
286 /// @param SSize Number of elements in sib.
287 /// @param Add The number of elements to add to this node, possibly < 0.
288 /// @return Number of elements added to this node, possibly negative.
289 int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
291 // We want to grow, copy from sib.
292 unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
293 Sib.transferToRightSib(SSize, *this, Size, Count);
296 // We want to shrink, copy to sib.
297 unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
298 transferToLeftSib(Size, Sib, SSize, Count);
304 /// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes.
305 /// @param Node Array of pointers to sibling nodes.
306 /// @param Nodes Number of nodes.
307 /// @param CurSize Array of current node sizes, will be overwritten.
308 /// @param NewSize Array of desired node sizes.
309 template <typename NodeT>
310 void adjustSiblingSizes(NodeT *Node[], unsigned Nodes,
311 unsigned CurSize[], const unsigned NewSize[]) {
312 // Move elements right.
313 for (int n = Nodes - 1; n; --n) {
314 if (CurSize[n] == NewSize[n])
316 for (int m = n - 1; m != -1; --m) {
317 int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m],
318 NewSize[n] - CurSize[n]);
321 // Keep going if the current node was exhausted.
322 if (CurSize[n] >= NewSize[n])
330 // Move elements left.
331 for (unsigned n = 0; n != Nodes - 1; ++n) {
332 if (CurSize[n] == NewSize[n])
334 for (unsigned m = n + 1; m != Nodes; ++m) {
335 int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n],
336 CurSize[n] - NewSize[n]);
339 // Keep going if the current node was exhausted.
340 if (CurSize[n] >= NewSize[n])
346 for (unsigned n = 0; n != Nodes; n++)
347 assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
351 /// IntervalMapImpl::distribute - Compute a new distribution of node elements
352 /// after an overflow or underflow. Reserve space for a new element at Position,
353 /// and compute the node that will hold Position after redistributing node
356 /// It is required that
358 /// Elements == sum(CurSize), and
359 /// Elements + Grow <= Nodes * Capacity.
361 /// NewSize[] will be filled in such that:
363 /// sum(NewSize) == Elements, and
364 /// NewSize[i] <= Capacity.
366 /// The returned index is the node where Position will go, so:
368 /// sum(NewSize[0..idx-1]) <= Position
369 /// sum(NewSize[0..idx]) >= Position
371 /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
372 /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
373 /// before the one holding the Position'th element where there is room for an
376 /// @param Nodes The number of nodes.
377 /// @param Elements Total elements in all nodes.
378 /// @param Capacity The capacity of each node.
379 /// @param CurSize Array[Nodes] of current node sizes, or NULL.
380 /// @param NewSize Array[Nodes] to receive the new node sizes.
381 /// @param Position Insert position.
382 /// @param Grow Reserve space for a new element at Position.
383 /// @return (node, offset) for Position.
384 IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
385 const unsigned *CurSize, unsigned NewSize[],
386 unsigned Position, bool Grow);
389 //===----------------------------------------------------------------------===//
390 //--- IntervalMapImpl::NodeSizer ---//
391 //===----------------------------------------------------------------------===//
393 // Compute node sizes from key and value types.
395 // The branching factors are chosen to make nodes fit in three cache lines.
396 // This may not be possible if keys or values are very large. Such large objects
397 // are handled correctly, but a std::map would probably give better performance.
399 //===----------------------------------------------------------------------===//
402 // Cache line size. Most architectures have 32 or 64 byte cache lines.
403 // We use 64 bytes here because it provides good branching factors.
405 CacheLineBytes = 1 << Log2CacheLine,
406 DesiredNodeBytes = 3 * CacheLineBytes
409 template <typename KeyT, typename ValT>
412 // Compute the leaf node branching factor that makes a node fit in three
413 // cache lines. The branching factor must be at least 3, or some B+-tree
414 // balancing algorithms won't work.
415 // LeafSize can't be larger than CacheLineBytes. This is required by the
416 // PointerIntPair used by NodeRef.
417 DesiredLeafSize = DesiredNodeBytes /
418 static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
420 LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
423 typedef NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize> LeafBase;
426 // Now that we have the leaf branching factor, compute the actual allocation
427 // unit size by rounding up to a whole number of cache lines.
428 AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
430 // Determine the branching factor for branch nodes.
431 BranchSize = AllocBytes /
432 static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
435 /// Allocator - The recycling allocator used for both branch and leaf nodes.
436 /// This typedef is very likely to be identical for all IntervalMaps with
437 /// reasonably sized entries, so the same allocator can be shared among
438 /// different kinds of maps.
439 typedef RecyclingAllocator<BumpPtrAllocator, char,
440 AllocBytes, CacheLineBytes> Allocator;
445 //===----------------------------------------------------------------------===//
446 //--- IntervalMapImpl::NodeRef ---//
447 //===----------------------------------------------------------------------===//
449 // B+-tree nodes can be leaves or branches, so we need a polymorphic node
450 // pointer that can point to both kinds.
452 // All nodes are cache line aligned and the low 6 bits of a node pointer are
453 // always 0. These bits are used to store the number of elements in the
454 // referenced node. Besides saving space, placing node sizes in the parents
455 // allow tree balancing algorithms to run without faulting cache lines for nodes
456 // that may not need to be modified.
458 // A NodeRef doesn't know whether it references a leaf node or a branch node.
459 // It is the responsibility of the caller to use the correct types.
461 // Nodes are never supposed to be empty, and it is invalid to store a node size
462 // of 0 in a NodeRef. The valid range of sizes is 1-64.
464 //===----------------------------------------------------------------------===//
467 struct CacheAlignedPointerTraits {
468 static inline void *getAsVoidPointer(void *P) { return P; }
469 static inline void *getFromVoidPointer(void *P) { return P; }
470 enum { NumLowBitsAvailable = Log2CacheLine };
472 PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
475 /// NodeRef - Create a null ref.
478 /// operator bool - Detect a null ref.
479 operator bool() const { return pip.getOpaqueValue(); }
481 /// NodeRef - Create a reference to the node p with n elements.
482 template <typename NodeT>
483 NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) {
484 assert(n <= NodeT::Capacity && "Size too big for node");
487 /// size - Return the number of elements in the referenced node.
488 unsigned size() const { return pip.getInt() + 1; }
490 /// setSize - Update the node size.
491 void setSize(unsigned n) { pip.setInt(n - 1); }
493 /// subtree - Access the i'th subtree reference in a branch node.
494 /// This depends on branch nodes storing the NodeRef array as their first
496 NodeRef &subtree(unsigned i) const {
497 return reinterpret_cast<NodeRef*>(pip.getPointer())[i];
500 /// get - Dereference as a NodeT reference.
501 template <typename NodeT>
503 return *reinterpret_cast<NodeT*>(pip.getPointer());
506 bool operator==(const NodeRef &RHS) const {
509 assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
513 bool operator!=(const NodeRef &RHS) const {
514 return !operator==(RHS);
518 //===----------------------------------------------------------------------===//
519 //--- IntervalMapImpl::LeafNode ---//
520 //===----------------------------------------------------------------------===//
522 // Leaf nodes store up to N disjoint intervals with corresponding values.
524 // The intervals are kept sorted and fully coalesced so there are no adjacent
525 // intervals mapping to the same value.
527 // These constraints are always satisfied:
529 // - Traits::stopLess(start(i), stop(i)) - Non-empty, sane intervals.
531 // - Traits::stopLess(stop(i), start(i + 1) - Sorted.
533 // - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1))
534 // - Fully coalesced.
536 //===----------------------------------------------------------------------===//
538 template <typename KeyT, typename ValT, unsigned N, typename Traits>
539 class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
541 const KeyT &start(unsigned i) const { return this->first[i].first; }
542 const KeyT &stop(unsigned i) const { return this->first[i].second; }
543 const ValT &value(unsigned i) const { return this->second[i]; }
545 KeyT &start(unsigned i) { return this->first[i].first; }
546 KeyT &stop(unsigned i) { return this->first[i].second; }
547 ValT &value(unsigned i) { return this->second[i]; }
549 /// findFrom - Find the first interval after i that may contain x.
550 /// @param i Starting index for the search.
551 /// @param Size Number of elements in node.
552 /// @param x Key to search for.
553 /// @return First index with !stopLess(key[i].stop, x), or size.
554 /// This is the first interval that can possibly contain x.
555 unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
556 assert(i <= Size && Size <= N && "Bad indices");
557 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
558 "Index is past the needed point");
559 while (i != Size && Traits::stopLess(stop(i), x)) ++i;
563 /// safeFind - Find an interval that is known to exist. This is the same as
564 /// findFrom except is it assumed that x is at least within range of the last
566 /// @param i Starting index for the search.
567 /// @param x Key to search for.
568 /// @return First index with !stopLess(key[i].stop, x), never size.
569 /// This is the first interval that can possibly contain x.
570 unsigned safeFind(unsigned i, KeyT x) const {
571 assert(i < N && "Bad index");
572 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
573 "Index is past the needed point");
574 while (Traits::stopLess(stop(i), x)) ++i;
575 assert(i < N && "Unsafe intervals");
579 /// safeLookup - Lookup mapped value for a safe key.
580 /// It is assumed that x is within range of the last entry.
581 /// @param x Key to search for.
582 /// @param NotFound Value to return if x is not in any interval.
583 /// @return The mapped value at x or NotFound.
584 ValT safeLookup(KeyT x, ValT NotFound) const {
585 unsigned i = safeFind(0, x);
586 return Traits::startLess(x, start(i)) ? NotFound : value(i);
589 unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y);
592 void dump(raw_ostream &OS, unsigned Size) {
593 OS << " N" << this << " [shape=record label=\"{ " << Size << '/' << N;
594 for (unsigned i = 0; i != Size; ++i)
595 OS << " | {" << start(i) << '-' << stop(i) << "|" << value(i) << '}';
602 /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
603 /// possible. This may cause the node to grow by 1, or it may cause the node
604 /// to shrink because of coalescing.
605 /// @param i Starting index = insertFrom(0, size, a)
606 /// @param Size Number of elements in node.
607 /// @param a Interval start.
608 /// @param b Interval stop.
609 /// @param y Value be mapped.
610 /// @return (insert position, new size), or (i, Capacity+1) on overflow.
611 template <typename KeyT, typename ValT, unsigned N, typename Traits>
612 unsigned LeafNode<KeyT, ValT, N, Traits>::
613 insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) {
615 assert(i <= Size && Size <= N && "Invalid index");
616 assert(!Traits::stopLess(b, a) && "Invalid interval");
618 // Verify the findFrom invariant.
619 assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
620 assert((i == Size || !Traits::stopLess(stop(i), a)));
621 assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert");
623 // Coalesce with previous interval.
624 if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) {
626 // Also coalesce with next interval?
627 if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) {
628 stop(i - 1) = stop(i);
629 this->erase(i, Size);
640 // Add new interval at end.
648 // Try to coalesce with following interval.
649 if (value(i) == y && Traits::adjacent(b, start(i))) {
654 // We must insert before i. Detect overflow.
659 this->shift(i, Size);
667 //===----------------------------------------------------------------------===//
668 //--- IntervalMapImpl::BranchNode ---//
669 //===----------------------------------------------------------------------===//
671 // A branch node stores references to 1--N subtrees all of the same height.
673 // The key array in a branch node holds the rightmost stop key of each subtree.
674 // It is redundant to store the last stop key since it can be found in the
675 // parent node, but doing so makes tree balancing a lot simpler.
677 // It is unusual for a branch node to only have one subtree, but it can happen
678 // in the root node if it is smaller than the normal nodes.
680 // When all of the leaf nodes from all the subtrees are concatenated, they must
681 // satisfy the same constraints as a single leaf node. They must be sorted,
682 // sane, and fully coalesced.
684 //===----------------------------------------------------------------------===//
686 template <typename KeyT, typename ValT, unsigned N, typename Traits>
687 class BranchNode : public NodeBase<NodeRef, KeyT, N> {
689 const KeyT &stop(unsigned i) const { return this->second[i]; }
690 const NodeRef &subtree(unsigned i) const { return this->first[i]; }
692 KeyT &stop(unsigned i) { return this->second[i]; }
693 NodeRef &subtree(unsigned i) { return this->first[i]; }
695 /// findFrom - Find the first subtree after i that may contain x.
696 /// @param i Starting index for the search.
697 /// @param Size Number of elements in node.
698 /// @param x Key to search for.
699 /// @return First index with !stopLess(key[i], x), or size.
700 /// This is the first subtree that can possibly contain x.
701 unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
702 assert(i <= Size && Size <= N && "Bad indices");
703 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
704 "Index to findFrom is past the needed point");
705 while (i != Size && Traits::stopLess(stop(i), x)) ++i;
709 /// safeFind - Find a subtree that is known to exist. This is the same as
710 /// findFrom except is it assumed that x is in range.
711 /// @param i Starting index for the search.
712 /// @param x Key to search for.
713 /// @return First index with !stopLess(key[i], x), never size.
714 /// This is the first subtree that can possibly contain x.
715 unsigned safeFind(unsigned i, KeyT x) const {
716 assert(i < N && "Bad index");
717 assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
718 "Index is past the needed point");
719 while (Traits::stopLess(stop(i), x)) ++i;
720 assert(i < N && "Unsafe intervals");
724 /// safeLookup - Get the subtree containing x, Assuming that x is in range.
725 /// @param x Key to search for.
726 /// @return Subtree containing x
727 NodeRef safeLookup(KeyT x) const {
728 return subtree(safeFind(0, x));
731 /// insert - Insert a new (subtree, stop) pair.
732 /// @param i Insert position, following entries will be shifted.
733 /// @param Size Number of elements in node.
734 /// @param Node Subtree to insert.
735 /// @param Stop Last key in subtree.
736 void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) {
737 assert(Size < N && "branch node overflow");
738 assert(i <= Size && "Bad insert position");
739 this->shift(i, Size);
745 void dump(raw_ostream &OS, unsigned Size) {
746 OS << " N" << this << " [shape=record label=\"" << Size << '/' << N;
747 for (unsigned i = 0; i != Size; ++i)
748 OS << " | <s" << i << "> " << stop(i);
750 for (unsigned i = 0; i != Size; ++i)
751 OS << " N" << this << ":s" << i << " -> N"
752 << &subtree(i).template get<BranchNode>() << ";\n";
758 //===----------------------------------------------------------------------===//
759 //--- IntervalMapImpl::Path ---//
760 //===----------------------------------------------------------------------===//
762 // A Path is used by iterators to represent a position in a B+-tree, and the
763 // path to get there from the root.
765 // The Path class also constains the tree navigation code that doesn't have to
768 //===----------------------------------------------------------------------===//
771 /// Entry - Each step in the path is a node pointer and an offset into that
778 Entry(void *Node, unsigned Size, unsigned Offset)
779 : node(Node), size(Size), offset(Offset) {}
781 Entry(NodeRef Node, unsigned Offset)
782 : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {}
784 NodeRef &subtree(unsigned i) const {
785 return reinterpret_cast<NodeRef*>(node)[i];
789 /// path - The path entries, path[0] is the root node, path.back() is a leaf.
790 SmallVector<Entry, 4> path;
794 template <typename NodeT> NodeT &node(unsigned Level) const {
795 return *reinterpret_cast<NodeT*>(path[Level].node);
797 unsigned size(unsigned Level) const { return path[Level].size; }
798 unsigned offset(unsigned Level) const { return path[Level].offset; }
799 unsigned &offset(unsigned Level) { return path[Level].offset; }
802 template <typename NodeT> NodeT &leaf() const {
803 return *reinterpret_cast<NodeT*>(path.back().node);
805 unsigned leafSize() const { return path.back().size; }
806 unsigned leafOffset() const { return path.back().offset; }
807 unsigned &leafOffset() { return path.back().offset; }
809 /// valid - Return true if path is at a valid node, not at end().
811 return !path.empty() && path.front().offset < path.front().size;
814 /// height - Return the height of the tree corresponding to this path.
815 /// This matches map->height in a full path.
816 unsigned height() const { return path.size() - 1; }
818 /// subtree - Get the subtree referenced from Level. When the path is
819 /// consistent, node(Level + 1) == subtree(Level).
820 /// @param Level 0..height-1. The leaves have no subtrees.
821 NodeRef &subtree(unsigned Level) const {
822 return path[Level].subtree(path[Level].offset);
825 /// reset - Reset cached information about node(Level) from subtree(Level -1).
826 /// @param Level 1..height. THe node to update after parent node changed.
827 void reset(unsigned Level) {
828 path[Level] = Entry(subtree(Level - 1), offset(Level));
831 /// push - Add entry to path.
832 /// @param Node Node to add, should be subtree(path.size()-1).
833 /// @param Offset Offset into Node.
834 void push(NodeRef Node, unsigned Offset) {
835 path.push_back(Entry(Node, Offset));
838 /// pop - Remove the last path entry.
843 /// setSize - Set the size of a node both in the path and in the tree.
844 /// @param Level 0..height. Note that setting the root size won't change
846 /// @param Size New node size.
847 void setSize(unsigned Level, unsigned Size) {
848 path[Level].size = Size;
850 subtree(Level - 1).setSize(Size);
853 /// setRoot - Clear the path and set a new root node.
854 /// @param Node New root node.
855 /// @param Size New root size.
856 /// @param Offset Offset into root node.
857 void setRoot(void *Node, unsigned Size, unsigned Offset) {
859 path.push_back(Entry(Node, Size, Offset));
862 /// replaceRoot - Replace the current root node with two new entries after the
863 /// tree height has increased.
864 /// @param Root The new root node.
865 /// @param Size Number of entries in the new root.
866 /// @param Offsets Offsets into the root and first branch nodes.
867 void replaceRoot(void *Root, unsigned Size, IdxPair Offsets);
869 /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
870 /// @param Level Get the sibling to node(Level).
871 /// @return Left sibling, or NodeRef().
872 NodeRef getLeftSibling(unsigned Level) const;
874 /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level
876 /// @param Level Move node(Level).
877 void moveLeft(unsigned Level);
879 /// fillLeft - Grow path to Height by taking leftmost branches.
880 /// @param Height The target height.
881 void fillLeft(unsigned Height) {
882 while (height() < Height)
883 push(subtree(height()), 0);
886 /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
887 /// @param Level Get the sinbling to node(Level).
888 /// @return Left sibling, or NodeRef().
889 NodeRef getRightSibling(unsigned Level) const;
891 /// moveRight - Move path to the left sibling at Level. Leave nodes below
893 /// @param Level Move node(Level).
894 void moveRight(unsigned Level);
896 /// atBegin - Return true if path is at begin().
897 bool atBegin() const {
898 for (unsigned i = 0, e = path.size(); i != e; ++i)
899 if (path[i].offset != 0)
904 /// atLastBranch - Return true if the path is at the last branch of the node
906 /// @param Level Node to examine.
907 bool atLastBranch(unsigned Level) const {
908 return path[Level].offset == path[Level].size - 1;
911 /// legalizeForInsert - Prepare the path for an insertion at Level. When the
912 /// path is at end(), node(Level) may not be a legal node. legalizeForInsert
913 /// ensures that node(Level) is real by moving back to the last node at Level,
914 /// and setting offset(Level) to size(Level) if required.
915 /// @param Level The level where an insertion is about to take place.
916 void legalizeForInsert(unsigned Level) {
920 ++path[Level].offset;
925 for (unsigned l = 0, e = path.size(); l != e; ++l)
926 errs() << l << ": " << path[l].node << ' ' << path[l].size << ' '
927 << path[l].offset << '\n';
932 } // namespace IntervalMapImpl
935 //===----------------------------------------------------------------------===//
936 //--- IntervalMap ----//
937 //===----------------------------------------------------------------------===//
939 template <typename KeyT, typename ValT,
940 unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
941 typename Traits = IntervalMapInfo<KeyT> >
943 typedef IntervalMapImpl::NodeSizer<KeyT, ValT> Sizer;
944 typedef IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits> Leaf;
945 typedef IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>
947 typedef IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits> RootLeaf;
948 typedef IntervalMapImpl::IdxPair IdxPair;
950 // The RootLeaf capacity is given as a template parameter. We must compute the
951 // corresponding RootBranch capacity.
953 DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
954 (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)),
955 RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
958 typedef IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>
961 // When branched, we store a global start key as well as the branch node.
962 struct RootBranchData {
968 RootDataSize = sizeof(RootBranchData) > sizeof(RootLeaf) ?
969 sizeof(RootBranchData) : sizeof(RootLeaf)
973 typedef typename Sizer::Allocator Allocator;
976 // The root data is either a RootLeaf or a RootBranchData instance.
977 // We can't put them in a union since C++03 doesn't allow non-trivial
978 // constructors in unions.
979 // Instead, we use a char array with pointer alignment. The alignment is
980 // ensured by the allocator member in the class, but still verified in the
981 // constructor. We don't support keys or values that are more aligned than a
983 char data[RootDataSize];
986 // 0: Leaves in root.
987 // 1: Root points to leaf.
988 // 2: root->branch->leaf ...
991 // Number of entries in the root node.
994 // Allocator used for creating external nodes.
995 Allocator &allocator;
997 /// dataAs - Represent data as a node type without breaking aliasing rules.
998 template <typename T>
1008 const RootLeaf &rootLeaf() const {
1009 assert(!branched() && "Cannot acces leaf data in branched root");
1010 return dataAs<RootLeaf>();
1012 RootLeaf &rootLeaf() {
1013 assert(!branched() && "Cannot acces leaf data in branched root");
1014 return dataAs<RootLeaf>();
1016 RootBranchData &rootBranchData() const {
1017 assert(branched() && "Cannot access branch data in non-branched root");
1018 return dataAs<RootBranchData>();
1020 RootBranchData &rootBranchData() {
1021 assert(branched() && "Cannot access branch data in non-branched root");
1022 return dataAs<RootBranchData>();
1024 const RootBranch &rootBranch() const { return rootBranchData().node; }
1025 RootBranch &rootBranch() { return rootBranchData().node; }
1026 KeyT rootBranchStart() const { return rootBranchData().start; }
1027 KeyT &rootBranchStart() { return rootBranchData().start; }
1029 template <typename NodeT> NodeT *newNode() {
1030 return new(allocator.template Allocate<NodeT>()) NodeT();
1033 template <typename NodeT> void deleteNode(NodeT *P) {
1035 allocator.Deallocate(P);
1038 IdxPair branchRoot(unsigned Position);
1039 IdxPair splitRoot(unsigned Position);
1041 void switchRootToBranch() {
1042 rootLeaf().~RootLeaf();
1044 new (&rootBranchData()) RootBranchData();
1047 void switchRootToLeaf() {
1048 rootBranchData().~RootBranchData();
1050 new(&rootLeaf()) RootLeaf();
1053 bool branched() const { return height > 0; }
1055 ValT treeSafeLookup(KeyT x, ValT NotFound) const;
1056 void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef,
1058 void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level);
1061 explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
1062 assert((uintptr_t(data) & (alignOf<RootLeaf>() - 1)) == 0 &&
1063 "Insufficient alignment");
1064 new(&rootLeaf()) RootLeaf();
1069 rootLeaf().~RootLeaf();
1072 /// empty - Return true when no intervals are mapped.
1073 bool empty() const {
1074 return rootSize == 0;
1077 /// start - Return the smallest mapped key in a non-empty map.
1078 KeyT start() const {
1079 assert(!empty() && "Empty IntervalMap has no start");
1080 return !branched() ? rootLeaf().start(0) : rootBranchStart();
1083 /// stop - Return the largest mapped key in a non-empty map.
1085 assert(!empty() && "Empty IntervalMap has no stop");
1086 return !branched() ? rootLeaf().stop(rootSize - 1) :
1087 rootBranch().stop(rootSize - 1);
1090 /// lookup - Return the mapped value at x or NotFound.
1091 ValT lookup(KeyT x, ValT NotFound = ValT()) const {
1092 if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
1094 return branched() ? treeSafeLookup(x, NotFound) :
1095 rootLeaf().safeLookup(x, NotFound);
1098 /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
1099 /// It is assumed that no key in the interval is mapped to another value, but
1100 /// overlapping intervals already mapped to y will be coalesced.
1101 void insert(KeyT a, KeyT b, ValT y) {
1102 if (branched() || rootSize == RootLeaf::Capacity)
1103 return find(a).insert(a, b, y);
1105 // Easy insert into root leaf.
1106 unsigned p = rootLeaf().findFrom(0, rootSize, a);
1107 rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y);
1110 /// clear - Remove all entries.
1113 class const_iterator;
1115 friend class const_iterator;
1116 friend class iterator;
1118 const_iterator begin() const {
1130 const_iterator end() const {
1142 /// find - Return an iterator pointing to the first interval ending at or
1143 /// after x, or end().
1144 const_iterator find(KeyT x) const {
1150 iterator find(KeyT x) {
1159 void dumpNode(IntervalMapImpl::NodeRef Node, unsigned Height);
1163 /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
1165 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1166 ValT IntervalMap<KeyT, ValT, N, Traits>::
1167 treeSafeLookup(KeyT x, ValT NotFound) const {
1168 assert(branched() && "treeLookup assumes a branched root");
1170 IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x);
1171 for (unsigned h = height-1; h; --h)
1172 NR = NR.get<Branch>().safeLookup(x);
1173 return NR.get<Leaf>().safeLookup(x, NotFound);
1177 // branchRoot - Switch from a leaf root to a branched root.
1178 // Return the new (root offset, node offset) corresponding to Position.
1179 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1180 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
1181 branchRoot(unsigned Position) {
1182 using namespace IntervalMapImpl;
1183 // How many external leaf nodes to hold RootLeaf+1?
1184 const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
1186 // Compute element distribution among new nodes.
1187 unsigned size[Nodes];
1188 IdxPair NewOffset(0, Position);
1190 // Is is very common for the root node to be smaller than external nodes.
1194 NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, size,
1197 // Allocate new nodes.
1199 NodeRef node[Nodes];
1200 for (unsigned n = 0; n != Nodes; ++n) {
1201 Leaf *L = newNode<Leaf>();
1202 L->copy(rootLeaf(), pos, 0, size[n]);
1203 node[n] = NodeRef(L, size[n]);
1207 // Destroy the old leaf node, construct branch node instead.
1208 switchRootToBranch();
1209 for (unsigned n = 0; n != Nodes; ++n) {
1210 rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1);
1211 rootBranch().subtree(n) = node[n];
1213 rootBranchStart() = node[0].template get<Leaf>().start(0);
1218 // splitRoot - Split the current BranchRoot into multiple Branch nodes.
1219 // Return the new (root offset, node offset) corresponding to Position.
1220 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1221 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
1222 splitRoot(unsigned Position) {
1223 using namespace IntervalMapImpl;
1224 // How many external leaf nodes to hold RootBranch+1?
1225 const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
1227 // Compute element distribution among new nodes.
1228 unsigned Size[Nodes];
1229 IdxPair NewOffset(0, Position);
1231 // Is is very common for the root node to be smaller than external nodes.
1235 NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, NULL, Size,
1238 // Allocate new nodes.
1240 NodeRef Node[Nodes];
1241 for (unsigned n = 0; n != Nodes; ++n) {
1242 Branch *B = newNode<Branch>();
1243 B->copy(rootBranch(), Pos, 0, Size[n]);
1244 Node[n] = NodeRef(B, Size[n]);
1248 for (unsigned n = 0; n != Nodes; ++n) {
1249 rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1);
1250 rootBranch().subtree(n) = Node[n];
1257 /// visitNodes - Visit each external node.
1258 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1259 void IntervalMap<KeyT, ValT, N, Traits>::
1260 visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) {
1263 SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs;
1265 // Collect level 0 nodes from the root.
1266 for (unsigned i = 0; i != rootSize; ++i)
1267 Refs.push_back(rootBranch().subtree(i));
1269 // Visit all branch nodes.
1270 for (unsigned h = height - 1; h; --h) {
1271 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
1272 for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
1273 NextRefs.push_back(Refs[i].subtree(j));
1274 (this->*f)(Refs[i], h);
1277 Refs.swap(NextRefs);
1280 // Visit all leaf nodes.
1281 for (unsigned i = 0, e = Refs.size(); i != e; ++i)
1282 (this->*f)(Refs[i], 0);
1285 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1286 void IntervalMap<KeyT, ValT, N, Traits>::
1287 deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) {
1289 deleteNode(&Node.get<Branch>());
1291 deleteNode(&Node.get<Leaf>());
1294 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1295 void IntervalMap<KeyT, ValT, N, Traits>::
1298 visitNodes(&IntervalMap::deleteNode);
1305 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1306 void IntervalMap<KeyT, ValT, N, Traits>::
1307 dumpNode(IntervalMapImpl::NodeRef Node, unsigned Height) {
1309 Node.get<Branch>().dump(*OS, Node.size());
1311 Node.get<Leaf>().dump(*OS, Node.size());
1314 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1315 void IntervalMap<KeyT, ValT, N, Traits>::
1318 raw_fd_ostream ofs("tree.dot", errors);
1320 ofs << "digraph {\n";
1322 rootBranch().dump(ofs, rootSize);
1324 rootLeaf().dump(ofs, rootSize);
1325 visitNodes(&IntervalMap::dumpNode);
1330 //===----------------------------------------------------------------------===//
1331 //--- IntervalMap::const_iterator ----//
1332 //===----------------------------------------------------------------------===//
1334 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1335 class IntervalMap<KeyT, ValT, N, Traits>::const_iterator :
1336 public std::iterator<std::bidirectional_iterator_tag, ValT> {
1338 friend class IntervalMap;
1340 // The map referred to.
1343 // We store a full path from the root to the current position.
1344 // The path may be partially filled, but never between iterator calls.
1345 IntervalMapImpl::Path path;
1347 explicit const_iterator(IntervalMap &map) : map(&map) {}
1349 bool branched() const {
1350 assert(map && "Invalid iterator");
1351 return map->branched();
1354 void setRoot(unsigned Offset) {
1356 path.setRoot(&map->rootBranch(), map->rootSize, Offset);
1358 path.setRoot(&map->rootLeaf(), map->rootSize, Offset);
1361 void pathFillFind(KeyT x);
1362 void treeFind(KeyT x);
1363 void treeAdvanceTo(KeyT x);
1366 /// const_iterator - Create an iterator that isn't pointing anywhere.
1367 const_iterator() : map(0) {}
1369 /// valid - Return true if the current position is valid, false for end().
1370 bool valid() const { return path.valid(); }
1372 /// start - Return the beginning of the current interval.
1373 const KeyT &start() const {
1374 assert(valid() && "Cannot access invalid iterator");
1375 return branched() ? path.leaf<Leaf>().start(path.leafOffset()) :
1376 path.leaf<RootLeaf>().start(path.leafOffset());
1379 /// stop - Return the end of the current interval.
1380 const KeyT &stop() const {
1381 assert(valid() && "Cannot access invalid iterator");
1382 return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) :
1383 path.leaf<RootLeaf>().stop(path.leafOffset());
1386 /// value - Return the mapped value at the current interval.
1387 const ValT &value() const {
1388 assert(valid() && "Cannot access invalid iterator");
1389 return branched() ? path.leaf<Leaf>().value(path.leafOffset()) :
1390 path.leaf<RootLeaf>().value(path.leafOffset());
1393 const ValT &operator*() const {
1397 bool operator==(const const_iterator &RHS) const {
1398 assert(map == RHS.map && "Cannot compare iterators from different maps");
1400 return !RHS.valid();
1401 if (path.leafOffset() != RHS.path.leafOffset())
1403 return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>();
1406 bool operator!=(const const_iterator &RHS) const {
1407 return !operator==(RHS);
1410 /// goToBegin - Move to the first interval in map.
1414 path.fillLeft(map->height);
1417 /// goToEnd - Move beyond the last interval in map.
1419 setRoot(map->rootSize);
1422 /// preincrement - move to the next interval.
1423 const_iterator &operator++() {
1424 assert(valid() && "Cannot increment end()");
1425 if (++path.leafOffset() == path.leafSize() && branched())
1426 path.moveRight(map->height);
1430 /// postincrement - Dont do that!
1431 const_iterator operator++(int) {
1432 const_iterator tmp = *this;
1437 /// predecrement - move to the previous interval.
1438 const_iterator &operator--() {
1439 if (path.leafOffset() && (valid() || !branched()))
1440 --path.leafOffset();
1442 path.moveLeft(map->height);
1446 /// postdecrement - Dont do that!
1447 const_iterator operator--(int) {
1448 const_iterator tmp = *this;
1453 /// find - Move to the first interval with stop >= x, or end().
1454 /// This is a full search from the root, the current position is ignored.
1459 setRoot(map->rootLeaf().findFrom(0, map->rootSize, x));
1462 /// advanceTo - Move to the first interval with stop >= x, or end().
1463 /// The search is started from the current position, and no earlier positions
1464 /// can be found. This is much faster than find() for small moves.
1465 void advanceTo(KeyT x) {
1470 map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x);
1475 /// pathFillFind - Complete path by searching for x.
1476 /// @param x Key to search for.
1477 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1478 void IntervalMap<KeyT, ValT, N, Traits>::
1479 const_iterator::pathFillFind(KeyT x) {
1480 IntervalMapImpl::NodeRef NR = path.subtree(path.height());
1481 for (unsigned i = map->height - path.height() - 1; i; --i) {
1482 unsigned p = NR.get<Branch>().safeFind(0, x);
1486 path.push(NR, NR.get<Leaf>().safeFind(0, x));
1489 /// treeFind - Find in a branched tree.
1490 /// @param x Key to search for.
1491 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1492 void IntervalMap<KeyT, ValT, N, Traits>::
1493 const_iterator::treeFind(KeyT x) {
1494 setRoot(map->rootBranch().findFrom(0, map->rootSize, x));
1499 /// treeAdvanceTo - Find position after the current one.
1500 /// @param x Key to search for.
1501 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1502 void IntervalMap<KeyT, ValT, N, Traits>::
1503 const_iterator::treeAdvanceTo(KeyT x) {
1504 // Can we stay on the same leaf node?
1505 if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) {
1506 path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x);
1510 // Drop the current leaf.
1513 // Search towards the root for a usable subtree.
1514 if (path.height()) {
1515 for (unsigned l = path.height() - 1; l; --l) {
1516 if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) {
1517 // The branch node at l+1 is usable
1518 path.offset(l + 1) =
1519 path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x);
1520 return pathFillFind(x);
1524 // Is the level-1 Branch usable?
1525 if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) {
1526 path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x);
1527 return pathFillFind(x);
1531 // We reached the root.
1532 setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x));
1537 //===----------------------------------------------------------------------===//
1538 //--- IntervalMap::iterator ----//
1539 //===----------------------------------------------------------------------===//
1541 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1542 class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
1543 friend class IntervalMap;
1544 typedef IntervalMapImpl::IdxPair IdxPair;
1546 explicit iterator(IntervalMap &map) : const_iterator(map) {}
1548 void setNodeStop(unsigned Level, KeyT Stop);
1549 bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop);
1550 template <typename NodeT> bool overflow(unsigned Level);
1551 void treeInsert(KeyT a, KeyT b, ValT y);
1552 void eraseNode(unsigned Level);
1553 void treeErase(bool UpdateRoot = true);
1555 /// iterator - Create null iterator.
1558 /// insert - Insert mapping [a;b] -> y before the current position.
1559 void insert(KeyT a, KeyT b, ValT y);
1561 /// erase - Erase the current interval.
1564 iterator &operator++() {
1565 const_iterator::operator++();
1569 iterator operator++(int) {
1570 iterator tmp = *this;
1575 iterator &operator--() {
1576 const_iterator::operator--();
1580 iterator operator--(int) {
1581 iterator tmp = *this;
1588 /// setNodeStop - Update the stop key of the current node at level and above.
1589 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1590 void IntervalMap<KeyT, ValT, N, Traits>::
1591 iterator::setNodeStop(unsigned Level, KeyT Stop) {
1592 // There are no references to the root node, so nothing to update.
1595 IntervalMapImpl::Path &P = this->path;
1596 // Update nodes pointing to the current node.
1598 P.node<Branch>(Level).stop(P.offset(Level)) = Stop;
1599 if (!P.atLastBranch(Level))
1602 // Update root separately since it has a different layout.
1603 P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop;
1606 /// insertNode - insert a node before the current path at level.
1607 /// Leave the current path pointing at the new node.
1608 /// @param Level path index of the node to be inserted.
1609 /// @param Node The node to be inserted.
1610 /// @param Stop The last index in the new node.
1611 /// @return True if the tree height was increased.
1612 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1613 bool IntervalMap<KeyT, ValT, N, Traits>::
1614 iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) {
1615 assert(Level && "Cannot insert next to the root");
1616 bool SplitRoot = false;
1617 IntervalMap &IM = *this->map;
1618 IntervalMapImpl::Path &P = this->path;
1621 // Insert into the root branch node.
1622 if (IM.rootSize < RootBranch::Capacity) {
1623 IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop);
1624 P.setSize(0, ++IM.rootSize);
1629 // We need to split the root while keeping our position.
1631 IdxPair Offset = IM.splitRoot(P.offset(0));
1632 P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
1634 // Fall through to insert at the new higher level.
1638 // When inserting before end(), make sure we have a valid path.
1639 P.legalizeForInsert(--Level);
1641 // Insert into the branch node at Level-1.
1642 if (P.size(Level) == Branch::Capacity) {
1643 // Branch node is full, handle handle the overflow.
1644 assert(!SplitRoot && "Cannot overflow after splitting the root");
1645 SplitRoot = overflow<Branch>(Level);
1648 P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop);
1649 P.setSize(Level, P.size(Level) + 1);
1650 if (P.atLastBranch(Level))
1651 setNodeStop(Level, Stop);
1657 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1658 void IntervalMap<KeyT, ValT, N, Traits>::
1659 iterator::insert(KeyT a, KeyT b, ValT y) {
1660 if (this->branched())
1661 return treeInsert(a, b, y);
1662 IntervalMap &IM = *this->map;
1663 IntervalMapImpl::Path &P = this->path;
1665 // Try simple root leaf insert.
1666 unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y);
1668 // Was the root node insert successful?
1669 if (Size <= RootLeaf::Capacity) {
1670 P.setSize(0, IM.rootSize = Size);
1674 // Root leaf node is full, we must branch.
1675 IdxPair Offset = IM.branchRoot(P.leafOffset());
1676 P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
1678 // Now it fits in the new leaf.
1679 treeInsert(a, b, y);
1683 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1684 void IntervalMap<KeyT, ValT, N, Traits>::
1685 iterator::treeInsert(KeyT a, KeyT b, ValT y) {
1686 using namespace IntervalMapImpl;
1687 Path &P = this->path;
1690 P.legalizeForInsert(this->map->height);
1692 // Check if this insertion will extend the node to the left.
1693 if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) {
1694 // Node is growing to the left, will it affect a left sibling node?
1695 if (NodeRef Sib = P.getLeftSibling(P.height())) {
1696 Leaf &SibLeaf = Sib.get<Leaf>();
1697 unsigned SibOfs = Sib.size() - 1;
1698 if (SibLeaf.value(SibOfs) == y &&
1699 Traits::adjacent(SibLeaf.stop(SibOfs), a)) {
1700 // This insertion will coalesce with the last entry in SibLeaf. We can
1701 // handle it in two ways:
1702 // 1. Extend SibLeaf.stop to b and be done, or
1703 // 2. Extend a to SibLeaf, erase the SibLeaf entry and continue.
1704 // We prefer 1., but need 2 when coalescing to the right as well.
1705 Leaf &CurLeaf = P.leaf<Leaf>();
1706 P.moveLeft(P.height());
1707 if (Traits::stopLess(b, CurLeaf.start(0)) &&
1708 (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) {
1709 // Easy, just extend SibLeaf and we're done.
1710 setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b);
1713 // We have both left and right coalescing. Erase the old SibLeaf entry
1714 // and continue inserting the larger interval.
1715 a = SibLeaf.start(SibOfs);
1716 treeErase(/* UpdateRoot= */false);
1720 // No left sibling means we are at begin(). Update cached bound.
1721 this->map->rootBranchStart() = a;
1725 // When we are inserting at the end of a leaf node, we must update stops.
1726 unsigned Size = P.leafSize();
1727 bool Grow = P.leafOffset() == Size;
1728 Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y);
1730 // Leaf insertion unsuccessful? Overflow and try again.
1731 if (Size > Leaf::Capacity) {
1732 overflow<Leaf>(P.height());
1733 Grow = P.leafOffset() == P.leafSize();
1734 Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y);
1735 assert(Size <= Leaf::Capacity && "overflow() didn't make room");
1738 // Inserted, update offset and leaf size.
1739 P.setSize(P.height(), Size);
1741 // Insert was the last node entry, update stops.
1743 setNodeStop(P.height(), b);
1746 /// erase - erase the current interval and move to the next position.
1747 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1748 void IntervalMap<KeyT, ValT, N, Traits>::
1750 IntervalMap &IM = *this->map;
1751 IntervalMapImpl::Path &P = this->path;
1752 assert(P.valid() && "Cannot erase end()");
1753 if (this->branched())
1755 IM.rootLeaf().erase(P.leafOffset(), IM.rootSize);
1756 P.setSize(0, --IM.rootSize);
1759 /// treeErase - erase() for a branched tree.
1760 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1761 void IntervalMap<KeyT, ValT, N, Traits>::
1762 iterator::treeErase(bool UpdateRoot) {
1763 IntervalMap &IM = *this->map;
1764 IntervalMapImpl::Path &P = this->path;
1765 Leaf &Node = P.leaf<Leaf>();
1767 // Nodes are not allowed to become empty.
1768 if (P.leafSize() == 1) {
1769 IM.deleteNode(&Node);
1770 eraseNode(IM.height);
1771 // Update rootBranchStart if we erased begin().
1772 if (UpdateRoot && IM.branched() && P.valid() && P.atBegin())
1773 IM.rootBranchStart() = P.leaf<Leaf>().start(0);
1777 // Erase current entry.
1778 Node.erase(P.leafOffset(), P.leafSize());
1779 unsigned NewSize = P.leafSize() - 1;
1780 P.setSize(IM.height, NewSize);
1781 // When we erase the last entry, update stop and move to a legal position.
1782 if (P.leafOffset() == NewSize) {
1783 setNodeStop(IM.height, Node.stop(NewSize - 1));
1784 P.moveRight(IM.height);
1785 } else if (UpdateRoot && P.atBegin())
1786 IM.rootBranchStart() = P.leaf<Leaf>().start(0);
1789 /// eraseNode - Erase the current node at Level from its parent and move path to
1790 /// the first entry of the next sibling node.
1791 /// The node must be deallocated by the caller.
1792 /// @param Level 1..height, the root node cannot be erased.
1793 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1794 void IntervalMap<KeyT, ValT, N, Traits>::
1795 iterator::eraseNode(unsigned Level) {
1796 assert(Level && "Cannot erase root node");
1797 IntervalMap &IM = *this->map;
1798 IntervalMapImpl::Path &P = this->path;
1801 IM.rootBranch().erase(P.offset(0), IM.rootSize);
1802 P.setSize(0, --IM.rootSize);
1803 // If this cleared the root, switch to height=0.
1805 IM.switchRootToLeaf();
1810 // Remove node ref from branch node at Level.
1811 Branch &Parent = P.node<Branch>(Level);
1812 if (P.size(Level) == 1) {
1813 // Branch node became empty, remove it recursively.
1814 IM.deleteNode(&Parent);
1817 // Branch node won't become empty.
1818 Parent.erase(P.offset(Level), P.size(Level));
1819 unsigned NewSize = P.size(Level) - 1;
1820 P.setSize(Level, NewSize);
1821 // If we removed the last branch, update stop and move to a legal pos.
1822 if (P.offset(Level) == NewSize) {
1823 setNodeStop(Level, Parent.stop(NewSize - 1));
1828 // Update path cache for the new right sibling position.
1831 P.offset(Level + 1) = 0;
1835 /// overflow - Distribute entries of the current node evenly among
1836 /// its siblings and ensure that the current node is not full.
1837 /// This may require allocating a new node.
1838 /// @param NodeT The type of node at Level (Leaf or Branch).
1839 /// @param Level path index of the overflowing node.
1840 /// @return True when the tree height was changed.
1841 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1842 template <typename NodeT>
1843 bool IntervalMap<KeyT, ValT, N, Traits>::
1844 iterator::overflow(unsigned Level) {
1845 using namespace IntervalMapImpl;
1846 Path &P = this->path;
1847 unsigned CurSize[4];
1850 unsigned Elements = 0;
1851 unsigned Offset = P.offset(Level);
1853 // Do we have a left sibling?
1854 NodeRef LeftSib = P.getLeftSibling(Level);
1856 Offset += Elements = CurSize[Nodes] = LeftSib.size();
1857 Node[Nodes++] = &LeftSib.get<NodeT>();
1861 Elements += CurSize[Nodes] = P.size(Level);
1862 Node[Nodes++] = &P.node<NodeT>(Level);
1864 // Do we have a right sibling?
1865 NodeRef RightSib = P.getRightSibling(Level);
1867 Elements += CurSize[Nodes] = RightSib.size();
1868 Node[Nodes++] = &RightSib.get<NodeT>();
1871 // Do we need to allocate a new node?
1872 unsigned NewNode = 0;
1873 if (Elements + 1 > Nodes * NodeT::Capacity) {
1874 // Insert NewNode at the penultimate position, or after a single node.
1875 NewNode = Nodes == 1 ? 1 : Nodes - 1;
1876 CurSize[Nodes] = CurSize[NewNode];
1877 Node[Nodes] = Node[NewNode];
1878 CurSize[NewNode] = 0;
1879 Node[NewNode] = this->map->newNode<NodeT>();
1883 // Compute the new element distribution.
1884 unsigned NewSize[4];
1885 IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity,
1886 CurSize, NewSize, Offset, true);
1887 adjustSiblingSizes(Node, Nodes, CurSize, NewSize);
1889 // Move current location to the leftmost node.
1893 // Elements have been rearranged, now update node sizes and stops.
1894 bool SplitRoot = false;
1897 KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
1898 if (NewNode && Pos == NewNode) {
1899 SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop);
1902 P.setSize(Level, NewSize[Pos]);
1903 setNodeStop(Level, Stop);
1905 if (Pos + 1 == Nodes)
1911 // Where was I? Find NewOffset.
1912 while(Pos != NewOffset.first) {
1916 P.offset(Level) = NewOffset.second;