sink most of the meat in smallvector back from SmallVectorTemplateCommon
[oota-llvm.git] / include / llvm / ADT / SmallVector.h
1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- 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 the SmallVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
16
17 #include "llvm/Support/type_traits.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cstring>
21 #include <memory>
22
23 #ifdef _MSC_VER
24 namespace std {
25 #if _MSC_VER <= 1310
26   // Work around flawed VC++ implementation of std::uninitialized_copy.  Define
27   // additional overloads so that elements with pointer types are recognized as
28   // scalars and not objects, causing bizarre type conversion errors.
29   template<class T1, class T2>
30   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
31     _Scalar_ptr_iterator_tag _Cat;
32     return _Cat;
33   }
34
35   template<class T1, class T2>
36   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
37     _Scalar_ptr_iterator_tag _Cat;
38     return _Cat;
39   }
40 #else
41 // FIXME: It is not clear if the problem is fixed in VS 2005.  What is clear
42 // is that the above hack won't work if it wasn't fixed.
43 #endif
44 }
45 #endif
46
47 namespace llvm {
48
49 /// SmallVectorBase - This is all the non-templated stuff common to all
50 /// SmallVectors.
51 class SmallVectorBase {
52 protected:
53   void *BeginX, *EndX, *CapacityX;
54
55   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
56   // don't want it to be automatically run, so we need to represent the space as
57   // something else.  An array of char would work great, but might not be
58   // aligned sufficiently.  Instead, we either use GCC extensions, or some
59   // number of union instances for the space, which guarantee maximal alignment.
60 #ifdef __GNUC__
61   typedef char U;
62   U FirstEl __attribute__((aligned));
63 #else
64   union U {
65     double D;
66     long double LD;
67     long long L;
68     void *P;
69   } FirstEl;
70 #endif
71   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
72   
73 protected:
74   SmallVectorBase(size_t Size)
75     : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
76   
77   /// isSmall - Return true if this is a smallvector which has not had dynamic
78   /// memory allocated for it.
79   bool isSmall() const {
80     return BeginX == static_cast<const void*>(&FirstEl);
81   }
82   
83 public:
84   bool empty() const { return BeginX == EndX; }
85 };
86
87 template <typename T>
88 class SmallVectorTemplateCommon : public SmallVectorBase {
89 protected:
90   void setEnd(T *P) { this->EndX = P; }
91 public:
92   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
93   
94   typedef size_t size_type;
95   typedef ptrdiff_t difference_type;
96   typedef T value_type;
97   typedef T *iterator;
98   typedef const T *const_iterator;
99   
100   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
101   typedef std::reverse_iterator<iterator> reverse_iterator;
102   
103   typedef T &reference;
104   typedef const T &const_reference;
105   typedef T *pointer;
106   typedef const T *const_pointer;
107   
108   // forward iterator creation methods.
109   iterator begin() { return (iterator)this->BeginX; }
110   const_iterator begin() const { return (const_iterator)this->BeginX; }
111   iterator end() { return (iterator)this->EndX; }
112   const_iterator end() const { return (const_iterator)this->EndX; }
113 protected:
114   iterator capacity_ptr() { return (iterator)this->CapacityX; }
115   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
116 public:
117   
118   // reverse iterator creation methods.
119   reverse_iterator rbegin()            { return reverse_iterator(end()); }
120   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
121   reverse_iterator rend()              { return reverse_iterator(begin()); }
122   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
123
124   size_type size() const { return end()-begin(); }
125   size_type max_size() const { return size_type(-1) / sizeof(T); }
126   
127   /// capacity - Return the total number of elements in the currently allocated
128   /// buffer.
129   size_t capacity() const { return capacity_ptr() - begin(); }
130   
131   /// data - Return a pointer to the vector's buffer, even if empty().
132   pointer data() { return pointer(begin()); }
133   /// data - Return a pointer to the vector's buffer, even if empty().
134   const_pointer data() const { return const_pointer(begin()); }
135   
136   reference operator[](unsigned idx) {
137     assert(begin() + idx < end());
138     return begin()[idx];
139   }
140   const_reference operator[](unsigned idx) const {
141     assert(begin() + idx < end());
142     return begin()[idx];
143   }
144
145   reference front() {
146     return begin()[0];
147   }
148   const_reference front() const {
149     return begin()[0];
150   }
151
152   reference back() {
153     return end()[-1];
154   }
155   const_reference back() const {
156     return end()[-1];
157   }
158 };
159   
160   
161 template <typename T, bool isPodLike>
162 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
163 public:
164   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
165
166 };
167
168 template <typename T>
169 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
170 public:
171   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
172   
173 };
174   
175   
176 /// SmallVectorImpl - This class consists of common code factored out of the
177 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
178 /// template parameter.
179 template <typename T>
180 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
181 public:
182   typedef typename SmallVectorTemplateBase<T, isPodLike<T>::value >::iterator
183     iterator;
184   typedef typename SmallVectorTemplateBase<T, isPodLike<T>::value >::size_type
185     size_type;
186   
187   // Default ctor - Initialize to empty.
188   explicit SmallVectorImpl(unsigned N)
189     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
190   }
191   
192   ~SmallVectorImpl() {
193     // Destroy the constructed elements in the vector.
194     destroy_range(this->begin(), this->end());
195     
196     // If this wasn't grown from the inline copy, deallocate the old space.
197     if (!this->isSmall())
198       operator delete(this->begin());
199   }
200   
201   
202   void clear() {
203     destroy_range(this->begin(), this->end());
204     this->EndX = this->BeginX;
205   }
206
207   void resize(unsigned N) {
208     if (N < this->size()) {
209       this->destroy_range(this->begin()+N, this->end());
210       this->setEnd(this->begin()+N);
211     } else if (N > this->size()) {
212       if (this->capacity() < N)
213         grow(N);
214       this->construct_range(this->end(), this->begin()+N, T());
215       this->setEnd(this->begin()+N);
216     }
217   }
218
219   void resize(unsigned N, const T &NV) {
220     if (N < this->size()) {
221       destroy_range(this->begin()+N, this->end());
222       setEnd(this->begin()+N);
223     } else if (N > this->size()) {
224       if (this->capacity() < N)
225         grow(N);
226       construct_range(this->end(), this->begin()+N, NV);
227       setEnd(this->begin()+N);
228     }
229   }
230
231   void reserve(unsigned N) {
232     if (this->capacity() < N)
233       grow(N);
234   }
235   
236   void push_back(const T &Elt) {
237     if (this->EndX < this->CapacityX) {
238     Retry:
239       new (this->end()) T(Elt);
240       setEnd(this->end()+1);
241       return;
242     }
243     this->grow();
244     goto Retry;
245   }
246   
247   void pop_back() {
248     setEnd(this->end()-1);
249     this->end()->~T();
250   }
251   
252   T pop_back_val() {
253     T Result = this->back();
254     pop_back();
255     return Result;
256   }
257   
258   
259   void swap(SmallVectorImpl &RHS);
260   
261   /// append - Add the specified range to the end of the SmallVector.
262   ///
263   template<typename in_iter>
264   void append(in_iter in_start, in_iter in_end) {
265     size_type NumInputs = std::distance(in_start, in_end);
266     // Grow allocated space if needed.
267     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
268       grow(this->size()+NumInputs);
269     
270     // Copy the new elements over.
271     // TODO: NEED To compile time dispatch on whether in_iter is a random access
272     // iterator to use the fast uninitialized_copy.
273     std::uninitialized_copy(in_start, in_end, this->end());
274     setEnd(this->end() + NumInputs);
275   }
276   
277   /// append - Add the specified range to the end of the SmallVector.
278   ///
279   void append(size_type NumInputs, const T &Elt) {
280     // Grow allocated space if needed.
281     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
282       grow(this->size()+NumInputs);
283     
284     // Copy the new elements over.
285     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
286     setEnd(this->end() + NumInputs);
287   }
288   
289   void assign(unsigned NumElts, const T &Elt) {
290     clear();
291     if (this->capacity() < NumElts)
292       grow(NumElts);
293     setEnd(this->begin()+NumElts);
294     construct_range(this->begin(), this->end(), Elt);
295   }
296   
297   iterator erase(iterator I) {
298     iterator N = I;
299     // Shift all elts down one.
300     std::copy(I+1, this->end(), I);
301     // Drop the last elt.
302     pop_back();
303     return(N);
304   }
305   
306   iterator erase(iterator S, iterator E) {
307     iterator N = S;
308     // Shift all elts down.
309     iterator I = std::copy(E, this->end(), S);
310     // Drop the last elts.
311     destroy_range(I, this->end());
312     setEnd(I);
313     return(N);
314   }
315   
316   iterator insert(iterator I, const T &Elt) {
317     if (I == this->end()) {  // Important special case for empty vector.
318       push_back(Elt);
319       return this->end()-1;
320     }
321     
322     if (this->EndX < this->CapacityX) {
323     Retry:
324       new (this->end()) T(this->back());
325       this->setEnd(this->end()+1);
326       // Push everything else over.
327       std::copy_backward(I, this->end()-1, this->end());
328       *I = Elt;
329       return I;
330     }
331     size_t EltNo = I-this->begin();
332     this->grow();
333     I = this->begin()+EltNo;
334     goto Retry;
335   }
336   
337   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
338     if (I == this->end()) {  // Important special case for empty vector.
339       append(NumToInsert, Elt);
340       return this->end()-1;
341     }
342     
343     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
344     size_t InsertElt = I - this->begin();
345     
346     // Ensure there is enough space.
347     reserve(static_cast<unsigned>(this->size() + NumToInsert));
348     
349     // Uninvalidate the iterator.
350     I = this->begin()+InsertElt;
351     
352     // If there are more elements between the insertion point and the end of the
353     // range than there are being inserted, we can use a simple approach to
354     // insertion.  Since we already reserved space, we know that this won't
355     // reallocate the vector.
356     if (size_t(this->end()-I) >= NumToInsert) {
357       T *OldEnd = this->end();
358       append(this->end()-NumToInsert, this->end());
359       
360       // Copy the existing elements that get replaced.
361       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
362       
363       std::fill_n(I, NumToInsert, Elt);
364       return I;
365     }
366     
367     // Otherwise, we're inserting more elements than exist already, and we're
368     // not inserting at the end.
369     
370     // Copy over the elements that we're about to overwrite.
371     T *OldEnd = this->end();
372     setEnd(this->end() + NumToInsert);
373     size_t NumOverwritten = OldEnd-I;
374     uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
375     
376     // Replace the overwritten part.
377     std::fill_n(I, NumOverwritten, Elt);
378     
379     // Insert the non-overwritten middle part.
380     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
381     return I;
382   }
383   
384   template<typename ItTy>
385   iterator insert(iterator I, ItTy From, ItTy To) {
386     if (I == this->end()) {  // Important special case for empty vector.
387       append(From, To);
388       return this->end()-1;
389     }
390     
391     size_t NumToInsert = std::distance(From, To);
392     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
393     size_t InsertElt = I - this->begin();
394     
395     // Ensure there is enough space.
396     reserve(static_cast<unsigned>(this->size() + NumToInsert));
397     
398     // Uninvalidate the iterator.
399     I = this->begin()+InsertElt;
400     
401     // If there are more elements between the insertion point and the end of the
402     // range than there are being inserted, we can use a simple approach to
403     // insertion.  Since we already reserved space, we know that this won't
404     // reallocate the vector.
405     if (size_t(this->end()-I) >= NumToInsert) {
406       T *OldEnd = this->end();
407       append(this->end()-NumToInsert, this->end());
408       
409       // Copy the existing elements that get replaced.
410       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
411       
412       std::copy(From, To, I);
413       return I;
414     }
415     
416     // Otherwise, we're inserting more elements than exist already, and we're
417     // not inserting at the end.
418     
419     // Copy over the elements that we're about to overwrite.
420     T *OldEnd = this->end();
421     setEnd(this->end() + NumToInsert);
422     size_t NumOverwritten = OldEnd-I;
423     uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
424     
425     // Replace the overwritten part.
426     std::copy(From, From+NumOverwritten, I);
427     
428     // Insert the non-overwritten middle part.
429     uninitialized_copy(From+NumOverwritten, To, OldEnd);
430     return I;
431   }
432   
433   const SmallVectorImpl
434   &operator=(const SmallVectorImpl &RHS);
435   
436   bool operator==(const SmallVectorImpl &RHS) const {
437     if (this->size() != RHS.size()) return false;
438     return std::equal(this->begin(), this->end(), RHS.begin());
439   }
440   bool operator!=(const SmallVectorImpl &RHS) const {
441     return !(*this == RHS);
442   }
443   
444   bool operator<(const SmallVectorImpl &RHS) const {
445     return std::lexicographical_compare(this->begin(), this->end(),
446                                         RHS.begin(), RHS.end());
447   }
448   
449   /// set_size - Set the array size to \arg N, which the current array must have
450   /// enough capacity for.
451   ///
452   /// This does not construct or destroy any elements in the vector.
453   ///
454   /// Clients can use this in conjunction with capacity() to write past the end
455   /// of the buffer when they know that more elements are available, and only
456   /// update the size later. This avoids the cost of value initializing elements
457   /// which will only be overwritten.
458   void set_size(unsigned N) {
459     assert(N <= this->capacity());
460     setEnd(this->begin() + N);
461   }
462   
463 private:
464   /// grow - double the size of the allocated memory, guaranteeing space for at
465   /// least one more element or MinSize if specified.
466   void grow(size_t MinSize = 0);
467   
468   static void construct_range(T *S, T *E, const T &Elt) {
469     for (; S != E; ++S)
470       new (S) T(Elt);
471   }
472   
473   static void destroy_range(T *S, T *E) {
474     // No need to do a destroy loop for POD's.
475     if (isPodLike<T>::value) return;
476     
477     while (S != E) {
478       --E;
479       E->~T();
480     }
481   }
482   
483   /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
484   /// starting with "Dest", constructing elements into it as needed.
485   template<typename It1, typename It2>
486   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
487     // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove.
488     if (isPodLike<T>::value)
489       memcpy(&*Dest, &*I, (E-I)*sizeof(T));
490     else
491       std::uninitialized_copy(I, E, Dest);
492   }
493 };
494   
495
496 // Define this out-of-line to dissuade the C++ compiler from inlining it.
497 template <typename T>
498 void SmallVectorImpl<T>::grow(size_t MinSize) {
499   size_t CurCapacity = this->capacity();
500   size_t CurSize = this->size();
501   size_t NewCapacity = 2*CurCapacity;
502   if (NewCapacity < MinSize)
503     NewCapacity = MinSize;
504   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
505
506   // Copy the elements over.
507   uninitialized_copy(this->begin(), this->end(), NewElts);
508
509   // Destroy the original elements.
510   destroy_range(this->begin(), this->end());
511
512   // If this wasn't grown from the inline copy, deallocate the old space.
513   if (!this->isSmall())
514     operator delete(this->begin());
515
516   setEnd(NewElts+CurSize);
517   this->BeginX = NewElts;
518   this->CapacityX = this->begin()+NewCapacity;
519 }
520
521 template <typename T>
522 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
523   if (this == &RHS) return;
524
525   // We can only avoid copying elements if neither vector is small.
526   if (!this->isSmall() && !RHS.isSmall()) {
527     std::swap(this->BeginX, RHS.BeginX);
528     std::swap(this->EndX, RHS.EndX);
529     std::swap(this->CapacityX, RHS.CapacityX);
530     return;
531   }
532   if (RHS.size() > this->capacity())
533     grow(RHS.size());
534   if (this->size() > RHS.capacity())
535     RHS.grow(this->size());
536
537   // Swap the shared elements.
538   size_t NumShared = this->size();
539   if (NumShared > RHS.size()) NumShared = RHS.size();
540   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
541     std::swap((*this)[i], RHS[i]);
542
543   // Copy over the extra elts.
544   if (this->size() > RHS.size()) {
545     size_t EltDiff = this->size() - RHS.size();
546     uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
547     RHS.setEnd(RHS.end()+EltDiff);
548     destroy_range(this->begin()+NumShared, this->end());
549     setEnd(this->begin()+NumShared);
550   } else if (RHS.size() > this->size()) {
551     size_t EltDiff = RHS.size() - this->size();
552     uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
553     setEnd(this->end() + EltDiff);
554     destroy_range(RHS.begin()+NumShared, RHS.end());
555     RHS.setEnd(RHS.begin()+NumShared);
556   }
557 }
558
559 template <typename T>
560 const SmallVectorImpl<T> &SmallVectorImpl<T>::
561   operator=(const SmallVectorImpl<T> &RHS) {
562   // Avoid self-assignment.
563   if (this == &RHS) return *this;
564
565   // If we already have sufficient space, assign the common elements, then
566   // destroy any excess.
567   size_t RHSSize = RHS.size();
568   size_t CurSize = this->size();
569   if (CurSize >= RHSSize) {
570     // Assign common elements.
571     iterator NewEnd;
572     if (RHSSize)
573       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
574     else
575       NewEnd = this->begin();
576
577     // Destroy excess elements.
578     destroy_range(NewEnd, this->end());
579
580     // Trim.
581     setEnd(NewEnd);
582     return *this;
583   }
584
585   // If we have to grow to have enough elements, destroy the current elements.
586   // This allows us to avoid copying them during the grow.
587   if (this->capacity() < RHSSize) {
588     // Destroy current elements.
589     destroy_range(this->begin(), this->end());
590     setEnd(this->begin());
591     CurSize = 0;
592     grow(RHSSize);
593   } else if (CurSize) {
594     // Otherwise, use assignment for the already-constructed elements.
595     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
596   }
597
598   // Copy construct the new elements in place.
599   uninitialized_copy(RHS.begin()+CurSize, RHS.end(), this->begin()+CurSize);
600
601   // Set end.
602   setEnd(this->begin()+RHSSize);
603   return *this;
604 }
605
606
607 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
608 /// for the case when the array is small.  It contains some number of elements
609 /// in-place, which allows it to avoid heap allocation when the actual number of
610 /// elements is below that threshold.  This allows normal "small" cases to be
611 /// fast without losing generality for large inputs.
612 ///
613 /// Note that this does not attempt to be exception safe.
614 ///
615 template <typename T, unsigned N>
616 class SmallVector : public SmallVectorImpl<T> {
617   /// InlineElts - These are 'N-1' elements that are stored inline in the body
618   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
619   typedef typename SmallVectorImpl<T>::U U;
620   enum {
621     // MinUs - The number of U's require to cover N T's.
622     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
623              static_cast<unsigned int>(sizeof(U)) - 1) /
624             static_cast<unsigned int>(sizeof(U)),
625
626     // NumInlineEltsElts - The number of elements actually in this array.  There
627     // is already one in the parent class, and we have to round up to avoid
628     // having a zero-element array.
629     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
630
631     // NumTsAvailable - The number of T's we actually have space for, which may
632     // be more than N due to rounding.
633     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
634                      static_cast<unsigned int>(sizeof(T))
635   };
636   U InlineElts[NumInlineEltsElts];
637 public:
638   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
639   }
640
641   explicit SmallVector(unsigned Size, const T &Value = T())
642     : SmallVectorImpl<T>(NumTsAvailable) {
643     this->reserve(Size);
644     while (Size--)
645       this->push_back(Value);
646   }
647
648   template<typename ItTy>
649   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
650     this->append(S, E);
651   }
652
653   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
654     if (!RHS.empty())
655       SmallVectorImpl<T>::operator=(RHS);
656   }
657
658   const SmallVector &operator=(const SmallVector &RHS) {
659     SmallVectorImpl<T>::operator=(RHS);
660     return *this;
661   }
662
663 };
664
665 } // End llvm namespace
666
667 namespace std {
668   /// Implement std::swap in terms of SmallVector swap.
669   template<typename T>
670   inline void
671   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
672     LHS.swap(RHS);
673   }
674
675   /// Implement std::swap in terms of SmallVector swap.
676   template<typename T, unsigned N>
677   inline void
678   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
679     LHS.swap(RHS);
680   }
681 }
682
683 #endif