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