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 <cstddef>
21 #include <cstdlib>
22 #include <cstring>
23 #include <memory>
24 
25 #ifdef _MSC_VER
26 namespace std {
27 #if _MSC_VER <= 1310
28   // Work around flawed VC++ implementation of std::uninitialized_copy.  Define
29   // additional overloads so that elements with pointer types are recognized as
30   // scalars and not objects, causing bizarre type conversion errors.
31   template<class T1, class T2>
_Ptr_cat(T1 **,T2 **)32   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
33     _Scalar_ptr_iterator_tag _Cat;
34     return _Cat;
35   }
36 
37   template<class T1, class T2>
_Ptr_cat(T1 * const *,T2 **)38   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
39     _Scalar_ptr_iterator_tag _Cat;
40     return _Cat;
41   }
42 #else
43 // FIXME: It is not clear if the problem is fixed in VS 2005.  What is clear
44 // is that the above hack won't work if it wasn't fixed.
45 #endif
46 }
47 #endif
48 
49 namespace llvm {
50 
51 /// SmallVectorBase - This is all the non-templated stuff common to all
52 /// SmallVectors.
53 class SmallVectorBase {
54 protected:
55   void *BeginX, *EndX, *CapacityX;
56 
57   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
58   // don't want it to be automatically run, so we need to represent the space as
59   // something else.  An array of char would work great, but might not be
60   // aligned sufficiently.  Instead, we either use GCC extensions, or some
61   // number of union instances for the space, which guarantee maximal alignment.
62 #ifdef __GNUC__
63   typedef char U;
64   U FirstEl __attribute__((aligned(8)));
65 #else
66   union U {
67     double D;
68     long double LD;
69     long long L;
70     void *P;
71   } FirstEl;
72 #endif
73   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
74 
75 protected:
SmallVectorBase(size_t Size)76   SmallVectorBase(size_t Size)
77     : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
78 
79   /// isSmall - Return true if this is a smallvector which has not had dynamic
80   /// memory allocated for it.
isSmall()81   bool isSmall() const {
82     return BeginX == static_cast<const void*>(&FirstEl);
83   }
84 
85   /// size_in_bytes - This returns size()*sizeof(T).
size_in_bytes()86   size_t size_in_bytes() const {
87     return size_t((char*)EndX - (char*)BeginX);
88   }
89 
90   /// capacity_in_bytes - This returns capacity()*sizeof(T).
capacity_in_bytes()91   size_t capacity_in_bytes() const {
92     return size_t((char*)CapacityX - (char*)BeginX);
93   }
94 
95   /// grow_pod - This is an implementation of the grow() method which only works
96   /// on POD-like datatypes and is out of line to reduce code duplication.
97   void grow_pod(size_t MinSizeInBytes, size_t TSize);
98 
99 public:
empty()100   bool empty() const { return BeginX == EndX; }
101 };
102 
103 
104 template <typename T>
105 class SmallVectorTemplateCommon : public SmallVectorBase {
106 protected:
setEnd(T * P)107   void setEnd(T *P) { this->EndX = P; }
108 public:
SmallVectorTemplateCommon(size_t Size)109   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
110 
111   typedef size_t size_type;
112   typedef ptrdiff_t difference_type;
113   typedef T value_type;
114   typedef T *iterator;
115   typedef const T *const_iterator;
116 
117   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
118   typedef std::reverse_iterator<iterator> reverse_iterator;
119 
120   typedef T &reference;
121   typedef const T &const_reference;
122   typedef T *pointer;
123   typedef const T *const_pointer;
124 
125   // forward iterator creation methods.
begin()126   iterator begin() { return (iterator)this->BeginX; }
begin()127   const_iterator begin() const { return (const_iterator)this->BeginX; }
end()128   iterator end() { return (iterator)this->EndX; }
end()129   const_iterator end() const { return (const_iterator)this->EndX; }
130 protected:
capacity_ptr()131   iterator capacity_ptr() { return (iterator)this->CapacityX; }
capacity_ptr()132   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
133 public:
134 
135   // reverse iterator creation methods.
rbegin()136   reverse_iterator rbegin()            { return reverse_iterator(end()); }
rbegin()137   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
rend()138   reverse_iterator rend()              { return reverse_iterator(begin()); }
rend()139   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
140 
size()141   size_type size() const { return end()-begin(); }
max_size()142   size_type max_size() const { return size_type(-1) / sizeof(T); }
143 
144   /// capacity - Return the total number of elements in the currently allocated
145   /// buffer.
capacity()146   size_t capacity() const { return capacity_ptr() - begin(); }
147 
148   /// data - Return a pointer to the vector's buffer, even if empty().
data()149   pointer data() { return pointer(begin()); }
150   /// data - Return a pointer to the vector's buffer, even if empty().
data()151   const_pointer data() const { return const_pointer(begin()); }
152 
153   reference operator[](unsigned idx) {
154     assert(begin() + idx < end());
155     return begin()[idx];
156   }
157   const_reference operator[](unsigned idx) const {
158     assert(begin() + idx < end());
159     return begin()[idx];
160   }
161 
front()162   reference front() {
163     return begin()[0];
164   }
front()165   const_reference front() const {
166     return begin()[0];
167   }
168 
back()169   reference back() {
170     return end()[-1];
171   }
back()172   const_reference back() const {
173     return end()[-1];
174   }
175 };
176 
177 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
178 /// implementations that are designed to work with non-POD-like T's.
179 template <typename T, bool isPodLike>
180 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
181 public:
SmallVectorTemplateBase(size_t Size)182   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
183 
destroy_range(T * S,T * E)184   static void destroy_range(T *S, T *E) {
185     while (S != E) {
186       --E;
187       E->~T();
188     }
189   }
190 
191   /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
192   /// starting with "Dest", constructing elements into it as needed.
193   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)194   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
195     std::uninitialized_copy(I, E, Dest);
196   }
197 
198   /// grow - double the size of the allocated memory, guaranteeing space for at
199   /// least one more element or MinSize if specified.
200   void grow(size_t MinSize = 0);
201 };
202 
203 // Define this out-of-line to dissuade the C++ compiler from inlining it.
204 template <typename T, bool isPodLike>
grow(size_t MinSize)205 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
206   size_t CurCapacity = this->capacity();
207   size_t CurSize = this->size();
208   size_t NewCapacity = 2*CurCapacity + 1; // Always grow, even from zero.
209   if (NewCapacity < MinSize)
210     NewCapacity = MinSize;
211   T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
212 
213   // Copy the elements over.
214   this->uninitialized_copy(this->begin(), this->end(), NewElts);
215 
216   // Destroy the original elements.
217   destroy_range(this->begin(), this->end());
218 
219   // If this wasn't grown from the inline copy, deallocate the old space.
220   if (!this->isSmall())
221     free(this->begin());
222 
223   this->setEnd(NewElts+CurSize);
224   this->BeginX = NewElts;
225   this->CapacityX = this->begin()+NewCapacity;
226 }
227 
228 
229 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
230 /// implementations that are designed to work with POD-like T's.
231 template <typename T>
232 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
233 public:
SmallVectorTemplateBase(size_t Size)234   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
235 
236   // No need to do a destroy loop for POD's.
destroy_range(T *,T *)237   static void destroy_range(T *, T *) {}
238 
239   /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
240   /// starting with "Dest", constructing elements into it as needed.
241   template<typename It1, typename It2>
uninitialized_copy(It1 I,It1 E,It2 Dest)242   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
243     // Arbitrary iterator types; just use the basic implementation.
244     std::uninitialized_copy(I, E, Dest);
245   }
246 
247   /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
248   /// starting with "Dest", constructing elements into it as needed.
249   template<typename T1, typename T2>
uninitialized_copy(T1 * I,T1 * E,T2 * Dest)250   static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) {
251     // Use memcpy for PODs iterated by pointers (which includes SmallVector
252     // iterators): std::uninitialized_copy optimizes to memmove, but we can
253     // use memcpy here.
254     memcpy(Dest, I, (E-I)*sizeof(T));
255   }
256 
257   /// grow - double the size of the allocated memory, guaranteeing space for at
258   /// least one more element or MinSize if specified.
259   void grow(size_t MinSize = 0) {
260     this->grow_pod(MinSize*sizeof(T), sizeof(T));
261   }
262 };
263 
264 
265 /// SmallVectorImpl - This class consists of common code factored out of the
266 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
267 /// template parameter.
268 template <typename T>
269 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
270   typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
271 
272   SmallVectorImpl(const SmallVectorImpl&); // DISABLED.
273 public:
274   typedef typename SuperClass::iterator iterator;
275   typedef typename SuperClass::size_type size_type;
276 
277   // Default ctor - Initialize to empty.
SmallVectorImpl(unsigned N)278   explicit SmallVectorImpl(unsigned N)
279     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
280   }
281 
~SmallVectorImpl()282   ~SmallVectorImpl() {
283     // Destroy the constructed elements in the vector.
284     this->destroy_range(this->begin(), this->end());
285 
286     // If this wasn't grown from the inline copy, deallocate the old space.
287     if (!this->isSmall())
288       free(this->begin());
289   }
290 
291 
clear()292   void clear() {
293     this->destroy_range(this->begin(), this->end());
294     this->EndX = this->BeginX;
295   }
296 
resize(unsigned N)297   void resize(unsigned N) {
298     if (N < this->size()) {
299       this->destroy_range(this->begin()+N, this->end());
300       this->setEnd(this->begin()+N);
301     } else if (N > this->size()) {
302       if (this->capacity() < N)
303         this->grow(N);
304       this->construct_range(this->end(), this->begin()+N, T());
305       this->setEnd(this->begin()+N);
306     }
307   }
308 
resize(unsigned N,const T & NV)309   void resize(unsigned N, const T &NV) {
310     if (N < this->size()) {
311       this->destroy_range(this->begin()+N, this->end());
312       this->setEnd(this->begin()+N);
313     } else if (N > this->size()) {
314       if (this->capacity() < N)
315         this->grow(N);
316       construct_range(this->end(), this->begin()+N, NV);
317       this->setEnd(this->begin()+N);
318     }
319   }
320 
reserve(unsigned N)321   void reserve(unsigned N) {
322     if (this->capacity() < N)
323       this->grow(N);
324   }
325 
push_back(const T & Elt)326   void push_back(const T &Elt) {
327     if (this->EndX < this->CapacityX) {
328     Retry:
329       new (this->end()) T(Elt);
330       this->setEnd(this->end()+1);
331       return;
332     }
333     this->grow();
334     goto Retry;
335   }
336 
pop_back()337   void pop_back() {
338     this->setEnd(this->end()-1);
339     this->end()->~T();
340   }
341 
pop_back_val()342   T pop_back_val() {
343     T Result = this->back();
344     pop_back();
345     return Result;
346   }
347 
348 
349   void swap(SmallVectorImpl &RHS);
350 
351   /// append - Add the specified range to the end of the SmallVector.
352   ///
353   template<typename in_iter>
append(in_iter in_start,in_iter in_end)354   void append(in_iter in_start, in_iter in_end) {
355     size_type NumInputs = std::distance(in_start, in_end);
356     // Grow allocated space if needed.
357     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
358       this->grow(this->size()+NumInputs);
359 
360     // Copy the new elements over.
361     // TODO: NEED To compile time dispatch on whether in_iter is a random access
362     // iterator to use the fast uninitialized_copy.
363     std::uninitialized_copy(in_start, in_end, this->end());
364     this->setEnd(this->end() + NumInputs);
365   }
366 
367   /// append - Add the specified range to the end of the SmallVector.
368   ///
append(size_type NumInputs,const T & Elt)369   void append(size_type NumInputs, const T &Elt) {
370     // Grow allocated space if needed.
371     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
372       this->grow(this->size()+NumInputs);
373 
374     // Copy the new elements over.
375     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
376     this->setEnd(this->end() + NumInputs);
377   }
378 
assign(unsigned NumElts,const T & Elt)379   void assign(unsigned NumElts, const T &Elt) {
380     clear();
381     if (this->capacity() < NumElts)
382       this->grow(NumElts);
383     this->setEnd(this->begin()+NumElts);
384     construct_range(this->begin(), this->end(), Elt);
385   }
386 
erase(iterator I)387   iterator erase(iterator I) {
388     iterator N = I;
389     // Shift all elts down one.
390     std::copy(I+1, this->end(), I);
391     // Drop the last elt.
392     pop_back();
393     return(N);
394   }
395 
erase(iterator S,iterator E)396   iterator erase(iterator S, iterator E) {
397     iterator N = S;
398     // Shift all elts down.
399     iterator I = std::copy(E, this->end(), S);
400     // Drop the last elts.
401     this->destroy_range(I, this->end());
402     this->setEnd(I);
403     return(N);
404   }
405 
insert(iterator I,const T & Elt)406   iterator insert(iterator I, const T &Elt) {
407     if (I == this->end()) {  // Important special case for empty vector.
408       push_back(Elt);
409       return this->end()-1;
410     }
411 
412     if (this->EndX < this->CapacityX) {
413     Retry:
414       new (this->end()) T(this->back());
415       this->setEnd(this->end()+1);
416       // Push everything else over.
417       std::copy_backward(I, this->end()-1, this->end());
418       *I = Elt;
419       return I;
420     }
421     size_t EltNo = I-this->begin();
422     this->grow();
423     I = this->begin()+EltNo;
424     goto Retry;
425   }
426 
insert(iterator I,size_type NumToInsert,const T & Elt)427   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
428     if (I == this->end()) {  // Important special case for empty vector.
429       append(NumToInsert, Elt);
430       return this->end()-1;
431     }
432 
433     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
434     size_t InsertElt = I - this->begin();
435 
436     // Ensure there is enough space.
437     reserve(static_cast<unsigned>(this->size() + NumToInsert));
438 
439     // Uninvalidate the iterator.
440     I = this->begin()+InsertElt;
441 
442     // If there are more elements between the insertion point and the end of the
443     // range than there are being inserted, we can use a simple approach to
444     // insertion.  Since we already reserved space, we know that this won't
445     // reallocate the vector.
446     if (size_t(this->end()-I) >= NumToInsert) {
447       T *OldEnd = this->end();
448       append(this->end()-NumToInsert, this->end());
449 
450       // Copy the existing elements that get replaced.
451       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
452 
453       std::fill_n(I, NumToInsert, Elt);
454       return I;
455     }
456 
457     // Otherwise, we're inserting more elements than exist already, and we're
458     // not inserting at the end.
459 
460     // Copy over the elements that we're about to overwrite.
461     T *OldEnd = this->end();
462     this->setEnd(this->end() + NumToInsert);
463     size_t NumOverwritten = OldEnd-I;
464     this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
465 
466     // Replace the overwritten part.
467     std::fill_n(I, NumOverwritten, Elt);
468 
469     // Insert the non-overwritten middle part.
470     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
471     return I;
472   }
473 
474   template<typename ItTy>
insert(iterator I,ItTy From,ItTy To)475   iterator insert(iterator I, ItTy From, ItTy To) {
476     if (I == this->end()) {  // Important special case for empty vector.
477       append(From, To);
478       return this->end()-1;
479     }
480 
481     size_t NumToInsert = std::distance(From, To);
482     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
483     size_t InsertElt = I - this->begin();
484 
485     // Ensure there is enough space.
486     reserve(static_cast<unsigned>(this->size() + NumToInsert));
487 
488     // Uninvalidate the iterator.
489     I = this->begin()+InsertElt;
490 
491     // If there are more elements between the insertion point and the end of the
492     // range than there are being inserted, we can use a simple approach to
493     // insertion.  Since we already reserved space, we know that this won't
494     // reallocate the vector.
495     if (size_t(this->end()-I) >= NumToInsert) {
496       T *OldEnd = this->end();
497       append(this->end()-NumToInsert, this->end());
498 
499       // Copy the existing elements that get replaced.
500       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
501 
502       std::copy(From, To, I);
503       return I;
504     }
505 
506     // Otherwise, we're inserting more elements than exist already, and we're
507     // not inserting at the end.
508 
509     // Copy over the elements that we're about to overwrite.
510     T *OldEnd = this->end();
511     this->setEnd(this->end() + NumToInsert);
512     size_t NumOverwritten = OldEnd-I;
513     this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
514 
515     // Replace the overwritten part.
516     for (; NumOverwritten > 0; --NumOverwritten) {
517       *I = *From;
518       ++I; ++From;
519     }
520 
521     // Insert the non-overwritten middle part.
522     this->uninitialized_copy(From, To, OldEnd);
523     return I;
524   }
525 
526   const SmallVectorImpl
527   &operator=(const SmallVectorImpl &RHS);
528 
529   bool operator==(const SmallVectorImpl &RHS) const {
530     if (this->size() != RHS.size()) return false;
531     return std::equal(this->begin(), this->end(), RHS.begin());
532   }
533   bool operator!=(const SmallVectorImpl &RHS) const {
534     return !(*this == RHS);
535   }
536 
537   bool operator<(const SmallVectorImpl &RHS) const {
538     return std::lexicographical_compare(this->begin(), this->end(),
539                                         RHS.begin(), RHS.end());
540   }
541 
542   /// set_size - Set the array size to \arg N, which the current array must have
543   /// enough capacity for.
544   ///
545   /// This does not construct or destroy any elements in the vector.
546   ///
547   /// Clients can use this in conjunction with capacity() to write past the end
548   /// of the buffer when they know that more elements are available, and only
549   /// update the size later. This avoids the cost of value initializing elements
550   /// which will only be overwritten.
set_size(unsigned N)551   void set_size(unsigned N) {
552     assert(N <= this->capacity());
553     this->setEnd(this->begin() + N);
554   }
555 
556 private:
construct_range(T * S,T * E,const T & Elt)557   static void construct_range(T *S, T *E, const T &Elt) {
558     for (; S != E; ++S)
559       new (S) T(Elt);
560   }
561 };
562 
563 
564 template <typename T>
swap(SmallVectorImpl<T> & RHS)565 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
566   if (this == &RHS) return;
567 
568   // We can only avoid copying elements if neither vector is small.
569   if (!this->isSmall() && !RHS.isSmall()) {
570     std::swap(this->BeginX, RHS.BeginX);
571     std::swap(this->EndX, RHS.EndX);
572     std::swap(this->CapacityX, RHS.CapacityX);
573     return;
574   }
575   if (RHS.size() > this->capacity())
576     this->grow(RHS.size());
577   if (this->size() > RHS.capacity())
578     RHS.grow(this->size());
579 
580   // Swap the shared elements.
581   size_t NumShared = this->size();
582   if (NumShared > RHS.size()) NumShared = RHS.size();
583   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
584     std::swap((*this)[i], RHS[i]);
585 
586   // Copy over the extra elts.
587   if (this->size() > RHS.size()) {
588     size_t EltDiff = this->size() - RHS.size();
589     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
590     RHS.setEnd(RHS.end()+EltDiff);
591     this->destroy_range(this->begin()+NumShared, this->end());
592     this->setEnd(this->begin()+NumShared);
593   } else if (RHS.size() > this->size()) {
594     size_t EltDiff = RHS.size() - this->size();
595     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
596     this->setEnd(this->end() + EltDiff);
597     this->destroy_range(RHS.begin()+NumShared, RHS.end());
598     RHS.setEnd(RHS.begin()+NumShared);
599   }
600 }
601 
602 template <typename T>
603 const SmallVectorImpl<T> &SmallVectorImpl<T>::
604   operator=(const SmallVectorImpl<T> &RHS) {
605   // Avoid self-assignment.
606   if (this == &RHS) return *this;
607 
608   // If we already have sufficient space, assign the common elements, then
609   // destroy any excess.
610   size_t RHSSize = RHS.size();
611   size_t CurSize = this->size();
612   if (CurSize >= RHSSize) {
613     // Assign common elements.
614     iterator NewEnd;
615     if (RHSSize)
616       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
617     else
618       NewEnd = this->begin();
619 
620     // Destroy excess elements.
621     this->destroy_range(NewEnd, this->end());
622 
623     // Trim.
624     this->setEnd(NewEnd);
625     return *this;
626   }
627 
628   // If we have to grow to have enough elements, destroy the current elements.
629   // This allows us to avoid copying them during the grow.
630   if (this->capacity() < RHSSize) {
631     // Destroy current elements.
632     this->destroy_range(this->begin(), this->end());
633     this->setEnd(this->begin());
634     CurSize = 0;
635     this->grow(RHSSize);
636   } else if (CurSize) {
637     // Otherwise, use assignment for the already-constructed elements.
638     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
639   }
640 
641   // Copy construct the new elements in place.
642   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
643                            this->begin()+CurSize);
644 
645   // Set end.
646   this->setEnd(this->begin()+RHSSize);
647   return *this;
648 }
649 
650 
651 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
652 /// for the case when the array is small.  It contains some number of elements
653 /// in-place, which allows it to avoid heap allocation when the actual number of
654 /// elements is below that threshold.  This allows normal "small" cases to be
655 /// fast without losing generality for large inputs.
656 ///
657 /// Note that this does not attempt to be exception safe.
658 ///
659 template <typename T, unsigned N>
660 class SmallVector : public SmallVectorImpl<T> {
661   /// InlineElts - These are 'N-1' elements that are stored inline in the body
662   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
663   typedef typename SmallVectorImpl<T>::U U;
664   enum {
665     // MinUs - The number of U's require to cover N T's.
666     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
667              static_cast<unsigned int>(sizeof(U)) - 1) /
668             static_cast<unsigned int>(sizeof(U)),
669 
670     // NumInlineEltsElts - The number of elements actually in this array.  There
671     // is already one in the parent class, and we have to round up to avoid
672     // having a zero-element array.
673     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
674 
675     // NumTsAvailable - The number of T's we actually have space for, which may
676     // be more than N due to rounding.
677     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
678                      static_cast<unsigned int>(sizeof(T))
679   };
680   U InlineElts[NumInlineEltsElts];
681 public:
SmallVector()682   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
683   }
684 
685   explicit SmallVector(unsigned Size, const T &Value = T())
686     : SmallVectorImpl<T>(NumTsAvailable) {
687     this->reserve(Size);
688     while (Size--)
689       this->push_back(Value);
690   }
691 
692   template<typename ItTy>
SmallVector(ItTy S,ItTy E)693   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
694     this->append(S, E);
695   }
696 
SmallVector(const SmallVector & RHS)697   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
698     if (!RHS.empty())
699       SmallVectorImpl<T>::operator=(RHS);
700   }
701 
702   const SmallVector &operator=(const SmallVector &RHS) {
703     SmallVectorImpl<T>::operator=(RHS);
704     return *this;
705   }
706 
707 };
708 
709 /// Specialize SmallVector at N=0.  This specialization guarantees
710 /// that it can be instantiated at an incomplete T if none of its
711 /// members are required.
712 template <typename T>
713 class SmallVector<T,0> : public SmallVectorImpl<T> {
714 public:
SmallVector()715   SmallVector() : SmallVectorImpl<T>(0) {}
716 
717   explicit SmallVector(unsigned Size, const T &Value = T())
718     : SmallVectorImpl<T>(0) {
719     this->reserve(Size);
720     while (Size--)
721       this->push_back(Value);
722   }
723 
724   template<typename ItTy>
SmallVector(ItTy S,ItTy E)725   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(0) {
726     this->append(S, E);
727   }
728 
SmallVector(const SmallVector & RHS)729   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(0) {
730     SmallVectorImpl<T>::operator=(RHS);
731   }
732 
733   SmallVector &operator=(const SmallVectorImpl<T> &RHS) {
734     return SmallVectorImpl<T>::operator=(RHS);
735   }
736 
737 };
738 
739 } // End llvm namespace
740 
741 namespace std {
742   /// Implement std::swap in terms of SmallVector swap.
743   template<typename T>
744   inline void
swap(llvm::SmallVectorImpl<T> & LHS,llvm::SmallVectorImpl<T> & RHS)745   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
746     LHS.swap(RHS);
747   }
748 
749   /// Implement std::swap in terms of SmallVector swap.
750   template<typename T, unsigned N>
751   inline void
swap(llvm::SmallVector<T,N> & LHS,llvm::SmallVector<T,N> & RHS)752   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
753     LHS.swap(RHS);
754   }
755 }
756 
757 #endif
758