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