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