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