1 //==-- llvm/ADT/ilist.h - Intrusive Linked List Template ---------*- 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 defines classes to implement an intrusive doubly linked list class
11 // (i.e. each node of the list must contain a next and previous field for the
14 // The ilist_traits trait class is used to gain access to the next and previous
15 // fields of the node type that the list is instantiated with. If it is not
16 // specialized, the list defaults to using the getPrev(), getNext() method calls
17 // to get the next and previous pointers.
19 // The ilist class itself, should be a plug in replacement for list, assuming
20 // that the nodes contain next/prev pointers. This list replacement does not
21 // provide a constant time size() method, so be careful to use empty() when you
22 // really want to know if it's empty.
24 // The ilist class is implemented by allocating a 'tail' node when the list is
25 // created (using ilist_traits<>::createSentinel()). This tail node is
26 // absolutely required because the user must be able to compute end()-1. Because
27 // of this, users of the direct next/prev links will see an extra link on the
28 // end of the list, which should be ignored.
30 // Requirements for a user of this list:
32 // 1. The user must provide {g|s}et{Next|Prev} methods, or specialize
33 // ilist_traits to provide an alternate way of getting and setting next and
36 //===----------------------------------------------------------------------===//
38 #ifndef LLVM_ADT_ILIST_H
39 #define LLVM_ADT_ILIST_H
41 #include "llvm/ADT/iterator.h"
47 template<typename NodeTy, typename Traits> class iplist;
48 template<typename NodeTy> class ilist_iterator;
50 // Template traits for intrusive list. By specializing this template class, you
51 // can change what next/prev fields are used to store the links...
52 template<typename NodeTy>
54 static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
55 static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
56 static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
57 static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
59 static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
60 static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
62 static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
63 static void deleteNode(NodeTy *V) { delete V; }
65 static NodeTy *createSentinel() { return new NodeTy(); }
66 static void destroySentinel(NodeTy *N) { delete N; }
68 void addNodeToList(NodeTy *NTy) {}
69 void removeNodeFromList(NodeTy *NTy) {}
70 void transferNodesFromList(iplist<NodeTy, ilist_traits> &L2,
71 ilist_iterator<NodeTy> first,
72 ilist_iterator<NodeTy> last) {}
75 // Const traits are the same as nonconst traits...
77 struct ilist_traits<const Ty> : public ilist_traits<Ty> {};
80 //===----------------------------------------------------------------------===//
81 // ilist_iterator<Node> - Iterator for intrusive list.
83 template<typename NodeTy>
85 : public bidirectional_iterator<NodeTy, ptrdiff_t> {
88 typedef ilist_traits<NodeTy> Traits;
89 typedef bidirectional_iterator<NodeTy, ptrdiff_t> super;
91 typedef size_t size_type;
92 typedef typename super::pointer pointer;
93 typedef typename super::reference reference;
97 // operator[] is not defined. Compile error instead of having a runtime bug.
98 void operator[](unsigned) {}
99 void operator[](unsigned) const {}
102 ilist_iterator(pointer NP) : NodePtr(NP) {}
103 ilist_iterator(reference NR) : NodePtr(&NR) {}
104 ilist_iterator() : NodePtr(0) {}
106 // This is templated so that we can allow constructing a const iterator from
107 // a nonconst iterator...
108 template<class node_ty>
109 ilist_iterator(const ilist_iterator<node_ty> &RHS)
110 : NodePtr(RHS.getNodePtrUnchecked()) {}
112 // This is templated so that we can allow assigning to a const iterator from
113 // a nonconst iterator...
114 template<class node_ty>
115 const ilist_iterator &operator=(const ilist_iterator<node_ty> &RHS) {
116 NodePtr = RHS.getNodePtrUnchecked();
121 operator pointer() const {
122 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
126 reference operator*() const {
127 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
130 pointer operator->() const { return &operator*(); }
132 // Comparison operators
133 bool operator==(const ilist_iterator &RHS) const {
134 return NodePtr == RHS.NodePtr;
136 bool operator!=(const ilist_iterator &RHS) const {
137 return NodePtr != RHS.NodePtr;
140 // Increment and decrement operators...
141 ilist_iterator &operator--() { // predecrement - Back up
142 NodePtr = Traits::getPrev(NodePtr);
143 assert(Traits::getNext(NodePtr) && "--'d off the beginning of an ilist!");
146 ilist_iterator &operator++() { // preincrement - Advance
147 NodePtr = Traits::getNext(NodePtr);
148 assert(NodePtr && "++'d off the end of an ilist!");
151 ilist_iterator operator--(int) { // postdecrement operators...
152 ilist_iterator tmp = *this;
156 ilist_iterator operator++(int) { // postincrement operators...
157 ilist_iterator tmp = *this;
162 // Internal interface, do not use...
163 pointer getNodePtrUnchecked() const { return NodePtr; }
166 // do not implement. this is to catch errors when people try to use
167 // them as random access iterators
169 void operator-(int, ilist_iterator<T>);
171 void operator-(ilist_iterator<T>,int);
174 void operator+(int, ilist_iterator<T>);
176 void operator+(ilist_iterator<T>,int);
178 // operator!=/operator== - Allow mixed comparisons without dereferencing
179 // the iterator, which could very likely be pointing to end().
181 bool operator!=(const T* LHS, const ilist_iterator<const T> &RHS) {
182 return LHS != RHS.getNodePtrUnchecked();
185 bool operator==(const T* LHS, const ilist_iterator<const T> &RHS) {
186 return LHS == RHS.getNodePtrUnchecked();
189 bool operator!=(T* LHS, const ilist_iterator<T> &RHS) {
190 return LHS != RHS.getNodePtrUnchecked();
193 bool operator==(T* LHS, const ilist_iterator<T> &RHS) {
194 return LHS == RHS.getNodePtrUnchecked();
198 // Allow ilist_iterators to convert into pointers to a node automatically when
199 // used by the dyn_cast, cast, isa mechanisms...
201 template<typename From> struct simplify_type;
203 template<typename NodeTy> struct simplify_type<ilist_iterator<NodeTy> > {
204 typedef NodeTy* SimpleType;
206 static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
210 template<typename NodeTy> struct simplify_type<const ilist_iterator<NodeTy> > {
211 typedef NodeTy* SimpleType;
213 static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
219 //===----------------------------------------------------------------------===//
221 /// iplist - The subset of list functionality that can safely be used on nodes
222 /// of polymorphic types, i.e. a heterogenous list with a common base class that
223 /// holds the next/prev pointers. The only state of the list itself is a single
224 /// pointer to the head of the list.
226 /// This list can be in one of three interesting states:
227 /// 1. The list may be completely unconstructed. In this case, the head
228 /// pointer is null. When in this form, any query for an iterator (e.g.
229 /// begin() or end()) causes the list to transparently change to state #2.
230 /// 2. The list may be empty, but contain a sentinal for the end iterator. This
231 /// sentinal is created by the Traits::createSentinel method and is a link
232 /// in the list. When the list is empty, the pointer in the iplist points
233 /// to the sentinal. Once the sentinal is constructed, it
234 /// is not destroyed until the list is.
235 /// 3. The list may contain actual objects in it, which are stored as a doubly
236 /// linked list of nodes. One invariant of the list is that the predecessor
237 /// of the first node in the list always points to the last node in the list,
238 /// and the successor pointer for the sentinal (which always stays at the
239 /// end of the list) is always null.
241 template<typename NodeTy, typename Traits=ilist_traits<NodeTy> >
242 class iplist : public Traits {
243 mutable NodeTy *Head;
245 // Use the prev node pointer of 'head' as the tail pointer. This is really a
246 // circularly linked list where we snip the 'next' link from the sentinel node
247 // back to the first node in the list (to preserve assertions about going off
248 // the end of the list).
249 NodeTy *getTail() { return getPrev(Head); }
250 const NodeTy *getTail() const { return getPrev(Head); }
251 void setTail(NodeTy *N) const { setPrev(Head, N); }
253 /// CreateLazySentinal - This method verifies whether the sentinal for the
254 /// list has been created and lazily makes it if not.
255 void CreateLazySentinal() const {
256 if (Head != 0) return;
257 Head = Traits::createSentinel();
262 static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
263 static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
265 // No fundamental reason why iplist can't by copyable, but the default
266 // copy/copy-assign won't do.
267 iplist(const iplist &); // do not implement
268 void operator=(const iplist &); // do not implement
271 typedef NodeTy *pointer;
272 typedef const NodeTy *const_pointer;
273 typedef NodeTy &reference;
274 typedef const NodeTy &const_reference;
275 typedef NodeTy value_type;
276 typedef ilist_iterator<NodeTy> iterator;
277 typedef ilist_iterator<const NodeTy> const_iterator;
278 typedef size_t size_type;
279 typedef ptrdiff_t difference_type;
280 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
281 typedef std::reverse_iterator<iterator> reverse_iterator;
283 iplist() : Head(0) {}
287 Traits::destroySentinel(getTail());
290 // Iterator creation methods.
292 CreateLazySentinal();
293 return iterator(Head);
295 const_iterator begin() const {
296 CreateLazySentinal();
297 return const_iterator(Head);
300 CreateLazySentinal();
301 return iterator(getTail());
303 const_iterator end() const {
304 CreateLazySentinal();
305 return const_iterator(getTail());
308 // reverse iterator creation methods.
309 reverse_iterator rbegin() { return reverse_iterator(end()); }
310 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
311 reverse_iterator rend() { return reverse_iterator(begin()); }
312 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
315 // Miscellaneous inspection routines.
316 size_type max_size() const { return size_type(-1); }
317 bool empty() const { return Head == 0 || Head == getTail(); }
319 // Front and back accessor functions...
321 assert(!empty() && "Called front() on empty list!");
324 const_reference front() const {
325 assert(!empty() && "Called front() on empty list!");
329 assert(!empty() && "Called back() on empty list!");
330 return *getPrev(getTail());
332 const_reference back() const {
333 assert(!empty() && "Called back() on empty list!");
334 return *getPrev(getTail());
337 void swap(iplist &RHS) {
338 abort(); // Swap does not use list traits callback correctly yet!
339 std::swap(Head, RHS.Head);
342 iterator insert(iterator where, NodeTy *New) {
343 NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = getPrev(CurNode);
344 setNext(New, CurNode);
345 setPrev(New, PrevNode);
347 if (CurNode != Head) // Is PrevNode off the beginning of the list?
348 setNext(PrevNode, New);
351 setPrev(CurNode, New);
353 addNodeToList(New); // Notify traits that we added a node...
357 NodeTy *remove(iterator &IT) {
358 assert(IT != end() && "Cannot remove end of list!");
360 NodeTy *NextNode = getNext(Node);
361 NodeTy *PrevNode = getPrev(Node);
363 if (Node != Head) // Is PrevNode off the beginning of the list?
364 setNext(PrevNode, NextNode);
367 setPrev(NextNode, PrevNode);
369 removeNodeFromList(Node); // Notify traits that we removed a node...
371 // Set the next/prev pointers of the current node to null. This isn't
372 // strictly required, but this catches errors where a node is removed from
373 // an ilist (and potentially deleted) with iterators still pointing at it.
374 // When those iterators are incremented or decremented, they will assert on
375 // the null next/prev pointer instead of "usually working".
381 NodeTy *remove(const iterator &IT) {
383 return remove(MutIt);
386 // erase - remove a node from the controlled sequence... and delete it.
387 iterator erase(iterator where) {
388 deleteNode(remove(where));
394 // transfer - The heart of the splice function. Move linked list nodes from
395 // [first, last) into position.
397 void transfer(iterator position, iplist &L2, iterator first, iterator last) {
398 assert(first != last && "Should be checked by callers");
400 if (position != last) {
401 // Note: we have to be careful about the case when we move the first node
402 // in the list. This node is the list sentinel node and we can't move it.
403 NodeTy *ThisSentinel = getTail();
405 NodeTy *L2Sentinel = L2.getTail();
408 // Remove [first, last) from its old position.
409 NodeTy *First = &*first, *Prev = getPrev(First);
410 NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
417 // Splice [first, last) into its new position.
418 NodeTy *PosNext = position.getNodePtrUnchecked();
419 NodeTy *PosPrev = getPrev(PosNext);
421 // Fix head of list...
423 setNext(PosPrev, First);
426 setPrev(First, PosPrev);
428 // Fix end of list...
429 setNext(Last, PosNext);
430 setPrev(PosNext, Last);
432 transferNodesFromList(L2, First, PosNext);
434 // Now that everything is set, restore the pointers to the list sentinals.
435 L2.setTail(L2Sentinel);
436 setTail(ThisSentinel);
442 //===----------------------------------------------------------------------===
443 // Functionality derived from other functions defined above...
446 size_type size() const {
447 if (Head == 0) return 0; // Don't require construction of sentinal if empty.
449 // GCC 2.95 has a broken std::distance
450 size_type Result = 0;
451 std::distance(begin(), end(), Result);
454 return std::distance(begin(), end());
458 iterator erase(iterator first, iterator last) {
459 while (first != last)
460 first = erase(first);
464 void clear() { if (Head) erase(begin(), end()); }
466 // Front and back inserters...
467 void push_front(NodeTy *val) { insert(begin(), val); }
468 void push_back(NodeTy *val) { insert(end(), val); }
470 assert(!empty() && "pop_front() on empty list!");
474 assert(!empty() && "pop_back() on empty list!");
475 iterator t = end(); erase(--t);
478 // Special forms of insert...
479 template<class InIt> void insert(iterator where, InIt first, InIt last) {
480 for (; first != last; ++first) insert(where, *first);
483 // Splice members - defined in terms of transfer...
484 void splice(iterator where, iplist &L2) {
486 transfer(where, L2, L2.begin(), L2.end());
488 void splice(iterator where, iplist &L2, iterator first) {
489 iterator last = first; ++last;
490 if (where == first || where == last) return; // No change
491 transfer(where, L2, first, last);
493 void splice(iterator where, iplist &L2, iterator first, iterator last) {
494 if (first != last) transfer(where, L2, first, last);
499 //===----------------------------------------------------------------------===
500 // High-Level Functionality that shouldn't really be here, but is part of list
503 // These two functions are actually called remove/remove_if in list<>, but
504 // they actually do the job of erase, rename them accordingly.
506 void erase(const NodeTy &val) {
507 for (iterator I = begin(), E = end(); I != E; ) {
508 iterator next = I; ++next;
509 if (*I == val) erase(I);
513 template<class Pr1> void erase_if(Pr1 pred) {
514 for (iterator I = begin(), E = end(); I != E; ) {
515 iterator next = I; ++next;
516 if (pred(*I)) erase(I);
521 template<class Pr2> void unique(Pr2 pred) {
523 for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
531 void unique() { unique(op_equal); }
533 template<class Pr3> void merge(iplist &right, Pr3 pred) {
534 iterator first1 = begin(), last1 = end();
535 iterator first2 = right.begin(), last2 = right.end();
536 while (first1 != last1 && first2 != last2)
537 if (pred(*first2, *first1)) {
538 iterator next = first2;
539 transfer(first1, right, first2, ++next);
544 if (first2 != last2) transfer(last1, right, first2, last2);
546 void merge(iplist &right) { return merge(right, op_less); }
548 template<class Pr3> void sort(Pr3 pred);
549 void sort() { sort(op_less); }
554 template<typename NodeTy>
555 struct ilist : public iplist<NodeTy> {
556 typedef typename iplist<NodeTy>::size_type size_type;
557 typedef typename iplist<NodeTy>::iterator iterator;
560 ilist(const ilist &right) {
561 insert(this->begin(), right.begin(), right.end());
563 explicit ilist(size_type count) {
564 insert(this->begin(), count, NodeTy());
566 ilist(size_type count, const NodeTy &val) {
567 insert(this->begin(), count, val);
569 template<class InIt> ilist(InIt first, InIt last) {
570 insert(this->begin(), first, last);
574 // Forwarding functions: A workaround for GCC 2.95 which does not correctly
575 // support 'using' declarations to bring a hidden member into scope.
577 iterator insert(iterator a, NodeTy *b){ return iplist<NodeTy>::insert(a, b); }
578 void push_front(NodeTy *a) { iplist<NodeTy>::push_front(a); }
579 void push_back(NodeTy *a) { iplist<NodeTy>::push_back(a); }
582 // Main implementation here - Insert for a node passed by value...
583 iterator insert(iterator where, const NodeTy &val) {
584 return insert(where, createNode(val));
588 // Front and back inserters...
589 void push_front(const NodeTy &val) { insert(this->begin(), val); }
590 void push_back(const NodeTy &val) { insert(this->end(), val); }
592 // Special forms of insert...
593 template<class InIt> void insert(iterator where, InIt first, InIt last) {
594 for (; first != last; ++first) insert(where, *first);
596 void insert(iterator where, size_type count, const NodeTy &val) {
597 for (; count != 0; --count) insert(where, val);
600 // Assign special forms...
601 void assign(size_type count, const NodeTy &val) {
602 iterator I = this->begin();
603 for (; I != this->end() && count != 0; ++I, --count)
606 insert(this->end(), val, val);
608 erase(I, this->end());
610 template<class InIt> void assign(InIt first1, InIt last1) {
611 iterator first2 = this->begin(), last2 = this->end();
612 for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
615 erase(first1, last1);
617 insert(last1, first2, last2);
622 void resize(size_type newsize, NodeTy val) {
623 iterator i = this->begin();
625 for ( ; i != this->end() && len < newsize; ++i, ++len) /* empty*/ ;
628 erase(i, this->end());
630 insert(this->end(), newsize - len, val);
632 void resize(size_type newsize) { resize(newsize, NodeTy()); }
635 } // End llvm namespace
638 // Ensure that swap uses the fast list swap...
640 void swap(llvm::iplist<Ty> &Left, llvm::iplist<Ty> &Right) {
643 } // End 'std' extensions...
645 #endif // LLVM_ADT_ILIST_H