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