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"
27 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
28 // additional overloads so that elements with pointer types are recognized as
29 // scalars and not objects, causing bizarre type conversion errors.
30 template<class T1, class T2>
31 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
32 _Scalar_ptr_iterator_tag _Cat;
36 template<class T1, class T2>
37 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
38 _Scalar_ptr_iterator_tag _Cat;
42 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
43 // is that the above hack won't work if it wasn't fixed.
50 /// SmallVectorImpl - This class consists of common code factored out of the
51 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
52 /// template parameter.
54 class SmallVectorImpl {
56 T *Begin, *End, *Capacity;
58 // Allocate raw space for N elements of type T. If T has a ctor or dtor, we
59 // don't want it to be automatically run, so we need to represent the space as
60 // something else. An array of char would work great, but might not be
61 // aligned sufficiently. Instead, we either use GCC extensions, or some
62 // number of union instances for the space, which guarantee maximal alignment.
66 U FirstEl __attribute__((aligned));
75 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
77 // Default ctor - Initialize to empty.
78 explicit SmallVectorImpl(unsigned N)
79 : Begin(reinterpret_cast<T*>(&FirstEl)),
80 End(reinterpret_cast<T*>(&FirstEl)),
81 Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
85 // Destroy the constructed elements in the vector.
86 destroy_range(Begin, End);
88 // If this wasn't grown from the inline copy, deallocate the old space.
90 operator delete(Begin);
93 typedef size_t size_type;
94 typedef ptrdiff_t difference_type;
97 typedef const T* const_iterator;
99 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
100 typedef std::reverse_iterator<iterator> reverse_iterator;
102 typedef T& reference;
103 typedef const T& const_reference;
105 typedef const T* const_pointer;
107 bool empty() const { return Begin == End; }
108 size_type size() const { return End-Begin; }
109 size_type max_size() const { return size_type(-1) / sizeof(T); }
111 // forward iterator creation methods.
112 iterator begin() { return Begin; }
113 const_iterator begin() const { return Begin; }
114 iterator end() { return End; }
115 const_iterator end() const { return End; }
117 // reverse iterator creation methods.
118 reverse_iterator rbegin() { return reverse_iterator(end()); }
119 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
120 reverse_iterator rend() { return reverse_iterator(begin()); }
121 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
124 /* These asserts could be "Begin + idx < End", but there are lots of places
125 in llvm where we use &v[v.size()] instead of v.end(). */
126 reference operator[](unsigned idx) {
127 assert (Begin + idx <= End);
130 const_reference operator[](unsigned idx) const {
131 assert (Begin + idx <= End);
138 const_reference front() const {
145 const_reference back() const {
149 void push_back(const_reference Elt) {
150 if (End < Capacity) {
172 destroy_range(Begin, End);
176 void resize(unsigned N) {
178 destroy_range(Begin+N, End);
180 } else if (N > size()) {
181 if (unsigned(Capacity-Begin) < N)
183 construct_range(End, Begin+N, T());
188 void resize(unsigned N, const T &NV) {
190 destroy_range(Begin+N, End);
192 } else if (N > size()) {
193 if (unsigned(Capacity-Begin) < N)
195 construct_range(End, Begin+N, NV);
200 void reserve(unsigned N) {
201 if (unsigned(Capacity-Begin) < N)
205 void swap(SmallVectorImpl &RHS);
207 /// append - Add the specified range to the end of the SmallVector.
209 template<typename in_iter>
210 void append(in_iter in_start, in_iter in_end) {
211 size_type NumInputs = std::distance(in_start, in_end);
212 // Grow allocated space if needed.
213 if (End+NumInputs > Capacity)
214 grow(size()+NumInputs);
216 // Copy the new elements over.
217 std::uninitialized_copy(in_start, in_end, End);
221 /// append - Add the specified range to the end of the SmallVector.
223 void append(size_type NumInputs, const T &Elt) {
224 // Grow allocated space if needed.
225 if (End+NumInputs > Capacity)
226 grow(size()+NumInputs);
228 // Copy the new elements over.
229 std::uninitialized_fill_n(End, NumInputs, Elt);
233 void assign(unsigned NumElts, const T &Elt) {
235 if (unsigned(Capacity-Begin) < NumElts)
238 construct_range(Begin, End, Elt);
241 iterator erase(iterator I) {
243 // Shift all elts down one.
244 std::copy(I+1, End, I);
245 // Drop the last elt.
250 iterator erase(iterator S, iterator E) {
252 // Shift all elts down.
253 iterator I = std::copy(E, End, S);
254 // Drop the last elts.
255 destroy_range(I, End);
260 iterator insert(iterator I, const T &Elt) {
261 if (I == End) { // Important special case for empty vector.
266 if (End < Capacity) {
270 // Push everything else over.
271 std::copy_backward(I, End-1, End);
275 size_t EltNo = I-Begin;
281 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
282 if (I == End) { // Important special case for empty vector.
283 append(NumToInsert, Elt);
287 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
288 size_t InsertElt = I-begin();
290 // Ensure there is enough space.
291 reserve(static_cast<unsigned>(size() + NumToInsert));
293 // Uninvalidate the iterator.
294 I = begin()+InsertElt;
296 // If we already have this many elements in the collection, append the
297 // dest elements at the end, then copy over the appropriate elements. Since
298 // we already reserved space, we know that this won't reallocate the vector.
299 if (size() >= NumToInsert) {
301 append(End-NumToInsert, End);
303 // Copy the existing elements that get replaced.
304 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
306 std::fill_n(I, NumToInsert, Elt);
310 // Otherwise, we're inserting more elements than exist already, and we're
311 // not inserting at the end.
313 // Copy over the elements that we're about to overwrite.
316 size_t NumOverwritten = OldEnd-I;
317 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
319 // Replace the overwritten part.
320 std::fill_n(I, NumOverwritten, Elt);
322 // Insert the non-overwritten middle part.
323 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
327 template<typename ItTy>
328 iterator insert(iterator I, ItTy From, ItTy To) {
329 if (I == End) { // Important special case for empty vector.
334 size_t NumToInsert = std::distance(From, To);
335 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
336 size_t InsertElt = I-begin();
338 // Ensure there is enough space.
339 reserve(static_cast<unsigned>(size() + NumToInsert));
341 // Uninvalidate the iterator.
342 I = begin()+InsertElt;
344 // If we already have this many elements in the collection, append the
345 // dest elements at the end, then copy over the appropriate elements. Since
346 // we already reserved space, we know that this won't reallocate the vector.
347 if (size() >= NumToInsert) {
349 append(End-NumToInsert, End);
351 // Copy the existing elements that get replaced.
352 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
354 std::copy(From, To, I);
358 // Otherwise, we're inserting more elements than exist already, and we're
359 // not inserting at the end.
361 // Copy over the elements that we're about to overwrite.
364 size_t NumOverwritten = OldEnd-I;
365 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
367 // Replace the overwritten part.
368 std::copy(From, From+NumOverwritten, I);
370 // Insert the non-overwritten middle part.
371 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
375 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
377 bool operator==(const SmallVectorImpl &RHS) const {
378 if (size() != RHS.size()) return false;
379 for (T *This = Begin, *That = RHS.Begin, *E = Begin+size();
380 This != E; ++This, ++That)
385 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
387 bool operator<(const SmallVectorImpl &RHS) const {
388 return std::lexicographical_compare(begin(), end(),
389 RHS.begin(), RHS.end());
393 /// isSmall - Return true if this is a smallvector which has not had dynamic
394 /// memory allocated for it.
395 bool isSmall() const {
396 return static_cast<const void*>(Begin) ==
397 static_cast<const void*>(&FirstEl);
400 /// grow - double the size of the allocated memory, guaranteeing space for at
401 /// least one more element or MinSize if specified.
402 void grow(size_type MinSize = 0);
404 void construct_range(T *S, T *E, const T &Elt) {
409 void destroy_range(T *S, T *E) {
417 // Define this out-of-line to dissuade the C++ compiler from inlining it.
418 template <typename T>
419 void SmallVectorImpl<T>::grow(size_t MinSize) {
420 size_t CurCapacity = Capacity-Begin;
421 size_t CurSize = size();
422 size_t NewCapacity = 2*CurCapacity;
423 if (NewCapacity < MinSize)
424 NewCapacity = MinSize;
425 T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
427 // Copy the elements over.
428 if (is_class<T>::value)
429 std::uninitialized_copy(Begin, End, NewElts);
431 // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
432 memcpy(NewElts, Begin, CurSize * sizeof(T));
434 // Destroy the original elements.
435 destroy_range(Begin, End);
437 // If this wasn't grown from the inline copy, deallocate the old space.
439 operator delete(Begin);
442 End = NewElts+CurSize;
443 Capacity = Begin+NewCapacity;
446 template <typename T>
447 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
448 if (this == &RHS) return;
450 // We can only avoid copying elements if neither vector is small.
451 if (!isSmall() && !RHS.isSmall()) {
452 std::swap(Begin, RHS.Begin);
453 std::swap(End, RHS.End);
454 std::swap(Capacity, RHS.Capacity);
457 if (Begin+RHS.size() > Capacity)
459 if (RHS.begin()+size() > RHS.Capacity)
462 // Swap the shared elements.
463 size_t NumShared = size();
464 if (NumShared > RHS.size()) NumShared = RHS.size();
465 for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
466 std::swap(Begin[i], RHS[i]);
468 // Copy over the extra elts.
469 if (size() > RHS.size()) {
470 size_t EltDiff = size() - RHS.size();
471 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
473 destroy_range(Begin+NumShared, End);
474 End = Begin+NumShared;
475 } else if (RHS.size() > size()) {
476 size_t EltDiff = RHS.size() - size();
477 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
479 destroy_range(RHS.Begin+NumShared, RHS.End);
480 RHS.End = RHS.Begin+NumShared;
484 template <typename T>
485 const SmallVectorImpl<T> &
486 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
487 // Avoid self-assignment.
488 if (this == &RHS) return *this;
490 // If we already have sufficient space, assign the common elements, then
491 // destroy any excess.
492 unsigned RHSSize = unsigned(RHS.size());
493 unsigned CurSize = unsigned(size());
494 if (CurSize >= RHSSize) {
495 // Assign common elements.
498 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
502 // Destroy excess elements.
503 destroy_range(NewEnd, End);
510 // If we have to grow to have enough elements, destroy the current elements.
511 // This allows us to avoid copying them during the grow.
512 if (unsigned(Capacity-Begin) < RHSSize) {
513 // Destroy current elements.
514 destroy_range(Begin, End);
518 } else if (CurSize) {
519 // Otherwise, use assignment for the already-constructed elements.
520 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
523 // Copy construct the new elements in place.
524 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
531 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
532 /// for the case when the array is small. It contains some number of elements
533 /// in-place, which allows it to avoid heap allocation when the actual number of
534 /// elements is below that threshold. This allows normal "small" cases to be
535 /// fast without losing generality for large inputs.
537 /// Note that this does not attempt to be exception safe.
539 template <typename T, unsigned N>
540 class SmallVector : public SmallVectorImpl<T> {
541 /// InlineElts - These are 'N-1' elements that are stored inline in the body
542 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
543 typedef typename SmallVectorImpl<T>::U U;
545 // MinUs - The number of U's require to cover N T's.
546 MinUs = (static_cast<unsigned int>(sizeof(T))*N +
547 static_cast<unsigned int>(sizeof(U)) - 1) /
548 static_cast<unsigned int>(sizeof(U)),
550 // NumInlineEltsElts - The number of elements actually in this array. There
551 // is already one in the parent class, and we have to round up to avoid
552 // having a zero-element array.
553 NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
555 // NumTsAvailable - The number of T's we actually have space for, which may
556 // be more than N due to rounding.
557 NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
558 static_cast<unsigned int>(sizeof(T))
560 U InlineElts[NumInlineEltsElts];
562 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
565 explicit SmallVector(unsigned Size, const T &Value = T())
566 : SmallVectorImpl<T>(NumTsAvailable) {
569 this->push_back(Value);
572 template<typename ItTy>
573 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
577 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
579 SmallVectorImpl<T>::operator=(RHS);
582 const SmallVector &operator=(const SmallVector &RHS) {
583 SmallVectorImpl<T>::operator=(RHS);
589 } // End llvm namespace
592 /// Implement std::swap in terms of SmallVector swap.
595 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
599 /// Implement std::swap in terms of SmallVector swap.
600 template<typename T, unsigned N>
602 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {