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