5b7ed9cb77da1953b1ecdadc4aaae3b520c7319d
[oota-llvm.git] / include / llvm / ADT / ArrayRef.h
1 //===--- ArrayRef.h - Array Reference Wrapper -------------------*- 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 #ifndef LLVM_ADT_ARRAYREF_H
11 #define LLVM_ADT_ARRAYREF_H
12
13 #include "llvm/ADT/None.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include <vector>
17
18 namespace llvm {
19
20   /// ArrayRef - Represent a constant reference to an array (0 or more elements
21   /// consecutively in memory), i.e. a start pointer and a length.  It allows
22   /// various APIs to take consecutive elements easily and conveniently.
23   ///
24   /// This class does not own the underlying data, it is expected to be used in
25   /// situations where the data resides in some other buffer, whose lifetime
26   /// extends past that of the ArrayRef. For this reason, it is not in general
27   /// safe to store an ArrayRef.
28   ///
29   /// This is intended to be trivially copyable, so it should be passed by
30   /// value.
31   template<typename T>
32   class ArrayRef {
33   public:
34     typedef const T *iterator;
35     typedef const T *const_iterator;
36     typedef size_t size_type;
37
38     typedef std::reverse_iterator<iterator> reverse_iterator;
39
40   private:
41     /// The start of the array, in an external buffer.
42     const T *Data;
43
44     /// The number of elements.
45     size_type Length;
46
47     /// \brief A dummy "optional" type that is only created by implicit
48     /// conversion from a reference to T.
49     ///
50     /// This type must *only* be used in a function argument or as a copy of
51     /// a function argument, as otherwise it will hold a pointer to a temporary
52     /// past that temporaries' lifetime.
53     struct TRefOrNothing {
54       const T *TPtr;
55
56       TRefOrNothing() : TPtr(nullptr) {}
57       TRefOrNothing(const T &TRef) : TPtr(&TRef) {}
58     };
59
60   public:
61     /// @name Constructors
62     /// @{
63
64     /// Construct an empty ArrayRef.
65     /*implicit*/ ArrayRef() : Data(nullptr), Length(0) {}
66
67     /// Construct an empty ArrayRef from None.
68     /*implicit*/ ArrayRef(NoneType) : Data(nullptr), Length(0) {}
69
70     /// Construct an ArrayRef from a single element.
71     /*implicit*/ ArrayRef(const T &OneElt)
72       : Data(&OneElt), Length(1) {}
73
74     /// Construct an ArrayRef from a pointer and length.
75     /*implicit*/ ArrayRef(const T *data, size_t length)
76       : Data(data), Length(length) {}
77
78     /// Construct an ArrayRef from a range.
79     ArrayRef(const T *begin, const T *end)
80       : Data(begin), Length(end - begin) {}
81
82     /// Construct an ArrayRef from a SmallVector. This is templated in order to
83     /// avoid instantiating SmallVectorTemplateCommon<T> whenever we
84     /// copy-construct an ArrayRef.
85     template<typename U>
86     /*implicit*/ ArrayRef(const SmallVectorTemplateCommon<T, U> &Vec)
87       : Data(Vec.data()), Length(Vec.size()) {
88     }
89
90     /// Construct an ArrayRef from a std::vector.
91     template<typename A>
92     /*implicit*/ ArrayRef(const std::vector<T, A> &Vec)
93       : Data(Vec.data()), Length(Vec.size()) {}
94
95     /// Construct an ArrayRef from a C array.
96     template <size_t N>
97     /*implicit*/ LLVM_CONSTEXPR ArrayRef(const T (&Arr)[N])
98       : Data(Arr), Length(N) {}
99
100     /// Construct an ArrayRef from a std::initializer_list.
101     /*implicit*/ ArrayRef(const std::initializer_list<T> &Vec)
102     : Data(Vec.begin() == Vec.end() ? (T*)0 : Vec.begin()),
103       Length(Vec.size()) {}
104
105     /// Construct an ArrayRef<const T*> from ArrayRef<T*>. This uses SFINAE to
106     /// ensure that only ArrayRefs of pointers can be converted.
107     template <typename U>
108     ArrayRef(const ArrayRef<U *> &A,
109              typename std::enable_if<
110                  std::is_convertible<U *const *, T const *>::value>::type* = 0)
111       : Data(A.data()), Length(A.size()) {}
112
113     /// @}
114     /// @name Simple Operations
115     /// @{
116
117     iterator begin() const { return Data; }
118     iterator end() const { return Data + Length; }
119
120     reverse_iterator rbegin() const { return reverse_iterator(end()); }
121     reverse_iterator rend() const { return reverse_iterator(begin()); }
122
123     /// empty - Check if the array is empty.
124     bool empty() const { return Length == 0; }
125
126     const T *data() const { return Data; }
127
128     /// size - Get the array size.
129     size_t size() const { return Length; }
130
131     /// front - Get the first element.
132     const T &front() const {
133       assert(!empty());
134       return Data[0];
135     }
136
137     /// back - Get the last element.
138     const T &back() const {
139       assert(!empty());
140       return Data[Length-1];
141     }
142
143     // copy - Allocate copy in Allocator and return ArrayRef<T> to it.
144     template <typename Allocator> ArrayRef<T> copy(Allocator &A) {
145       T *Buff = A.template Allocate<T>(Length);
146       std::copy(begin(), end(), Buff);
147       return ArrayRef<T>(Buff, Length);
148     }
149
150     /// equals - Check for element-wise equality.
151     bool equals(ArrayRef RHS) const {
152       if (Length != RHS.Length)
153         return false;
154       // Don't use std::equal(), since it asserts in MSVC on nullptr iterators.
155       for (auto L = begin(), LE = end(), R = RHS.begin(); L != LE; ++L, ++R)
156         // Match std::equal() in using == (instead of !=) to minimize API
157         // requirements of ArrayRef'ed types.
158         if (!(*L == *R))
159           return false;
160       return true;
161     }
162
163     /// slice(n) - Chop off the first N elements of the array.
164     ArrayRef<T> slice(unsigned N) const {
165       assert(N <= size() && "Invalid specifier");
166       return ArrayRef<T>(data()+N, size()-N);
167     }
168
169     /// slice(n, m) - Chop off the first N elements of the array, and keep M
170     /// elements in the array.
171     ArrayRef<T> slice(unsigned N, unsigned M) const {
172       assert(N+M <= size() && "Invalid specifier");
173       return ArrayRef<T>(data()+N, M);
174     }
175
176     // \brief Drop the last \p N elements of the array.
177     ArrayRef<T> drop_back(unsigned N = 1) const {
178       assert(size() >= N && "Dropping more elements than exist");
179       return slice(0, size() - N);
180     }
181
182     /// @}
183     /// @name Operator Overloads
184     /// @{
185     const T &operator[](size_t Index) const {
186       assert(Index < Length && "Invalid index!");
187       return Data[Index];
188     }
189
190     /// @}
191     /// @name Expensive Operations
192     /// @{
193     std::vector<T> vec() const {
194       return std::vector<T>(Data, Data+Length);
195     }
196
197     /// @}
198     /// @name Conversion operators
199     /// @{
200     operator std::vector<T>() const {
201       return std::vector<T>(Data, Data+Length);
202     }
203
204     /// @}
205     /// @{
206     /// @name Convenience methods
207
208     /// @brief Predicate for testing that the array equals the exact sequence of
209     /// arguments.
210     ///
211     /// Will return false if the size is not equal to the exact number of
212     /// arguments given or if the array elements don't equal the argument
213     /// elements in order. Currently supports up to 16 arguments, but can
214     /// easily be extended.
215     bool equals(TRefOrNothing Arg0 = TRefOrNothing(),
216                 TRefOrNothing Arg1 = TRefOrNothing(),
217                 TRefOrNothing Arg2 = TRefOrNothing(),
218                 TRefOrNothing Arg3 = TRefOrNothing(),
219                 TRefOrNothing Arg4 = TRefOrNothing(),
220                 TRefOrNothing Arg5 = TRefOrNothing(),
221                 TRefOrNothing Arg6 = TRefOrNothing(),
222                 TRefOrNothing Arg7 = TRefOrNothing(),
223                 TRefOrNothing Arg8 = TRefOrNothing(),
224                 TRefOrNothing Arg9 = TRefOrNothing(),
225                 TRefOrNothing Arg10 = TRefOrNothing(),
226                 TRefOrNothing Arg11 = TRefOrNothing(),
227                 TRefOrNothing Arg12 = TRefOrNothing(),
228                 TRefOrNothing Arg13 = TRefOrNothing(),
229                 TRefOrNothing Arg14 = TRefOrNothing(),
230                 TRefOrNothing Arg15 = TRefOrNothing()) {
231       TRefOrNothing Args[] = {Arg0,  Arg1,  Arg2,  Arg3, Arg4,  Arg5,
232                               Arg6,  Arg7,  Arg8,  Arg9, Arg10, Arg11,
233                               Arg12, Arg13, Arg14, Arg15};
234       if (size() > array_lengthof(Args))
235         return false;
236
237       for (unsigned i = 0, e = size(); i != e; ++i)
238         if (Args[i].TPtr == nullptr || (*this)[i] != *Args[i].TPtr)
239           return false;
240
241       // Either the size is exactly as many args, or the next arg must be null.
242       return size() == array_lengthof(Args) || Args[size()].TPtr == nullptr;
243     }
244
245     /// @}
246   };
247
248   /// MutableArrayRef - Represent a mutable reference to an array (0 or more
249   /// elements consecutively in memory), i.e. a start pointer and a length.  It
250   /// allows various APIs to take and modify consecutive elements easily and
251   /// conveniently.
252   ///
253   /// This class does not own the underlying data, it is expected to be used in
254   /// situations where the data resides in some other buffer, whose lifetime
255   /// extends past that of the MutableArrayRef. For this reason, it is not in
256   /// general safe to store a MutableArrayRef.
257   ///
258   /// This is intended to be trivially copyable, so it should be passed by
259   /// value.
260   template<typename T>
261   class MutableArrayRef : public ArrayRef<T> {
262   public:
263     typedef T *iterator;
264
265     typedef std::reverse_iterator<iterator> reverse_iterator;
266
267     /// Construct an empty MutableArrayRef.
268     /*implicit*/ MutableArrayRef() : ArrayRef<T>() {}
269
270     /// Construct an empty MutableArrayRef from None.
271     /*implicit*/ MutableArrayRef(NoneType) : ArrayRef<T>() {}
272
273     /// Construct an MutableArrayRef from a single element.
274     /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {}
275
276     /// Construct an MutableArrayRef from a pointer and length.
277     /*implicit*/ MutableArrayRef(T *data, size_t length)
278       : ArrayRef<T>(data, length) {}
279
280     /// Construct an MutableArrayRef from a range.
281     MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {}
282
283     /// Construct an MutableArrayRef from a SmallVector.
284     /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec)
285     : ArrayRef<T>(Vec) {}
286
287     /// Construct a MutableArrayRef from a std::vector.
288     /*implicit*/ MutableArrayRef(std::vector<T> &Vec)
289     : ArrayRef<T>(Vec) {}
290
291     /// Construct an MutableArrayRef from a C array.
292     template <size_t N>
293     /*implicit*/ LLVM_CONSTEXPR MutableArrayRef(T (&Arr)[N])
294       : ArrayRef<T>(Arr) {}
295
296     T *data() const { return const_cast<T*>(ArrayRef<T>::data()); }
297
298     iterator begin() const { return data(); }
299     iterator end() const { return data() + this->size(); }
300
301     reverse_iterator rbegin() const { return reverse_iterator(end()); }
302     reverse_iterator rend() const { return reverse_iterator(begin()); }
303
304     /// front - Get the first element.
305     T &front() const {
306       assert(!this->empty());
307       return data()[0];
308     }
309
310     /// back - Get the last element.
311     T &back() const {
312       assert(!this->empty());
313       return data()[this->size()-1];
314     }
315
316     /// slice(n) - Chop off the first N elements of the array.
317     MutableArrayRef<T> slice(unsigned N) const {
318       assert(N <= this->size() && "Invalid specifier");
319       return MutableArrayRef<T>(data()+N, this->size()-N);
320     }
321
322     /// slice(n, m) - Chop off the first N elements of the array, and keep M
323     /// elements in the array.
324     MutableArrayRef<T> slice(unsigned N, unsigned M) const {
325       assert(N+M <= this->size() && "Invalid specifier");
326       return MutableArrayRef<T>(data()+N, M);
327     }
328
329     /// @}
330     /// @name Operator Overloads
331     /// @{
332     T &operator[](size_t Index) const {
333       assert(Index < this->size() && "Invalid index!");
334       return data()[Index];
335     }
336   };
337
338   /// @name ArrayRef Convenience constructors
339   /// @{
340
341   /// Construct an ArrayRef from a single element.
342   template<typename T>
343   ArrayRef<T> makeArrayRef(const T &OneElt) {
344     return OneElt;
345   }
346
347   /// Construct an ArrayRef from a pointer and length.
348   template<typename T>
349   ArrayRef<T> makeArrayRef(const T *data, size_t length) {
350     return ArrayRef<T>(data, length);
351   }
352
353   /// Construct an ArrayRef from a range.
354   template<typename T>
355   ArrayRef<T> makeArrayRef(const T *begin, const T *end) {
356     return ArrayRef<T>(begin, end);
357   }
358
359   /// Construct an ArrayRef from a SmallVector.
360   template <typename T>
361   ArrayRef<T> makeArrayRef(const SmallVectorImpl<T> &Vec) {
362     return Vec;
363   }
364
365   /// Construct an ArrayRef from a SmallVector.
366   template <typename T, unsigned N>
367   ArrayRef<T> makeArrayRef(const SmallVector<T, N> &Vec) {
368     return Vec;
369   }
370
371   /// Construct an ArrayRef from a std::vector.
372   template<typename T>
373   ArrayRef<T> makeArrayRef(const std::vector<T> &Vec) {
374     return Vec;
375   }
376
377   /// Construct an ArrayRef from a C array.
378   template<typename T, size_t N>
379   ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
380     return ArrayRef<T>(Arr);
381   }
382
383   /// @}
384   /// @name ArrayRef Comparison Operators
385   /// @{
386
387   template<typename T>
388   inline bool operator==(ArrayRef<T> LHS, ArrayRef<T> RHS) {
389     return LHS.equals(RHS);
390   }
391
392   template<typename T>
393   inline bool operator!=(ArrayRef<T> LHS, ArrayRef<T> RHS) {
394     return !(LHS == RHS);
395   }
396
397   /// @}
398
399   // ArrayRefs can be treated like a POD type.
400   template <typename T> struct isPodLike;
401   template <typename T> struct isPodLike<ArrayRef<T> > {
402     static const bool value = true;
403   };
404 }
405
406 #endif