a few improvements:
[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     return std::equal(begin(), end(), RHS.begin());
406   }
407   bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
408
409   bool operator<(const SmallVectorImpl &RHS) const {
410     return std::lexicographical_compare(begin(), end(),
411                                         RHS.begin(), RHS.end());
412   }
413
414   /// set_size - Set the array size to \arg N, which the current array must have
415   /// enough capacity for.
416   ///
417   /// This does not construct or destroy any elements in the vector.
418   ///
419   /// Clients can use this in conjunction with capacity() to write past the end
420   /// of the buffer when they know that more elements are available, and only
421   /// update the size later. This avoids the cost of value initializing elements
422   /// which will only be overwritten.
423   void set_size(unsigned N) {
424     assert(N <= capacity());
425     setEnd(begin() + N);
426   }
427
428 private:
429   /// grow - double the size of the allocated memory, guaranteeing space for at
430   /// least one more element or MinSize if specified.
431   void grow(size_type MinSize = 0);
432
433   void construct_range(T *S, T *E, const T &Elt) {
434     for (; S != E; ++S)
435       new (S) T(Elt);
436   }
437
438   void destroy_range(T *S, T *E) {
439     // No need to do a destroy loop for POD's.
440     if (isPodLike<T>::value) return;
441     
442     while (S != E) {
443       --E;
444       E->~T();
445     }
446   }
447 };
448
449 // Define this out-of-line to dissuade the C++ compiler from inlining it.
450 template <typename T>
451 void SmallVectorImpl<T>::grow(size_t MinSize) {
452   size_t CurCapacity = capacity();
453   size_t CurSize = size();
454   size_t NewCapacity = 2*CurCapacity;
455   if (NewCapacity < MinSize)
456     NewCapacity = MinSize;
457   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
458
459   // Copy the elements over.
460   if (isPodLike<T>::value)
461     // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove.
462     memcpy(NewElts, begin(), CurSize * sizeof(T));
463   else
464     std::uninitialized_copy(begin(), end(), NewElts);
465
466   // Destroy the original elements.
467   destroy_range(begin(), end());
468
469   // If this wasn't grown from the inline copy, deallocate the old space.
470   if (!isSmall())
471     operator delete(begin());
472
473   setEnd(NewElts+CurSize);
474   BeginX = NewElts;
475   CapacityX = begin()+NewCapacity;
476 }
477
478 template <typename T>
479 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
480   if (this == &RHS) return;
481
482   // We can only avoid copying elements if neither vector is small.
483   if (!isSmall() && !RHS.isSmall()) {
484     std::swap(BeginX, RHS.BeginX);
485     std::swap(EndX, RHS.EndX);
486     std::swap(CapacityX, RHS.CapacityX);
487     return;
488   }
489   if (RHS.size() > capacity())
490     grow(RHS.size());
491   if (size() > RHS.capacity())
492     RHS.grow(size());
493
494   // Swap the shared elements.
495   size_t NumShared = size();
496   if (NumShared > RHS.size()) NumShared = RHS.size();
497   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
498     std::swap((*this)[i], RHS[i]);
499
500   // Copy over the extra elts.
501   if (size() > RHS.size()) {
502     size_t EltDiff = size() - RHS.size();
503     std::uninitialized_copy(begin()+NumShared, end(), RHS.end());
504     RHS.setEnd(RHS.end()+EltDiff);
505     destroy_range(begin()+NumShared, end());
506     setEnd(begin()+NumShared);
507   } else if (RHS.size() > size()) {
508     size_t EltDiff = RHS.size() - size();
509     std::uninitialized_copy(RHS.begin()+NumShared, RHS.end(), end());
510     setEnd(end() + EltDiff);
511     destroy_range(RHS.begin()+NumShared, RHS.end());
512     RHS.setEnd(RHS.begin()+NumShared);
513   }
514 }
515
516 template <typename T>
517 const SmallVectorImpl<T> &
518 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
519   // Avoid self-assignment.
520   if (this == &RHS) return *this;
521
522   // If we already have sufficient space, assign the common elements, then
523   // destroy any excess.
524   size_t RHSSize = RHS.size();
525   size_t CurSize = size();
526   if (CurSize >= RHSSize) {
527     // Assign common elements.
528     iterator NewEnd;
529     if (RHSSize)
530       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, begin());
531     else
532       NewEnd = begin();
533
534     // Destroy excess elements.
535     destroy_range(NewEnd, end());
536
537     // Trim.
538     setEnd(NewEnd);
539     return *this;
540   }
541
542   // If we have to grow to have enough elements, destroy the current elements.
543   // This allows us to avoid copying them during the grow.
544   if (capacity() < RHSSize) {
545     // Destroy current elements.
546     destroy_range(begin(), end());
547     setEnd(begin());
548     CurSize = 0;
549     grow(RHSSize);
550   } else if (CurSize) {
551     // Otherwise, use assignment for the already-constructed elements.
552     std::copy(RHS.begin(), RHS.begin()+CurSize, begin());
553   }
554
555   // Copy construct the new elements in place.
556   std::uninitialized_copy(RHS.begin()+CurSize, RHS.end(), begin()+CurSize);
557
558   // Set end.
559   setEnd(begin()+RHSSize);
560   return *this;
561 }
562
563 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
564 /// for the case when the array is small.  It contains some number of elements
565 /// in-place, which allows it to avoid heap allocation when the actual number of
566 /// elements is below that threshold.  This allows normal "small" cases to be
567 /// fast without losing generality for large inputs.
568 ///
569 /// Note that this does not attempt to be exception safe.
570 ///
571 template <typename T, unsigned N>
572 class SmallVector : public SmallVectorImpl<T> {
573   /// InlineElts - These are 'N-1' elements that are stored inline in the body
574   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
575   typedef typename SmallVectorImpl<T>::U U;
576   enum {
577     // MinUs - The number of U's require to cover N T's.
578     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
579              static_cast<unsigned int>(sizeof(U)) - 1) /
580             static_cast<unsigned int>(sizeof(U)),
581
582     // NumInlineEltsElts - The number of elements actually in this array.  There
583     // is already one in the parent class, and we have to round up to avoid
584     // having a zero-element array.
585     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
586
587     // NumTsAvailable - The number of T's we actually have space for, which may
588     // be more than N due to rounding.
589     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
590                      static_cast<unsigned int>(sizeof(T))
591   };
592   U InlineElts[NumInlineEltsElts];
593 public:
594   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
595   }
596
597   explicit SmallVector(unsigned Size, const T &Value = T())
598     : SmallVectorImpl<T>(NumTsAvailable) {
599     this->reserve(Size);
600     while (Size--)
601       this->push_back(Value);
602   }
603
604   template<typename ItTy>
605   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
606     this->append(S, E);
607   }
608
609   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
610     if (!RHS.empty())
611       SmallVectorImpl<T>::operator=(RHS);
612   }
613
614   const SmallVector &operator=(const SmallVector &RHS) {
615     SmallVectorImpl<T>::operator=(RHS);
616     return *this;
617   }
618
619 };
620
621 } // End llvm namespace
622
623 namespace std {
624   /// Implement std::swap in terms of SmallVector swap.
625   template<typename T>
626   inline void
627   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
628     LHS.swap(RHS);
629   }
630
631   /// Implement std::swap in terms of SmallVector swap.
632   template<typename T, unsigned N>
633   inline void
634   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
635     LHS.swap(RHS);
636   }
637 }
638
639 #endif