Clean up the minor mess I caused with removing iterator.h. I shall take care of 80...
[oota-llvm.git] / include / llvm / ADT / SmallVector.h
1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the SmallVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
16
17 #include "llvm/Support/type_traits.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cstring>
21 #include <memory>
22
23 #ifdef _MSC_VER
24 namespace std {
25 #if _MSC_VER <= 1310
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;
32     return _Cat;
33   }
34
35   template<class T1, class T2>
36   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
37     _Scalar_ptr_iterator_tag _Cat;
38     return _Cat;
39   }
40 #else
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.
43 #endif
44 }
45 #endif
46
47 namespace llvm {
48
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.
52 template <typename T>
53 class SmallVectorImpl {
54 protected:
55   T *Begin, *End, *Capacity;
56
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.
62 protected:
63 #ifdef __GNUC__
64   typedef char U;
65   U FirstEl __attribute__((aligned));
66 #else
67   union U {
68     double D;
69     long double LD;
70     long long L;
71     void *P;
72   } FirstEl;
73 #endif
74   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
75 public:
76   // Default ctor - Initialize to empty.
77   explicit SmallVectorImpl(unsigned N)
78     : Begin(reinterpret_cast<T*>(&FirstEl)),
79       End(reinterpret_cast<T*>(&FirstEl)),
80       Capacity(reinterpret_cast<T*>(&FirstEl)+N) {
81   }
82
83   ~SmallVectorImpl() {
84     // Destroy the constructed elements in the vector.
85     destroy_range(Begin, End);
86
87     // If this wasn't grown from the inline copy, deallocate the old space.
88     if (!isSmall())
89       operator delete(Begin);
90   }
91
92   typedef size_t size_type;
93   typedef ptrdiff_t difference_type;
94   typedef T value_type;
95   typedef T* iterator;
96   typedef const T* const_iterator;
97
98   typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;
99   typedef std::reverse_iterator<iterator>  reverse_iterator;
100
101   typedef T& reference;
102   typedef const T& const_reference;
103   typedef T* pointer;
104   typedef const T* const_pointer;
105
106   bool empty() const { return Begin == End; }
107   size_type size() const { return End-Begin; }
108   size_type max_size() const { return size_type(-1) / sizeof(T); }
109
110   // forward iterator creation methods.
111   iterator begin() { return Begin; }
112   const_iterator begin() const { return Begin; }
113   iterator end() { return End; }
114   const_iterator end() const { return End; }
115
116   // reverse iterator creation methods.
117   reverse_iterator rbegin()            { return reverse_iterator(end()); }
118   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
119   reverse_iterator rend()              { return reverse_iterator(begin()); }
120   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
121
122
123   reference operator[](unsigned idx) {
124     assert(Begin + idx < End);
125     return Begin[idx];
126   }
127   const_reference operator[](unsigned idx) const {
128     assert(Begin + idx < End);
129     return Begin[idx];
130   }
131
132   reference front() {
133     return begin()[0];
134   }
135   const_reference front() const {
136     return begin()[0];
137   }
138
139   reference back() {
140     return end()[-1];
141   }
142   const_reference back() const {
143     return end()[-1];
144   }
145
146   void push_back(const_reference Elt) {
147     if (End < Capacity) {
148   Retry:
149       new (End) T(Elt);
150       ++End;
151       return;
152     }
153     grow();
154     goto Retry;
155   }
156
157   void pop_back() {
158     --End;
159     End->~T();
160   }
161
162   T pop_back_val() {
163     T Result = back();
164     pop_back();
165     return Result;
166   }
167
168   void clear() {
169     destroy_range(Begin, End);
170     End = Begin;
171   }
172
173   void resize(unsigned N) {
174     if (N < size()) {
175       destroy_range(Begin+N, End);
176       End = Begin+N;
177     } else if (N > size()) {
178       if (unsigned(Capacity-Begin) < N)
179         grow(N);
180       construct_range(End, Begin+N, T());
181       End = Begin+N;
182     }
183   }
184
185   void resize(unsigned N, const T &NV) {
186     if (N < size()) {
187       destroy_range(Begin+N, End);
188       End = Begin+N;
189     } else if (N > size()) {
190       if (unsigned(Capacity-Begin) < N)
191         grow(N);
192       construct_range(End, Begin+N, NV);
193       End = Begin+N;
194     }
195   }
196
197   void reserve(unsigned N) {
198     if (unsigned(Capacity-Begin) < N)
199       grow(N);
200   }
201
202   void swap(SmallVectorImpl &RHS);
203
204   /// append - Add the specified range to the end of the SmallVector.
205   ///
206   template<typename in_iter>
207   void append(in_iter in_start, in_iter in_end) {
208     size_type NumInputs = std::distance(in_start, in_end);
209     // Grow allocated space if needed.
210     if (NumInputs > size_type(Capacity-End))
211       grow(size()+NumInputs);
212
213     // Copy the new elements over.
214     std::uninitialized_copy(in_start, in_end, End);
215     End += NumInputs;
216   }
217
218   /// append - Add the specified range to the end of the SmallVector.
219   ///
220   void append(size_type NumInputs, const T &Elt) {
221     // Grow allocated space if needed.
222     if (NumInputs > size_type(Capacity-End))
223       grow(size()+NumInputs);
224
225     // Copy the new elements over.
226     std::uninitialized_fill_n(End, NumInputs, Elt);
227     End += NumInputs;
228   }
229
230   void assign(unsigned NumElts, const T &Elt) {
231     clear();
232     if (unsigned(Capacity-Begin) < NumElts)
233       grow(NumElts);
234     End = Begin+NumElts;
235     construct_range(Begin, End, Elt);
236   }
237
238   iterator erase(iterator I) {
239     iterator N = I;
240     // Shift all elts down one.
241     std::copy(I+1, End, I);
242     // Drop the last elt.
243     pop_back();
244     return(N);
245   }
246
247   iterator erase(iterator S, iterator E) {
248     iterator N = S;
249     // Shift all elts down.
250     iterator I = std::copy(E, End, S);
251     // Drop the last elts.
252     destroy_range(I, End);
253     End = I;
254     return(N);
255   }
256
257   iterator insert(iterator I, const T &Elt) {
258     if (I == End) {  // Important special case for empty vector.
259       push_back(Elt);
260       return end()-1;
261     }
262
263     if (End < Capacity) {
264   Retry:
265       new (End) T(back());
266       ++End;
267       // Push everything else over.
268       std::copy_backward(I, End-1, End);
269       *I = Elt;
270       return I;
271     }
272     size_t EltNo = I-Begin;
273     grow();
274     I = Begin+EltNo;
275     goto Retry;
276   }
277
278   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
279     if (I == End) {  // Important special case for empty vector.
280       append(NumToInsert, Elt);
281       return end()-1;
282     }
283
284     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
285     size_t InsertElt = I-begin();
286
287     // Ensure there is enough space.
288     reserve(static_cast<unsigned>(size() + NumToInsert));
289
290     // Uninvalidate the iterator.
291     I = begin()+InsertElt;
292
293     // If there are more elements between the insertion point and the end of the
294     // range than there are being inserted, we can use a simple approach to
295     // insertion.  Since we already reserved space, we know that this won't
296     // reallocate the vector.
297     if (size_t(end()-I) >= NumToInsert) {
298       T *OldEnd = End;
299       append(End-NumToInsert, End);
300
301       // Copy the existing elements that get replaced.
302       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
303
304       std::fill_n(I, NumToInsert, Elt);
305       return I;
306     }
307
308     // Otherwise, we're inserting more elements than exist already, and we're
309     // not inserting at the end.
310
311     // Copy over the elements that we're about to overwrite.
312     T *OldEnd = End;
313     End += NumToInsert;
314     size_t NumOverwritten = OldEnd-I;
315     std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
316
317     // Replace the overwritten part.
318     std::fill_n(I, NumOverwritten, Elt);
319
320     // Insert the non-overwritten middle part.
321     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
322     return I;
323   }
324
325   template<typename ItTy>
326   iterator insert(iterator I, ItTy From, ItTy To) {
327     if (I == End) {  // Important special case for empty vector.
328       append(From, To);
329       return end()-1;
330     }
331
332     size_t NumToInsert = std::distance(From, To);
333     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
334     size_t InsertElt = I-begin();
335
336     // Ensure there is enough space.
337     reserve(static_cast<unsigned>(size() + NumToInsert));
338
339     // Uninvalidate the iterator.
340     I = begin()+InsertElt;
341
342     // If there are more elements between the insertion point and the end of the
343     // range than there are being inserted, we can use a simple approach to
344     // insertion.  Since we already reserved space, we know that this won't
345     // reallocate the vector.
346     if (size_t(end()-I) >= NumToInsert) {
347       T *OldEnd = End;
348       append(End-NumToInsert, End);
349
350       // Copy the existing elements that get replaced.
351       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
352
353       std::copy(From, To, I);
354       return I;
355     }
356
357     // Otherwise, we're inserting more elements than exist already, and we're
358     // not inserting at the end.
359
360     // Copy over the elements that we're about to overwrite.
361     T *OldEnd = End;
362     End += NumToInsert;
363     size_t NumOverwritten = OldEnd-I;
364     std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
365
366     // Replace the overwritten part.
367     std::copy(From, From+NumOverwritten, I);
368
369     // Insert the non-overwritten middle part.
370     std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
371     return I;
372   }
373
374   /// data - Return a pointer to the vector's buffer, even if empty().
375   pointer data() {
376     return pointer(Begin);
377   }
378
379   /// data - Return a pointer to the vector's buffer, even if empty().
380   const_pointer data() const {
381     return const_pointer(Begin);
382   }
383
384   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
385
386   bool operator==(const SmallVectorImpl &RHS) const {
387     if (size() != RHS.size()) return false;
388     for (T *This = Begin, *That = RHS.Begin, *E = Begin+size();
389          This != E; ++This, ++That)
390       if (*This != *That)
391         return false;
392     return true;
393   }
394   bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
395
396   bool operator<(const SmallVectorImpl &RHS) const {
397     return std::lexicographical_compare(begin(), end(),
398                                         RHS.begin(), RHS.end());
399   }
400
401   /// capacity - Return the total number of elements in the currently allocated
402   /// buffer.
403   size_t capacity() const { return Capacity - Begin; }
404
405   /// set_size - Set the array size to \arg N, which the current array must have
406   /// enough capacity for.
407   ///
408   /// This does not construct or destroy any elements in the vector.
409   ///
410   /// Clients can use this in conjunction with capacity() to write past the end
411   /// of the buffer when they know that more elements are available, and only
412   /// update the size later. This avoids the cost of value initializing elements
413   /// which will only be overwritten.
414   void set_size(unsigned N) {
415     assert(N <= capacity());
416     End = Begin + N;
417   }
418
419 private:
420   /// isSmall - Return true if this is a smallvector which has not had dynamic
421   /// memory allocated for it.
422   bool isSmall() const {
423     return static_cast<const void*>(Begin) ==
424            static_cast<const void*>(&FirstEl);
425   }
426
427   /// grow - double the size of the allocated memory, guaranteeing space for at
428   /// least one more element or MinSize if specified.
429   void grow(size_type MinSize = 0);
430
431   void construct_range(T *S, T *E, const T &Elt) {
432     for (; S != E; ++S)
433       new (S) T(Elt);
434   }
435
436   void destroy_range(T *S, T *E) {
437     while (S != E) {
438       --E;
439       E->~T();
440     }
441   }
442 };
443
444 // Define this out-of-line to dissuade the C++ compiler from inlining it.
445 template <typename T>
446 void SmallVectorImpl<T>::grow(size_t MinSize) {
447   size_t CurCapacity = Capacity-Begin;
448   size_t CurSize = size();
449   size_t NewCapacity = 2*CurCapacity;
450   if (NewCapacity < MinSize)
451     NewCapacity = MinSize;
452   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
453
454   // Copy the elements over.
455   if (is_class<T>::value)
456     std::uninitialized_copy(Begin, End, NewElts);
457   else
458     // Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
459     memcpy(NewElts, Begin, CurSize * sizeof(T));
460
461   // Destroy the original elements.
462   destroy_range(Begin, End);
463
464   // If this wasn't grown from the inline copy, deallocate the old space.
465   if (!isSmall())
466     operator delete(Begin);
467
468   Begin = NewElts;
469   End = NewElts+CurSize;
470   Capacity = Begin+NewCapacity;
471 }
472
473 template <typename T>
474 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
475   if (this == &RHS) return;
476
477   // We can only avoid copying elements if neither vector is small.
478   if (!isSmall() && !RHS.isSmall()) {
479     std::swap(Begin, RHS.Begin);
480     std::swap(End, RHS.End);
481     std::swap(Capacity, RHS.Capacity);
482     return;
483   }
484   if (RHS.size() > size_type(Capacity-Begin))
485     grow(RHS.size());
486   if (size() > size_type(RHS.Capacity-RHS.begin()))
487     RHS.grow(size());
488
489   // Swap the shared elements.
490   size_t NumShared = size();
491   if (NumShared > RHS.size()) NumShared = RHS.size();
492   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
493     std::swap(Begin[i], RHS[i]);
494
495   // Copy over the extra elts.
496   if (size() > RHS.size()) {
497     size_t EltDiff = size() - RHS.size();
498     std::uninitialized_copy(Begin+NumShared, End, RHS.End);
499     RHS.End += EltDiff;
500     destroy_range(Begin+NumShared, End);
501     End = Begin+NumShared;
502   } else if (RHS.size() > size()) {
503     size_t EltDiff = RHS.size() - size();
504     std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
505     End += EltDiff;
506     destroy_range(RHS.Begin+NumShared, RHS.End);
507     RHS.End = RHS.Begin+NumShared;
508   }
509 }
510
511 template <typename T>
512 const SmallVectorImpl<T> &
513 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
514   // Avoid self-assignment.
515   if (this == &RHS) return *this;
516
517   // If we already have sufficient space, assign the common elements, then
518   // destroy any excess.
519   unsigned RHSSize = unsigned(RHS.size());
520   unsigned CurSize = unsigned(size());
521   if (CurSize >= RHSSize) {
522     // Assign common elements.
523     iterator NewEnd;
524     if (RHSSize)
525       NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
526     else
527       NewEnd = Begin;
528
529     // Destroy excess elements.
530     destroy_range(NewEnd, End);
531
532     // Trim.
533     End = NewEnd;
534     return *this;
535   }
536
537   // If we have to grow to have enough elements, destroy the current elements.
538   // This allows us to avoid copying them during the grow.
539   if (unsigned(Capacity-Begin) < RHSSize) {
540     // Destroy current elements.
541     destroy_range(Begin, End);
542     End = Begin;
543     CurSize = 0;
544     grow(RHSSize);
545   } else if (CurSize) {
546     // Otherwise, use assignment for the already-constructed elements.
547     std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
548   }
549
550   // Copy construct the new elements in place.
551   std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
552
553   // Set end.
554   End = Begin+RHSSize;
555   return *this;
556 }
557
558 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
559 /// for the case when the array is small.  It contains some number of elements
560 /// in-place, which allows it to avoid heap allocation when the actual number of
561 /// elements is below that threshold.  This allows normal "small" cases to be
562 /// fast without losing generality for large inputs.
563 ///
564 /// Note that this does not attempt to be exception safe.
565 ///
566 template <typename T, unsigned N>
567 class SmallVector : public SmallVectorImpl<T> {
568   /// InlineElts - These are 'N-1' elements that are stored inline in the body
569   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
570   typedef typename SmallVectorImpl<T>::U U;
571   enum {
572     // MinUs - The number of U's require to cover N T's.
573     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
574              static_cast<unsigned int>(sizeof(U)) - 1) /
575             static_cast<unsigned int>(sizeof(U)),
576
577     // NumInlineEltsElts - The number of elements actually in this array.  There
578     // is already one in the parent class, and we have to round up to avoid
579     // having a zero-element array.
580     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
581
582     // NumTsAvailable - The number of T's we actually have space for, which may
583     // be more than N due to rounding.
584     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
585                      static_cast<unsigned int>(sizeof(T))
586   };
587   U InlineElts[NumInlineEltsElts];
588 public:
589   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
590   }
591
592   explicit SmallVector(unsigned Size, const T &Value = T())
593     : SmallVectorImpl<T>(NumTsAvailable) {
594     this->reserve(Size);
595     while (Size--)
596       this->push_back(Value);
597   }
598
599   template<typename ItTy>
600   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
601     this->append(S, E);
602   }
603
604   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
605     if (!RHS.empty())
606       SmallVectorImpl<T>::operator=(RHS);
607   }
608
609   const SmallVector &operator=(const SmallVector &RHS) {
610     SmallVectorImpl<T>::operator=(RHS);
611     return *this;
612   }
613
614 };
615
616 } // End llvm namespace
617
618 namespace std {
619   /// Implement std::swap in terms of SmallVector swap.
620   template<typename T>
621   inline void
622   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
623     LHS.swap(RHS);
624   }
625
626   /// Implement std::swap in terms of SmallVector swap.
627   template<typename T, unsigned N>
628   inline void
629   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
630     LHS.swap(RHS);
631   }
632 }
633
634 #endif