LLVM  mainline
SmallVector.h
Go to the documentation of this file.
00001 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the SmallVector class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_ADT_SMALLVECTOR_H
00015 #define LLVM_ADT_SMALLVECTOR_H
00016 
00017 #include "llvm/ADT/iterator_range.h"
00018 #include "llvm/Support/AlignOf.h"
00019 #include "llvm/Support/Compiler.h"
00020 #include "llvm/Support/MathExtras.h"
00021 #include "llvm/Support/type_traits.h"
00022 #include <algorithm>
00023 #include <cassert>
00024 #include <cstddef>
00025 #include <cstdlib>
00026 #include <cstring>
00027 #include <initializer_list>
00028 #include <iterator>
00029 #include <memory>
00030 
00031 namespace llvm {
00032 
00033 /// This is all the non-templated stuff common to all SmallVectors.
00034 class SmallVectorBase {
00035 protected:
00036   void *BeginX, *EndX, *CapacityX;
00037 
00038 protected:
00039   SmallVectorBase(void *FirstEl, size_t Size)
00040     : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {}
00041 
00042   /// This is an implementation of the grow() method which only works
00043   /// on POD-like data types and is out of line to reduce code duplication.
00044   void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize);
00045 
00046 public:
00047   /// This returns size()*sizeof(T).
00048   size_t size_in_bytes() const {
00049     return size_t((char*)EndX - (char*)BeginX);
00050   }
00051 
00052   /// capacity_in_bytes - This returns capacity()*sizeof(T).
00053   size_t capacity_in_bytes() const {
00054     return size_t((char*)CapacityX - (char*)BeginX);
00055   }
00056 
00057   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return BeginX == EndX; }
00058 };
00059 
00060 template <typename T, unsigned N> struct SmallVectorStorage;
00061 
00062 /// This is the part of SmallVectorTemplateBase which does not depend on whether
00063 /// the type T is a POD. The extra dummy template argument is used by ArrayRef
00064 /// to avoid unnecessarily requiring T to be complete.
00065 template <typename T, typename = void>
00066 class SmallVectorTemplateCommon : public SmallVectorBase {
00067 private:
00068   template <typename, unsigned> friend struct SmallVectorStorage;
00069 
00070   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
00071   // don't want it to be automatically run, so we need to represent the space as
00072   // something else.  Use an array of char of sufficient alignment.
00073   typedef llvm::AlignedCharArrayUnion<T> U;
00074   U FirstEl;
00075   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
00076 
00077 protected:
00078   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {}
00079 
00080   void grow_pod(size_t MinSizeInBytes, size_t TSize) {
00081     SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize);
00082   }
00083 
00084   /// Return true if this is a smallvector which has not had dynamic
00085   /// memory allocated for it.
00086   bool isSmall() const {
00087     return BeginX == static_cast<const void*>(&FirstEl);
00088   }
00089 
00090   /// Put this vector in a state of being small.
00091   void resetToSmall() {
00092     BeginX = EndX = CapacityX = &FirstEl;
00093   }
00094 
00095   void setEnd(T *P) { this->EndX = P; }
00096 public:
00097   typedef size_t size_type;
00098   typedef ptrdiff_t difference_type;
00099   typedef T value_type;
00100   typedef T *iterator;
00101   typedef const T *const_iterator;
00102 
00103   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
00104   typedef std::reverse_iterator<iterator> reverse_iterator;
00105 
00106   typedef T &reference;
00107   typedef const T &const_reference;
00108   typedef T *pointer;
00109   typedef const T *const_pointer;
00110 
00111   // forward iterator creation methods.
00112   LLVM_ATTRIBUTE_ALWAYS_INLINE
00113   iterator begin() { return (iterator)this->BeginX; }
00114   LLVM_ATTRIBUTE_ALWAYS_INLINE
00115   const_iterator begin() const { return (const_iterator)this->BeginX; }
00116   LLVM_ATTRIBUTE_ALWAYS_INLINE
00117   iterator end() { return (iterator)this->EndX; }
00118   LLVM_ATTRIBUTE_ALWAYS_INLINE
00119   const_iterator end() const { return (const_iterator)this->EndX; }
00120 protected:
00121   iterator capacity_ptr() { return (iterator)this->CapacityX; }
00122   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
00123 public:
00124 
00125   // reverse iterator creation methods.
00126   reverse_iterator rbegin()            { return reverse_iterator(end()); }
00127   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
00128   reverse_iterator rend()              { return reverse_iterator(begin()); }
00129   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
00130 
00131   LLVM_ATTRIBUTE_ALWAYS_INLINE
00132   size_type size() const { return end()-begin(); }
00133   size_type max_size() const { return size_type(-1) / sizeof(T); }
00134 
00135   /// Return the total number of elements in the currently allocated buffer.
00136   size_t capacity() const { return capacity_ptr() - begin(); }
00137 
00138   /// Return a pointer to the vector's buffer, even if empty().
00139   pointer data() { return pointer(begin()); }
00140   /// Return a pointer to the vector's buffer, even if empty().
00141   const_pointer data() const { return const_pointer(begin()); }
00142 
00143   LLVM_ATTRIBUTE_ALWAYS_INLINE
00144   reference operator[](size_type idx) {
00145     assert(idx < size());
00146     return begin()[idx];
00147   }
00148   LLVM_ATTRIBUTE_ALWAYS_INLINE
00149   const_reference operator[](size_type idx) const {
00150     assert(idx < size());
00151     return begin()[idx];
00152   }
00153 
00154   reference front() {
00155     assert(!empty());
00156     return begin()[0];
00157   }
00158   const_reference front() const {
00159     assert(!empty());
00160     return begin()[0];
00161   }
00162 
00163   reference back() {
00164     assert(!empty());
00165     return end()[-1];
00166   }
00167   const_reference back() const {
00168     assert(!empty());
00169     return end()[-1];
00170   }
00171 };
00172 
00173 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
00174 /// implementations that are designed to work with non-POD-like T's.
00175 template <typename T, bool isPodLike>
00176 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
00177 protected:
00178   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
00179 
00180   static void destroy_range(T *S, T *E) {
00181     while (S != E) {
00182       --E;
00183       E->~T();
00184     }
00185   }
00186 
00187   /// Use move-assignment to move the range [I, E) onto the
00188   /// objects starting with "Dest".  This is just <memory>'s
00189   /// std::move, but not all stdlibs actually provide that.
00190   template<typename It1, typename It2>
00191   static It2 move(It1 I, It1 E, It2 Dest) {
00192     for (; I != E; ++I, ++Dest)
00193       *Dest = ::std::move(*I);
00194     return Dest;
00195   }
00196 
00197   /// Use move-assignment to move the range
00198   /// [I, E) onto the objects ending at "Dest", moving objects
00199   /// in reverse order.  This is just <algorithm>'s
00200   /// std::move_backward, but not all stdlibs actually provide that.
00201   template<typename It1, typename It2>
00202   static It2 move_backward(It1 I, It1 E, It2 Dest) {
00203     while (I != E)
00204       *--Dest = ::std::move(*--E);
00205     return Dest;
00206   }
00207 
00208   /// Move the range [I, E) into the uninitialized memory starting with "Dest",
00209   /// constructing elements as needed.
00210   template<typename It1, typename It2>
00211   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
00212     for (; I != E; ++I, ++Dest)
00213       ::new ((void*) &*Dest) T(::std::move(*I));
00214   }
00215 
00216   /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
00217   /// constructing elements as needed.
00218   template<typename It1, typename It2>
00219   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
00220     std::uninitialized_copy(I, E, Dest);
00221   }
00222 
00223   /// Grow the allocated memory (without initializing new elements), doubling
00224   /// the size of the allocated memory. Guarantees space for at least one more
00225   /// element, or MinSize more elements if specified.
00226   void grow(size_t MinSize = 0);
00227 
00228 public:
00229   void push_back(const T &Elt) {
00230     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
00231       this->grow();
00232     ::new ((void*) this->end()) T(Elt);
00233     this->setEnd(this->end()+1);
00234   }
00235 
00236   void push_back(T &&Elt) {
00237     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
00238       this->grow();
00239     ::new ((void*) this->end()) T(::std::move(Elt));
00240     this->setEnd(this->end()+1);
00241   }
00242 
00243   void pop_back() {
00244     this->setEnd(this->end()-1);
00245     this->end()->~T();
00246   }
00247 };
00248 
00249 // Define this out-of-line to dissuade the C++ compiler from inlining it.
00250 template <typename T, bool isPodLike>
00251 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
00252   size_t CurCapacity = this->capacity();
00253   size_t CurSize = this->size();
00254   // Always grow, even from zero.
00255   size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2));
00256   if (NewCapacity < MinSize)
00257     NewCapacity = MinSize;
00258   T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
00259 
00260   // Move the elements over.
00261   this->uninitialized_move(this->begin(), this->end(), NewElts);
00262 
00263   // Destroy the original elements.
00264   destroy_range(this->begin(), this->end());
00265 
00266   // If this wasn't grown from the inline copy, deallocate the old space.
00267   if (!this->isSmall())
00268     free(this->begin());
00269 
00270   this->setEnd(NewElts+CurSize);
00271   this->BeginX = NewElts;
00272   this->CapacityX = this->begin()+NewCapacity;
00273 }
00274 
00275 
00276 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
00277 /// implementations that are designed to work with POD-like T's.
00278 template <typename T>
00279 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
00280 protected:
00281   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
00282 
00283   // No need to do a destroy loop for POD's.
00284   static void destroy_range(T *, T *) {}
00285 
00286   /// Use move-assignment to move the range [I, E) onto the
00287   /// objects starting with "Dest".  For PODs, this is just memcpy.
00288   template<typename It1, typename It2>
00289   static It2 move(It1 I, It1 E, It2 Dest) {
00290     return ::std::copy(I, E, Dest);
00291   }
00292 
00293   /// Use move-assignment to move the range [I, E) onto the objects ending at
00294   /// "Dest", moving objects in reverse order.
00295   template<typename It1, typename It2>
00296   static It2 move_backward(It1 I, It1 E, It2 Dest) {
00297     return ::std::copy_backward(I, E, Dest);
00298   }
00299 
00300   /// Move the range [I, E) onto the uninitialized memory
00301   /// starting with "Dest", constructing elements into it as needed.
00302   template<typename It1, typename It2>
00303   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
00304     // Just do a copy.
00305     uninitialized_copy(I, E, Dest);
00306   }
00307 
00308   /// Copy the range [I, E) onto the uninitialized memory
00309   /// starting with "Dest", constructing elements into it as needed.
00310   template<typename It1, typename It2>
00311   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
00312     // Arbitrary iterator types; just use the basic implementation.
00313     std::uninitialized_copy(I, E, Dest);
00314   }
00315 
00316   /// Copy the range [I, E) onto the uninitialized memory
00317   /// starting with "Dest", constructing elements into it as needed.
00318   template <typename T1, typename T2>
00319   static void uninitialized_copy(
00320       T1 *I, T1 *E, T2 *Dest,
00321       typename std::enable_if<std::is_same<typename std::remove_const<T1>::type,
00322                                            T2>::value>::type * = nullptr) {
00323     // Use memcpy for PODs iterated by pointers (which includes SmallVector
00324     // iterators): std::uninitialized_copy optimizes to memmove, but we can
00325     // use memcpy here. Note that I and E are iterators and thus might be
00326     // invalid for memcpy if they are equal.
00327     if (I != E)
00328       memcpy(Dest, I, (E - I) * sizeof(T));
00329   }
00330 
00331   /// Double the size of the allocated memory, guaranteeing space for at
00332   /// least one more element or MinSize if specified.
00333   void grow(size_t MinSize = 0) {
00334     this->grow_pod(MinSize*sizeof(T), sizeof(T));
00335   }
00336 public:
00337   void push_back(const T &Elt) {
00338     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
00339       this->grow();
00340     memcpy(this->end(), &Elt, sizeof(T));
00341     this->setEnd(this->end()+1);
00342   }
00343 
00344   void pop_back() {
00345     this->setEnd(this->end()-1);
00346   }
00347 };
00348 
00349 
00350 /// This class consists of common code factored out of the SmallVector class to
00351 /// reduce code duplication based on the SmallVector 'N' template parameter.
00352 template <typename T>
00353 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
00354   typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
00355 
00356   SmallVectorImpl(const SmallVectorImpl&) = delete;
00357 public:
00358   typedef typename SuperClass::iterator iterator;
00359   typedef typename SuperClass::size_type size_type;
00360 
00361 protected:
00362   // Default ctor - Initialize to empty.
00363   explicit SmallVectorImpl(unsigned N)
00364     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
00365   }
00366 
00367 public:
00368   ~SmallVectorImpl() {
00369     // Destroy the constructed elements in the vector.
00370     this->destroy_range(this->begin(), this->end());
00371 
00372     // If this wasn't grown from the inline copy, deallocate the old space.
00373     if (!this->isSmall())
00374       free(this->begin());
00375   }
00376 
00377 
00378   void clear() {
00379     this->destroy_range(this->begin(), this->end());
00380     this->EndX = this->BeginX;
00381   }
00382 
00383   void resize(size_type N) {
00384     if (N < this->size()) {
00385       this->destroy_range(this->begin()+N, this->end());
00386       this->setEnd(this->begin()+N);
00387     } else if (N > this->size()) {
00388       if (this->capacity() < N)
00389         this->grow(N);
00390       for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
00391         new (&*I) T();
00392       this->setEnd(this->begin()+N);
00393     }
00394   }
00395 
00396   void resize(size_type N, const T &NV) {
00397     if (N < this->size()) {
00398       this->destroy_range(this->begin()+N, this->end());
00399       this->setEnd(this->begin()+N);
00400     } else if (N > this->size()) {
00401       if (this->capacity() < N)
00402         this->grow(N);
00403       std::uninitialized_fill(this->end(), this->begin()+N, NV);
00404       this->setEnd(this->begin()+N);
00405     }
00406   }
00407 
00408   void reserve(size_type N) {
00409     if (this->capacity() < N)
00410       this->grow(N);
00411   }
00412 
00413   T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() {
00414     T Result = ::std::move(this->back());
00415     this->pop_back();
00416     return Result;
00417   }
00418 
00419   void swap(SmallVectorImpl &RHS);
00420 
00421   /// Add the specified range to the end of the SmallVector.
00422   template<typename in_iter>
00423   void append(in_iter in_start, in_iter in_end) {
00424     size_type NumInputs = std::distance(in_start, in_end);
00425     // Grow allocated space if needed.
00426     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
00427       this->grow(this->size()+NumInputs);
00428 
00429     // Copy the new elements over.
00430     this->uninitialized_copy(in_start, in_end, this->end());
00431     this->setEnd(this->end() + NumInputs);
00432   }
00433 
00434   /// Add the specified range to the end of the SmallVector.
00435   void append(size_type NumInputs, const T &Elt) {
00436     // Grow allocated space if needed.
00437     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
00438       this->grow(this->size()+NumInputs);
00439 
00440     // Copy the new elements over.
00441     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
00442     this->setEnd(this->end() + NumInputs);
00443   }
00444 
00445   void append(std::initializer_list<T> IL) {
00446     append(IL.begin(), IL.end());
00447   }
00448 
00449   void assign(size_type NumElts, const T &Elt) {
00450     clear();
00451     if (this->capacity() < NumElts)
00452       this->grow(NumElts);
00453     this->setEnd(this->begin()+NumElts);
00454     std::uninitialized_fill(this->begin(), this->end(), Elt);
00455   }
00456 
00457   void assign(std::initializer_list<T> IL) {
00458     clear();
00459     append(IL);
00460   }
00461 
00462   iterator erase(iterator I) {
00463     assert(I >= this->begin() && "Iterator to erase is out of bounds.");
00464     assert(I < this->end() && "Erasing at past-the-end iterator.");
00465 
00466     iterator N = I;
00467     // Shift all elts down one.
00468     this->move(I+1, this->end(), I);
00469     // Drop the last elt.
00470     this->pop_back();
00471     return(N);
00472   }
00473 
00474   iterator erase(iterator S, iterator E) {
00475     assert(S >= this->begin() && "Range to erase is out of bounds.");
00476     assert(S <= E && "Trying to erase invalid range.");
00477     assert(E <= this->end() && "Trying to erase past the end.");
00478 
00479     iterator N = S;
00480     // Shift all elts down.
00481     iterator I = this->move(E, this->end(), S);
00482     // Drop the last elts.
00483     this->destroy_range(I, this->end());
00484     this->setEnd(I);
00485     return(N);
00486   }
00487 
00488   iterator insert(iterator I, T &&Elt) {
00489     if (I == this->end()) {  // Important special case for empty vector.
00490       this->push_back(::std::move(Elt));
00491       return this->end()-1;
00492     }
00493 
00494     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
00495     assert(I <= this->end() && "Inserting past the end of the vector.");
00496 
00497     if (this->EndX >= this->CapacityX) {
00498       size_t EltNo = I-this->begin();
00499       this->grow();
00500       I = this->begin()+EltNo;
00501     }
00502 
00503     ::new ((void*) this->end()) T(::std::move(this->back()));
00504     // Push everything else over.
00505     this->move_backward(I, this->end()-1, this->end());
00506     this->setEnd(this->end()+1);
00507 
00508     // If we just moved the element we're inserting, be sure to update
00509     // the reference.
00510     T *EltPtr = &Elt;
00511     if (I <= EltPtr && EltPtr < this->EndX)
00512       ++EltPtr;
00513 
00514     *I = ::std::move(*EltPtr);
00515     return I;
00516   }
00517 
00518   iterator insert(iterator I, const T &Elt) {
00519     if (I == this->end()) {  // Important special case for empty vector.
00520       this->push_back(Elt);
00521       return this->end()-1;
00522     }
00523 
00524     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
00525     assert(I <= this->end() && "Inserting past the end of the vector.");
00526 
00527     if (this->EndX >= this->CapacityX) {
00528       size_t EltNo = I-this->begin();
00529       this->grow();
00530       I = this->begin()+EltNo;
00531     }
00532     ::new ((void*) this->end()) T(std::move(this->back()));
00533     // Push everything else over.
00534     this->move_backward(I, this->end()-1, this->end());
00535     this->setEnd(this->end()+1);
00536 
00537     // If we just moved the element we're inserting, be sure to update
00538     // the reference.
00539     const T *EltPtr = &Elt;
00540     if (I <= EltPtr && EltPtr < this->EndX)
00541       ++EltPtr;
00542 
00543     *I = *EltPtr;
00544     return I;
00545   }
00546 
00547   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
00548     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
00549     size_t InsertElt = I - this->begin();
00550 
00551     if (I == this->end()) {  // Important special case for empty vector.
00552       append(NumToInsert, Elt);
00553       return this->begin()+InsertElt;
00554     }
00555 
00556     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
00557     assert(I <= this->end() && "Inserting past the end of the vector.");
00558 
00559     // Ensure there is enough space.
00560     reserve(this->size() + NumToInsert);
00561 
00562     // Uninvalidate the iterator.
00563     I = this->begin()+InsertElt;
00564 
00565     // If there are more elements between the insertion point and the end of the
00566     // range than there are being inserted, we can use a simple approach to
00567     // insertion.  Since we already reserved space, we know that this won't
00568     // reallocate the vector.
00569     if (size_t(this->end()-I) >= NumToInsert) {
00570       T *OldEnd = this->end();
00571       append(std::move_iterator<iterator>(this->end() - NumToInsert),
00572              std::move_iterator<iterator>(this->end()));
00573 
00574       // Copy the existing elements that get replaced.
00575       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
00576 
00577       std::fill_n(I, NumToInsert, Elt);
00578       return I;
00579     }
00580 
00581     // Otherwise, we're inserting more elements than exist already, and we're
00582     // not inserting at the end.
00583 
00584     // Move over the elements that we're about to overwrite.
00585     T *OldEnd = this->end();
00586     this->setEnd(this->end() + NumToInsert);
00587     size_t NumOverwritten = OldEnd-I;
00588     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
00589 
00590     // Replace the overwritten part.
00591     std::fill_n(I, NumOverwritten, Elt);
00592 
00593     // Insert the non-overwritten middle part.
00594     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
00595     return I;
00596   }
00597 
00598   template<typename ItTy>
00599   iterator insert(iterator I, ItTy From, ItTy To) {
00600     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
00601     size_t InsertElt = I - this->begin();
00602 
00603     if (I == this->end()) {  // Important special case for empty vector.
00604       append(From, To);
00605       return this->begin()+InsertElt;
00606     }
00607 
00608     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
00609     assert(I <= this->end() && "Inserting past the end of the vector.");
00610 
00611     size_t NumToInsert = std::distance(From, To);
00612 
00613     // Ensure there is enough space.
00614     reserve(this->size() + NumToInsert);
00615 
00616     // Uninvalidate the iterator.
00617     I = this->begin()+InsertElt;
00618 
00619     // If there are more elements between the insertion point and the end of the
00620     // range than there are being inserted, we can use a simple approach to
00621     // insertion.  Since we already reserved space, we know that this won't
00622     // reallocate the vector.
00623     if (size_t(this->end()-I) >= NumToInsert) {
00624       T *OldEnd = this->end();
00625       append(std::move_iterator<iterator>(this->end() - NumToInsert),
00626              std::move_iterator<iterator>(this->end()));
00627 
00628       // Copy the existing elements that get replaced.
00629       this->move_backward(I, OldEnd-NumToInsert, OldEnd);
00630 
00631       std::copy(From, To, I);
00632       return I;
00633     }
00634 
00635     // Otherwise, we're inserting more elements than exist already, and we're
00636     // not inserting at the end.
00637 
00638     // Move over the elements that we're about to overwrite.
00639     T *OldEnd = this->end();
00640     this->setEnd(this->end() + NumToInsert);
00641     size_t NumOverwritten = OldEnd-I;
00642     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
00643 
00644     // Replace the overwritten part.
00645     for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
00646       *J = *From;
00647       ++J; ++From;
00648     }
00649 
00650     // Insert the non-overwritten middle part.
00651     this->uninitialized_copy(From, To, OldEnd);
00652     return I;
00653   }
00654 
00655   void insert(iterator I, std::initializer_list<T> IL) {
00656     insert(I, IL.begin(), IL.end());
00657   }
00658 
00659   template <typename... ArgTypes> void emplace_back(ArgTypes &&... Args) {
00660     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
00661       this->grow();
00662     ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
00663     this->setEnd(this->end() + 1);
00664   }
00665 
00666   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
00667 
00668   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
00669 
00670   bool operator==(const SmallVectorImpl &RHS) const {
00671     if (this->size() != RHS.size()) return false;
00672     return std::equal(this->begin(), this->end(), RHS.begin());
00673   }
00674   bool operator!=(const SmallVectorImpl &RHS) const {
00675     return !(*this == RHS);
00676   }
00677 
00678   bool operator<(const SmallVectorImpl &RHS) const {
00679     return std::lexicographical_compare(this->begin(), this->end(),
00680                                         RHS.begin(), RHS.end());
00681   }
00682 
00683   /// Set the array size to \p N, which the current array must have enough
00684   /// capacity for.
00685   ///
00686   /// This does not construct or destroy any elements in the vector.
00687   ///
00688   /// Clients can use this in conjunction with capacity() to write past the end
00689   /// of the buffer when they know that more elements are available, and only
00690   /// update the size later. This avoids the cost of value initializing elements
00691   /// which will only be overwritten.
00692   void set_size(size_type N) {
00693     assert(N <= this->capacity());
00694     this->setEnd(this->begin() + N);
00695   }
00696 };
00697 
00698 
00699 template <typename T>
00700 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
00701   if (this == &RHS) return;
00702 
00703   // We can only avoid copying elements if neither vector is small.
00704   if (!this->isSmall() && !RHS.isSmall()) {
00705     std::swap(this->BeginX, RHS.BeginX);
00706     std::swap(this->EndX, RHS.EndX);
00707     std::swap(this->CapacityX, RHS.CapacityX);
00708     return;
00709   }
00710   if (RHS.size() > this->capacity())
00711     this->grow(RHS.size());
00712   if (this->size() > RHS.capacity())
00713     RHS.grow(this->size());
00714 
00715   // Swap the shared elements.
00716   size_t NumShared = this->size();
00717   if (NumShared > RHS.size()) NumShared = RHS.size();
00718   for (size_type i = 0; i != NumShared; ++i)
00719     std::swap((*this)[i], RHS[i]);
00720 
00721   // Copy over the extra elts.
00722   if (this->size() > RHS.size()) {
00723     size_t EltDiff = this->size() - RHS.size();
00724     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
00725     RHS.setEnd(RHS.end()+EltDiff);
00726     this->destroy_range(this->begin()+NumShared, this->end());
00727     this->setEnd(this->begin()+NumShared);
00728   } else if (RHS.size() > this->size()) {
00729     size_t EltDiff = RHS.size() - this->size();
00730     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
00731     this->setEnd(this->end() + EltDiff);
00732     this->destroy_range(RHS.begin()+NumShared, RHS.end());
00733     RHS.setEnd(RHS.begin()+NumShared);
00734   }
00735 }
00736 
00737 template <typename T>
00738 SmallVectorImpl<T> &SmallVectorImpl<T>::
00739   operator=(const SmallVectorImpl<T> &RHS) {
00740   // Avoid self-assignment.
00741   if (this == &RHS) return *this;
00742 
00743   // If we already have sufficient space, assign the common elements, then
00744   // destroy any excess.
00745   size_t RHSSize = RHS.size();
00746   size_t CurSize = this->size();
00747   if (CurSize >= RHSSize) {
00748     // Assign common elements.
00749     iterator NewEnd;
00750     if (RHSSize)
00751       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
00752     else
00753       NewEnd = this->begin();
00754 
00755     // Destroy excess elements.
00756     this->destroy_range(NewEnd, this->end());
00757 
00758     // Trim.
00759     this->setEnd(NewEnd);
00760     return *this;
00761   }
00762 
00763   // If we have to grow to have enough elements, destroy the current elements.
00764   // This allows us to avoid copying them during the grow.
00765   // FIXME: don't do this if they're efficiently moveable.
00766   if (this->capacity() < RHSSize) {
00767     // Destroy current elements.
00768     this->destroy_range(this->begin(), this->end());
00769     this->setEnd(this->begin());
00770     CurSize = 0;
00771     this->grow(RHSSize);
00772   } else if (CurSize) {
00773     // Otherwise, use assignment for the already-constructed elements.
00774     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
00775   }
00776 
00777   // Copy construct the new elements in place.
00778   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
00779                            this->begin()+CurSize);
00780 
00781   // Set end.
00782   this->setEnd(this->begin()+RHSSize);
00783   return *this;
00784 }
00785 
00786 template <typename T>
00787 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
00788   // Avoid self-assignment.
00789   if (this == &RHS) return *this;
00790 
00791   // If the RHS isn't small, clear this vector and then steal its buffer.
00792   if (!RHS.isSmall()) {
00793     this->destroy_range(this->begin(), this->end());
00794     if (!this->isSmall()) free(this->begin());
00795     this->BeginX = RHS.BeginX;
00796     this->EndX = RHS.EndX;
00797     this->CapacityX = RHS.CapacityX;
00798     RHS.resetToSmall();
00799     return *this;
00800   }
00801 
00802   // If we already have sufficient space, assign the common elements, then
00803   // destroy any excess.
00804   size_t RHSSize = RHS.size();
00805   size_t CurSize = this->size();
00806   if (CurSize >= RHSSize) {
00807     // Assign common elements.
00808     iterator NewEnd = this->begin();
00809     if (RHSSize)
00810       NewEnd = this->move(RHS.begin(), RHS.end(), NewEnd);
00811 
00812     // Destroy excess elements and trim the bounds.
00813     this->destroy_range(NewEnd, this->end());
00814     this->setEnd(NewEnd);
00815 
00816     // Clear the RHS.
00817     RHS.clear();
00818 
00819     return *this;
00820   }
00821 
00822   // If we have to grow to have enough elements, destroy the current elements.
00823   // This allows us to avoid copying them during the grow.
00824   // FIXME: this may not actually make any sense if we can efficiently move
00825   // elements.
00826   if (this->capacity() < RHSSize) {
00827     // Destroy current elements.
00828     this->destroy_range(this->begin(), this->end());
00829     this->setEnd(this->begin());
00830     CurSize = 0;
00831     this->grow(RHSSize);
00832   } else if (CurSize) {
00833     // Otherwise, use assignment for the already-constructed elements.
00834     this->move(RHS.begin(), RHS.begin()+CurSize, this->begin());
00835   }
00836 
00837   // Move-construct the new elements in place.
00838   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
00839                            this->begin()+CurSize);
00840 
00841   // Set end.
00842   this->setEnd(this->begin()+RHSSize);
00843 
00844   RHS.clear();
00845   return *this;
00846 }
00847 
00848 /// Storage for the SmallVector elements which aren't contained in
00849 /// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1'
00850 /// element is in the base class. This is specialized for the N=1 and N=0 cases
00851 /// to avoid allocating unnecessary storage.
00852 template <typename T, unsigned N>
00853 struct SmallVectorStorage {
00854   typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1];
00855 };
00856 template <typename T> struct SmallVectorStorage<T, 1> {};
00857 template <typename T> struct SmallVectorStorage<T, 0> {};
00858 
00859 /// This is a 'vector' (really, a variable-sized array), optimized
00860 /// for the case when the array is small.  It contains some number of elements
00861 /// in-place, which allows it to avoid heap allocation when the actual number of
00862 /// elements is below that threshold.  This allows normal "small" cases to be
00863 /// fast without losing generality for large inputs.
00864 ///
00865 /// Note that this does not attempt to be exception safe.
00866 ///
00867 template <typename T, unsigned N>
00868 class SmallVector : public SmallVectorImpl<T> {
00869   /// Inline space for elements which aren't stored in the base class.
00870   SmallVectorStorage<T, N> Storage;
00871 public:
00872   SmallVector() : SmallVectorImpl<T>(N) {
00873   }
00874 
00875   explicit SmallVector(size_t Size, const T &Value = T())
00876     : SmallVectorImpl<T>(N) {
00877     this->assign(Size, Value);
00878   }
00879 
00880   template<typename ItTy>
00881   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
00882     this->append(S, E);
00883   }
00884 
00885   template <typename RangeTy>
00886   explicit SmallVector(const llvm::iterator_range<RangeTy> R)
00887       : SmallVectorImpl<T>(N) {
00888     this->append(R.begin(), R.end());
00889   }
00890 
00891   SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
00892     this->assign(IL);
00893   }
00894 
00895   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
00896     if (!RHS.empty())
00897       SmallVectorImpl<T>::operator=(RHS);
00898   }
00899 
00900   const SmallVector &operator=(const SmallVector &RHS) {
00901     SmallVectorImpl<T>::operator=(RHS);
00902     return *this;
00903   }
00904 
00905   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
00906     if (!RHS.empty())
00907       SmallVectorImpl<T>::operator=(::std::move(RHS));
00908   }
00909 
00910   const SmallVector &operator=(SmallVector &&RHS) {
00911     SmallVectorImpl<T>::operator=(::std::move(RHS));
00912     return *this;
00913   }
00914 
00915   SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
00916     if (!RHS.empty())
00917       SmallVectorImpl<T>::operator=(::std::move(RHS));
00918   }
00919 
00920   const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
00921     SmallVectorImpl<T>::operator=(::std::move(RHS));
00922     return *this;
00923   }
00924 
00925   const SmallVector &operator=(std::initializer_list<T> IL) {
00926     this->assign(IL);
00927     return *this;
00928   }
00929 };
00930 
00931 template<typename T, unsigned N>
00932 static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
00933   return X.capacity_in_bytes();
00934 }
00935 
00936 } // End llvm namespace
00937 
00938 namespace std {
00939   /// Implement std::swap in terms of SmallVector swap.
00940   template<typename T>
00941   inline void
00942   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
00943     LHS.swap(RHS);
00944   }
00945 
00946   /// Implement std::swap in terms of SmallVector swap.
00947   template<typename T, unsigned N>
00948   inline void
00949   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
00950     LHS.swap(RHS);
00951   }
00952 }
00953 
00954 #endif