1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SmallVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
17 #include "llvm/Support/type_traits.h"
28 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
29 // additional overloads so that elements with pointer types are recognized as
30 // scalars and not objects, causing bizarre type conversion errors.
31 template<class T1, class T2>
32 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
33 _Scalar_ptr_iterator_tag _Cat;
37 template<class T1, class T2>
38 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
39 _Scalar_ptr_iterator_tag _Cat;
43 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
44 // is that the above hack won't work if it wasn't fixed.
51 /// SmallVectorBase - This is all the non-templated stuff common to all
53 class SmallVectorBase {
55 void *BeginX, *EndX, *CapacityX;
57 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
58 // don't want it to be automatically run, so we need to represent the space as
59 // something else. An array of char would work great, but might not be
60 // aligned sufficiently. Instead, we either use GCC extensions, or some
61 // number of union instances for the space, which guarantee maximal alignment.
64 char X __attribute__((aligned(8)));
74 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
77 SmallVectorBase(size_t Size)
78 : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
80 /// isSmall - Return true if this is a smallvector which has not had dynamic
81 /// memory allocated for it.
82 bool isSmall() const {
83 return BeginX == static_cast<const void*>(&FirstEl);
86 /// size_in_bytes - This returns size()*sizeof(T).
87 size_t size_in_bytes() const {
88 return size_t((char*)EndX - (char*)BeginX);
91 /// capacity_in_bytes - This returns capacity()*sizeof(T).
92 size_t capacity_in_bytes() const {
93 return size_t((char*)CapacityX - (char*)BeginX);
96 /// grow_pod - This is an implementation of the grow() method which only works
97 /// on POD-like datatypes and is out of line to reduce code duplication.
98 void grow_pod(size_t MinSizeInBytes, size_t TSize);
101 bool empty() const { return BeginX == EndX; }
105 template <typename T>
106 class SmallVectorTemplateCommon : public SmallVectorBase {
108 void setEnd(T *P) { this->EndX = P; }
110 SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
112 typedef size_t size_type;
113 typedef ptrdiff_t difference_type;
114 typedef T value_type;
116 typedef const T *const_iterator;
118 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
119 typedef std::reverse_iterator<iterator> reverse_iterator;
121 typedef T &reference;
122 typedef const T &const_reference;
124 typedef const T *const_pointer;
126 // forward iterator creation methods.
127 iterator begin() { return (iterator)this->BeginX; }
128 const_iterator begin() const { return (const_iterator)this->BeginX; }
129 iterator end() { return (iterator)this->EndX; }
130 const_iterator end() const { return (const_iterator)this->EndX; }
132 iterator capacity_ptr() { return (iterator)this->CapacityX; }
133 const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
136 // reverse iterator creation methods.
137 reverse_iterator rbegin() { return reverse_iterator(end()); }
138 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
139 reverse_iterator rend() { return reverse_iterator(begin()); }
140 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
142 size_type size() const { return end()-begin(); }
143 size_type max_size() const { return size_type(-1) / sizeof(T); }
145 /// capacity - Return the total number of elements in the currently allocated
147 size_t capacity() const { return capacity_ptr() - begin(); }
149 /// data - Return a pointer to the vector's buffer, even if empty().
150 pointer data() { return pointer(begin()); }
151 /// data - Return a pointer to the vector's buffer, even if empty().
152 const_pointer data() const { return const_pointer(begin()); }
154 reference operator[](unsigned idx) {
155 assert(begin() + idx < end());
158 const_reference operator[](unsigned idx) const {
159 assert(begin() + idx < end());
166 const_reference front() const {
173 const_reference back() const {
178 /// SmallVectorTemplateBase<isPodLike = false> - This is where we put method
179 /// implementations that are designed to work with non-POD-like T's.
180 template <typename T, bool isPodLike>
181 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
183 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
185 static void destroy_range(T *S, T *E) {
192 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
193 /// starting with "Dest", constructing elements into it as needed.
194 template<typename It1, typename It2>
195 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
196 std::uninitialized_copy(I, E, Dest);
199 /// grow - double the size of the allocated memory, guaranteeing space for at
200 /// least one more element or MinSize if specified.
201 void grow(size_t MinSize = 0);
204 // Define this out-of-line to dissuade the C++ compiler from inlining it.
205 template <typename T, bool isPodLike>
206 void SmallVectorTemplateBase<T, isPodLike>::grow(size_t MinSize) {
207 size_t CurCapacity = this->capacity();
208 size_t CurSize = this->size();
209 size_t NewCapacity = 2*CurCapacity;
210 if (NewCapacity < MinSize)
211 NewCapacity = MinSize;
212 T *NewElts = static_cast<T*>(malloc(NewCapacity*sizeof(T)));
214 // Copy the elements over.
215 this->uninitialized_copy(this->begin(), this->end(), NewElts);
217 // Destroy the original elements.
218 destroy_range(this->begin(), this->end());
220 // If this wasn't grown from the inline copy, deallocate the old space.
221 if (!this->isSmall())
224 this->setEnd(NewElts+CurSize);
225 this->BeginX = NewElts;
226 this->CapacityX = this->begin()+NewCapacity;
230 /// SmallVectorTemplateBase<isPodLike = true> - This is where we put method
231 /// implementations that are designed to work with POD-like T's.
232 template <typename T>
233 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
235 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
237 // No need to do a destroy loop for POD's.
238 static void destroy_range(T *, T *) {}
240 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
241 /// starting with "Dest", constructing elements into it as needed.
242 template<typename It1, typename It2>
243 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
244 // Arbitrary iterator types; just use the basic implementation.
245 std::uninitialized_copy(I, E, Dest);
248 /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
249 /// starting with "Dest", constructing elements into it as needed.
250 template<typename T1, typename T2>
251 static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) {
252 // Use memcpy for PODs iterated by pointers (which includes SmallVector
253 // iterators): std::uninitialized_copy optimizes to memmove, but we can
255 memcpy(Dest, I, (E-I)*sizeof(T));
258 /// grow - double the size of the allocated memory, guaranteeing space for at
259 /// least one more element or MinSize if specified.
260 void grow(size_t MinSize = 0) {
261 this->grow_pod(MinSize*sizeof(T), sizeof(T));
266 /// SmallVectorImpl - This class consists of common code factored out of the
267 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
268 /// template parameter.
269 template <typename T>
270 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
271 typedef SmallVectorTemplateBase<T, isPodLike<T>::value > SuperClass;
273 typedef typename SuperClass::iterator iterator;
274 typedef typename SuperClass::size_type size_type;
276 // Default ctor - Initialize to empty.
277 explicit SmallVectorImpl(unsigned N)
278 : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
282 // Destroy the constructed elements in the vector.
283 this->destroy_range(this->begin(), this->end());
285 // If this wasn't grown from the inline copy, deallocate the old space.
286 if (!this->isSmall())
292 this->destroy_range(this->begin(), this->end());
293 this->EndX = this->BeginX;
296 void resize(unsigned N) {
297 if (N < this->size()) {
298 this->destroy_range(this->begin()+N, this->end());
299 this->setEnd(this->begin()+N);
300 } else if (N > this->size()) {
301 if (this->capacity() < N)
303 this->construct_range(this->end(), this->begin()+N, T());
304 this->setEnd(this->begin()+N);
308 void resize(unsigned N, const T &NV) {
309 if (N < this->size()) {
310 this->destroy_range(this->begin()+N, this->end());
311 this->setEnd(this->begin()+N);
312 } else if (N > this->size()) {
313 if (this->capacity() < N)
315 construct_range(this->end(), this->begin()+N, NV);
316 this->setEnd(this->begin()+N);
320 void reserve(unsigned N) {
321 if (this->capacity() < N)
325 void push_back(const T &Elt) {
326 if (this->EndX < this->CapacityX) {
328 new (this->end()) T(Elt);
329 this->setEnd(this->end()+1);
337 this->setEnd(this->end()-1);
342 T Result = this->back();
348 void swap(SmallVectorImpl &RHS);
350 /// append - Add the specified range to the end of the SmallVector.
352 template<typename in_iter>
353 void append(in_iter in_start, in_iter in_end) {
354 size_type NumInputs = std::distance(in_start, in_end);
355 // Grow allocated space if needed.
356 if (NumInputs > size_type(this->capacity_ptr()-this->end()))
357 this->grow(this->size()+NumInputs);
359 // Copy the new elements over.
360 // TODO: NEED To compile time dispatch on whether in_iter is a random access
361 // iterator to use the fast uninitialized_copy.
362 std::uninitialized_copy(in_start, in_end, this->end());
363 this->setEnd(this->end() + NumInputs);
366 /// append - Add the specified range to the end of the SmallVector.
368 void append(size_type NumInputs, const T &Elt) {
369 // Grow allocated space if needed.
370 if (NumInputs > size_type(this->capacity_ptr()-this->end()))
371 this->grow(this->size()+NumInputs);
373 // Copy the new elements over.
374 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
375 this->setEnd(this->end() + NumInputs);
378 void assign(unsigned NumElts, const T &Elt) {
380 if (this->capacity() < NumElts)
382 this->setEnd(this->begin()+NumElts);
383 construct_range(this->begin(), this->end(), Elt);
386 iterator erase(iterator I) {
388 // Shift all elts down one.
389 std::copy(I+1, this->end(), I);
390 // Drop the last elt.
395 iterator erase(iterator S, iterator E) {
397 // Shift all elts down.
398 iterator I = std::copy(E, this->end(), S);
399 // Drop the last elts.
400 this->destroy_range(I, this->end());
405 iterator insert(iterator I, const T &Elt) {
406 if (I == this->end()) { // Important special case for empty vector.
408 return this->end()-1;
411 if (this->EndX < this->CapacityX) {
413 new (this->end()) T(this->back());
414 this->setEnd(this->end()+1);
415 // Push everything else over.
416 std::copy_backward(I, this->end()-1, this->end());
420 size_t EltNo = I-this->begin();
422 I = this->begin()+EltNo;
426 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
427 if (I == this->end()) { // Important special case for empty vector.
428 append(NumToInsert, Elt);
429 return this->end()-1;
432 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
433 size_t InsertElt = I - this->begin();
435 // Ensure there is enough space.
436 reserve(static_cast<unsigned>(this->size() + NumToInsert));
438 // Uninvalidate the iterator.
439 I = this->begin()+InsertElt;
441 // If there are more elements between the insertion point and the end of the
442 // range than there are being inserted, we can use a simple approach to
443 // insertion. Since we already reserved space, we know that this won't
444 // reallocate the vector.
445 if (size_t(this->end()-I) >= NumToInsert) {
446 T *OldEnd = this->end();
447 append(this->end()-NumToInsert, this->end());
449 // Copy the existing elements that get replaced.
450 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
452 std::fill_n(I, NumToInsert, Elt);
456 // Otherwise, we're inserting more elements than exist already, and we're
457 // not inserting at the end.
459 // Copy over the elements that we're about to overwrite.
460 T *OldEnd = this->end();
461 this->setEnd(this->end() + NumToInsert);
462 size_t NumOverwritten = OldEnd-I;
463 this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
465 // Replace the overwritten part.
466 std::fill_n(I, NumOverwritten, Elt);
468 // Insert the non-overwritten middle part.
469 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
473 template<typename ItTy>
474 iterator insert(iterator I, ItTy From, ItTy To) {
475 if (I == this->end()) { // Important special case for empty vector.
477 return this->end()-1;
480 size_t NumToInsert = std::distance(From, To);
481 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
482 size_t InsertElt = I - this->begin();
484 // Ensure there is enough space.
485 reserve(static_cast<unsigned>(this->size() + NumToInsert));
487 // Uninvalidate the iterator.
488 I = this->begin()+InsertElt;
490 // If there are more elements between the insertion point and the end of the
491 // range than there are being inserted, we can use a simple approach to
492 // insertion. Since we already reserved space, we know that this won't
493 // reallocate the vector.
494 if (size_t(this->end()-I) >= NumToInsert) {
495 T *OldEnd = this->end();
496 append(this->end()-NumToInsert, this->end());
498 // Copy the existing elements that get replaced.
499 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
501 std::copy(From, To, I);
505 // Otherwise, we're inserting more elements than exist already, and we're
506 // not inserting at the end.
508 // Copy over the elements that we're about to overwrite.
509 T *OldEnd = this->end();
510 this->setEnd(this->end() + NumToInsert);
511 size_t NumOverwritten = OldEnd-I;
512 this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
514 // Replace the overwritten part.
515 for (; NumOverwritten > 0; --NumOverwritten) {
520 // Insert the non-overwritten middle part.
521 this->uninitialized_copy(From, To, OldEnd);
525 const SmallVectorImpl
526 &operator=(const SmallVectorImpl &RHS);
528 bool operator==(const SmallVectorImpl &RHS) const {
529 if (this->size() != RHS.size()) return false;
530 return std::equal(this->begin(), this->end(), RHS.begin());
532 bool operator!=(const SmallVectorImpl &RHS) const {
533 return !(*this == RHS);
536 bool operator<(const SmallVectorImpl &RHS) const {
537 return std::lexicographical_compare(this->begin(), this->end(),
538 RHS.begin(), RHS.end());
541 /// set_size - Set the array size to \arg N, which the current array must have
542 /// enough capacity for.
544 /// This does not construct or destroy any elements in the vector.
546 /// Clients can use this in conjunction with capacity() to write past the end
547 /// of the buffer when they know that more elements are available, and only
548 /// update the size later. This avoids the cost of value initializing elements
549 /// which will only be overwritten.
550 void set_size(unsigned N) {
551 assert(N <= this->capacity());
552 this->setEnd(this->begin() + N);
556 static void construct_range(T *S, T *E, const T &Elt) {
563 template <typename T>
564 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
565 if (this == &RHS) return;
567 // We can only avoid copying elements if neither vector is small.
568 if (!this->isSmall() && !RHS.isSmall()) {
569 std::swap(this->BeginX, RHS.BeginX);
570 std::swap(this->EndX, RHS.EndX);
571 std::swap(this->CapacityX, RHS.CapacityX);
574 if (RHS.size() > this->capacity())
575 this->grow(RHS.size());
576 if (this->size() > RHS.capacity())
577 RHS.grow(this->size());
579 // Swap the shared elements.
580 size_t NumShared = this->size();
581 if (NumShared > RHS.size()) NumShared = RHS.size();
582 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
583 std::swap((*this)[i], RHS[i]);
585 // Copy over the extra elts.
586 if (this->size() > RHS.size()) {
587 size_t EltDiff = this->size() - RHS.size();
588 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
589 RHS.setEnd(RHS.end()+EltDiff);
590 this->destroy_range(this->begin()+NumShared, this->end());
591 this->setEnd(this->begin()+NumShared);
592 } else if (RHS.size() > this->size()) {
593 size_t EltDiff = RHS.size() - this->size();
594 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
595 this->setEnd(this->end() + EltDiff);
596 this->destroy_range(RHS.begin()+NumShared, RHS.end());
597 RHS.setEnd(RHS.begin()+NumShared);
601 template <typename T>
602 const SmallVectorImpl<T> &SmallVectorImpl<T>::
603 operator=(const SmallVectorImpl<T> &RHS) {
604 // Avoid self-assignment.
605 if (this == &RHS) return *this;
607 // If we already have sufficient space, assign the common elements, then
608 // destroy any excess.
609 size_t RHSSize = RHS.size();
610 size_t CurSize = this->size();
611 if (CurSize >= RHSSize) {
612 // Assign common elements.
615 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
617 NewEnd = this->begin();
619 // Destroy excess elements.
620 this->destroy_range(NewEnd, this->end());
623 this->setEnd(NewEnd);
627 // If we have to grow to have enough elements, destroy the current elements.
628 // This allows us to avoid copying them during the grow.
629 if (this->capacity() < RHSSize) {
630 // Destroy current elements.
631 this->destroy_range(this->begin(), this->end());
632 this->setEnd(this->begin());
635 } else if (CurSize) {
636 // Otherwise, use assignment for the already-constructed elements.
637 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
640 // Copy construct the new elements in place.
641 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
642 this->begin()+CurSize);
645 this->setEnd(this->begin()+RHSSize);
650 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
651 /// for the case when the array is small. It contains some number of elements
652 /// in-place, which allows it to avoid heap allocation when the actual number of
653 /// elements is below that threshold. This allows normal "small" cases to be
654 /// fast without losing generality for large inputs.
656 /// Note that this does not attempt to be exception safe.
658 template <typename T, unsigned N>
659 class SmallVector : public SmallVectorImpl<T> {
660 /// InlineElts - These are 'N-1' elements that are stored inline in the body
661 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
662 typedef typename SmallVectorImpl<T>::U U;
664 // MinUs - The number of U's require to cover N T's.
665 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
666 static_cast<unsigned int>(sizeof(U)) - 1) /
667 static_cast<unsigned int>(sizeof(U)),
669 // NumInlineEltsElts - The number of elements actually in this array. There
670 // is already one in the parent class, and we have to round up to avoid
671 // having a zero-element array.
672 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
674 // NumTsAvailable - The number of T's we actually have space for, which may
675 // be more than N due to rounding.
676 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
677 static_cast<unsigned int>(sizeof(T))
679 U InlineElts[NumInlineEltsElts];
681 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
684 explicit SmallVector(unsigned Size, const T &Value = T())
685 : SmallVectorImpl<T>(NumTsAvailable) {
688 this->push_back(Value);
691 template<typename ItTy>
692 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
696 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
698 SmallVectorImpl<T>::operator=(RHS);
701 const SmallVector &operator=(const SmallVector &RHS) {
702 SmallVectorImpl<T>::operator=(RHS);
708 } // End llvm namespace
711 /// Implement std::swap in terms of SmallVector swap.
714 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
718 /// Implement std::swap in terms of SmallVector swap.
719 template<typename T, unsigned N>
721 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {