44400d591da9b1186a48f43043d5544948963e2a
[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 #if LLVM_HAS_INITIALIZER_LISTS
101     /// Construct an ArrayRef from a std::initializer_list.
102     /*implicit*/ ArrayRef(const std::initializer_list<T> &Vec)
103     : Data(Vec.begin() == Vec.end() ? (T*)0 : Vec.begin()),
104       Length(Vec.size()) {}
105 #endif
106
107     /// @}
108     /// @name Simple Operations
109     /// @{
110
111     iterator begin() const { return Data; }
112     iterator end() const { return Data + Length; }
113
114     reverse_iterator rbegin() const { return reverse_iterator(end()); }
115     reverse_iterator rend() const { return reverse_iterator(begin()); }
116
117     /// empty - Check if the array is empty.
118     bool empty() const { return Length == 0; }
119
120     const T *data() const { return Data; }
121
122     /// size - Get the array size.
123     size_t size() const { return Length; }
124
125     /// front - Get the first element.
126     const T &front() const {
127       assert(!empty());
128       return Data[0];
129     }
130
131     /// back - Get the last element.
132     const T &back() const {
133       assert(!empty());
134       return Data[Length-1];
135     }
136
137     // copy - Allocate copy in Allocator and return ArrayRef<T> to it.
138     template <typename Allocator> ArrayRef<T> copy(Allocator &A) {
139       T *Buff = A.template Allocate<T>(Length);
140       std::copy(begin(), end(), Buff);
141       return ArrayRef<T>(Buff, Length);
142     }
143
144     /// equals - Check for element-wise equality.
145     bool equals(ArrayRef RHS) const {
146       if (Length != RHS.Length)
147         return false;
148       return std::equal(begin(), end(), RHS.begin());
149     }
150
151     /// slice(n) - Chop off the first N elements of the array.
152     ArrayRef<T> slice(unsigned N) const {
153       assert(N <= size() && "Invalid specifier");
154       return ArrayRef<T>(data()+N, size()-N);
155     }
156
157     /// slice(n, m) - Chop off the first N elements of the array, and keep M
158     /// elements in the array.
159     ArrayRef<T> slice(unsigned N, unsigned M) const {
160       assert(N+M <= size() && "Invalid specifier");
161       return ArrayRef<T>(data()+N, M);
162     }
163
164     // \brief Drop the last \p N elements of the array.
165     ArrayRef<T> drop_back(unsigned N = 1) const {
166       assert(size() >= N && "Dropping more elements than exist");
167       return slice(0, size() - N);
168     }
169
170     /// @}
171     /// @name Operator Overloads
172     /// @{
173     const T &operator[](size_t Index) const {
174       assert(Index < Length && "Invalid index!");
175       return Data[Index];
176     }
177
178     /// @}
179     /// @name Expensive Operations
180     /// @{
181     std::vector<T> vec() const {
182       return std::vector<T>(Data, Data+Length);
183     }
184
185     /// @}
186     /// @name Conversion operators
187     /// @{
188     operator std::vector<T>() const {
189       return std::vector<T>(Data, Data+Length);
190     }
191
192     /// @}
193     /// @{
194     /// @name Convenience methods
195
196     /// @brief Predicate for testing that the array equals the exact sequence of
197     /// arguments.
198     ///
199     /// Will return false if the size is not equal to the exact number of
200     /// arguments given or if the array elements don't equal the argument
201     /// elements in order. Currently supports up to 16 arguments, but can
202     /// easily be extended.
203     bool equals(TRefOrNothing Arg0 = TRefOrNothing(),
204                 TRefOrNothing Arg1 = TRefOrNothing(),
205                 TRefOrNothing Arg2 = TRefOrNothing(),
206                 TRefOrNothing Arg3 = TRefOrNothing(),
207                 TRefOrNothing Arg4 = TRefOrNothing(),
208                 TRefOrNothing Arg5 = TRefOrNothing(),
209                 TRefOrNothing Arg6 = TRefOrNothing(),
210                 TRefOrNothing Arg7 = TRefOrNothing(),
211                 TRefOrNothing Arg8 = TRefOrNothing(),
212                 TRefOrNothing Arg9 = TRefOrNothing(),
213                 TRefOrNothing Arg10 = TRefOrNothing(),
214                 TRefOrNothing Arg11 = TRefOrNothing(),
215                 TRefOrNothing Arg12 = TRefOrNothing(),
216                 TRefOrNothing Arg13 = TRefOrNothing(),
217                 TRefOrNothing Arg14 = TRefOrNothing(),
218                 TRefOrNothing Arg15 = TRefOrNothing()) {
219       TRefOrNothing Args[] = {Arg0,  Arg1,  Arg2,  Arg3, Arg4,  Arg5,
220                               Arg6,  Arg7,  Arg8,  Arg9, Arg10, Arg11,
221                               Arg12, Arg13, Arg14, Arg15};
222       if (size() > array_lengthof(Args))
223         return false;
224
225       for (unsigned i = 0, e = size(); i != e; ++i)
226         if (Args[i].TPtr == nullptr || (*this)[i] != *Args[i].TPtr)
227           return false;
228
229       // Either the size is exactly as many args, or the next arg must be null.
230       return size() == array_lengthof(Args) || Args[size()].TPtr == nullptr;
231     }
232
233     /// @}
234   };
235
236   /// MutableArrayRef - Represent a mutable reference to an array (0 or more
237   /// elements consecutively in memory), i.e. a start pointer and a length.  It
238   /// allows various APIs to take and modify consecutive elements easily and
239   /// conveniently.
240   ///
241   /// This class does not own the underlying data, it is expected to be used in
242   /// situations where the data resides in some other buffer, whose lifetime
243   /// extends past that of the MutableArrayRef. For this reason, it is not in
244   /// general safe to store a MutableArrayRef.
245   ///
246   /// This is intended to be trivially copyable, so it should be passed by
247   /// value.
248   template<typename T>
249   class MutableArrayRef : public ArrayRef<T> {
250   public:
251     typedef T *iterator;
252
253     typedef std::reverse_iterator<iterator> reverse_iterator;
254
255     /// Construct an empty MutableArrayRef.
256     /*implicit*/ MutableArrayRef() : ArrayRef<T>() {}
257
258     /// Construct an empty MutableArrayRef from None.
259     /*implicit*/ MutableArrayRef(NoneType) : ArrayRef<T>() {}
260
261     /// Construct an MutableArrayRef from a single element.
262     /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {}
263
264     /// Construct an MutableArrayRef from a pointer and length.
265     /*implicit*/ MutableArrayRef(T *data, size_t length)
266       : ArrayRef<T>(data, length) {}
267
268     /// Construct an MutableArrayRef from a range.
269     MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {}
270
271     /// Construct an MutableArrayRef from a SmallVector.
272     /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec)
273     : ArrayRef<T>(Vec) {}
274
275     /// Construct a MutableArrayRef from a std::vector.
276     /*implicit*/ MutableArrayRef(std::vector<T> &Vec)
277     : ArrayRef<T>(Vec) {}
278
279     /// Construct an MutableArrayRef from a C array.
280     template <size_t N>
281     /*implicit*/ LLVM_CONSTEXPR MutableArrayRef(T (&Arr)[N])
282       : ArrayRef<T>(Arr) {}
283
284     T *data() const { return const_cast<T*>(ArrayRef<T>::data()); }
285
286     iterator begin() const { return data(); }
287     iterator end() const { return data() + this->size(); }
288
289     reverse_iterator rbegin() const { return reverse_iterator(end()); }
290     reverse_iterator rend() const { return reverse_iterator(begin()); }
291
292     /// front - Get the first element.
293     T &front() const {
294       assert(!this->empty());
295       return data()[0];
296     }
297
298     /// back - Get the last element.
299     T &back() const {
300       assert(!this->empty());
301       return data()[this->size()-1];
302     }
303
304     /// slice(n) - Chop off the first N elements of the array.
305     MutableArrayRef<T> slice(unsigned N) const {
306       assert(N <= this->size() && "Invalid specifier");
307       return MutableArrayRef<T>(data()+N, this->size()-N);
308     }
309
310     /// slice(n, m) - Chop off the first N elements of the array, and keep M
311     /// elements in the array.
312     MutableArrayRef<T> slice(unsigned N, unsigned M) const {
313       assert(N+M <= this->size() && "Invalid specifier");
314       return MutableArrayRef<T>(data()+N, M);
315     }
316
317     /// @}
318     /// @name Operator Overloads
319     /// @{
320     T &operator[](size_t Index) const {
321       assert(Index < this->size() && "Invalid index!");
322       return data()[Index];
323     }
324   };
325
326   /// @name ArrayRef Convenience constructors
327   /// @{
328
329   /// Construct an ArrayRef from a single element.
330   template<typename T>
331   ArrayRef<T> makeArrayRef(const T &OneElt) {
332     return OneElt;
333   }
334
335   /// Construct an ArrayRef from a pointer and length.
336   template<typename T>
337   ArrayRef<T> makeArrayRef(const T *data, size_t length) {
338     return ArrayRef<T>(data, length);
339   }
340
341   /// Construct an ArrayRef from a range.
342   template<typename T>
343   ArrayRef<T> makeArrayRef(const T *begin, const T *end) {
344     return ArrayRef<T>(begin, end);
345   }
346
347   /// Construct an ArrayRef from a SmallVector.
348   template <typename T>
349   ArrayRef<T> makeArrayRef(const SmallVectorImpl<T> &Vec) {
350     return Vec;
351   }
352
353   /// Construct an ArrayRef from a SmallVector.
354   template <typename T, unsigned N>
355   ArrayRef<T> makeArrayRef(const SmallVector<T, N> &Vec) {
356     return Vec;
357   }
358
359   /// Construct an ArrayRef from a std::vector.
360   template<typename T>
361   ArrayRef<T> makeArrayRef(const std::vector<T> &Vec) {
362     return Vec;
363   }
364
365   /// Construct an ArrayRef from a C array.
366   template<typename T, size_t N>
367   ArrayRef<T> makeArrayRef(const T (&Arr)[N]) {
368     return ArrayRef<T>(Arr);
369   }
370
371   /// @}
372   /// @name ArrayRef Comparison Operators
373   /// @{
374
375   template<typename T>
376   inline bool operator==(ArrayRef<T> LHS, ArrayRef<T> RHS) {
377     return LHS.equals(RHS);
378   }
379
380   template<typename T>
381   inline bool operator!=(ArrayRef<T> LHS, ArrayRef<T> RHS) {
382     return !(LHS == RHS);
383   }
384
385   /// @}
386
387   // ArrayRefs can be treated like a POD type.
388   template <typename T> struct isPodLike;
389   template <typename T> struct isPodLike<ArrayRef<T> > {
390     static const bool value = true;
391   };
392 }
393
394 #endif