add resize, move swap out of line
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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 <algorithm>
18 #include <iterator>
19 #include <memory>
20
21 namespace llvm {
22
23 /// SmallVectorImpl - This class consists of common code factored out of the
24 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
25 /// template parameter.
26 template <typename T>
27 class SmallVectorImpl {
28   T *Begin, *End, *Capacity;
29   
30   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
31   // don't want it to be automatically run, so we need to represent the space as
32   // something else.  An array of char would work great, but might not be
33   // aligned sufficiently.  Instead, we either use GCC extensions, or some
34   // number of union instances for the space, which guarantee maximal alignment.
35 protected:
36   union U {
37     double D;
38     long double LD;
39     long long L;
40     void *P;
41   } FirstEl;
42   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
43 public:
44   // Default ctor - Initialize to empty.
45   SmallVectorImpl(unsigned N)
46     : Begin((T*)&FirstEl), End((T*)&FirstEl), Capacity((T*)&FirstEl+N) {
47   }
48   
49   ~SmallVectorImpl() {
50     // Destroy the constructed elements in the vector.
51     destroy_range(Begin, End);
52
53     // If this wasn't grown from the inline copy, deallocate the old space.
54     if (!isSmall())
55       delete[] (char*)Begin;
56   }
57   
58   typedef size_t size_type;
59   typedef T* iterator;
60   typedef const T* const_iterator;
61   typedef T& reference;
62   typedef const T& const_reference;
63
64   bool empty() const { return Begin == End; }
65   size_type size() const { return End-Begin; }
66   
67   iterator begin() { return Begin; }
68   const_iterator begin() const { return Begin; }
69
70   iterator end() { return End; }
71   const_iterator end() const { return End; }
72   
73   reference operator[](unsigned idx) {
74     return Begin[idx];
75   }
76   const_reference operator[](unsigned idx) const {
77     return Begin[idx];
78   }
79   
80   reference front() {
81     return begin()[0];
82   }
83   const_reference front() const {
84     return begin()[0];
85   }
86   
87   reference back() {
88     return end()[-1];
89   }
90   const_reference back() const {
91     return end()[-1];
92   }
93   
94   void push_back(const_reference Elt) {
95     if (End < Capacity) {
96   Retry:
97       new (End) T(Elt);
98       ++End;
99       return;
100     }
101     grow();
102     goto Retry;
103   }
104   
105   void pop_back() {
106     --End;
107     End->~T();
108   }
109   
110   void clear() {
111     destroy_range(Begin, End);
112     End = Begin;
113   }
114   
115   void resize(unsigned N) {
116     if (N < size()) {
117       destroy_range(Begin+N, End);
118       End = Begin+N;
119     } else if (N > size()) {
120       if (Begin+N > Capacity)
121         grow(N);
122       construct_range(End, Begin+N, T());
123       End = Begin+N;
124     }
125   }
126   
127   void swap(SmallVectorImpl &RHS);
128   
129   /// append - Add the specified range to the end of the SmallVector.
130   ///
131   template<typename in_iter>
132   void append(in_iter in_start, in_iter in_end) {
133     unsigned NumInputs = std::distance(in_start, in_end);
134     // Grow allocated space if needed.
135     if (End+NumInputs > Capacity)
136       grow(size()+NumInputs);
137
138     // Copy the new elements over.
139     std::uninitialized_copy(in_start, in_end, End);
140     End += NumInputs;
141   }
142   
143   void assign(unsigned NumElts, const T &Elt) {
144     clear();
145     if (Begin+NumElts > Capacity)
146       grow(NumElts);
147     End = Begin+NumElts;
148     construct_range(Begin, End, Elt);
149   }
150   
151   void erase(iterator I) {
152     // Shift all elts down one.
153     std::copy(I+1, End, I);
154     // Drop the last elt.
155     pop_back();
156   }
157   
158   void erase(iterator S, iterator E) {
159     // Shift all elts down.
160     iterator I = std::copy(E, End, S);
161     // Drop the last elts.
162     destroy_range(I, End);
163     End = I;
164   }
165   
166   iterator insert(iterator I, const T &Elt) {
167     if (I == End) {  // Important special case for empty vector.
168       push_back(Elt);
169       return end()-1;
170     }
171     
172     if (End < Capacity) {
173   Retry:
174       new (End) T(back());
175       ++End;
176       // Push everything else over.
177       std::copy_backward(I, End-1, End);
178       *I = Elt;
179       return I;
180     }
181     unsigned EltNo = I-Begin;
182     grow();
183     I = Begin+EltNo;
184     goto Retry;
185   }
186   
187   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
188   
189 private:
190   /// isSmall - Return true if this is a smallvector which has not had dynamic
191   /// memory allocated for it.
192   bool isSmall() const {
193     return (void*)Begin == (void*)&FirstEl;
194   }
195
196   /// grow - double the size of the allocated memory, guaranteeing space for at
197   /// least one more element or MinSize if specified.
198   void grow(unsigned MinSize = 0);
199
200   void construct_range(T *S, T *E, const T &Elt) {
201     for (; S != E; ++S)
202       new (S) T(Elt);
203   }
204
205   
206   void destroy_range(T *S, T *E) {
207     while (S != E) {
208       E->~T();
209       --E;
210     }
211   }
212 };
213
214 // Define this out-of-line to dissuade the C++ compiler from inlining it.
215 template <typename T>
216 void SmallVectorImpl<T>::grow(unsigned MinSize) {
217   unsigned CurCapacity = Capacity-Begin;
218   unsigned CurSize = size();
219   unsigned NewCapacity = 2*CurCapacity;
220   if (NewCapacity < MinSize)
221     NewCapacity = MinSize;
222   T *NewElts = reinterpret_cast<T*>(new char[NewCapacity*sizeof(T)]);
223   
224   // Copy the elements over.
225   std::uninitialized_copy(Begin, End, NewElts);
226   
227   // Destroy the original elements.
228   destroy_range(Begin, End);
229   
230   // If this wasn't grown from the inline copy, deallocate the old space.
231   if (!isSmall())
232     delete[] (char*)Begin;
233   
234   Begin = NewElts;
235   End = NewElts+CurSize;
236   Capacity = Begin+NewCapacity;
237 }
238
239 template <typename T>
240 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
241   if (this == &RHS) return;
242   
243   // We can only avoid copying elements if neither vector is small.
244   if (!isSmall() && !RHS.isSmall()) {
245     std::swap(Begin, RHS.Begin);
246     std::swap(End, RHS.End);
247     std::swap(Capacity, RHS.Capacity);
248     return;
249   }
250   if (Begin+RHS.size() > Capacity)
251     grow(RHS.size());
252   if (RHS.begin()+size() > RHS.Capacity)
253     RHS.grow(size());
254   
255   // Swap the shared elements.
256   unsigned NumShared = size();
257   if (NumShared > RHS.size()) NumShared = RHS.size();
258   for (unsigned i = 0; i != NumShared; ++i)
259     std::swap(Begin[i], RHS[i]);
260   
261   // Copy over the extra elts.
262   if (size() > RHS.size()) {
263     unsigned EltDiff = size() - RHS.size();
264     std::uninitialized_copy(Begin+NumShared, End, RHS.End);
265     RHS.End += EltDiff;
266     destroy_range(Begin+NumShared, End);
267     End = Begin+NumShared;
268   } else if (RHS.size() > size()) {
269     unsigned EltDiff = RHS.size() - size();
270     std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
271     End += EltDiff;
272     destroy_range(RHS.Begin+NumShared, RHS.End);
273     RHS.End = RHS.Begin+NumShared;
274   }
275 }
276   
277 template <typename T>
278 const SmallVectorImpl<T> &
279 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
280   // Avoid self-assignment.
281   if (this == &RHS) return *this;
282   
283   // If we already have sufficient space, assign the common elements, then
284   // destroy any excess.
285   unsigned RHSSize = RHS.size();
286   unsigned CurSize = size();
287   if (CurSize >= RHSSize) {
288     // Assign common elements.
289     iterator NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
290     
291     // Destroy excess elements.
292     destroy_range(NewEnd, End);
293     
294     // Trim.
295     End = NewEnd;
296     return *this;
297   }
298   
299   // If we have to grow to have enough elements, destroy the current elements.
300   // This allows us to avoid copying them during the grow.
301   if (unsigned(Capacity-Begin) < RHSSize) {
302     // Destroy current elements.
303     destroy_range(Begin, End);
304     End = Begin;
305     CurSize = 0;
306     grow(RHSSize);
307   } else if (CurSize) {
308     // Otherwise, use assignment for the already-constructed elements.
309     std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
310   }
311   
312   // Copy construct the new elements in place.
313   std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
314   
315   // Set end.
316   End = Begin+RHSSize;
317   return *this;
318 }
319   
320 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
321 /// for the case when the array is small.  It contains some number of elements
322 /// in-place, which allows it to avoid heap allocation when the actual number of
323 /// elements is below that threshold.  This allows normal "small" cases to be
324 /// fast without losing generality for large inputs.
325 ///
326 /// Note that this does not attempt to be exception safe.
327 ///
328 template <typename T, unsigned N>
329 class SmallVector : public SmallVectorImpl<T> {
330   /// InlineElts - These are 'N-1' elements that are stored inline in the body
331   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
332   typedef typename SmallVectorImpl<T>::U U;
333   enum {
334     // MinUs - The number of U's require to cover N T's.
335     MinUs = (sizeof(T)*N+sizeof(U)-1)/sizeof(U),
336     
337     // NumInlineEltsElts - The number of elements actually in this array.  There
338     // is already one in the parent class, and we have to round up to avoid
339     // having a zero-element array.
340     NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
341     
342     // NumTsAvailable - The number of T's we actually have space for, which may
343     // be more than N due to rounding.
344     NumTsAvailable = (NumInlineEltsElts+1)*sizeof(U) / sizeof(T)
345   };
346   U InlineElts[NumInlineEltsElts];
347 public:  
348   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
349   }
350   
351   template<typename ItTy>
352   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
353     append(S, E);
354   }
355   
356   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
357     operator=(RHS);
358   }
359   
360   const SmallVector &operator=(const SmallVector &RHS) {
361     SmallVectorImpl<T>::operator=(RHS);
362     return *this;
363   }
364 };
365
366 } // End llvm namespace
367
368 namespace std {
369   /// Implement std::swap in terms of SmallVector swap.
370   template<typename T>
371   inline void
372   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
373     LHS.swap(RHS);
374   }
375   
376   /// Implement std::swap in terms of SmallVector swap.
377   template<typename T, unsigned N>
378   inline void
379   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
380     LHS.swap(RHS);
381   }
382 }
383
384 #endif