hoist the begin/end/capacity members and a few trivial methods
[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   
84 public:
85   bool empty() const { return BeginX == EndX; }
86 };
87   
88 /// SmallVectorImpl - This class consists of common code factored out of the
89 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
90 /// template parameter.
91 template <typename T>
92 class SmallVectorImpl : public SmallVectorBase {
93   void setEnd(T *P) { EndX = P; }
94 public:
95   // Default ctor - Initialize to empty.
96   explicit SmallVectorImpl(unsigned N) : SmallVectorBase(N*sizeof(T)) {
97   }
98
99   ~SmallVectorImpl() {
100     // Destroy the constructed elements in the vector.
101     destroy_range(begin(), end());
102
103     // If this wasn't grown from the inline copy, deallocate the old space.
104     if (!isSmall())
105       operator delete(begin());
106   }
107
108   typedef size_t size_type;
109   typedef ptrdiff_t difference_type;
110   typedef T value_type;
111   typedef T *iterator;
112   typedef const T *const_iterator;
113
114   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
115   typedef std::reverse_iterator<iterator> reverse_iterator;
116
117   typedef T &reference;
118   typedef const T &const_reference;
119   typedef T *pointer;
120   typedef const T *const_pointer;
121
122   // forward iterator creation methods.
123   iterator begin() { return (iterator)BeginX; }
124   const_iterator begin() const { return (const_iterator)BeginX; }
125   iterator end() { return (iterator)EndX; }
126   const_iterator end() const { return (const_iterator)EndX; }
127 private:
128   iterator capacity_ptr() { return (iterator)CapacityX; }
129   const_iterator capacity_ptr() const { return (const_iterator)CapacityX; }
130 public:
131
132   // reverse iterator creation methods.
133   reverse_iterator rbegin()            { return reverse_iterator(end()); }
134   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
135   reverse_iterator rend()              { return reverse_iterator(begin()); }
136   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
137
138   size_type size() const { return end()-begin(); }
139   size_type max_size() const { return size_type(-1) / sizeof(T); }
140   
141   /// capacity - Return the total number of elements in the currently allocated
142   /// buffer.
143   size_t capacity() const { return capacity_ptr() - begin(); }
144   
145   /// data - Return a pointer to the vector's buffer, even if empty().
146   pointer data() { return pointer(begin()); }
147   /// data - Return a pointer to the vector's buffer, even if empty().
148   const_pointer data() const { return const_pointer(begin()); }
149   
150   reference operator[](unsigned idx) {
151     assert(begin() + idx < end());
152     return begin()[idx];
153   }
154   const_reference operator[](unsigned idx) const {
155     assert(begin() + idx < end());
156     return begin()[idx];
157   }
158
159   reference front() {
160     return begin()[0];
161   }
162   const_reference front() const {
163     return begin()[0];
164   }
165
166   reference back() {
167     return end()[-1];
168   }
169   const_reference back() const {
170     return end()[-1];
171   }
172
173   void push_back(const_reference Elt) {
174     if (EndX < CapacityX) {
175   Retry:
176       new (end()) T(Elt);
177       setEnd(end()+1);
178       return;
179     }
180     grow();
181     goto Retry;
182   }
183
184   void pop_back() {
185     setEnd(end()-1);
186     end()->~T();
187   }
188
189   T pop_back_val() {
190     T Result = back();
191     pop_back();
192     return Result;
193   }
194
195   void clear() {
196     destroy_range(begin(), end());
197     EndX = BeginX;
198   }
199
200   void resize(unsigned N) {
201     if (N < size()) {
202       destroy_range(begin()+N, end());
203       setEnd(begin()+N);
204     } else if (N > size()) {
205       if (capacity() < N)
206         grow(N);
207       construct_range(end(), begin()+N, T());
208       setEnd(begin()+N);
209     }
210   }
211
212   void resize(unsigned N, const T &NV) {
213     if (N < size()) {
214       destroy_range(begin()+N, end());
215       setEnd(begin()+N);
216     } else if (N > size()) {
217       if (capacity() < N)
218         grow(N);
219       construct_range(end(), begin()+N, NV);
220       setEnd(begin()+N);
221     }
222   }
223
224   void reserve(unsigned N) {
225     if (capacity() < N)
226       grow(N);
227   }
228
229   void swap(SmallVectorImpl &RHS);
230
231   /// append - Add the specified range to the end of the SmallVector.
232   ///
233   template<typename in_iter>
234   void append(in_iter in_start, in_iter in_end) {
235     size_type NumInputs = std::distance(in_start, in_end);
236     // Grow allocated space if needed.
237     if (NumInputs > size_type(capacity_ptr()-end()))
238       grow(size()+NumInputs);
239
240     // Copy the new elements over.
241     std::uninitialized_copy(in_start, in_end, end());
242     setEnd(end() + NumInputs);
243   }
244
245   /// append - Add the specified range to the end of the SmallVector.
246   ///
247   void append(size_type NumInputs, const T &Elt) {
248     // Grow allocated space if needed.
249     if (NumInputs > size_type(capacity_ptr()-end()))
250       grow(size()+NumInputs);
251
252     // Copy the new elements over.
253     std::uninitialized_fill_n(end(), NumInputs, Elt);
254     setEnd(end() + NumInputs);
255   }
256
257   void assign(unsigned NumElts, const T &Elt) {
258     clear();
259     if (capacity() < NumElts)
260       grow(NumElts);
261     setEnd(begin()+NumElts);
262     construct_range(begin(), end(), Elt);
263   }
264
265   iterator erase(iterator I) {
266     iterator N = I;
267     // Shift all elts down one.
268     std::copy(I+1, end(), I);
269     // Drop the last elt.
270     pop_back();
271     return(N);
272   }
273
274   iterator erase(iterator S, iterator E) {
275     iterator N = S;
276     // Shift all elts down.
277     iterator I = std::copy(E, end(), S);
278     // Drop the last elts.
279     destroy_range(I, end());
280     setEnd(I);
281     return(N);
282   }
283
284   iterator insert(iterator I, const T &Elt) {
285     if (I == end()) {  // Important special case for empty vector.
286       push_back(Elt);
287       return end()-1;
288     }
289
290     if (EndX < CapacityX) {
291   Retry:
292       new (end()) T(back());
293       setEnd(end()+1);
294       // Push everything else over.
295       std::copy_backward(I, end()-1, end());
296       *I = Elt;
297       return I;
298     }
299     size_t EltNo = I-begin();
300     grow();
301     I = begin()+EltNo;
302     goto Retry;
303   }
304
305   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
306     if (I == end()) {  // Important special case for empty vector.
307       append(NumToInsert, Elt);
308       return end()-1;
309     }
310
311     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
312     size_t InsertElt = I-begin();
313
314     // Ensure there is enough space.
315     reserve(static_cast<unsigned>(size() + NumToInsert));
316
317     // Uninvalidate the iterator.
318     I = begin()+InsertElt;
319
320     // If there are more elements between the insertion point and the end of the
321     // range than there are being inserted, we can use a simple approach to
322     // insertion.  Since we already reserved space, we know that this won't
323     // reallocate the vector.
324     if (size_t(end()-I) >= NumToInsert) {
325       T *OldEnd = end();
326       append(end()-NumToInsert, end());
327
328       // Copy the existing elements that get replaced.
329       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
330
331       std::fill_n(I, NumToInsert, Elt);
332       return I;
333     }
334
335     // Otherwise, we're inserting more elements than exist already, and we're
336     // not inserting at the end.
337
338     // Copy over the elements that we're about to overwrite.
339     T *OldEnd = end();
340     setEnd(end() + NumToInsert);
341     size_t NumOverwritten = OldEnd-I;
342     std::uninitialized_copy(I, OldEnd, end()-NumOverwritten);
343
344     // Replace the overwritten part.
345     std::fill_n(I, NumOverwritten, Elt);
346
347     // Insert the non-overwritten middle part.
348     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
349     return I;
350   }
351
352   template<typename ItTy>
353   iterator insert(iterator I, ItTy From, ItTy To) {
354     if (I == end()) {  // Important special case for empty vector.
355       append(From, To);
356       return end()-1;
357     }
358
359     size_t NumToInsert = std::distance(From, To);
360     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
361     size_t InsertElt = I-begin();
362
363     // Ensure there is enough space.
364     reserve(static_cast<unsigned>(size() + NumToInsert));
365
366     // Uninvalidate the iterator.
367     I = begin()+InsertElt;
368
369     // If there are more elements between the insertion point and the end of the
370     // range than there are being inserted, we can use a simple approach to
371     // insertion.  Since we already reserved space, we know that this won't
372     // reallocate the vector.
373     if (size_t(end()-I) >= NumToInsert) {
374       T *OldEnd = end();
375       append(end()-NumToInsert, end());
376
377       // Copy the existing elements that get replaced.
378       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
379
380       std::copy(From, To, I);
381       return I;
382     }
383
384     // Otherwise, we're inserting more elements than exist already, and we're
385     // not inserting at the end.
386
387     // Copy over the elements that we're about to overwrite.
388     T *OldEnd = end();
389     setEnd(end() + NumToInsert);
390     size_t NumOverwritten = OldEnd-I;
391     std::uninitialized_copy(I, OldEnd, end()-NumOverwritten);
392
393     // Replace the overwritten part.
394     std::copy(From, From+NumOverwritten, I);
395
396     // Insert the non-overwritten middle part.
397     std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
398     return I;
399   }
400
401   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
402
403   bool operator==(const SmallVectorImpl &RHS) const {
404     if (size() != RHS.size()) return false;
405     for (const T *This = begin(), *That = RHS.begin(), *E = end();
406          This != E; ++This, ++That)
407       if (*This != *That)
408         return false;
409     return true;
410   }
411   bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
412
413   bool operator<(const SmallVectorImpl &RHS) const {
414     return std::lexicographical_compare(begin(), end(),
415                                         RHS.begin(), RHS.end());
416   }
417
418   /// set_size - Set the array size to \arg N, which the current array must have
419   /// enough capacity for.
420   ///
421   /// This does not construct or destroy any elements in the vector.
422   ///
423   /// Clients can use this in conjunction with capacity() to write past the end
424   /// of the buffer when they know that more elements are available, and only
425   /// update the size later. This avoids the cost of value initializing elements
426   /// which will only be overwritten.
427   void set_size(unsigned N) {
428     assert(N <= capacity());
429     setEnd(begin() + N);
430   }
431
432 private:
433   /// grow - double the size of the allocated memory, guaranteeing space for at
434   /// least one more element or MinSize if specified.
435   void grow(size_type MinSize = 0);
436
437   void construct_range(T *S, T *E, const T &Elt) {
438     for (; S != E; ++S)
439       new (S) T(Elt);
440   }
441
442   void destroy_range(T *S, T *E) {
443     // TODO: POD
444     while (S != E) {
445       --E;
446       E->~T();
447     }
448   }
449 };
450
451 // Define this out-of-line to dissuade the C++ compiler from inlining it.
452 template <typename T>
453 void SmallVectorImpl<T>::grow(size_t MinSize) {
454   size_t CurCapacity = capacity();
455   size_t CurSize = size();
456   size_t NewCapacity = 2*CurCapacity;
457   if (NewCapacity < MinSize)
458     NewCapacity = MinSize;
459   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
460
461   // Copy the elements over.
462   if (is_class<T>::value)
463     std::uninitialized_copy(begin(), end(), NewElts);
464   else
465     // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
466     memcpy(NewElts, begin(), CurSize * sizeof(T));
467
468   // Destroy the original elements.
469   destroy_range(begin(), end());
470
471   // If this wasn't grown from the inline copy, deallocate the old space.
472   if (!isSmall())
473     operator delete(begin());
474
475   setEnd(NewElts+CurSize);
476   BeginX = NewElts;
477   CapacityX = begin()+NewCapacity;
478 }
479
480 template <typename T>
481 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
482   if (this == &RHS) return;
483
484   // We can only avoid copying elements if neither vector is small.
485   if (!isSmall() && !RHS.isSmall()) {
486     std::swap(BeginX, RHS.BeginX);
487     std::swap(EndX, RHS.EndX);
488     std::swap(CapacityX, RHS.CapacityX);
489     return;
490   }
491   if (RHS.size() > capacity())
492     grow(RHS.size());
493   if (size() > RHS.capacity())
494     RHS.grow(size());
495
496   // Swap the shared elements.
497   size_t NumShared = size();
498   if (NumShared > RHS.size()) NumShared = RHS.size();
499   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
500     std::swap((*this)[i], RHS[i]);
501
502   // Copy over the extra elts.
503   if (size() > RHS.size()) {
504     size_t EltDiff = size() - RHS.size();
505     std::uninitialized_copy(begin()+NumShared, end(), RHS.end());
506     RHS.setEnd(RHS.end()+EltDiff);
507     destroy_range(begin()+NumShared, end());
508     setEnd(begin()+NumShared);
509   } else if (RHS.size() > size()) {
510     size_t EltDiff = RHS.size() - size();
511     std::uninitialized_copy(RHS.begin()+NumShared, RHS.end(), end());
512     setEnd(end() + EltDiff);
513     destroy_range(RHS.begin()+NumShared, RHS.end());
514     RHS.setEnd(RHS.begin()+NumShared);
515   }
516 }
517
518 template <typename T>
519 const SmallVectorImpl<T> &
520 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
521   // Avoid self-assignment.
522   if (this == &RHS) return *this;
523
524   // If we already have sufficient space, assign the common elements, then
525   // destroy any excess.
526   size_t RHSSize = RHS.size();
527   size_t CurSize = size();
528   if (CurSize >= RHSSize) {
529     // Assign common elements.
530     iterator NewEnd;
531     if (RHSSize)
532       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, begin());
533     else
534       NewEnd = begin();
535
536     // Destroy excess elements.
537     destroy_range(NewEnd, end());
538
539     // Trim.
540     setEnd(NewEnd);
541     return *this;
542   }
543
544   // If we have to grow to have enough elements, destroy the current elements.
545   // This allows us to avoid copying them during the grow.
546   if (capacity() < RHSSize) {
547     // Destroy current elements.
548     destroy_range(begin(), end());
549     setEnd(begin());
550     CurSize = 0;
551     grow(RHSSize);
552   } else if (CurSize) {
553     // Otherwise, use assignment for the already-constructed elements.
554     std::copy(RHS.begin(), RHS.begin()+CurSize, begin());
555   }
556
557   // Copy construct the new elements in place.
558   std::uninitialized_copy(RHS.begin()+CurSize, RHS.end(), begin()+CurSize);
559
560   // Set end.
561   setEnd(begin()+RHSSize);
562   return *this;
563 }
564
565 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
566 /// for the case when the array is small.  It contains some number of elements
567 /// in-place, which allows it to avoid heap allocation when the actual number of
568 /// elements is below that threshold.  This allows normal "small" cases to be
569 /// fast without losing generality for large inputs.
570 ///
571 /// Note that this does not attempt to be exception safe.
572 ///
573 template <typename T, unsigned N>
574 class SmallVector : public SmallVectorImpl<T> {
575   /// InlineElts - These are 'N-1' elements that are stored inline in the body
576   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
577   typedef typename SmallVectorImpl<T>::U U;
578   enum {
579     // MinUs - The number of U's require to cover N T's.
580     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
581              static_cast<unsigned int>(sizeof(U)) - 1) /
582             static_cast<unsigned int>(sizeof(U)),
583
584     // NumInlineEltsElts - The number of elements actually in this array.  There
585     // is already one in the parent class, and we have to round up to avoid
586     // having a zero-element array.
587     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
588
589     // NumTsAvailable - The number of T's we actually have space for, which may
590     // be more than N due to rounding.
591     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
592                      static_cast<unsigned int>(sizeof(T))
593   };
594   U InlineElts[NumInlineEltsElts];
595 public:
596   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
597   }
598
599   explicit SmallVector(unsigned Size, const T &Value = T())
600     : SmallVectorImpl<T>(NumTsAvailable) {
601     this->reserve(Size);
602     while (Size--)
603       this->push_back(Value);
604   }
605
606   template<typename ItTy>
607   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
608     this->append(S, E);
609   }
610
611   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
612     if (!RHS.empty())
613       SmallVectorImpl<T>::operator=(RHS);
614   }
615
616   const SmallVector &operator=(const SmallVector &RHS) {
617     SmallVectorImpl<T>::operator=(RHS);
618     return *this;
619   }
620
621 };
622
623 } // End llvm namespace
624
625 namespace std {
626   /// Implement std::swap in terms of SmallVector swap.
627   template<typename T>
628   inline void
629   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
630     LHS.swap(RHS);
631   }
632
633   /// Implement std::swap in terms of SmallVector swap.
634   template<typename T, unsigned N>
635   inline void
636   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
637     LHS.swap(RHS);
638   }
639 }
640
641 #endif