Add several more unimplemented operator overloads to ilist_iterator
[oota-llvm.git] / include / llvm / ADT / ilist.h
1 //==-- llvm/ADT/ilist.h - Intrusive Linked List Template ---------*- C++ -*-==//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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
12 // list.
13 //
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.
18 //
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.
23 //
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.
29 //
30 // Requirements for a user of this list:
31 //
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
34 //      prev links.
35 //
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_ADT_ILIST_H
39 #define LLVM_ADT_ILIST_H
40
41 #include "llvm/ADT/iterator.h"
42 #include <cassert>
43 #include <cstdlib>
44
45 namespace llvm {
46
47 template<typename NodeTy, typename Traits> class iplist;
48 template<typename NodeTy> class ilist_iterator;
49
50 /// ilist_nextprev_traits - A fragment for template traits for intrusive list
51 /// that provides default next/prev implementations for common operations.
52 ///
53 template<typename NodeTy>
54 struct ilist_nextprev_traits {
55   static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
56   static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
57   static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
58   static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
59
60   static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
61   static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
62 };
63
64 /// ilist_sentinel_traits - A fragment for template traits for intrusive list
65 /// that provides default sentinel implementations for common operations.
66 ///
67 template<typename NodeTy>
68 struct ilist_sentinel_traits {
69   static NodeTy *createSentinel() { return new NodeTy(); }
70   static void destroySentinel(NodeTy *N) { delete N; }
71 };
72
73 /// ilist_default_traits - Default template traits for intrusive list.
74 /// By inheriting from this, you can easily use default implementations
75 /// for all common operations.
76 ///
77 template<typename NodeTy>
78 struct ilist_default_traits : ilist_nextprev_traits<NodeTy>,
79                               ilist_sentinel_traits<NodeTy> {
80   static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
81   static void deleteNode(NodeTy *V) { delete V; }
82
83   void addNodeToList(NodeTy *) {}
84   void removeNodeFromList(NodeTy *) {}
85   void transferNodesFromList(ilist_default_traits & /*SrcTraits*/,
86                              ilist_iterator<NodeTy> /*first*/,
87                              ilist_iterator<NodeTy> /*last*/) {}
88 };
89
90 // Template traits for intrusive list.  By specializing this template class, you
91 // can change what next/prev fields are used to store the links...
92 template<typename NodeTy>
93 struct ilist_traits : ilist_default_traits<NodeTy> {};
94
95 // Const traits are the same as nonconst traits...
96 template<typename Ty>
97 struct ilist_traits<const Ty> : public ilist_traits<Ty> {};
98
99 //===----------------------------------------------------------------------===//
100 // ilist_iterator<Node> - Iterator for intrusive list.
101 //
102 template<typename NodeTy>
103 class ilist_iterator
104   : public bidirectional_iterator<NodeTy, ptrdiff_t> {
105     
106 public:
107   typedef ilist_traits<NodeTy> Traits;
108   typedef bidirectional_iterator<NodeTy, ptrdiff_t> super;
109
110   typedef typename super::value_type value_type;
111   typedef typename super::difference_type difference_type;
112   typedef typename super::pointer pointer;
113   typedef typename super::reference reference;
114 private:
115   pointer NodePtr;
116
117   // ilist_iterator is not a random-access iterator, but it has an
118   // implicit conversion to pointer-type, which is. Declare (but
119   // don't define) these functions as private to help catch
120   // accidental misuse.
121   void operator[](difference_type) const;
122   void operator+(difference_type) const;
123   void operator-(difference_type) const;
124   void operator+=(difference_type) const;
125   void operator-=(difference_type) const;
126   template<class T> void operator<(T) const;
127   template<class T> void operator<=(T) const;
128   template<class T> void operator>(T) const;
129   template<class T> void operator>=(T) const;
130   template<class T> void operator-(T) const;
131 public:
132
133   ilist_iterator(pointer NP) : NodePtr(NP) {}
134   ilist_iterator(reference NR) : NodePtr(&NR) {}
135   ilist_iterator() : NodePtr(0) {}
136
137   // This is templated so that we can allow constructing a const iterator from
138   // a nonconst iterator...
139   template<class node_ty>
140   ilist_iterator(const ilist_iterator<node_ty> &RHS)
141     : NodePtr(RHS.getNodePtrUnchecked()) {}
142
143   // This is templated so that we can allow assigning to a const iterator from
144   // a nonconst iterator...
145   template<class node_ty>
146   const ilist_iterator &operator=(const ilist_iterator<node_ty> &RHS) {
147     NodePtr = RHS.getNodePtrUnchecked();
148     return *this;
149   }
150
151   // Accessors...
152   operator pointer() const {
153     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
154     return NodePtr;
155   }
156
157   reference operator*() const {
158     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
159     return *NodePtr;
160   }
161   pointer operator->() const { return &operator*(); }
162
163   // Comparison operators
164   bool operator==(const ilist_iterator &RHS) const {
165     return NodePtr == RHS.NodePtr;
166   }
167   bool operator!=(const ilist_iterator &RHS) const {
168     return NodePtr != RHS.NodePtr;
169   }
170
171   // Increment and decrement operators...
172   ilist_iterator &operator--() {      // predecrement - Back up
173     NodePtr = Traits::getPrev(NodePtr);
174     assert(Traits::getNext(NodePtr) && "--'d off the beginning of an ilist!");
175     return *this;
176   }
177   ilist_iterator &operator++() {      // preincrement - Advance
178     NodePtr = Traits::getNext(NodePtr);
179     assert(NodePtr && "++'d off the end of an ilist!");
180     return *this;
181   }
182   ilist_iterator operator--(int) {    // postdecrement operators...
183     ilist_iterator tmp = *this;
184     --*this;
185     return tmp;
186   }
187   ilist_iterator operator++(int) {    // postincrement operators...
188     ilist_iterator tmp = *this;
189     ++*this;
190     return tmp;
191   }
192
193   // Internal interface, do not use...
194   pointer getNodePtrUnchecked() const { return NodePtr; }
195 };
196
197 // do not implement. this is to catch errors when people try to use
198 // them as random access iterators
199 template<typename T>
200 void operator-(int, ilist_iterator<T>);
201 template<typename T>
202 void operator-(ilist_iterator<T>,int);
203
204 template<typename T>
205 void operator+(int, ilist_iterator<T>);
206 template<typename T>
207 void operator+(ilist_iterator<T>,int);
208
209 // operator!=/operator== - Allow mixed comparisons without dereferencing
210 // the iterator, which could very likely be pointing to end().
211 template<typename T>
212 bool operator!=(const T* LHS, const ilist_iterator<const T> &RHS) {
213   return LHS != RHS.getNodePtrUnchecked();
214 }
215 template<typename T>
216 bool operator==(const T* LHS, const ilist_iterator<const T> &RHS) {
217   return LHS == RHS.getNodePtrUnchecked();
218 }
219 template<typename T>
220 bool operator!=(T* LHS, const ilist_iterator<T> &RHS) {
221   return LHS != RHS.getNodePtrUnchecked();
222 }
223 template<typename T>
224 bool operator==(T* LHS, const ilist_iterator<T> &RHS) {
225   return LHS == RHS.getNodePtrUnchecked();
226 }
227
228
229 // Allow ilist_iterators to convert into pointers to a node automatically when
230 // used by the dyn_cast, cast, isa mechanisms...
231
232 template<typename From> struct simplify_type;
233
234 template<typename NodeTy> struct simplify_type<ilist_iterator<NodeTy> > {
235   typedef NodeTy* SimpleType;
236   
237   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
238     return &*Node;
239   }
240 };
241 template<typename NodeTy> struct simplify_type<const ilist_iterator<NodeTy> > {
242   typedef NodeTy* SimpleType;
243   
244   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
245     return &*Node;
246   }
247 };
248
249
250 //===----------------------------------------------------------------------===//
251 //
252 /// iplist - The subset of list functionality that can safely be used on nodes
253 /// of polymorphic types, i.e. a heterogenous list with a common base class that
254 /// holds the next/prev pointers.  The only state of the list itself is a single
255 /// pointer to the head of the list.
256 ///
257 /// This list can be in one of three interesting states:
258 /// 1. The list may be completely unconstructed.  In this case, the head
259 ///    pointer is null.  When in this form, any query for an iterator (e.g.
260 ///    begin() or end()) causes the list to transparently change to state #2.
261 /// 2. The list may be empty, but contain a sentinal for the end iterator. This
262 ///    sentinal is created by the Traits::createSentinel method and is a link
263 ///    in the list.  When the list is empty, the pointer in the iplist points
264 ///    to the sentinal.  Once the sentinal is constructed, it
265 ///    is not destroyed until the list is.
266 /// 3. The list may contain actual objects in it, which are stored as a doubly
267 ///    linked list of nodes.  One invariant of the list is that the predecessor
268 ///    of the first node in the list always points to the last node in the list,
269 ///    and the successor pointer for the sentinal (which always stays at the
270 ///    end of the list) is always null.  
271 ///
272 template<typename NodeTy, typename Traits=ilist_traits<NodeTy> >
273 class iplist : public Traits {
274   mutable NodeTy *Head;
275
276   // Use the prev node pointer of 'head' as the tail pointer.  This is really a
277   // circularly linked list where we snip the 'next' link from the sentinel node
278   // back to the first node in the list (to preserve assertions about going off
279   // the end of the list).
280   NodeTy *getTail() { return this->getPrev(Head); }
281   const NodeTy *getTail() const { return this->getPrev(Head); }
282   void setTail(NodeTy *N) const { this->setPrev(Head, N); }
283   
284   /// CreateLazySentinal - This method verifies whether the sentinal for the
285   /// list has been created and lazily makes it if not.
286   void CreateLazySentinal() const {
287     if (Head != 0) return;
288     Head = Traits::createSentinel();
289     this->setNext(Head, 0);
290     setTail(Head);
291   }
292
293   static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
294   static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
295
296   // No fundamental reason why iplist can't by copyable, but the default
297   // copy/copy-assign won't do.
298   iplist(const iplist &);         // do not implement
299   void operator=(const iplist &); // do not implement
300
301 public:
302   typedef NodeTy *pointer;
303   typedef const NodeTy *const_pointer;
304   typedef NodeTy &reference;
305   typedef const NodeTy &const_reference;
306   typedef NodeTy value_type;
307   typedef ilist_iterator<NodeTy> iterator;
308   typedef ilist_iterator<const NodeTy> const_iterator;
309   typedef size_t size_type;
310   typedef ptrdiff_t difference_type;
311   typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;
312   typedef std::reverse_iterator<iterator>  reverse_iterator;
313
314   iplist() : Head(0) {}
315   ~iplist() {
316     if (!Head) return;
317     clear();
318     Traits::destroySentinel(getTail());
319   }
320
321   // Iterator creation methods.
322   iterator begin() {
323     CreateLazySentinal(); 
324     return iterator(Head); 
325   }
326   const_iterator begin() const {
327     CreateLazySentinal();
328     return const_iterator(Head);
329   }
330   iterator end() {
331     CreateLazySentinal();
332     return iterator(getTail());
333   }
334   const_iterator end() const {
335     CreateLazySentinal();
336     return const_iterator(getTail());
337   }
338
339   // reverse iterator creation methods.
340   reverse_iterator rbegin()            { return reverse_iterator(end()); }
341   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
342   reverse_iterator rend()              { return reverse_iterator(begin()); }
343   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
344
345
346   // Miscellaneous inspection routines.
347   size_type max_size() const { return size_type(-1); }
348   bool empty() const { return Head == 0 || Head == getTail(); }
349
350   // Front and back accessor functions...
351   reference front() {
352     assert(!empty() && "Called front() on empty list!");
353     return *Head;
354   }
355   const_reference front() const {
356     assert(!empty() && "Called front() on empty list!");
357     return *Head;
358   }
359   reference back() {
360     assert(!empty() && "Called back() on empty list!");
361     return *this->getPrev(getTail());
362   }
363   const_reference back() const {
364     assert(!empty() && "Called back() on empty list!");
365     return *this->getPrev(getTail());
366   }
367
368   void swap(iplist &RHS) {
369     abort();     // Swap does not use list traits callback correctly yet!
370     std::swap(Head, RHS.Head);
371   }
372
373   iterator insert(iterator where, NodeTy *New) {
374     NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = this->getPrev(CurNode);
375     this->setNext(New, CurNode);
376     this->setPrev(New, PrevNode);
377
378     if (CurNode != Head)  // Is PrevNode off the beginning of the list?
379       this->setNext(PrevNode, New);
380     else
381       Head = New;
382     this->setPrev(CurNode, New);
383
384     this->addNodeToList(New);  // Notify traits that we added a node...
385     return New;
386   }
387
388   NodeTy *remove(iterator &IT) {
389     assert(IT != end() && "Cannot remove end of list!");
390     NodeTy *Node = &*IT;
391     NodeTy *NextNode = this->getNext(Node);
392     NodeTy *PrevNode = this->getPrev(Node);
393
394     if (Node != Head)  // Is PrevNode off the beginning of the list?
395       this->setNext(PrevNode, NextNode);
396     else
397       Head = NextNode;
398     this->setPrev(NextNode, PrevNode);
399     IT = NextNode;
400     removeNodeFromList(Node);  // Notify traits that we removed a node...
401     
402     // Set the next/prev pointers of the current node to null.  This isn't
403     // strictly required, but this catches errors where a node is removed from
404     // an ilist (and potentially deleted) with iterators still pointing at it.
405     // When those iterators are incremented or decremented, they will assert on
406     // the null next/prev pointer instead of "usually working".
407     this->setNext(Node, 0);
408     this->setPrev(Node, 0);
409     return Node;
410   }
411
412   NodeTy *remove(const iterator &IT) {
413     iterator MutIt = IT;
414     return remove(MutIt);
415   }
416
417   // erase - remove a node from the controlled sequence... and delete it.
418   iterator erase(iterator where) {
419     deleteNode(remove(where));
420     return where;
421   }
422
423
424 private:
425   // transfer - The heart of the splice function.  Move linked list nodes from
426   // [first, last) into position.
427   //
428   void transfer(iterator position, iplist &L2, iterator first, iterator last) {
429     assert(first != last && "Should be checked by callers");
430
431     if (position != last) {
432       // Note: we have to be careful about the case when we move the first node
433       // in the list.  This node is the list sentinel node and we can't move it.
434       NodeTy *ThisSentinel = getTail();
435       setTail(0);
436       NodeTy *L2Sentinel = L2.getTail();
437       L2.setTail(0);
438
439       // Remove [first, last) from its old position.
440       NodeTy *First = &*first, *Prev = getPrev(First);
441       NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
442       if (Prev)
443         this->setNext(Prev, Next);
444       else
445         L2.Head = Next;
446       this->setPrev(Next, Prev);
447
448       // Splice [first, last) into its new position.
449       NodeTy *PosNext = position.getNodePtrUnchecked();
450       NodeTy *PosPrev = getPrev(PosNext);
451
452       // Fix head of list...
453       if (PosPrev)
454         this->setNext(PosPrev, First);
455       else
456         Head = First;
457       this->setPrev(First, PosPrev);
458
459       // Fix end of list...
460       this->setNext(Last, PosNext);
461       this->setPrev(PosNext, Last);
462
463       transferNodesFromList(L2, First, PosNext);
464
465       // Now that everything is set, restore the pointers to the list sentinals.
466       L2.setTail(L2Sentinel);
467       setTail(ThisSentinel);
468     }
469   }
470
471 public:
472
473   //===----------------------------------------------------------------------===
474   // Functionality derived from other functions defined above...
475   //
476
477   size_type size() const {
478     if (Head == 0) return 0; // Don't require construction of sentinal if empty.
479 #if __GNUC__ == 2
480     // GCC 2.95 has a broken std::distance
481     size_type Result = 0;
482     std::distance(begin(), end(), Result);
483     return Result;
484 #else
485     return std::distance(begin(), end());
486 #endif
487   }
488
489   iterator erase(iterator first, iterator last) {
490     while (first != last)
491       first = erase(first);
492     return last;
493   }
494
495   void clear() { if (Head) erase(begin(), end()); }
496
497   // Front and back inserters...
498   void push_front(NodeTy *val) { insert(begin(), val); }
499   void push_back(NodeTy *val) { insert(end(), val); }
500   void pop_front() {
501     assert(!empty() && "pop_front() on empty list!");
502     erase(begin());
503   }
504   void pop_back() {
505     assert(!empty() && "pop_back() on empty list!");
506     iterator t = end(); erase(--t);
507   }
508
509   // Special forms of insert...
510   template<class InIt> void insert(iterator where, InIt first, InIt last) {
511     for (; first != last; ++first) insert(where, *first);
512   }
513
514   // Splice members - defined in terms of transfer...
515   void splice(iterator where, iplist &L2) {
516     if (!L2.empty())
517       transfer(where, L2, L2.begin(), L2.end());
518   }
519   void splice(iterator where, iplist &L2, iterator first) {
520     iterator last = first; ++last;
521     if (where == first || where == last) return; // No change
522     transfer(where, L2, first, last);
523   }
524   void splice(iterator where, iplist &L2, iterator first, iterator last) {
525     if (first != last) transfer(where, L2, first, last);
526   }
527
528
529
530   //===----------------------------------------------------------------------===
531   // High-Level Functionality that shouldn't really be here, but is part of list
532   //
533
534   // These two functions are actually called remove/remove_if in list<>, but
535   // they actually do the job of erase, rename them accordingly.
536   //
537   void erase(const NodeTy &val) {
538     for (iterator I = begin(), E = end(); I != E; ) {
539       iterator next = I; ++next;
540       if (*I == val) erase(I);
541       I = next;
542     }
543   }
544   template<class Pr1> void erase_if(Pr1 pred) {
545     for (iterator I = begin(), E = end(); I != E; ) {
546       iterator next = I; ++next;
547       if (pred(*I)) erase(I);
548       I = next;
549     }
550   }
551
552   template<class Pr2> void unique(Pr2 pred) {
553     if (empty()) return;
554     for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
555       if (pred(*I))
556         erase(Next);
557       else
558         I = Next;
559       Next = I;
560     }
561   }
562   void unique() { unique(op_equal); }
563
564   template<class Pr3> void merge(iplist &right, Pr3 pred) {
565     iterator first1 = begin(), last1 = end();
566     iterator first2 = right.begin(), last2 = right.end();
567     while (first1 != last1 && first2 != last2)
568       if (pred(*first2, *first1)) {
569         iterator next = first2;
570         transfer(first1, right, first2, ++next);
571         first2 = next;
572       } else {
573         ++first1;
574       }
575     if (first2 != last2) transfer(last1, right, first2, last2);
576   }
577   void merge(iplist &right) { return merge(right, op_less); }
578
579   template<class Pr3> void sort(Pr3 pred);
580   void sort() { sort(op_less); }
581   void reverse();
582 };
583
584
585 template<typename NodeTy>
586 struct ilist : public iplist<NodeTy> {
587   typedef typename iplist<NodeTy>::size_type size_type;
588   typedef typename iplist<NodeTy>::iterator iterator;
589
590   ilist() {}
591   ilist(const ilist &right) {
592     insert(this->begin(), right.begin(), right.end());
593   }
594   explicit ilist(size_type count) {
595     insert(this->begin(), count, NodeTy());
596   } 
597   ilist(size_type count, const NodeTy &val) {
598     insert(this->begin(), count, val);
599   }
600   template<class InIt> ilist(InIt first, InIt last) {
601     insert(this->begin(), first, last);
602   }
603
604
605   // Forwarding functions: A workaround for GCC 2.95 which does not correctly
606   // support 'using' declarations to bring a hidden member into scope.
607   //
608   iterator insert(iterator a, NodeTy *b){ return iplist<NodeTy>::insert(a, b); }
609   void push_front(NodeTy *a) { iplist<NodeTy>::push_front(a); }
610   void push_back(NodeTy *a)  { iplist<NodeTy>::push_back(a); }
611   
612
613   // Main implementation here - Insert for a node passed by value...
614   iterator insert(iterator where, const NodeTy &val) {
615     return insert(where, createNode(val));
616   }
617
618
619   // Front and back inserters...
620   void push_front(const NodeTy &val) { insert(this->begin(), val); }
621   void push_back(const NodeTy &val) { insert(this->end(), val); }
622
623   // Special forms of insert...
624   template<class InIt> void insert(iterator where, InIt first, InIt last) {
625     for (; first != last; ++first) insert(where, *first);
626   }
627   void insert(iterator where, size_type count, const NodeTy &val) {
628     for (; count != 0; --count) insert(where, val);
629   }
630
631   // Assign special forms...
632   void assign(size_type count, const NodeTy &val) {
633     iterator I = this->begin();
634     for (; I != this->end() && count != 0; ++I, --count)
635       *I = val;
636     if (count != 0)
637       insert(this->end(), val, val);
638     else
639       erase(I, this->end());
640   }
641   template<class InIt> void assign(InIt first1, InIt last1) {
642     iterator first2 = this->begin(), last2 = this->end();
643     for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
644       *first1 = *first2;
645     if (first2 == last2)
646       erase(first1, last1);
647     else
648       insert(last1, first2, last2);
649   }
650
651
652   // Resize members...
653   void resize(size_type newsize, NodeTy val) {
654     iterator i = this->begin();
655     size_type len = 0;
656     for ( ; i != this->end() && len < newsize; ++i, ++len) /* empty*/ ;
657
658     if (len == newsize)
659       erase(i, this->end());
660     else                                          // i == end()
661       insert(this->end(), newsize - len, val);
662   }
663   void resize(size_type newsize) { resize(newsize, NodeTy()); }
664 };
665
666 } // End llvm namespace
667
668 namespace std {
669   // Ensure that swap uses the fast list swap...
670   template<class Ty>
671   void swap(llvm::iplist<Ty> &Left, llvm::iplist<Ty> &Right) {
672     Left.swap(Right);
673   }
674 }  // End 'std' extensions...
675
676 #endif // LLVM_ADT_ILIST_H