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/ADT/iterator.h"
18 #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 /// SmallVectorImpl - This class consists of common code factored out of the
50 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
51 /// template parameter.
53 class SmallVectorImpl {
55 T *Begin, *End, *Capacity;
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.
65 U FirstEl __attribute__((aligned));
74 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
76 // Default ctor - Initialize to empty.
77 SmallVectorImpl(unsigned N)
78 : Begin(reinterpret_cast<T*>(&FirstEl)),
79 End(reinterpret_cast<T*>(&FirstEl)),
80 Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
84 // Destroy the constructed elements in the vector.
85 destroy_range(Begin, End);
87 // If this wasn't grown from the inline copy, deallocate the old space.
89 operator delete(Begin);
92 typedef size_t size_type;
94 typedef const T* const_iterator;
96 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
97 typedef std::reverse_iterator<iterator> reverse_iterator;
100 typedef const T& const_reference;
102 bool empty() const { return Begin == End; }
103 size_type size() const { return End-Begin; }
105 // forward iterator creation methods.
106 iterator begin() { return Begin; }
107 const_iterator begin() const { return Begin; }
108 iterator end() { return End; }
109 const_iterator end() const { return End; }
111 // reverse iterator creation methods.
112 reverse_iterator rbegin() { return reverse_iterator(end()); }
113 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
114 reverse_iterator rend() { return reverse_iterator(begin()); }
115 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
118 reference operator[](unsigned idx) {
121 const_reference operator[](unsigned idx) const {
128 const_reference front() const {
135 const_reference back() const {
139 void push_back(const_reference Elt) {
140 if (End < Capacity) {
156 destroy_range(Begin, End);
160 void resize(unsigned N) {
162 destroy_range(Begin+N, End);
164 } else if (N > size()) {
165 if (unsigned(Capacity-Begin) < N)
167 construct_range(End, Begin+N, T());
172 void resize(unsigned N, const T &NV) {
174 destroy_range(Begin+N, End);
176 } else if (N > size()) {
177 if (unsigned(Capacity-Begin) < N)
179 construct_range(End, Begin+N, NV);
184 void reserve(unsigned N) {
185 if (unsigned(Capacity-Begin) < N)
189 void swap(SmallVectorImpl &RHS);
191 /// append - Add the specified range to the end of the SmallVector.
193 template<typename in_iter>
194 void append(in_iter in_start, in_iter in_end) {
195 size_type NumInputs = std::distance(in_start, in_end);
196 // Grow allocated space if needed.
197 if (End+NumInputs > Capacity)
198 grow(size()+NumInputs);
200 // Copy the new elements over.
201 std::uninitialized_copy(in_start, in_end, End);
205 void assign(unsigned NumElts, const T &Elt) {
207 if (unsigned(Capacity-Begin) < NumElts)
210 construct_range(Begin, End, Elt);
213 iterator erase(iterator I) {
215 // Shift all elts down one.
216 std::copy(I+1, End, I);
217 // Drop the last elt.
222 iterator erase(iterator S, iterator E) {
224 // Shift all elts down.
225 iterator I = std::copy(E, End, S);
226 // Drop the last elts.
227 destroy_range(I, End);
232 iterator insert(iterator I, const T &Elt) {
233 if (I == End) { // Important special case for empty vector.
238 if (End < Capacity) {
242 // Push everything else over.
243 std::copy_backward(I, End-1, End);
247 size_t EltNo = I-Begin;
253 template<typename ItTy>
254 iterator insert(iterator I, ItTy From, ItTy To) {
255 if (I == End) { // Important special case for empty vector.
260 size_t NumToInsert = std::distance(From, To);
261 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
262 size_t InsertElt = I-begin();
264 // Ensure there is enough space.
265 reserve(static_cast<unsigned>(size() + NumToInsert));
267 // Uninvalidate the iterator.
268 I = begin()+InsertElt;
270 // If we already have this many elements in the collection, append the
271 // dest elements at the end, then copy over the appropriate elements. Since
272 // we already reserved space, we know that this won't reallocate the vector.
273 if (size() >= NumToInsert) {
275 append(End-NumToInsert, End);
277 // Copy the existing elements that get replaced.
278 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
280 std::copy(From, To, I);
284 // Otherwise, we're inserting more elements than exist already, and we're
285 // not inserting at the end.
287 // Copy over the elements that we're about to overwrite.
290 size_t NumOverwritten = OldEnd-I;
291 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
293 // Replace the overwritten part.
294 std::copy(From, From+NumOverwritten, I);
296 // Insert the non-overwritten middle part.
297 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
301 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
303 bool operator==(const SmallVectorImpl &RHS) const {
304 if (size() != RHS.size()) return false;
305 for (T *This = Begin, *That = RHS.Begin, *E = Begin+size();
306 This != E; ++This, ++That)
311 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
313 bool operator<(const SmallVectorImpl &RHS) const {
314 return std::lexicographical_compare(begin(), end(),
315 RHS.begin(), RHS.end());
319 /// isSmall - Return true if this is a smallvector which has not had dynamic
320 /// memory allocated for it.
321 bool isSmall() const {
322 return static_cast<const void*>(Begin) ==
323 static_cast<const void*>(&FirstEl);
326 /// grow - double the size of the allocated memory, guaranteeing space for at
327 /// least one more element or MinSize if specified.
328 void grow(size_type MinSize = 0);
330 void construct_range(T *S, T *E, const T &Elt) {
335 void destroy_range(T *S, T *E) {
343 // Define this out-of-line to dissuade the C++ compiler from inlining it.
344 template <typename T>
345 void SmallVectorImpl<T>::grow(size_t MinSize) {
346 size_t CurCapacity = Capacity-Begin;
347 size_t CurSize = size();
348 size_t NewCapacity = 2*CurCapacity;
349 if (NewCapacity < MinSize)
350 NewCapacity = MinSize;
351 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
353 // Copy the elements over.
354 if (is_class<T>::value)
355 std::uninitialized_copy(Begin, End, NewElts);
357 // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
358 memcpy(NewElts, Begin, CurSize * sizeof(T));
360 // Destroy the original elements.
361 destroy_range(Begin, End);
363 // If this wasn't grown from the inline copy, deallocate the old space.
365 operator delete(Begin);
368 End = NewElts+CurSize;
369 Capacity = Begin+NewCapacity;
372 template <typename T>
373 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
374 if (this == &RHS) return;
376 // We can only avoid copying elements if neither vector is small.
377 if (!isSmall() && !RHS.isSmall()) {
378 std::swap(Begin, RHS.Begin);
379 std::swap(End, RHS.End);
380 std::swap(Capacity, RHS.Capacity);
383 if (Begin+RHS.size() > Capacity)
385 if (RHS.begin()+size() > RHS.Capacity)
388 // Swap the shared elements.
389 size_t NumShared = size();
390 if (NumShared > RHS.size()) NumShared = RHS.size();
391 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
392 std::swap(Begin[i], RHS[i]);
394 // Copy over the extra elts.
395 if (size() > RHS.size()) {
396 size_t EltDiff = size() - RHS.size();
397 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
399 destroy_range(Begin+NumShared, End);
400 End = Begin+NumShared;
401 } else if (RHS.size() > size()) {
402 size_t EltDiff = RHS.size() - size();
403 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
405 destroy_range(RHS.Begin+NumShared, RHS.End);
406 RHS.End = RHS.Begin+NumShared;
410 template <typename T>
411 const SmallVectorImpl<T> &
412 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
413 // Avoid self-assignment.
414 if (this == &RHS) return *this;
416 // If we already have sufficient space, assign the common elements, then
417 // destroy any excess.
418 unsigned RHSSize = unsigned(RHS.size());
419 unsigned CurSize = unsigned(size());
420 if (CurSize >= RHSSize) {
421 // Assign common elements.
424 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
428 // Destroy excess elements.
429 destroy_range(NewEnd, End);
436 // If we have to grow to have enough elements, destroy the current elements.
437 // This allows us to avoid copying them during the grow.
438 if (unsigned(Capacity-Begin) < RHSSize) {
439 // Destroy current elements.
440 destroy_range(Begin, End);
444 } else if (CurSize) {
445 // Otherwise, use assignment for the already-constructed elements.
446 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
449 // Copy construct the new elements in place.
450 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
457 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
458 /// for the case when the array is small. It contains some number of elements
459 /// in-place, which allows it to avoid heap allocation when the actual number of
460 /// elements is below that threshold. This allows normal "small" cases to be
461 /// fast without losing generality for large inputs.
463 /// Note that this does not attempt to be exception safe.
465 template <typename T, unsigned N>
466 class SmallVector : public SmallVectorImpl<T> {
467 /// InlineElts - These are 'N-1' elements that are stored inline in the body
468 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
469 typedef typename SmallVectorImpl<T>::U U;
471 // MinUs - The number of U's require to cover N T's.
472 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
473 static_cast<unsigned int>(sizeof(U)) - 1) /
474 static_cast<unsigned int>(sizeof(U)),
476 // NumInlineEltsElts - The number of elements actually in this array. There
477 // is already one in the parent class, and we have to round up to avoid
478 // having a zero-element array.
479 NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
481 // NumTsAvailable - The number of T's we actually have space for, which may
482 // be more than N due to rounding.
483 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
484 static_cast<unsigned int>(sizeof(T))
486 U InlineElts[NumInlineEltsElts];
488 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
491 explicit SmallVector(unsigned Size, const T &Value = T())
492 : SmallVectorImpl<T>(NumTsAvailable) {
498 template<typename ItTy>
499 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
503 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
508 const SmallVector &operator=(const SmallVector &RHS) {
509 SmallVectorImpl<T>::operator=(RHS);
515 } // End llvm namespace
518 /// Implement std::swap in terms of SmallVector swap.
521 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
525 /// Implement std::swap in terms of SmallVector swap.
526 template<typename T, unsigned N>
528 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {