1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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
24 // Work around flawed VC++ implementation of std::uninitialized_copy. Define
25 // additional overloads so that elements with pointer types are recognized as
26 // scalars and not objects, causing bizarre type conversion errors.
27 template<class T1, class T2>
28 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
29 _Scalar_ptr_iterator_tag _Cat;
33 template<class T1, class T2>
34 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
35 _Scalar_ptr_iterator_tag _Cat;
39 // FIXME: It is not clear if the problem is fixed in VS 2005. What is clear
40 // is that the above hack won't work if it wasn't fixed.
47 /// SmallVectorImpl - This class consists of common code factored out of the
48 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
49 /// template parameter.
51 class SmallVectorImpl {
53 T *Begin, *End, *Capacity;
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.
63 U FirstEl __attribute__((aligned));
72 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
74 // Default ctor - Initialize to empty.
75 SmallVectorImpl(unsigned N)
76 : Begin(reinterpret_cast<T*>(&FirstEl)),
77 End(reinterpret_cast<T*>(&FirstEl)),
78 Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
82 // Destroy the constructed elements in the vector.
83 destroy_range(Begin, End);
85 // If this wasn't grown from the inline copy, deallocate the old space.
87 delete[] reinterpret_cast<char*>(Begin);
90 typedef size_t size_type;
92 typedef const T* const_iterator;
94 typedef const T& const_reference;
96 bool empty() const { return Begin == End; }
97 size_type size() const { return End-Begin; }
99 iterator begin() { return Begin; }
100 const_iterator begin() const { return Begin; }
102 iterator end() { return End; }
103 const_iterator end() const { return End; }
105 reference operator[](unsigned idx) {
108 const_reference operator[](unsigned idx) const {
115 const_reference front() const {
122 const_reference back() const {
126 void push_back(const_reference Elt) {
127 if (End < Capacity) {
143 destroy_range(Begin, End);
147 void resize(unsigned N) {
149 destroy_range(Begin+N, End);
151 } else if (N > size()) {
152 if (unsigned(Capacity-Begin) < N)
154 construct_range(End, Begin+N, T());
159 void resize(unsigned N, const T &NV) {
161 destroy_range(Begin+N, End);
163 } else if (N > size()) {
164 if (unsigned(Capacity-Begin) < N)
166 construct_range(End, Begin+N, NV);
171 void reserve(unsigned N) {
172 if (unsigned(Capacity-Begin) < N)
176 void swap(SmallVectorImpl &RHS);
178 /// append - Add the specified range to the end of the SmallVector.
180 template<typename in_iter>
181 void append(in_iter in_start, in_iter in_end) {
182 unsigned NumInputs = std::distance(in_start, in_end);
183 // Grow allocated space if needed.
184 if (End+NumInputs > Capacity)
185 grow(size()+NumInputs);
187 // Copy the new elements over.
188 std::uninitialized_copy(in_start, in_end, End);
192 void assign(unsigned NumElts, const T &Elt) {
194 if (unsigned(Capacity-Begin) < NumElts)
197 construct_range(Begin, End, Elt);
200 void erase(iterator I) {
201 // Shift all elts down one.
202 std::copy(I+1, End, I);
203 // Drop the last elt.
207 void erase(iterator S, iterator E) {
208 // Shift all elts down.
209 iterator I = std::copy(E, End, S);
210 // Drop the last elts.
211 destroy_range(I, End);
215 iterator insert(iterator I, const T &Elt) {
216 if (I == End) { // Important special case for empty vector.
221 if (End < Capacity) {
225 // Push everything else over.
226 std::copy_backward(I, End-1, End);
230 unsigned EltNo = I-Begin;
236 template<typename ItTy>
237 iterator insert(iterator I, ItTy From, ItTy To) {
238 if (I == End) { // Important special case for empty vector.
243 unsigned NumToInsert = std::distance(From, To);
244 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
245 unsigned InsertElt = I-begin();
247 // Ensure there is enough space.
248 reserve(size() + NumToInsert);
250 // Uninvalidate the iterator.
251 I = begin()+InsertElt;
253 // If we already have this many elements in the collection, append the
254 // dest elements at the end, then copy over the appropriate elements. Since
255 // we already reserved space, we know that this won't reallocate the vector.
256 if (size() >= NumToInsert) {
258 append(End-NumToInsert, End);
260 // Copy the existing elements that get replaced.
261 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
263 std::copy(From, To, I);
267 // Otherwise, we're inserting more elements than exist already, and we're
268 // not inserting at the end.
270 // Copy over the elements that we're about to overwrite.
273 unsigned NumOverwritten = OldEnd-I;
274 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
276 // Replace the overwritten part.
277 std::copy(From, From+NumOverwritten, I);
279 // Insert the non-overwritten middle part.
280 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
284 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
287 /// isSmall - Return true if this is a smallvector which has not had dynamic
288 /// memory allocated for it.
289 bool isSmall() const {
290 return reinterpret_cast<const void*>(Begin) ==
291 reinterpret_cast<const void*>(&FirstEl);
294 /// grow - double the size of the allocated memory, guaranteeing space for at
295 /// least one more element or MinSize if specified.
296 void grow(unsigned MinSize = 0);
298 void construct_range(T *S, T *E, const T &Elt) {
303 void destroy_range(T *S, T *E) {
311 // Define this out-of-line to dissuade the C++ compiler from inlining it.
312 template <typename T>
313 void SmallVectorImpl<T>::grow(unsigned MinSize) {
314 unsigned CurCapacity = unsigned(Capacity-Begin);
315 unsigned CurSize = unsigned(size());
316 unsigned NewCapacity = 2*CurCapacity;
317 if (NewCapacity < MinSize)
318 NewCapacity = MinSize;
319 T *NewElts = reinterpret_cast<T*>(new char[NewCapacity*sizeof(T)]);
321 // Copy the elements over.
322 std::uninitialized_copy(Begin, End, NewElts);
324 // Destroy the original elements.
325 destroy_range(Begin, End);
327 // If this wasn't grown from the inline copy, deallocate the old space.
329 delete[] reinterpret_cast<char*>(Begin);
332 End = NewElts+CurSize;
333 Capacity = Begin+NewCapacity;
336 template <typename T>
337 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
338 if (this == &RHS) return;
340 // We can only avoid copying elements if neither vector is small.
341 if (!isSmall() && !RHS.isSmall()) {
342 std::swap(Begin, RHS.Begin);
343 std::swap(End, RHS.End);
344 std::swap(Capacity, RHS.Capacity);
347 if (Begin+RHS.size() > Capacity)
349 if (RHS.begin()+size() > RHS.Capacity)
352 // Swap the shared elements.
353 unsigned NumShared = size();
354 if (NumShared > RHS.size()) NumShared = RHS.size();
355 for (unsigned i = 0; i != NumShared; ++i)
356 std::swap(Begin[i], RHS[i]);
358 // Copy over the extra elts.
359 if (size() > RHS.size()) {
360 unsigned EltDiff = size() - RHS.size();
361 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
363 destroy_range(Begin+NumShared, End);
364 End = Begin+NumShared;
365 } else if (RHS.size() > size()) {
366 unsigned EltDiff = RHS.size() - size();
367 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
369 destroy_range(RHS.Begin+NumShared, RHS.End);
370 RHS.End = RHS.Begin+NumShared;
374 template <typename T>
375 const SmallVectorImpl<T> &
376 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
377 // Avoid self-assignment.
378 if (this == &RHS) return *this;
380 // If we already have sufficient space, assign the common elements, then
381 // destroy any excess.
382 unsigned RHSSize = unsigned(RHS.size());
383 unsigned CurSize = unsigned(size());
384 if (CurSize >= RHSSize) {
385 // Assign common elements.
388 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
392 // Destroy excess elements.
393 destroy_range(NewEnd, End);
400 // If we have to grow to have enough elements, destroy the current elements.
401 // This allows us to avoid copying them during the grow.
402 if (unsigned(Capacity-Begin) < RHSSize) {
403 // Destroy current elements.
404 destroy_range(Begin, End);
408 } else if (CurSize) {
409 // Otherwise, use assignment for the already-constructed elements.
410 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
413 // Copy construct the new elements in place.
414 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
421 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
422 /// for the case when the array is small. It contains some number of elements
423 /// in-place, which allows it to avoid heap allocation when the actual number of
424 /// elements is below that threshold. This allows normal "small" cases to be
425 /// fast without losing generality for large inputs.
427 /// Note that this does not attempt to be exception safe.
429 template <typename T, unsigned N>
430 class SmallVector : public SmallVectorImpl<T> {
431 /// InlineElts - These are 'N-1' elements that are stored inline in the body
432 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
433 typedef typename SmallVectorImpl<T>::U U;
435 // MinUs - The number of U's require to cover N T's.
436 MinUs = (sizeof(T)*N+sizeof(U)-1)/sizeof(U),
438 // NumInlineEltsElts - The number of elements actually in this array. There
439 // is already one in the parent class, and we have to round up to avoid
440 // having a zero-element array.
441 NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
443 // NumTsAvailable - The number of T's we actually have space for, which may
444 // be more than N due to rounding.
445 NumTsAvailable = (NumInlineEltsElts+1)*sizeof(U) / sizeof(T)
447 U InlineElts[NumInlineEltsElts];
449 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
452 explicit SmallVector(unsigned Size, const T &Value = T())
453 : SmallVectorImpl<T>(NumTsAvailable) {
459 template<typename ItTy>
460 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
464 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
469 const SmallVector &operator=(const SmallVector &RHS) {
470 SmallVectorImpl<T>::operator=(RHS);
475 } // End llvm namespace
478 /// Implement std::swap in terms of SmallVector swap.
481 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
485 /// Implement std::swap in terms of SmallVector swap.
486 template<typename T, unsigned N>
488 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {