e3aec7fec050c42f1dddc97c62aaafb2f248de93
[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 resize(unsigned N, const T &NV) {
128     if (N < size()) {
129       destroy_range(Begin+N, End);
130       End = Begin+N;
131     } else if (N > size()) {
132       if (Begin+N > Capacity)
133         grow(N);
134       construct_range(End, Begin+N, NV);
135       End = Begin+N;
136     }
137   }
138   
139   void reserve(unsigned N) {
140     if (unsigned(Capacity-Begin) < N)
141       grow(N);
142   }
143   
144   void swap(SmallVectorImpl &RHS);
145   
146   /// append - Add the specified range to the end of the SmallVector.
147   ///
148   template<typename in_iter>
149   void append(in_iter in_start, in_iter in_end) {
150     unsigned NumInputs = std::distance(in_start, in_end);
151     // Grow allocated space if needed.
152     if (End+NumInputs > Capacity)
153       grow(size()+NumInputs);
154
155     // Copy the new elements over.
156     std::uninitialized_copy(in_start, in_end, End);
157     End += NumInputs;
158   }
159   
160   void assign(unsigned NumElts, const T &Elt) {
161     clear();
162     if (Begin+NumElts > Capacity)
163       grow(NumElts);
164     End = Begin+NumElts;
165     construct_range(Begin, End, Elt);
166   }
167   
168   void erase(iterator I) {
169     // Shift all elts down one.
170     std::copy(I+1, End, I);
171     // Drop the last elt.
172     pop_back();
173   }
174   
175   void erase(iterator S, iterator E) {
176     // Shift all elts down.
177     iterator I = std::copy(E, End, S);
178     // Drop the last elts.
179     destroy_range(I, End);
180     End = I;
181   }
182   
183   iterator insert(iterator I, const T &Elt) {
184     if (I == End) {  // Important special case for empty vector.
185       push_back(Elt);
186       return end()-1;
187     }
188     
189     if (End < Capacity) {
190   Retry:
191       new (End) T(back());
192       ++End;
193       // Push everything else over.
194       std::copy_backward(I, End-1, End);
195       *I = Elt;
196       return I;
197     }
198     unsigned EltNo = I-Begin;
199     grow();
200     I = Begin+EltNo;
201     goto Retry;
202   }
203   
204   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
205   
206 private:
207   /// isSmall - Return true if this is a smallvector which has not had dynamic
208   /// memory allocated for it.
209   bool isSmall() const {
210     return (void*)Begin == (void*)&FirstEl;
211   }
212
213   /// grow - double the size of the allocated memory, guaranteeing space for at
214   /// least one more element or MinSize if specified.
215   void grow(unsigned MinSize = 0);
216
217   void construct_range(T *S, T *E, const T &Elt) {
218     for (; S != E; ++S)
219       new (S) T(Elt);
220   }
221
222   
223   void destroy_range(T *S, T *E) {
224     while (S != E) {
225       E->~T();
226       --E;
227     }
228   }
229 };
230
231 // Define this out-of-line to dissuade the C++ compiler from inlining it.
232 template <typename T>
233 void SmallVectorImpl<T>::grow(unsigned MinSize) {
234   unsigned CurCapacity = Capacity-Begin;
235   unsigned CurSize = size();
236   unsigned NewCapacity = 2*CurCapacity;
237   if (NewCapacity < MinSize)
238     NewCapacity = MinSize;
239   T *NewElts = reinterpret_cast<T*>(new char[NewCapacity*sizeof(T)]);
240   
241   // Copy the elements over.
242   std::uninitialized_copy(Begin, End, NewElts);
243   
244   // Destroy the original elements.
245   destroy_range(Begin, End);
246   
247   // If this wasn't grown from the inline copy, deallocate the old space.
248   if (!isSmall())
249     delete[] (char*)Begin;
250   
251   Begin = NewElts;
252   End = NewElts+CurSize;
253   Capacity = Begin+NewCapacity;
254 }
255
256 template <typename T>
257 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
258   if (this == &RHS) return;
259   
260   // We can only avoid copying elements if neither vector is small.
261   if (!isSmall() && !RHS.isSmall()) {
262     std::swap(Begin, RHS.Begin);
263     std::swap(End, RHS.End);
264     std::swap(Capacity, RHS.Capacity);
265     return;
266   }
267   if (Begin+RHS.size() > Capacity)
268     grow(RHS.size());
269   if (RHS.begin()+size() > RHS.Capacity)
270     RHS.grow(size());
271   
272   // Swap the shared elements.
273   unsigned NumShared = size();
274   if (NumShared > RHS.size()) NumShared = RHS.size();
275   for (unsigned i = 0; i != NumShared; ++i)
276     std::swap(Begin[i], RHS[i]);
277   
278   // Copy over the extra elts.
279   if (size() > RHS.size()) {
280     unsigned EltDiff = size() - RHS.size();
281     std::uninitialized_copy(Begin+NumShared, End, RHS.End);
282     RHS.End += EltDiff;
283     destroy_range(Begin+NumShared, End);
284     End = Begin+NumShared;
285   } else if (RHS.size() > size()) {
286     unsigned EltDiff = RHS.size() - size();
287     std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
288     End += EltDiff;
289     destroy_range(RHS.Begin+NumShared, RHS.End);
290     RHS.End = RHS.Begin+NumShared;
291   }
292 }
293   
294 template <typename T>
295 const SmallVectorImpl<T> &
296 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
297   // Avoid self-assignment.
298   if (this == &RHS) return *this;
299   
300   // If we already have sufficient space, assign the common elements, then
301   // destroy any excess.
302   unsigned RHSSize = RHS.size();
303   unsigned CurSize = size();
304   if (CurSize >= RHSSize) {
305     // Assign common elements.
306     iterator NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
307     
308     // Destroy excess elements.
309     destroy_range(NewEnd, End);
310     
311     // Trim.
312     End = NewEnd;
313     return *this;
314   }
315   
316   // If we have to grow to have enough elements, destroy the current elements.
317   // This allows us to avoid copying them during the grow.
318   if (unsigned(Capacity-Begin) < RHSSize) {
319     // Destroy current elements.
320     destroy_range(Begin, End);
321     End = Begin;
322     CurSize = 0;
323     grow(RHSSize);
324   } else if (CurSize) {
325     // Otherwise, use assignment for the already-constructed elements.
326     std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
327   }
328   
329   // Copy construct the new elements in place.
330   std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
331   
332   // Set end.
333   End = Begin+RHSSize;
334   return *this;
335 }
336   
337 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
338 /// for the case when the array is small.  It contains some number of elements
339 /// in-place, which allows it to avoid heap allocation when the actual number of
340 /// elements is below that threshold.  This allows normal "small" cases to be
341 /// fast without losing generality for large inputs.
342 ///
343 /// Note that this does not attempt to be exception safe.
344 ///
345 template <typename T, unsigned N>
346 class SmallVector : public SmallVectorImpl<T> {
347   /// InlineElts - These are 'N-1' elements that are stored inline in the body
348   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
349   typedef typename SmallVectorImpl<T>::U U;
350   enum {
351     // MinUs - The number of U's require to cover N T's.
352     MinUs = (sizeof(T)*N+sizeof(U)-1)/sizeof(U),
353     
354     // NumInlineEltsElts - The number of elements actually in this array.  There
355     // is already one in the parent class, and we have to round up to avoid
356     // having a zero-element array.
357     NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
358     
359     // NumTsAvailable - The number of T's we actually have space for, which may
360     // be more than N due to rounding.
361     NumTsAvailable = (NumInlineEltsElts+1)*sizeof(U) / sizeof(T)
362   };
363   U InlineElts[NumInlineEltsElts];
364 public:  
365   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
366   }
367   
368   template<typename ItTy>
369   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
370     append(S, E);
371   }
372   
373   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
374     operator=(RHS);
375   }
376   
377   const SmallVector &operator=(const SmallVector &RHS) {
378     SmallVectorImpl<T>::operator=(RHS);
379     return *this;
380   }
381 };
382
383 } // End llvm namespace
384
385 namespace std {
386   /// Implement std::swap in terms of SmallVector swap.
387   template<typename T>
388   inline void
389   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
390     LHS.swap(RHS);
391   }
392   
393   /// Implement std::swap in terms of SmallVector swap.
394   template<typename T, unsigned N>
395   inline void
396   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
397     LHS.swap(RHS);
398   }
399 }
400
401 #endif