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"
25 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
26 // additional overloads so that elements with pointer types are recognized as
27 // scalars and not objects, causing bizarre type conversion errors.
28 template<class T1, class T2>
29 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
30 _Scalar_ptr_iterator_tag _Cat;
34 template<class T1, class T2>
35 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
36 _Scalar_ptr_iterator_tag _Cat;
40 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
41 // is that the above hack won't work if it wasn't fixed.
48 /// SmallVectorImpl - This class consists of common code factored out of the
49 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
50 /// template parameter.
52 class SmallVectorImpl {
54 T *Begin, *End, *Capacity;
56 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
57 // don't want it to be automatically run, so we need to represent the space as
58 // something else. An array of char would work great, but might not be
59 // aligned sufficiently. Instead, we either use GCC extensions, or some
60 // number of union instances for the space, which guarantee maximal alignment.
64 U FirstEl __attribute__((aligned));
73 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
75 // Default ctor - Initialize to empty.
76 SmallVectorImpl(unsigned N)
77 : Begin(reinterpret_cast<T*>(&FirstEl)),
78 End(reinterpret_cast<T*>(&FirstEl)),
79 Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
83 // Destroy the constructed elements in the vector.
84 destroy_range(Begin, End);
86 // If this wasn't grown from the inline copy, deallocate the old space.
88 operator delete(static_cast<void*>(Begin));
91 typedef size_t size_type;
93 typedef const T* const_iterator;
95 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
96 typedef std::reverse_iterator<iterator> reverse_iterator;
99 typedef const T& const_reference;
101 bool empty() const { return Begin == End; }
102 size_type size() const { return End-Begin; }
104 // forward iterator creation methods.
105 iterator begin() { return Begin; }
106 const_iterator begin() const { return Begin; }
107 iterator end() { return End; }
108 const_iterator end() const { return End; }
110 // reverse iterator creation methods.
111 reverse_iterator rbegin() { return reverse_iterator(end()); }
112 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
113 reverse_iterator rend() { return reverse_iterator(begin()); }
114 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
117 reference operator[](unsigned idx) {
120 const_reference operator[](unsigned idx) const {
127 const_reference front() const {
134 const_reference back() const {
138 void push_back(const_reference Elt) {
139 if (End < Capacity) {
155 destroy_range(Begin, End);
159 void resize(unsigned N) {
161 destroy_range(Begin+N, End);
163 } else if (N > size()) {
164 if (unsigned(Capacity-Begin) < N)
166 construct_range(End, Begin+N, T());
171 void resize(unsigned N, const T &NV) {
173 destroy_range(Begin+N, End);
175 } else if (N > size()) {
176 if (unsigned(Capacity-Begin) < N)
178 construct_range(End, Begin+N, NV);
183 void reserve(unsigned N) {
184 if (unsigned(Capacity-Begin) < N)
188 void swap(SmallVectorImpl &RHS);
190 /// append - Add the specified range to the end of the SmallVector.
192 template<typename in_iter>
193 void append(in_iter in_start, in_iter in_end) {
194 size_type NumInputs = std::distance(in_start, in_end);
195 // Grow allocated space if needed.
196 if (End+NumInputs > Capacity)
197 grow(size()+NumInputs);
199 // Copy the new elements over.
200 std::uninitialized_copy(in_start, in_end, End);
204 void assign(unsigned NumElts, const T &Elt) {
206 if (unsigned(Capacity-Begin) < NumElts)
209 construct_range(Begin, End, Elt);
212 iterator erase(iterator I) {
214 // Shift all elts down one.
215 std::copy(I+1, End, I);
216 // Drop the last elt.
221 iterator erase(iterator S, iterator E) {
223 // Shift all elts down.
224 iterator I = std::copy(E, End, S);
225 // Drop the last elts.
226 destroy_range(I, End);
231 iterator insert(iterator I, const T &Elt) {
232 if (I == End) { // Important special case for empty vector.
237 if (End < Capacity) {
241 // Push everything else over.
242 std::copy_backward(I, End-1, End);
246 size_t EltNo = I-Begin;
252 template<typename ItTy>
253 iterator insert(iterator I, ItTy From, ItTy To) {
254 if (I == End) { // Important special case for empty vector.
259 size_t NumToInsert = std::distance(From, To);
260 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
261 size_t InsertElt = I-begin();
263 // Ensure there is enough space.
264 reserve(static_cast<unsigned>(size() + NumToInsert));
266 // Uninvalidate the iterator.
267 I = begin()+InsertElt;
269 // If we already have this many elements in the collection, append the
270 // dest elements at the end, then copy over the appropriate elements. Since
271 // we already reserved space, we know that this won't reallocate the vector.
272 if (size() >= NumToInsert) {
274 append(End-NumToInsert, End);
276 // Copy the existing elements that get replaced.
277 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
279 std::copy(From, To, I);
283 // Otherwise, we're inserting more elements than exist already, and we're
284 // not inserting at the end.
286 // Copy over the elements that we're about to overwrite.
289 size_t NumOverwritten = OldEnd-I;
290 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
292 // Replace the overwritten part.
293 std::copy(From, From+NumOverwritten, I);
295 // Insert the non-overwritten middle part.
296 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
300 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
302 bool operator==(const SmallVectorImpl &RHS) const {
303 if (size() != RHS.size()) return false;
304 for (T *This = Begin, *That = RHS.Begin, *E = Begin+size();
305 This != E; ++This, ++That)
310 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
312 bool operator<(const SmallVectorImpl &RHS) const {
313 return std::lexicographical_compare(begin(), end(),
314 RHS.begin(), RHS.end());
318 /// isSmall - Return true if this is a smallvector which has not had dynamic
319 /// memory allocated for it.
320 bool isSmall() const {
321 return static_cast<const void*>(Begin) ==
322 static_cast<const void*>(&FirstEl);
325 /// grow - double the size of the allocated memory, guaranteeing space for at
326 /// least one more element or MinSize if specified.
327 void grow(size_type MinSize = 0);
329 void construct_range(T *S, T *E, const T &Elt) {
334 void destroy_range(T *S, T *E) {
342 // Define this out-of-line to dissuade the C++ compiler from inlining it.
343 template <typename T>
344 void SmallVectorImpl<T>::grow(size_t MinSize) {
345 size_t CurCapacity = Capacity-Begin;
346 size_t CurSize = size();
347 size_t NewCapacity = 2*CurCapacity;
348 if (NewCapacity < MinSize)
349 NewCapacity = MinSize;
350 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
352 // Copy the elements over.
353 if (is_class<T>::value)
354 std::uninitialized_copy(Begin, End, NewElts);
356 // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
357 memcpy(NewElts, Begin, CurSize * sizeof(T));
359 // Destroy the original elements.
360 destroy_range(Begin, End);
362 // If this wasn't grown from the inline copy, deallocate the old space.
364 operator delete(static_cast<void*>(Begin));
367 End = NewElts+CurSize;
368 Capacity = Begin+NewCapacity;
371 template <typename T>
372 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
373 if (this == &RHS) return;
375 // We can only avoid copying elements if neither vector is small.
376 if (!isSmall() && !RHS.isSmall()) {
377 std::swap(Begin, RHS.Begin);
378 std::swap(End, RHS.End);
379 std::swap(Capacity, RHS.Capacity);
382 if (Begin+RHS.size() > Capacity)
384 if (RHS.begin()+size() > RHS.Capacity)
387 // Swap the shared elements.
388 size_t NumShared = size();
389 if (NumShared > RHS.size()) NumShared = RHS.size();
390 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
391 std::swap(Begin[i], RHS[i]);
393 // Copy over the extra elts.
394 if (size() > RHS.size()) {
395 size_t EltDiff = size() - RHS.size();
396 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
398 destroy_range(Begin+NumShared, End);
399 End = Begin+NumShared;
400 } else if (RHS.size() > size()) {
401 size_t EltDiff = RHS.size() - size();
402 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
404 destroy_range(RHS.Begin+NumShared, RHS.End);
405 RHS.End = RHS.Begin+NumShared;
409 template <typename T>
410 const SmallVectorImpl<T> &
411 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
412 // Avoid self-assignment.
413 if (this == &RHS) return *this;
415 // If we already have sufficient space, assign the common elements, then
416 // destroy any excess.
417 unsigned RHSSize = unsigned(RHS.size());
418 unsigned CurSize = unsigned(size());
419 if (CurSize >= RHSSize) {
420 // Assign common elements.
423 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
427 // Destroy excess elements.
428 destroy_range(NewEnd, End);
435 // If we have to grow to have enough elements, destroy the current elements.
436 // This allows us to avoid copying them during the grow.
437 if (unsigned(Capacity-Begin) < RHSSize) {
438 // Destroy current elements.
439 destroy_range(Begin, End);
443 } else if (CurSize) {
444 // Otherwise, use assignment for the already-constructed elements.
445 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
448 // Copy construct the new elements in place.
449 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
456 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
457 /// for the case when the array is small. It contains some number of elements
458 /// in-place, which allows it to avoid heap allocation when the actual number of
459 /// elements is below that threshold. This allows normal "small" cases to be
460 /// fast without losing generality for large inputs.
462 /// Note that this does not attempt to be exception safe.
464 template <typename T, unsigned N>
465 class SmallVector : public SmallVectorImpl<T> {
466 /// InlineElts - These are 'N-1' elements that are stored inline in the body
467 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
468 typedef typename SmallVectorImpl<T>::U U;
470 // MinUs - The number of U's require to cover N T's.
471 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
472 static_cast<unsigned int>(sizeof(U)) - 1) /
473 static_cast<unsigned int>(sizeof(U)),
475 // NumInlineEltsElts - The number of elements actually in this array. There
476 // is already one in the parent class, and we have to round up to avoid
477 // having a zero-element array.
478 NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
480 // NumTsAvailable - The number of T's we actually have space for, which may
481 // be more than N due to rounding.
482 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
483 static_cast<unsigned int>(sizeof(T))
485 U InlineElts[NumInlineEltsElts];
487 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
490 explicit SmallVector(unsigned Size, const T &Value = T())
491 : SmallVectorImpl<T>(NumTsAvailable) {
497 template<typename ItTy>
498 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
502 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
507 const SmallVector &operator=(const SmallVector &RHS) {
508 SmallVectorImpl<T>::operator=(RHS);
514 } // End llvm namespace
517 /// Implement std::swap in terms of SmallVector swap.
520 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
524 /// Implement std::swap in terms of SmallVector swap.
525 template<typename T, unsigned N>
527 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {