LLVM API Documentation

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