Elminate tabs and improve comments.
[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 #ifdef _MSC_VER
22 namespace std {
23   // Work around flawed VC++ implementation of std::uninitialized_copy.  Define
24   // additional overloads so that elements with pointer types are recognized as
25   // scalars and not objects, causing bizarre type conversion errors.
26   // FIXME: this hack may or may not be correct for Visual Studio 2005.
27   template<class T1, class T2>
28   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
29     _Scalar_ptr_iterator_tag _Cat;
30     return _Cat;
31   }
32
33   template<class T1, class T2>
34   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
35     _Scalar_ptr_iterator_tag _Cat;
36     return _Cat;
37   }
38 }
39 #endif
40
41 namespace llvm {
42
43 /// SmallVectorImpl - This class consists of common code factored out of the
44 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
45 /// template parameter.
46 template <typename T>
47 class SmallVectorImpl {
48 protected:
49   T *Begin, *End, *Capacity;
50   
51   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
52   // don't want it to be automatically run, so we need to represent the space as
53   // something else.  An array of char would work great, but might not be
54   // aligned sufficiently.  Instead, we either use GCC extensions, or some
55   // number of union instances for the space, which guarantee maximal alignment.
56 protected:
57 #ifdef __GNUC__
58   typedef char U;
59   U FirstEl __attribute__((aligned));
60 #else
61   union U {
62     double D;
63     long double LD;
64     long long L;
65     void *P;
66   } FirstEl;
67 #endif
68   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
69 public:
70   // Default ctor - Initialize to empty.
71   SmallVectorImpl(unsigned N)
72     : Begin((T*)&FirstEl), End((T*)&FirstEl), Capacity((T*)&FirstEl+N) {
73   }
74   
75   ~SmallVectorImpl() {
76     // Destroy the constructed elements in the vector.
77     destroy_range(Begin, End);
78
79     // If this wasn't grown from the inline copy, deallocate the old space.
80     if (!isSmall())
81       delete[] (char*)Begin;
82   }
83   
84   typedef size_t size_type;
85   typedef T* iterator;
86   typedef const T* const_iterator;
87   typedef T& reference;
88   typedef const T& const_reference;
89
90   bool empty() const { return Begin == End; }
91   size_type size() const { return End-Begin; }
92   
93   iterator begin() { return Begin; }
94   const_iterator begin() const { return Begin; }
95
96   iterator end() { return End; }
97   const_iterator end() const { return End; }
98   
99   reference operator[](unsigned idx) {
100     return Begin[idx];
101   }
102   const_reference operator[](unsigned idx) const {
103     return Begin[idx];
104   }
105   
106   reference front() {
107     return begin()[0];
108   }
109   const_reference front() const {
110     return begin()[0];
111   }
112   
113   reference back() {
114     return end()[-1];
115   }
116   const_reference back() const {
117     return end()[-1];
118   }
119   
120   void push_back(const_reference Elt) {
121     if (End < Capacity) {
122   Retry:
123       new (End) T(Elt);
124       ++End;
125       return;
126     }
127     grow();
128     goto Retry;
129   }
130   
131   void pop_back() {
132     --End;
133     End->~T();
134   }
135   
136   void clear() {
137     destroy_range(Begin, End);
138     End = Begin;
139   }
140   
141   void resize(unsigned N) {
142     if (N < size()) {
143       destroy_range(Begin+N, End);
144       End = Begin+N;
145     } else if (N > size()) {
146       if (Begin+N > Capacity)
147         grow(N);
148       construct_range(End, Begin+N, T());
149       End = Begin+N;
150     }
151   }
152   
153   void resize(unsigned N, const T &NV) {
154     if (N < size()) {
155       destroy_range(Begin+N, End);
156       End = Begin+N;
157     } else if (N > size()) {
158       if (Begin+N > Capacity)
159         grow(N);
160       construct_range(End, Begin+N, NV);
161       End = Begin+N;
162     }
163   }
164   
165   void reserve(unsigned N) {
166     if (unsigned(Capacity-Begin) < N)
167       grow(N);
168   }
169   
170   void swap(SmallVectorImpl &RHS);
171   
172   /// append - Add the specified range to the end of the SmallVector.
173   ///
174   template<typename in_iter>
175   void append(in_iter in_start, in_iter in_end) {
176     unsigned NumInputs = std::distance(in_start, in_end);
177     // Grow allocated space if needed.
178     if (End+NumInputs > Capacity)
179       grow(size()+NumInputs);
180
181     // Copy the new elements over.
182     std::uninitialized_copy(in_start, in_end, End);
183     End += NumInputs;
184   }
185   
186   void assign(unsigned NumElts, const T &Elt) {
187     clear();
188     if (Begin+NumElts > Capacity)
189       grow(NumElts);
190     End = Begin+NumElts;
191     construct_range(Begin, End, Elt);
192   }
193   
194   void erase(iterator I) {
195     // Shift all elts down one.
196     std::copy(I+1, End, I);
197     // Drop the last elt.
198     pop_back();
199   }
200   
201   void erase(iterator S, iterator E) {
202     // Shift all elts down.
203     iterator I = std::copy(E, End, S);
204     // Drop the last elts.
205     destroy_range(I, End);
206     End = I;
207   }
208   
209   iterator insert(iterator I, const T &Elt) {
210     if (I == End) {  // Important special case for empty vector.
211       push_back(Elt);
212       return end()-1;
213     }
214     
215     if (End < Capacity) {
216   Retry:
217       new (End) T(back());
218       ++End;
219       // Push everything else over.
220       std::copy_backward(I, End-1, End);
221       *I = Elt;
222       return I;
223     }
224     unsigned EltNo = I-Begin;
225     grow();
226     I = Begin+EltNo;
227     goto Retry;
228   }
229   
230   template<typename ItTy>
231   iterator insert(iterator I, ItTy From, ItTy To) {
232     if (I == End) {  // Important special case for empty vector.
233       append(From, To);
234       return end()-1;
235     }
236     
237     unsigned NumToInsert = std::distance(From, To);
238     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
239     unsigned InsertElt = I-begin();
240     
241     // Ensure there is enough space.
242     reserve(size() + NumToInsert);
243     
244     // Uninvalidate the iterator.
245     I = begin()+InsertElt;
246     
247     // If we already have this many elements in the collection, append the
248     // dest elements at the end, then copy over the appropriate elements.  Since
249     // we already reserved space, we know that this won't reallocate the vector.
250     if (size() >= NumToInsert) {
251       T *OldEnd = End;
252       append(End-NumToInsert, End);
253       
254       // Copy the existing elements that get replaced.
255       std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
256       
257       std::copy(From, To, I);
258       return I;
259     }
260
261     // Otherwise, we're inserting more elements than exist already, and we're
262     // not inserting at the end.
263     
264     // Copy over the elements that we're about to overwrite.
265     T *OldEnd = End;
266     End += NumToInsert;
267     unsigned NumOverwritten = OldEnd-I;
268     std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
269     
270     // Replace the overwritten part.
271     std::copy(From, From+NumOverwritten, I);
272     
273     // Insert the non-overwritten middle part.
274     std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
275     return I;
276   }
277   
278   const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
279   
280 private:
281   /// isSmall - Return true if this is a smallvector which has not had dynamic
282   /// memory allocated for it.
283   bool isSmall() const {
284     return (void*)Begin == (void*)&FirstEl;
285   }
286
287   /// grow - double the size of the allocated memory, guaranteeing space for at
288   /// least one more element or MinSize if specified.
289   void grow(unsigned MinSize = 0);
290
291   void construct_range(T *S, T *E, const T &Elt) {
292     for (; S != E; ++S)
293       new (S) T(Elt);
294   }
295   
296   void destroy_range(T *S, T *E) {
297     while (S != E) {
298       --E;
299       E->~T();
300     }
301   }
302 };
303
304 // Define this out-of-line to dissuade the C++ compiler from inlining it.
305 template <typename T>
306 void SmallVectorImpl<T>::grow(unsigned MinSize) {
307   unsigned CurCapacity = Capacity-Begin;
308   unsigned CurSize = size();
309   unsigned NewCapacity = 2*CurCapacity;
310   if (NewCapacity < MinSize)
311     NewCapacity = MinSize;
312   T *NewElts = reinterpret_cast<T*>(new char[NewCapacity*sizeof(T)]);
313   
314   // Copy the elements over.
315   std::uninitialized_copy(Begin, End, NewElts);
316   
317   // Destroy the original elements.
318   destroy_range(Begin, End);
319   
320   // If this wasn't grown from the inline copy, deallocate the old space.
321   if (!isSmall())
322     delete[] (char*)Begin;
323   
324   Begin = NewElts;
325   End = NewElts+CurSize;
326   Capacity = Begin+NewCapacity;
327 }
328
329 template <typename T>
330 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
331   if (this == &RHS) return;
332   
333   // We can only avoid copying elements if neither vector is small.
334   if (!isSmall() && !RHS.isSmall()) {
335     std::swap(Begin, RHS.Begin);
336     std::swap(End, RHS.End);
337     std::swap(Capacity, RHS.Capacity);
338     return;
339   }
340   if (Begin+RHS.size() > Capacity)
341     grow(RHS.size());
342   if (RHS.begin()+size() > RHS.Capacity)
343     RHS.grow(size());
344   
345   // Swap the shared elements.
346   unsigned NumShared = size();
347   if (NumShared > RHS.size()) NumShared = RHS.size();
348   for (unsigned i = 0; i != NumShared; ++i)
349     std::swap(Begin[i], RHS[i]);
350   
351   // Copy over the extra elts.
352   if (size() > RHS.size()) {
353     unsigned EltDiff = size() - RHS.size();
354     std::uninitialized_copy(Begin+NumShared, End, RHS.End);
355     RHS.End += EltDiff;
356     destroy_range(Begin+NumShared, End);
357     End = Begin+NumShared;
358   } else if (RHS.size() > size()) {
359     unsigned EltDiff = RHS.size() - size();
360     std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
361     End += EltDiff;
362     destroy_range(RHS.Begin+NumShared, RHS.End);
363     RHS.End = RHS.Begin+NumShared;
364   }
365 }
366   
367 template <typename T>
368 const SmallVectorImpl<T> &
369 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
370   // Avoid self-assignment.
371   if (this == &RHS) return *this;
372   
373   // If we already have sufficient space, assign the common elements, then
374   // destroy any excess.
375   unsigned RHSSize = RHS.size();
376   unsigned CurSize = size();
377   if (CurSize >= RHSSize) {
378     // Assign common elements.
379     iterator NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
380     
381     // Destroy excess elements.
382     destroy_range(NewEnd, End);
383     
384     // Trim.
385     End = NewEnd;
386     return *this;
387   }
388   
389   // If we have to grow to have enough elements, destroy the current elements.
390   // This allows us to avoid copying them during the grow.
391   if (unsigned(Capacity-Begin) < RHSSize) {
392     // Destroy current elements.
393     destroy_range(Begin, End);
394     End = Begin;
395     CurSize = 0;
396     grow(RHSSize);
397   } else if (CurSize) {
398     // Otherwise, use assignment for the already-constructed elements.
399     std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
400   }
401   
402   // Copy construct the new elements in place.
403   std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
404   
405   // Set end.
406   End = Begin+RHSSize;
407   return *this;
408 }
409   
410 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
411 /// for the case when the array is small.  It contains some number of elements
412 /// in-place, which allows it to avoid heap allocation when the actual number of
413 /// elements is below that threshold.  This allows normal "small" cases to be
414 /// fast without losing generality for large inputs.
415 ///
416 /// Note that this does not attempt to be exception safe.
417 ///
418 template <typename T, unsigned N>
419 class SmallVector : public SmallVectorImpl<T> {
420   /// InlineElts - These are 'N-1' elements that are stored inline in the body
421   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
422   typedef typename SmallVectorImpl<T>::U U;
423   enum {
424     // MinUs - The number of U's require to cover N T's.
425     MinUs = (sizeof(T)*N+sizeof(U)-1)/sizeof(U),
426     
427     // NumInlineEltsElts - The number of elements actually in this array.  There
428     // is already one in the parent class, and we have to round up to avoid
429     // having a zero-element array.
430     NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
431     
432     // NumTsAvailable - The number of T's we actually have space for, which may
433     // be more than N due to rounding.
434     NumTsAvailable = (NumInlineEltsElts+1)*sizeof(U) / sizeof(T)
435   };
436   U InlineElts[NumInlineEltsElts];
437 public:  
438   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
439   }
440   
441   SmallVector(unsigned Size, const T &Value)
442     : SmallVectorImpl<T>(NumTsAvailable) {
443     this->reserve(Size);
444     while (Size--)
445       push_back(Value);
446   }
447   
448   template<typename ItTy>
449   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
450     append(S, E);
451   }
452   
453   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
454     operator=(RHS);
455   }
456   
457   const SmallVector &operator=(const SmallVector &RHS) {
458     SmallVectorImpl<T>::operator=(RHS);
459     return *this;
460   }
461 };
462
463 } // End llvm namespace
464
465 namespace std {
466   /// Implement std::swap in terms of SmallVector swap.
467   template<typename T>
468   inline void
469   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
470     LHS.swap(RHS);
471   }
472   
473   /// Implement std::swap in terms of SmallVector swap.
474   template<typename T, unsigned N>
475   inline void
476   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
477     LHS.swap(RHS);
478   }
479 }
480
481 #endif