]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/ADT/SmallVector.h
Update tcpdump to 4.9.0.
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / ADT / SmallVector.h
1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the SmallVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
16
17 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/type_traits.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstddef>
25 #include <cstdlib>
26 #include <cstring>
27 #include <initializer_list>
28 #include <iterator>
29 #include <memory>
30
31 namespace llvm {
32
33 /// This is all the non-templated stuff common to all SmallVectors.
34 class SmallVectorBase {
35 protected:
36   void *BeginX, *EndX, *CapacityX;
37
38 protected:
39   SmallVectorBase(void *FirstEl, size_t Size)
40     : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {}
41
42   /// This is an implementation of the grow() method which only works
43   /// on POD-like data types and is out of line to reduce code duplication.
44   void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize);
45
46 public:
47   /// This returns size()*sizeof(T).
48   size_t size_in_bytes() const {
49     return size_t((char*)EndX - (char*)BeginX);
50   }
51
52   /// capacity_in_bytes - This returns capacity()*sizeof(T).
53   size_t capacity_in_bytes() const {
54     return size_t((char*)CapacityX - (char*)BeginX);
55   }
56
57   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return BeginX == EndX; }
58 };
59
60 template <typename T, unsigned N> struct SmallVectorStorage;
61
62 /// This is the part of SmallVectorTemplateBase which does not depend on whether
63 /// the type T is a POD. The extra dummy template argument is used by ArrayRef
64 /// to avoid unnecessarily requiring T to be complete.
65 template <typename T, typename = void>
66 class SmallVectorTemplateCommon : public SmallVectorBase {
67 private:
68   template <typename, unsigned> friend struct SmallVectorStorage;
69
70   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
71   // don't want it to be automatically run, so we need to represent the space as
72   // something else.  Use an array of char of sufficient alignment.
73   typedef llvm::AlignedCharArrayUnion<T> U;
74   U FirstEl;
75   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
76
77 protected:
78   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {}
79
80   void grow_pod(size_t MinSizeInBytes, size_t TSize) {
81     SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize);
82   }
83
84   /// Return true if this is a smallvector which has not had dynamic
85   /// memory allocated for it.
86   bool isSmall() const {
87     return BeginX == static_cast<const void*>(&FirstEl);
88   }
89
90   /// Put this vector in a state of being small.
91   void resetToSmall() {
92     BeginX = EndX = CapacityX = &FirstEl;
93   }
94
95   void setEnd(T *P) { this->EndX = P; }
96 public:
97   typedef size_t size_type;
98   typedef ptrdiff_t difference_type;
99   typedef T value_type;
100   typedef T *iterator;
101   typedef const T *const_iterator;
102
103   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
104   typedef std::reverse_iterator<iterator> reverse_iterator;
105
106   typedef T &reference;
107   typedef const T &const_reference;
108   typedef T *pointer;
109   typedef const T *const_pointer;
110
111   // forward iterator creation methods.
112   LLVM_ATTRIBUTE_ALWAYS_INLINE
113   iterator begin() { return (iterator)this->BeginX; }
114   LLVM_ATTRIBUTE_ALWAYS_INLINE
115   const_iterator begin() const { return (const_iterator)this->BeginX; }
116   LLVM_ATTRIBUTE_ALWAYS_INLINE
117   iterator end() { return (iterator)this->EndX; }
118   LLVM_ATTRIBUTE_ALWAYS_INLINE
119   const_iterator end() const { return (const_iterator)this->EndX; }
120 protected:
121   iterator capacity_ptr() { return (iterator)this->CapacityX; }
122   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
123 public:
124
125   // reverse iterator creation methods.
126   reverse_iterator rbegin()            { return reverse_iterator(end()); }
127   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
128   reverse_iterator rend()              { return reverse_iterator(begin()); }
129   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
130
131   LLVM_ATTRIBUTE_ALWAYS_INLINE
132   size_type size() const { return end()-begin(); }
133   size_type max_size() const { return size_type(-1) / sizeof(T); }
134
135   /// Return the total number of elements in the currently allocated buffer.
136   size_t capacity() const { return capacity_ptr() - begin(); }
137
138   /// Return a pointer to the vector's buffer, even if empty().
139   pointer data() { return pointer(begin()); }
140   /// Return a pointer to the vector's buffer, even if empty().
141   const_pointer data() const { return const_pointer(begin()); }
142
143   LLVM_ATTRIBUTE_ALWAYS_INLINE
144   reference operator[](size_type idx) {
145     assert(idx < size());
146     return begin()[idx];
147   }
148   LLVM_ATTRIBUTE_ALWAYS_INLINE
149   const_reference operator[](size_type idx) const {
150     assert(idx < size());
151     return begin()[idx];
152   }
153
154   reference front() {
155     assert(!empty());
156     return begin()[0];
157   }
158   const_reference front() const {
159     assert(!empty());
160     return begin()[0];
161   }
162
163   reference back() {
164     assert(!empty());
165     return end()[-1];
166   }
167   const_reference back() const {
168     assert(!empty());
169     return end()[-1];
170   }
171 };
172
173 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
174 /// implementations that are designed to work with non-POD-like T's.
175 template <typename T, bool isPodLike>
176 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
177 protected:
178   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
179
180   static void destroy_range(T *S, T *E) {
181     while (S != E) {
182       --E;
183       E->~T();
184     }
185   }
186
187   /// Move the range [I, E) into the uninitialized memory starting with "Dest",
188   /// constructing elements as needed.
189   template<typename It1, typename It2>
190   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
191     std::uninitialized_copy(std::make_move_iterator(I),
192                             std::make_move_iterator(E), Dest);
193   }
194
195   /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
196   /// constructing elements as needed.
197   template<typename It1, typename It2>
198   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
199     std::uninitialized_copy(I, E, Dest);
200   }
201
202   /// Grow the allocated memory (without initializing new elements), doubling
203   /// the size of the allocated memory. Guarantees space for at least one more
204   /// element, or MinSize more elements if specified.
205   void grow(size_t MinSize = 0);
206
207 public:
208   void push_back(const T &Elt) {
209     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
210       this->grow();
211     ::new ((void*) this->end()) T(Elt);
212     this->setEnd(this->end()+1);
213   }
214
215   void push_back(T &&Elt) {
216     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
217       this->grow();
218     ::new ((void*) this->end()) T(::std::move(Elt));
219     this->setEnd(this->end()+1);
220   }
221
222   void pop_back() {
223     this->setEnd(this->end()-1);
224     this->end()->~T();
225   }
226 };
227
228 // Define this out-of-line to dissuade the C++ compiler from inlining it.
229 template <typename T, bool isPodLike>
230 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
231   size_t CurCapacity = this->capacity();
232   size_t CurSize = this->size();
233   // Always grow, even from zero.
234   size_t NewCapacity = size_t(NextPowerOf2(CurCapacity+2));
235   if (NewCapacity < MinSize)
236     NewCapacity = MinSize;
237   T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
238
239   // Move the elements over.
240   this->uninitialized_move(this->begin(), this->end(), NewElts);
241
242   // Destroy the original elements.
243   destroy_range(this->begin(), this->end());
244
245   // If this wasn't grown from the inline copy, deallocate the old space.
246   if (!this->isSmall())
247     free(this->begin());
248
249   this->setEnd(NewElts+CurSize);
250   this->BeginX = NewElts;
251   this->CapacityX = this->begin()+NewCapacity;
252 }
253
254
255 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
256 /// implementations that are designed to work with POD-like T's.
257 template <typename T>
258 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
259 protected:
260   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
261
262   // No need to do a destroy loop for POD's.
263   static void destroy_range(T *, T *) {}
264
265   /// Move the range [I, E) onto the uninitialized memory
266   /// starting with "Dest", constructing elements into it as needed.
267   template<typename It1, typename It2>
268   static void uninitialized_move(It1 I, It1 E, It2 Dest) {
269     // Just do a copy.
270     uninitialized_copy(I, E, Dest);
271   }
272
273   /// Copy the range [I, E) onto the uninitialized memory
274   /// starting with "Dest", constructing elements into it as needed.
275   template<typename It1, typename It2>
276   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
277     // Arbitrary iterator types; just use the basic implementation.
278     std::uninitialized_copy(I, E, Dest);
279   }
280
281   /// Copy the range [I, E) onto the uninitialized memory
282   /// starting with "Dest", constructing elements into it as needed.
283   template <typename T1, typename T2>
284   static void uninitialized_copy(
285       T1 *I, T1 *E, T2 *Dest,
286       typename std::enable_if<std::is_same<typename std::remove_const<T1>::type,
287                                            T2>::value>::type * = nullptr) {
288     // Use memcpy for PODs iterated by pointers (which includes SmallVector
289     // iterators): std::uninitialized_copy optimizes to memmove, but we can
290     // use memcpy here. Note that I and E are iterators and thus might be
291     // invalid for memcpy if they are equal.
292     if (I != E)
293       memcpy(Dest, I, (E - I) * sizeof(T));
294   }
295
296   /// Double the size of the allocated memory, guaranteeing space for at
297   /// least one more element or MinSize if specified.
298   void grow(size_t MinSize = 0) {
299     this->grow_pod(MinSize*sizeof(T), sizeof(T));
300   }
301 public:
302   void push_back(const T &Elt) {
303     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
304       this->grow();
305     memcpy(this->end(), &Elt, sizeof(T));
306     this->setEnd(this->end()+1);
307   }
308
309   void pop_back() {
310     this->setEnd(this->end()-1);
311   }
312 };
313
314
315 /// This class consists of common code factored out of the SmallVector class to
316 /// reduce code duplication based on the SmallVector 'N' template parameter.
317 template <typename T>
318 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
319   typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
320
321   SmallVectorImpl(const SmallVectorImpl&) = delete;
322 public:
323   typedef typename SuperClass::iterator iterator;
324   typedef typename SuperClass::const_iterator const_iterator;
325   typedef typename SuperClass::size_type size_type;
326
327 protected:
328   // Default ctor - Initialize to empty.
329   explicit SmallVectorImpl(unsigned N)
330     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
331   }
332
333 public:
334   ~SmallVectorImpl() {
335     // Destroy the constructed elements in the vector.
336     this->destroy_range(this->begin(), this->end());
337
338     // If this wasn't grown from the inline copy, deallocate the old space.
339     if (!this->isSmall())
340       free(this->begin());
341   }
342
343
344   void clear() {
345     this->destroy_range(this->begin(), this->end());
346     this->EndX = this->BeginX;
347   }
348
349   void resize(size_type N) {
350     if (N < this->size()) {
351       this->destroy_range(this->begin()+N, this->end());
352       this->setEnd(this->begin()+N);
353     } else if (N > this->size()) {
354       if (this->capacity() < N)
355         this->grow(N);
356       for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
357         new (&*I) T();
358       this->setEnd(this->begin()+N);
359     }
360   }
361
362   void resize(size_type N, const T &NV) {
363     if (N < this->size()) {
364       this->destroy_range(this->begin()+N, this->end());
365       this->setEnd(this->begin()+N);
366     } else if (N > this->size()) {
367       if (this->capacity() < N)
368         this->grow(N);
369       std::uninitialized_fill(this->end(), this->begin()+N, NV);
370       this->setEnd(this->begin()+N);
371     }
372   }
373
374   void reserve(size_type N) {
375     if (this->capacity() < N)
376       this->grow(N);
377   }
378
379   T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val() {
380     T Result = ::std::move(this->back());
381     this->pop_back();
382     return Result;
383   }
384
385   void swap(SmallVectorImpl &RHS);
386
387   /// Add the specified range to the end of the SmallVector.
388   template<typename in_iter>
389   void append(in_iter in_start, in_iter in_end) {
390     size_type NumInputs = std::distance(in_start, in_end);
391     // Grow allocated space if needed.
392     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
393       this->grow(this->size()+NumInputs);
394
395     // Copy the new elements over.
396     this->uninitialized_copy(in_start, in_end, this->end());
397     this->setEnd(this->end() + NumInputs);
398   }
399
400   /// Add the specified range to the end of the SmallVector.
401   void append(size_type NumInputs, const T &Elt) {
402     // Grow allocated space if needed.
403     if (NumInputs > size_type(this->capacity_ptr()-this->end()))
404       this->grow(this->size()+NumInputs);
405
406     // Copy the new elements over.
407     std::uninitialized_fill_n(this->end(), NumInputs, Elt);
408     this->setEnd(this->end() + NumInputs);
409   }
410
411   void append(std::initializer_list<T> IL) {
412     append(IL.begin(), IL.end());
413   }
414
415   void assign(size_type NumElts, const T &Elt) {
416     clear();
417     if (this->capacity() < NumElts)
418       this->grow(NumElts);
419     this->setEnd(this->begin()+NumElts);
420     std::uninitialized_fill(this->begin(), this->end(), Elt);
421   }
422
423   void assign(std::initializer_list<T> IL) {
424     clear();
425     append(IL);
426   }
427
428   iterator erase(const_iterator CI) {
429     // Just cast away constness because this is a non-const member function.
430     iterator I = const_cast<iterator>(CI);
431
432     assert(I >= this->begin() && "Iterator to erase is out of bounds.");
433     assert(I < this->end() && "Erasing at past-the-end iterator.");
434
435     iterator N = I;
436     // Shift all elts down one.
437     std::move(I+1, this->end(), I);
438     // Drop the last elt.
439     this->pop_back();
440     return(N);
441   }
442
443   iterator erase(const_iterator CS, const_iterator CE) {
444     // Just cast away constness because this is a non-const member function.
445     iterator S = const_cast<iterator>(CS);
446     iterator E = const_cast<iterator>(CE);
447
448     assert(S >= this->begin() && "Range to erase is out of bounds.");
449     assert(S <= E && "Trying to erase invalid range.");
450     assert(E <= this->end() && "Trying to erase past the end.");
451
452     iterator N = S;
453     // Shift all elts down.
454     iterator I = std::move(E, this->end(), S);
455     // Drop the last elts.
456     this->destroy_range(I, this->end());
457     this->setEnd(I);
458     return(N);
459   }
460
461   iterator insert(iterator I, T &&Elt) {
462     if (I == this->end()) {  // Important special case for empty vector.
463       this->push_back(::std::move(Elt));
464       return this->end()-1;
465     }
466
467     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
468     assert(I <= this->end() && "Inserting past the end of the vector.");
469
470     if (this->EndX >= this->CapacityX) {
471       size_t EltNo = I-this->begin();
472       this->grow();
473       I = this->begin()+EltNo;
474     }
475
476     ::new ((void*) this->end()) T(::std::move(this->back()));
477     // Push everything else over.
478     std::move_backward(I, this->end()-1, this->end());
479     this->setEnd(this->end()+1);
480
481     // If we just moved the element we're inserting, be sure to update
482     // the reference.
483     T *EltPtr = &Elt;
484     if (I <= EltPtr && EltPtr < this->EndX)
485       ++EltPtr;
486
487     *I = ::std::move(*EltPtr);
488     return I;
489   }
490
491   iterator insert(iterator I, const T &Elt) {
492     if (I == this->end()) {  // Important special case for empty vector.
493       this->push_back(Elt);
494       return this->end()-1;
495     }
496
497     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
498     assert(I <= this->end() && "Inserting past the end of the vector.");
499
500     if (this->EndX >= this->CapacityX) {
501       size_t EltNo = I-this->begin();
502       this->grow();
503       I = this->begin()+EltNo;
504     }
505     ::new ((void*) this->end()) T(std::move(this->back()));
506     // Push everything else over.
507     std::move_backward(I, this->end()-1, this->end());
508     this->setEnd(this->end()+1);
509
510     // If we just moved the element we're inserting, be sure to update
511     // the reference.
512     const T *EltPtr = &Elt;
513     if (I <= EltPtr && EltPtr < this->EndX)
514       ++EltPtr;
515
516     *I = *EltPtr;
517     return I;
518   }
519
520   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
521     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
522     size_t InsertElt = I - this->begin();
523
524     if (I == this->end()) {  // Important special case for empty vector.
525       append(NumToInsert, Elt);
526       return this->begin()+InsertElt;
527     }
528
529     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
530     assert(I <= this->end() && "Inserting past the end of the vector.");
531
532     // Ensure there is enough space.
533     reserve(this->size() + NumToInsert);
534
535     // Uninvalidate the iterator.
536     I = this->begin()+InsertElt;
537
538     // If there are more elements between the insertion point and the end of the
539     // range than there are being inserted, we can use a simple approach to
540     // insertion.  Since we already reserved space, we know that this won't
541     // reallocate the vector.
542     if (size_t(this->end()-I) >= NumToInsert) {
543       T *OldEnd = this->end();
544       append(std::move_iterator<iterator>(this->end() - NumToInsert),
545              std::move_iterator<iterator>(this->end()));
546
547       // Copy the existing elements that get replaced.
548       std::move_backward(I, OldEnd-NumToInsert, OldEnd);
549
550       std::fill_n(I, NumToInsert, Elt);
551       return I;
552     }
553
554     // Otherwise, we're inserting more elements than exist already, and we're
555     // not inserting at the end.
556
557     // Move over the elements that we're about to overwrite.
558     T *OldEnd = this->end();
559     this->setEnd(this->end() + NumToInsert);
560     size_t NumOverwritten = OldEnd-I;
561     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
562
563     // Replace the overwritten part.
564     std::fill_n(I, NumOverwritten, Elt);
565
566     // Insert the non-overwritten middle part.
567     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
568     return I;
569   }
570
571   template<typename ItTy>
572   iterator insert(iterator I, ItTy From, ItTy To) {
573     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
574     size_t InsertElt = I - this->begin();
575
576     if (I == this->end()) {  // Important special case for empty vector.
577       append(From, To);
578       return this->begin()+InsertElt;
579     }
580
581     assert(I >= this->begin() && "Insertion iterator is out of bounds.");
582     assert(I <= this->end() && "Inserting past the end of the vector.");
583
584     size_t NumToInsert = std::distance(From, To);
585
586     // Ensure there is enough space.
587     reserve(this->size() + NumToInsert);
588
589     // Uninvalidate the iterator.
590     I = this->begin()+InsertElt;
591
592     // If there are more elements between the insertion point and the end of the
593     // range than there are being inserted, we can use a simple approach to
594     // insertion.  Since we already reserved space, we know that this won't
595     // reallocate the vector.
596     if (size_t(this->end()-I) >= NumToInsert) {
597       T *OldEnd = this->end();
598       append(std::move_iterator<iterator>(this->end() - NumToInsert),
599              std::move_iterator<iterator>(this->end()));
600
601       // Copy the existing elements that get replaced.
602       std::move_backward(I, OldEnd-NumToInsert, OldEnd);
603
604       std::copy(From, To, I);
605       return I;
606     }
607
608     // Otherwise, we're inserting more elements than exist already, and we're
609     // not inserting at the end.
610
611     // Move over the elements that we're about to overwrite.
612     T *OldEnd = this->end();
613     this->setEnd(this->end() + NumToInsert);
614     size_t NumOverwritten = OldEnd-I;
615     this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
616
617     // Replace the overwritten part.
618     for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
619       *J = *From;
620       ++J; ++From;
621     }
622
623     // Insert the non-overwritten middle part.
624     this->uninitialized_copy(From, To, OldEnd);
625     return I;
626   }
627
628   void insert(iterator I, std::initializer_list<T> IL) {
629     insert(I, IL.begin(), IL.end());
630   }
631
632   template <typename... ArgTypes> void emplace_back(ArgTypes &&... Args) {
633     if (LLVM_UNLIKELY(this->EndX >= this->CapacityX))
634       this->grow();
635     ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
636     this->setEnd(this->end() + 1);
637   }
638
639   SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
640
641   SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
642
643   bool operator==(const SmallVectorImpl &RHS) const {
644     if (this->size() != RHS.size()) return false;
645     return std::equal(this->begin(), this->end(), RHS.begin());
646   }
647   bool operator!=(const SmallVectorImpl &RHS) const {
648     return !(*this == RHS);
649   }
650
651   bool operator<(const SmallVectorImpl &RHS) const {
652     return std::lexicographical_compare(this->begin(), this->end(),
653                                         RHS.begin(), RHS.end());
654   }
655
656   /// Set the array size to \p N, which the current array must have enough
657   /// capacity for.
658   ///
659   /// This does not construct or destroy any elements in the vector.
660   ///
661   /// Clients can use this in conjunction with capacity() to write past the end
662   /// of the buffer when they know that more elements are available, and only
663   /// update the size later. This avoids the cost of value initializing elements
664   /// which will only be overwritten.
665   void set_size(size_type N) {
666     assert(N <= this->capacity());
667     this->setEnd(this->begin() + N);
668   }
669 };
670
671
672 template <typename T>
673 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
674   if (this == &RHS) return;
675
676   // We can only avoid copying elements if neither vector is small.
677   if (!this->isSmall() && !RHS.isSmall()) {
678     std::swap(this->BeginX, RHS.BeginX);
679     std::swap(this->EndX, RHS.EndX);
680     std::swap(this->CapacityX, RHS.CapacityX);
681     return;
682   }
683   if (RHS.size() > this->capacity())
684     this->grow(RHS.size());
685   if (this->size() > RHS.capacity())
686     RHS.grow(this->size());
687
688   // Swap the shared elements.
689   size_t NumShared = this->size();
690   if (NumShared > RHS.size()) NumShared = RHS.size();
691   for (size_type i = 0; i != NumShared; ++i)
692     std::swap((*this)[i], RHS[i]);
693
694   // Copy over the extra elts.
695   if (this->size() > RHS.size()) {
696     size_t EltDiff = this->size() - RHS.size();
697     this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
698     RHS.setEnd(RHS.end()+EltDiff);
699     this->destroy_range(this->begin()+NumShared, this->end());
700     this->setEnd(this->begin()+NumShared);
701   } else if (RHS.size() > this->size()) {
702     size_t EltDiff = RHS.size() - this->size();
703     this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
704     this->setEnd(this->end() + EltDiff);
705     this->destroy_range(RHS.begin()+NumShared, RHS.end());
706     RHS.setEnd(RHS.begin()+NumShared);
707   }
708 }
709
710 template <typename T>
711 SmallVectorImpl<T> &SmallVectorImpl<T>::
712   operator=(const SmallVectorImpl<T> &RHS) {
713   // Avoid self-assignment.
714   if (this == &RHS) return *this;
715
716   // If we already have sufficient space, assign the common elements, then
717   // destroy any excess.
718   size_t RHSSize = RHS.size();
719   size_t CurSize = this->size();
720   if (CurSize >= RHSSize) {
721     // Assign common elements.
722     iterator NewEnd;
723     if (RHSSize)
724       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
725     else
726       NewEnd = this->begin();
727
728     // Destroy excess elements.
729     this->destroy_range(NewEnd, this->end());
730
731     // Trim.
732     this->setEnd(NewEnd);
733     return *this;
734   }
735
736   // If we have to grow to have enough elements, destroy the current elements.
737   // This allows us to avoid copying them during the grow.
738   // FIXME: don't do this if they're efficiently moveable.
739   if (this->capacity() < RHSSize) {
740     // Destroy current elements.
741     this->destroy_range(this->begin(), this->end());
742     this->setEnd(this->begin());
743     CurSize = 0;
744     this->grow(RHSSize);
745   } else if (CurSize) {
746     // Otherwise, use assignment for the already-constructed elements.
747     std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
748   }
749
750   // Copy construct the new elements in place.
751   this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
752                            this->begin()+CurSize);
753
754   // Set end.
755   this->setEnd(this->begin()+RHSSize);
756   return *this;
757 }
758
759 template <typename T>
760 SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
761   // Avoid self-assignment.
762   if (this == &RHS) return *this;
763
764   // If the RHS isn't small, clear this vector and then steal its buffer.
765   if (!RHS.isSmall()) {
766     this->destroy_range(this->begin(), this->end());
767     if (!this->isSmall()) free(this->begin());
768     this->BeginX = RHS.BeginX;
769     this->EndX = RHS.EndX;
770     this->CapacityX = RHS.CapacityX;
771     RHS.resetToSmall();
772     return *this;
773   }
774
775   // If we already have sufficient space, assign the common elements, then
776   // destroy any excess.
777   size_t RHSSize = RHS.size();
778   size_t CurSize = this->size();
779   if (CurSize >= RHSSize) {
780     // Assign common elements.
781     iterator NewEnd = this->begin();
782     if (RHSSize)
783       NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
784
785     // Destroy excess elements and trim the bounds.
786     this->destroy_range(NewEnd, this->end());
787     this->setEnd(NewEnd);
788
789     // Clear the RHS.
790     RHS.clear();
791
792     return *this;
793   }
794
795   // If we have to grow to have enough elements, destroy the current elements.
796   // This allows us to avoid copying them during the grow.
797   // FIXME: this may not actually make any sense if we can efficiently move
798   // elements.
799   if (this->capacity() < RHSSize) {
800     // Destroy current elements.
801     this->destroy_range(this->begin(), this->end());
802     this->setEnd(this->begin());
803     CurSize = 0;
804     this->grow(RHSSize);
805   } else if (CurSize) {
806     // Otherwise, use assignment for the already-constructed elements.
807     std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
808   }
809
810   // Move-construct the new elements in place.
811   this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
812                            this->begin()+CurSize);
813
814   // Set end.
815   this->setEnd(this->begin()+RHSSize);
816
817   RHS.clear();
818   return *this;
819 }
820
821 /// Storage for the SmallVector elements which aren't contained in
822 /// SmallVectorTemplateCommon. There are 'N-1' elements here. The remaining '1'
823 /// element is in the base class. This is specialized for the N=1 and N=0 cases
824 /// to avoid allocating unnecessary storage.
825 template <typename T, unsigned N>
826 struct SmallVectorStorage {
827   typename SmallVectorTemplateCommon<T>::U InlineElts[N - 1];
828 };
829 template <typename T> struct SmallVectorStorage<T, 1> {};
830 template <typename T> struct SmallVectorStorage<T, 0> {};
831
832 /// This is a 'vector' (really, a variable-sized array), optimized
833 /// for the case when the array is small.  It contains some number of elements
834 /// in-place, which allows it to avoid heap allocation when the actual number of
835 /// elements is below that threshold.  This allows normal "small" cases to be
836 /// fast without losing generality for large inputs.
837 ///
838 /// Note that this does not attempt to be exception safe.
839 ///
840 template <typename T, unsigned N>
841 class SmallVector : public SmallVectorImpl<T> {
842   /// Inline space for elements which aren't stored in the base class.
843   SmallVectorStorage<T, N> Storage;
844 public:
845   SmallVector() : SmallVectorImpl<T>(N) {
846   }
847
848   explicit SmallVector(size_t Size, const T &Value = T())
849     : SmallVectorImpl<T>(N) {
850     this->assign(Size, Value);
851   }
852
853   template<typename ItTy>
854   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
855     this->append(S, E);
856   }
857
858   template <typename RangeTy>
859   explicit SmallVector(const llvm::iterator_range<RangeTy> R)
860       : SmallVectorImpl<T>(N) {
861     this->append(R.begin(), R.end());
862   }
863
864   SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
865     this->assign(IL);
866   }
867
868   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
869     if (!RHS.empty())
870       SmallVectorImpl<T>::operator=(RHS);
871   }
872
873   const SmallVector &operator=(const SmallVector &RHS) {
874     SmallVectorImpl<T>::operator=(RHS);
875     return *this;
876   }
877
878   SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
879     if (!RHS.empty())
880       SmallVectorImpl<T>::operator=(::std::move(RHS));
881   }
882
883   const SmallVector &operator=(SmallVector &&RHS) {
884     SmallVectorImpl<T>::operator=(::std::move(RHS));
885     return *this;
886   }
887
888   SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
889     if (!RHS.empty())
890       SmallVectorImpl<T>::operator=(::std::move(RHS));
891   }
892
893   const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
894     SmallVectorImpl<T>::operator=(::std::move(RHS));
895     return *this;
896   }
897
898   const SmallVector &operator=(std::initializer_list<T> IL) {
899     this->assign(IL);
900     return *this;
901   }
902 };
903
904 template<typename T, unsigned N>
905 static inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
906   return X.capacity_in_bytes();
907 }
908
909 } // End llvm namespace
910
911 namespace std {
912   /// Implement std::swap in terms of SmallVector swap.
913   template<typename T>
914   inline void
915   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
916     LHS.swap(RHS);
917   }
918
919   /// Implement std::swap in terms of SmallVector swap.
920   template<typename T, unsigned N>
921   inline void
922   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
923     LHS.swap(RHS);
924   }
925 }
926
927 #endif