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"
26 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
27 // additional overloads so that elements with pointer types are recognized as
28 // scalars and not objects, causing bizarre type conversion errors.
29 template<class T1, class T2>
30 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
31 _Scalar_ptr_iterator_tag _Cat;
35 template<class T1, class T2>
36 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
37 _Scalar_ptr_iterator_tag _Cat;
41 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
42 // is that the above hack won't work if it wasn't fixed.
49 /// SmallVectorBase - This is all the non-templated stuff common to all
51 class SmallVectorBase {
53 void *BeginX, *EndX, *CapacityX;
55 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
56 // don't want it to be automatically run, so we need to represent the space as
57 // something else. An array of char would work great, but might not be
58 // aligned sufficiently. Instead, we either use GCC extensions, or some
59 // number of union instances for the space, which guarantee maximal alignment.
62 U FirstEl __attribute__((aligned));
71 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
74 SmallVectorBase(size_t Size)
75 : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
77 /// isSmall - Return true if this is a smallvector which has not had dynamic
78 /// memory allocated for it.
79 bool isSmall() const {
80 return BeginX == static_cast<const void*>(&FirstEl);
85 bool empty() const { return BeginX == EndX; }
88 /// SmallVectorImpl - This class consists of common code factored out of the
89 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
90 /// template parameter.
92 class SmallVectorImpl : public SmallVectorBase {
93 void setEnd(T *P) { EndX = P; }
95 // Default ctor - Initialize to empty.
96 explicit SmallVectorImpl(unsigned N) : SmallVectorBase(N*sizeof(T)) {
100 // Destroy the constructed elements in the vector.
101 destroy_range(begin(), end());
103 // If this wasn't grown from the inline copy, deallocate the old space.
105 operator delete(begin());
108 typedef size_t size_type;
109 typedef ptrdiff_t difference_type;
110 typedef T value_type;
112 typedef const T *const_iterator;
114 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
115 typedef std::reverse_iterator<iterator> reverse_iterator;
117 typedef T &reference;
118 typedef const T &const_reference;
120 typedef const T *const_pointer;
122 // forward iterator creation methods.
123 iterator begin() { return (iterator)BeginX; }
124 const_iterator begin() const { return (const_iterator)BeginX; }
125 iterator end() { return (iterator)EndX; }
126 const_iterator end() const { return (const_iterator)EndX; }
128 iterator capacity_ptr() { return (iterator)CapacityX; }
129 const_iterator capacity_ptr() const { return (const_iterator)CapacityX; }
132 // reverse iterator creation methods.
133 reverse_iterator rbegin() { return reverse_iterator(end()); }
134 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
135 reverse_iterator rend() { return reverse_iterator(begin()); }
136 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
138 size_type size() const { return end()-begin(); }
139 size_type max_size() const { return size_type(-1) / sizeof(T); }
141 /// capacity - Return the total number of elements in the currently allocated
143 size_t capacity() const { return capacity_ptr() - begin(); }
145 /// data - Return a pointer to the vector's buffer, even if empty().
146 pointer data() { return pointer(begin()); }
147 /// data - Return a pointer to the vector's buffer, even if empty().
148 const_pointer data() const { return const_pointer(begin()); }
150 reference operator[](unsigned idx) {
151 assert(begin() + idx < end());
154 const_reference operator[](unsigned idx) const {
155 assert(begin() + idx < end());
162 const_reference front() const {
169 const_reference back() const {
173 void push_back(const_reference Elt) {
174 if (EndX < CapacityX) {
196 destroy_range(begin(), end());
200 void resize(unsigned N) {
202 destroy_range(begin()+N, end());
204 } else if (N > size()) {
207 construct_range(end(), begin()+N, T());
212 void resize(unsigned N, const T &NV) {
214 destroy_range(begin()+N, end());
216 } else if (N > size()) {
219 construct_range(end(), begin()+N, NV);
224 void reserve(unsigned N) {
229 void swap(SmallVectorImpl &RHS);
231 /// append - Add the specified range to the end of the SmallVector.
233 template<typename in_iter>
234 void append(in_iter in_start, in_iter in_end) {
235 size_type NumInputs = std::distance(in_start, in_end);
236 // Grow allocated space if needed.
237 if (NumInputs > size_type(capacity_ptr()-end()))
238 grow(size()+NumInputs);
240 // Copy the new elements over.
241 std::uninitialized_copy(in_start, in_end, end());
242 setEnd(end() + NumInputs);
245 /// append - Add the specified range to the end of the SmallVector.
247 void append(size_type NumInputs, const T &Elt) {
248 // Grow allocated space if needed.
249 if (NumInputs > size_type(capacity_ptr()-end()))
250 grow(size()+NumInputs);
252 // Copy the new elements over.
253 std::uninitialized_fill_n(end(), NumInputs, Elt);
254 setEnd(end() + NumInputs);
257 void assign(unsigned NumElts, const T &Elt) {
259 if (capacity() < NumElts)
261 setEnd(begin()+NumElts);
262 construct_range(begin(), end(), Elt);
265 iterator erase(iterator I) {
267 // Shift all elts down one.
268 std::copy(I+1, end(), I);
269 // Drop the last elt.
274 iterator erase(iterator S, iterator E) {
276 // Shift all elts down.
277 iterator I = std::copy(E, end(), S);
278 // Drop the last elts.
279 destroy_range(I, end());
284 iterator insert(iterator I, const T &Elt) {
285 if (I == end()) { // Important special case for empty vector.
290 if (EndX < CapacityX) {
292 new (end()) T(back());
294 // Push everything else over.
295 std::copy_backward(I, end()-1, end());
299 size_t EltNo = I-begin();
305 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
306 if (I == end()) { // Important special case for empty vector.
307 append(NumToInsert, Elt);
311 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
312 size_t InsertElt = I-begin();
314 // Ensure there is enough space.
315 reserve(static_cast<unsigned>(size() + NumToInsert));
317 // Uninvalidate the iterator.
318 I = begin()+InsertElt;
320 // If there are more elements between the insertion point and the end of the
321 // range than there are being inserted, we can use a simple approach to
322 // insertion. Since we already reserved space, we know that this won't
323 // reallocate the vector.
324 if (size_t(end()-I) >= NumToInsert) {
326 append(end()-NumToInsert, end());
328 // Copy the existing elements that get replaced.
329 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
331 std::fill_n(I, NumToInsert, Elt);
335 // Otherwise, we're inserting more elements than exist already, and we're
336 // not inserting at the end.
338 // Copy over the elements that we're about to overwrite.
340 setEnd(end() + NumToInsert);
341 size_t NumOverwritten = OldEnd-I;
342 std::uninitialized_copy(I, OldEnd, end()-NumOverwritten);
344 // Replace the overwritten part.
345 std::fill_n(I, NumOverwritten, Elt);
347 // Insert the non-overwritten middle part.
348 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
352 template<typename ItTy>
353 iterator insert(iterator I, ItTy From, ItTy To) {
354 if (I == end()) { // Important special case for empty vector.
359 size_t NumToInsert = std::distance(From, To);
360 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
361 size_t InsertElt = I-begin();
363 // Ensure there is enough space.
364 reserve(static_cast<unsigned>(size() + NumToInsert));
366 // Uninvalidate the iterator.
367 I = begin()+InsertElt;
369 // If there are more elements between the insertion point and the end of the
370 // range than there are being inserted, we can use a simple approach to
371 // insertion. Since we already reserved space, we know that this won't
372 // reallocate the vector.
373 if (size_t(end()-I) >= NumToInsert) {
375 append(end()-NumToInsert, end());
377 // Copy the existing elements that get replaced.
378 std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
380 std::copy(From, To, I);
384 // Otherwise, we're inserting more elements than exist already, and we're
385 // not inserting at the end.
387 // Copy over the elements that we're about to overwrite.
389 setEnd(end() + NumToInsert);
390 size_t NumOverwritten = OldEnd-I;
391 std::uninitialized_copy(I, OldEnd, end()-NumOverwritten);
393 // Replace the overwritten part.
394 std::copy(From, From+NumOverwritten, I);
396 // Insert the non-overwritten middle part.
397 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
401 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
403 bool operator==(const SmallVectorImpl &RHS) const {
404 if (size() != RHS.size()) return false;
405 return std::equal(begin(), end(), RHS.begin());
407 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
409 bool operator<(const SmallVectorImpl &RHS) const {
410 return std::lexicographical_compare(begin(), end(),
411 RHS.begin(), RHS.end());
414 /// set_size - Set the array size to \arg N, which the current array must have
415 /// enough capacity for.
417 /// This does not construct or destroy any elements in the vector.
419 /// Clients can use this in conjunction with capacity() to write past the end
420 /// of the buffer when they know that more elements are available, and only
421 /// update the size later. This avoids the cost of value initializing elements
422 /// which will only be overwritten.
423 void set_size(unsigned N) {
424 assert(N <= capacity());
429 /// grow - double the size of the allocated memory, guaranteeing space for at
430 /// least one more element or MinSize if specified.
431 void grow(size_type MinSize = 0);
433 void construct_range(T *S, T *E, const T &Elt) {
438 void destroy_range(T *S, T *E) {
439 // No need to do a destroy loop for POD's.
440 if (isPodLike<T>::value) return;
449 // Define this out-of-line to dissuade the C++ compiler from inlining it.
450 template <typename T>
451 void SmallVectorImpl<T>::grow(size_t MinSize) {
452 size_t CurCapacity = capacity();
453 size_t CurSize = size();
454 size_t NewCapacity = 2*CurCapacity;
455 if (NewCapacity < MinSize)
456 NewCapacity = MinSize;
457 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
459 // Copy the elements over.
460 if (isPodLike<T>::value)
461 // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove.
462 memcpy(NewElts, begin(), CurSize * sizeof(T));
464 std::uninitialized_copy(begin(), end(), NewElts);
466 // Destroy the original elements.
467 destroy_range(begin(), end());
469 // If this wasn't grown from the inline copy, deallocate the old space.
471 operator delete(begin());
473 setEnd(NewElts+CurSize);
475 CapacityX = begin()+NewCapacity;
478 template <typename T>
479 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
480 if (this == &RHS) return;
482 // We can only avoid copying elements if neither vector is small.
483 if (!isSmall() && !RHS.isSmall()) {
484 std::swap(BeginX, RHS.BeginX);
485 std::swap(EndX, RHS.EndX);
486 std::swap(CapacityX, RHS.CapacityX);
489 if (RHS.size() > capacity())
491 if (size() > RHS.capacity())
494 // Swap the shared elements.
495 size_t NumShared = size();
496 if (NumShared > RHS.size()) NumShared = RHS.size();
497 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
498 std::swap((*this)[i], RHS[i]);
500 // Copy over the extra elts.
501 if (size() > RHS.size()) {
502 size_t EltDiff = size() - RHS.size();
503 std::uninitialized_copy(begin()+NumShared, end(), RHS.end());
504 RHS.setEnd(RHS.end()+EltDiff);
505 destroy_range(begin()+NumShared, end());
506 setEnd(begin()+NumShared);
507 } else if (RHS.size() > size()) {
508 size_t EltDiff = RHS.size() - size();
509 std::uninitialized_copy(RHS.begin()+NumShared, RHS.end(), end());
510 setEnd(end() + EltDiff);
511 destroy_range(RHS.begin()+NumShared, RHS.end());
512 RHS.setEnd(RHS.begin()+NumShared);
516 template <typename T>
517 const SmallVectorImpl<T> &
518 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
519 // Avoid self-assignment.
520 if (this == &RHS) return *this;
522 // If we already have sufficient space, assign the common elements, then
523 // destroy any excess.
524 size_t RHSSize = RHS.size();
525 size_t CurSize = size();
526 if (CurSize >= RHSSize) {
527 // Assign common elements.
530 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, begin());
534 // Destroy excess elements.
535 destroy_range(NewEnd, end());
542 // If we have to grow to have enough elements, destroy the current elements.
543 // This allows us to avoid copying them during the grow.
544 if (capacity() < RHSSize) {
545 // Destroy current elements.
546 destroy_range(begin(), end());
550 } else if (CurSize) {
551 // Otherwise, use assignment for the already-constructed elements.
552 std::copy(RHS.begin(), RHS.begin()+CurSize, begin());
555 // Copy construct the new elements in place.
556 std::uninitialized_copy(RHS.begin()+CurSize, RHS.end(), begin()+CurSize);
559 setEnd(begin()+RHSSize);
563 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
564 /// for the case when the array is small. It contains some number of elements
565 /// in-place, which allows it to avoid heap allocation when the actual number of
566 /// elements is below that threshold. This allows normal "small" cases to be
567 /// fast without losing generality for large inputs.
569 /// Note that this does not attempt to be exception safe.
571 template <typename T, unsigned N>
572 class SmallVector : public SmallVectorImpl<T> {
573 /// InlineElts - These are 'N-1' elements that are stored inline in the body
574 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
575 typedef typename SmallVectorImpl<T>::U U;
577 // MinUs - The number of U's require to cover N T's.
578 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
579 static_cast<unsigned int>(sizeof(U)) - 1) /
580 static_cast<unsigned int>(sizeof(U)),
582 // NumInlineEltsElts - The number of elements actually in this array. There
583 // is already one in the parent class, and we have to round up to avoid
584 // having a zero-element array.
585 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
587 // NumTsAvailable - The number of T's we actually have space for, which may
588 // be more than N due to rounding.
589 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
590 static_cast<unsigned int>(sizeof(T))
592 U InlineElts[NumInlineEltsElts];
594 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
597 explicit SmallVector(unsigned Size, const T &Value = T())
598 : SmallVectorImpl<T>(NumTsAvailable) {
601 this->push_back(Value);
604 template<typename ItTy>
605 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
609 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
611 SmallVectorImpl<T>::operator=(RHS);
614 const SmallVector &operator=(const SmallVector &RHS) {
615 SmallVectorImpl<T>::operator=(RHS);
621 } // End llvm namespace
624 /// Implement std::swap in terms of SmallVector swap.
627 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
631 /// Implement std::swap in terms of SmallVector swap.
632 template<typename T, unsigned N>
634 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {