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