1//===-- llvm/Constants.h - Constant class subclass definitions --*- 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/// @file
11/// This file contains the declarations for the subclasses of Constant,
12/// which represent the different flavors of constant values that live in LLVM.
13/// Note that Constants are immutable (once created they never change) and are
14/// fully shared by structural equivalence.  This means that two structurally
15/// equivalent constants will always have the same address.  Constant's are
16/// created on demand as needed and never deleted: thus clients don't have to
17/// worry about the lifetime of the objects.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_IR_CONSTANTS_H
22#define LLVM_IR_CONSTANTS_H
23
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/IR/Constant.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/OperandTraits.h"
30
31namespace llvm {
32
33class ArrayType;
34class IntegerType;
35class StructType;
36class PointerType;
37class VectorType;
38class SequentialType;
39
40template<class ConstantClass, class TypeClass, class ValType>
41struct ConstantCreator;
42template<class ConstantClass, class TypeClass>
43struct ConstantArrayCreator;
44template<class ConstantClass, class TypeClass>
45struct ConvertConstantType;
46
47//===----------------------------------------------------------------------===//
48/// This is the shared class of boolean and integer constants. This class
49/// represents both boolean and integral constants.
50/// @brief Class for constant integers.
51class ConstantInt : public Constant {
52  void anchor() override;
53  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
54  ConstantInt(const ConstantInt &) LLVM_DELETED_FUNCTION;
55  ConstantInt(IntegerType *Ty, const APInt& V);
56  APInt Val;
57protected:
58  // allocate space for exactly zero operands
59  void *operator new(size_t s) {
60    return User::operator new(s, 0);
61  }
62public:
63  static ConstantInt *getTrue(LLVMContext &Context);
64  static ConstantInt *getFalse(LLVMContext &Context);
65  static Constant *getTrue(Type *Ty);
66  static Constant *getFalse(Type *Ty);
67
68  /// If Ty is a vector type, return a Constant with a splat of the given
69  /// value. Otherwise return a ConstantInt for the given value.
70  static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);
71
72  /// Return a ConstantInt with the specified integer value for the specified
73  /// type. If the type is wider than 64 bits, the value will be zero-extended
74  /// to fit the type, unless isSigned is true, in which case the value will
75  /// be interpreted as a 64-bit signed integer and sign-extended to fit
76  /// the type.
77  /// @brief Get a ConstantInt for a specific value.
78  static ConstantInt *get(IntegerType *Ty, uint64_t V,
79                          bool isSigned = false);
80
81  /// Return a ConstantInt with the specified value for the specified type. The
82  /// value V will be canonicalized to a an unsigned APInt. Accessing it with
83  /// either getSExtValue() or getZExtValue() will yield a correctly sized and
84  /// signed value for the type Ty.
85  /// @brief Get a ConstantInt for a specific signed value.
86  static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
87  static Constant *getSigned(Type *Ty, int64_t V);
88
89  /// Return a ConstantInt with the specified value and an implied Type. The
90  /// type is the integer type that corresponds to the bit width of the value.
91  static ConstantInt *get(LLVMContext &Context, const APInt &V);
92
93  /// Return a ConstantInt constructed from the string strStart with the given
94  /// radix.
95  static ConstantInt *get(IntegerType *Ty, StringRef Str,
96                          uint8_t radix);
97
98  /// If Ty is a vector type, return a Constant with a splat of the given
99  /// value. Otherwise return a ConstantInt for the given value.
100  static Constant *get(Type* Ty, const APInt& V);
101
102  /// Return the constant as an APInt value reference. This allows clients to
103  /// obtain a copy of the value, with all its precision in tact.
104  /// @brief Return the constant's value.
105  inline const APInt &getValue() const {
106    return Val;
107  }
108
109  /// getBitWidth - Return the bitwidth of this constant.
110  unsigned getBitWidth() const { return Val.getBitWidth(); }
111
112  /// Return the constant as a 64-bit unsigned integer value after it
113  /// has been zero extended as appropriate for the type of this constant. Note
114  /// that this method can assert if the value does not fit in 64 bits.
115  /// @brief Return the zero extended value.
116  inline uint64_t getZExtValue() const {
117    return Val.getZExtValue();
118  }
119
120  /// Return the constant as a 64-bit integer value after it has been sign
121  /// extended as appropriate for the type of this constant. Note that
122  /// this method can assert if the value does not fit in 64 bits.
123  /// @brief Return the sign extended value.
124  inline int64_t getSExtValue() const {
125    return Val.getSExtValue();
126  }
127
128  /// A helper method that can be used to determine if the constant contained
129  /// within is equal to a constant.  This only works for very small values,
130  /// because this is all that can be represented with all types.
131  /// @brief Determine if this constant's value is same as an unsigned char.
132  bool equalsInt(uint64_t V) const {
133    return Val == V;
134  }
135
136  /// getType - Specialize the getType() method to always return an IntegerType,
137  /// which reduces the amount of casting needed in parts of the compiler.
138  ///
139  inline IntegerType *getType() const {
140    return cast<IntegerType>(Value::getType());
141  }
142
143  /// This static method returns true if the type Ty is big enough to
144  /// represent the value V. This can be used to avoid having the get method
145  /// assert when V is larger than Ty can represent. Note that there are two
146  /// versions of this method, one for unsigned and one for signed integers.
147  /// Although ConstantInt canonicalizes everything to an unsigned integer,
148  /// the signed version avoids callers having to convert a signed quantity
149  /// to the appropriate unsigned type before calling the method.
150  /// @returns true if V is a valid value for type Ty
151  /// @brief Determine if the value is in range for the given type.
152  static bool isValueValidForType(Type *Ty, uint64_t V);
153  static bool isValueValidForType(Type *Ty, int64_t V);
154
155  bool isNegative() const { return Val.isNegative(); }
156
157  /// This is just a convenience method to make client code smaller for a
158  /// common code. It also correctly performs the comparison without the
159  /// potential for an assertion from getZExtValue().
160  bool isZero() const {
161    return Val == 0;
162  }
163
164  /// This is just a convenience method to make client code smaller for a
165  /// common case. It also correctly performs the comparison without the
166  /// potential for an assertion from getZExtValue().
167  /// @brief Determine if the value is one.
168  bool isOne() const {
169    return Val == 1;
170  }
171
172  /// This function will return true iff every bit in this constant is set
173  /// to true.
174  /// @returns true iff this constant's bits are all set to true.
175  /// @brief Determine if the value is all ones.
176  bool isMinusOne() const {
177    return Val.isAllOnesValue();
178  }
179
180  /// This function will return true iff this constant represents the largest
181  /// value that may be represented by the constant's type.
182  /// @returns true iff this is the largest value that may be represented
183  /// by this type.
184  /// @brief Determine if the value is maximal.
185  bool isMaxValue(bool isSigned) const {
186    if (isSigned)
187      return Val.isMaxSignedValue();
188    else
189      return Val.isMaxValue();
190  }
191
192  /// This function will return true iff this constant represents the smallest
193  /// value that may be represented by this constant's type.
194  /// @returns true if this is the smallest value that may be represented by
195  /// this type.
196  /// @brief Determine if the value is minimal.
197  bool isMinValue(bool isSigned) const {
198    if (isSigned)
199      return Val.isMinSignedValue();
200    else
201      return Val.isMinValue();
202  }
203
204  /// This function will return true iff this constant represents a value with
205  /// active bits bigger than 64 bits or a value greater than the given uint64_t
206  /// value.
207  /// @returns true iff this constant is greater or equal to the given number.
208  /// @brief Determine if the value is greater or equal to the given number.
209  bool uge(uint64_t Num) const {
210    return Val.getActiveBits() > 64 || Val.getZExtValue() >= Num;
211  }
212
213  /// getLimitedValue - If the value is smaller than the specified limit,
214  /// return it, otherwise return the limit value.  This causes the value
215  /// to saturate to the limit.
216  /// @returns the min of the value of the constant and the specified value
217  /// @brief Get the constant's value with a saturation limit
218  uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
219    return Val.getLimitedValue(Limit);
220  }
221
222  /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
223  static bool classof(const Value *V) {
224    return V->getValueID() == ConstantIntVal;
225  }
226};
227
228
229//===----------------------------------------------------------------------===//
230/// ConstantFP - Floating Point Values [float, double]
231///
232class ConstantFP : public Constant {
233  APFloat Val;
234  void anchor() override;
235  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
236  ConstantFP(const ConstantFP &) LLVM_DELETED_FUNCTION;
237  friend class LLVMContextImpl;
238protected:
239  ConstantFP(Type *Ty, const APFloat& V);
240protected:
241  // allocate space for exactly zero operands
242  void *operator new(size_t s) {
243    return User::operator new(s, 0);
244  }
245public:
246  /// Floating point negation must be implemented with f(x) = -0.0 - x. This
247  /// method returns the negative zero constant for floating point or vector
248  /// floating point types; for all other types, it returns the null value.
249  static Constant *getZeroValueForNegation(Type *Ty);
250
251  /// get() - This returns a ConstantFP, or a vector containing a splat of a
252  /// ConstantFP, for the specified value in the specified type.  This should
253  /// only be used for simple constant values like 2.0/1.0 etc, that are
254  /// known-valid both as host double and as the target format.
255  static Constant *get(Type* Ty, double V);
256  static Constant *get(Type* Ty, StringRef Str);
257  static ConstantFP *get(LLVMContext &Context, const APFloat &V);
258  static Constant *getNegativeZero(Type *Ty);
259  static Constant *getInfinity(Type *Ty, bool Negative = false);
260
261  /// isValueValidForType - return true if Ty is big enough to represent V.
262  static bool isValueValidForType(Type *Ty, const APFloat &V);
263  inline const APFloat &getValueAPF() const { return Val; }
264
265  /// isZero - Return true if the value is positive or negative zero.
266  bool isZero() const { return Val.isZero(); }
267
268  /// isNegative - Return true if the sign bit is set.
269  bool isNegative() const { return Val.isNegative(); }
270
271  /// isNaN - Return true if the value is a NaN.
272  bool isNaN() const { return Val.isNaN(); }
273
274  /// isExactlyValue - We don't rely on operator== working on double values, as
275  /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
276  /// As such, this method can be used to do an exact bit-for-bit comparison of
277  /// two floating point values.  The version with a double operand is retained
278  /// because it's so convenient to write isExactlyValue(2.0), but please use
279  /// it only for simple constants.
280  bool isExactlyValue(const APFloat &V) const;
281
282  bool isExactlyValue(double V) const {
283    bool ignored;
284    APFloat FV(V);
285    FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
286    return isExactlyValue(FV);
287  }
288  /// Methods for support type inquiry through isa, cast, and dyn_cast:
289  static bool classof(const Value *V) {
290    return V->getValueID() == ConstantFPVal;
291  }
292};
293
294//===----------------------------------------------------------------------===//
295/// ConstantAggregateZero - All zero aggregate value
296///
297class ConstantAggregateZero : public Constant {
298  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
299  ConstantAggregateZero(const ConstantAggregateZero &) LLVM_DELETED_FUNCTION;
300protected:
301  explicit ConstantAggregateZero(Type *ty)
302    : Constant(ty, ConstantAggregateZeroVal, nullptr, 0) {}
303protected:
304  // allocate space for exactly zero operands
305  void *operator new(size_t s) {
306    return User::operator new(s, 0);
307  }
308public:
309  static ConstantAggregateZero *get(Type *Ty);
310
311  void destroyConstant() override;
312
313  /// getSequentialElement - If this CAZ has array or vector type, return a zero
314  /// with the right element type.
315  Constant *getSequentialElement() const;
316
317  /// getStructElement - If this CAZ has struct type, return a zero with the
318  /// right element type for the specified element.
319  Constant *getStructElement(unsigned Elt) const;
320
321  /// getElementValue - Return a zero of the right value for the specified GEP
322  /// index.
323  Constant *getElementValue(Constant *C) const;
324
325  /// getElementValue - Return a zero of the right value for the specified GEP
326  /// index.
327  Constant *getElementValue(unsigned Idx) const;
328
329  /// Methods for support type inquiry through isa, cast, and dyn_cast:
330  ///
331  static bool classof(const Value *V) {
332    return V->getValueID() == ConstantAggregateZeroVal;
333  }
334};
335
336
337//===----------------------------------------------------------------------===//
338/// ConstantArray - Constant Array Declarations
339///
340class ConstantArray : public Constant {
341  friend struct ConstantArrayCreator<ConstantArray, ArrayType>;
342  ConstantArray(const ConstantArray &) LLVM_DELETED_FUNCTION;
343protected:
344  ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
345public:
346  // ConstantArray accessors
347  static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
348
349  /// Transparently provide more efficient getOperand methods.
350  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
351
352  /// getType - Specialize the getType() method to always return an ArrayType,
353  /// which reduces the amount of casting needed in parts of the compiler.
354  ///
355  inline ArrayType *getType() const {
356    return cast<ArrayType>(Value::getType());
357  }
358
359  void destroyConstant() override;
360  void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
361
362  /// Methods for support type inquiry through isa, cast, and dyn_cast:
363  static bool classof(const Value *V) {
364    return V->getValueID() == ConstantArrayVal;
365  }
366};
367
368template <>
369struct OperandTraits<ConstantArray> :
370  public VariadicOperandTraits<ConstantArray> {
371};
372
373DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantArray, Constant)
374
375//===----------------------------------------------------------------------===//
376// ConstantStruct - Constant Struct Declarations
377//
378class ConstantStruct : public Constant {
379  friend struct ConstantArrayCreator<ConstantStruct, StructType>;
380  ConstantStruct(const ConstantStruct &) LLVM_DELETED_FUNCTION;
381protected:
382  ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
383public:
384  // ConstantStruct accessors
385  static Constant *get(StructType *T, ArrayRef<Constant*> V);
386  static Constant *get(StructType *T, ...) END_WITH_NULL;
387
388  /// getAnon - Return an anonymous struct that has the specified
389  /// elements.  If the struct is possibly empty, then you must specify a
390  /// context.
391  static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) {
392    return get(getTypeForElements(V, Packed), V);
393  }
394  static Constant *getAnon(LLVMContext &Ctx,
395                           ArrayRef<Constant*> V, bool Packed = false) {
396    return get(getTypeForElements(Ctx, V, Packed), V);
397  }
398
399  /// getTypeForElements - Return an anonymous struct type to use for a constant
400  /// with the specified set of elements.  The list must not be empty.
401  static StructType *getTypeForElements(ArrayRef<Constant*> V,
402                                        bool Packed = false);
403  /// getTypeForElements - This version of the method allows an empty list.
404  static StructType *getTypeForElements(LLVMContext &Ctx,
405                                        ArrayRef<Constant*> V,
406                                        bool Packed = false);
407
408  /// Transparently provide more efficient getOperand methods.
409  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
410
411  /// getType() specialization - Reduce amount of casting...
412  ///
413  inline StructType *getType() const {
414    return cast<StructType>(Value::getType());
415  }
416
417  void destroyConstant() override;
418  void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
419
420  /// Methods for support type inquiry through isa, cast, and dyn_cast:
421  static bool classof(const Value *V) {
422    return V->getValueID() == ConstantStructVal;
423  }
424};
425
426template <>
427struct OperandTraits<ConstantStruct> :
428  public VariadicOperandTraits<ConstantStruct> {
429};
430
431DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantStruct, Constant)
432
433
434//===----------------------------------------------------------------------===//
435/// ConstantVector - Constant Vector Declarations
436///
437class ConstantVector : public Constant {
438  friend struct ConstantArrayCreator<ConstantVector, VectorType>;
439  ConstantVector(const ConstantVector &) LLVM_DELETED_FUNCTION;
440protected:
441  ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
442public:
443  // ConstantVector accessors
444  static Constant *get(ArrayRef<Constant*> V);
445
446  /// getSplat - Return a ConstantVector with the specified constant in each
447  /// element.
448  static Constant *getSplat(unsigned NumElts, Constant *Elt);
449
450  /// Transparently provide more efficient getOperand methods.
451  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
452
453  /// getType - Specialize the getType() method to always return a VectorType,
454  /// which reduces the amount of casting needed in parts of the compiler.
455  ///
456  inline VectorType *getType() const {
457    return cast<VectorType>(Value::getType());
458  }
459
460  /// getSplatValue - If this is a splat constant, meaning that all of the
461  /// elements have the same value, return that value. Otherwise return NULL.
462  Constant *getSplatValue() const;
463
464  void destroyConstant() override;
465  void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
466
467  /// Methods for support type inquiry through isa, cast, and dyn_cast:
468  static bool classof(const Value *V) {
469    return V->getValueID() == ConstantVectorVal;
470  }
471};
472
473template <>
474struct OperandTraits<ConstantVector> :
475  public VariadicOperandTraits<ConstantVector> {
476};
477
478DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantVector, Constant)
479
480//===----------------------------------------------------------------------===//
481/// ConstantPointerNull - a constant pointer value that points to null
482///
483class ConstantPointerNull : public Constant {
484  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
485  ConstantPointerNull(const ConstantPointerNull &) LLVM_DELETED_FUNCTION;
486protected:
487  explicit ConstantPointerNull(PointerType *T)
488    : Constant(T,
489               Value::ConstantPointerNullVal, nullptr, 0) {}
490
491protected:
492  // allocate space for exactly zero operands
493  void *operator new(size_t s) {
494    return User::operator new(s, 0);
495  }
496public:
497  /// get() - Static factory methods - Return objects of the specified value
498  static ConstantPointerNull *get(PointerType *T);
499
500  void destroyConstant() override;
501
502  /// getType - Specialize the getType() method to always return an PointerType,
503  /// which reduces the amount of casting needed in parts of the compiler.
504  ///
505  inline PointerType *getType() const {
506    return cast<PointerType>(Value::getType());
507  }
508
509  /// Methods for support type inquiry through isa, cast, and dyn_cast:
510  static bool classof(const Value *V) {
511    return V->getValueID() == ConstantPointerNullVal;
512  }
513};
514
515//===----------------------------------------------------------------------===//
516/// ConstantDataSequential - A vector or array constant whose element type is a
517/// simple 1/2/4/8-byte integer or float/double, and whose elements are just
518/// simple data values (i.e. ConstantInt/ConstantFP).  This Constant node has no
519/// operands because it stores all of the elements of the constant as densely
520/// packed data, instead of as Value*'s.
521///
522/// This is the common base class of ConstantDataArray and ConstantDataVector.
523///
524class ConstantDataSequential : public Constant {
525  friend class LLVMContextImpl;
526  /// DataElements - A pointer to the bytes underlying this constant (which is
527  /// owned by the uniquing StringMap).
528  const char *DataElements;
529
530  /// Next - This forms a link list of ConstantDataSequential nodes that have
531  /// the same value but different type.  For example, 0,0,0,1 could be a 4
532  /// element array of i8, or a 1-element array of i32.  They'll both end up in
533  /// the same StringMap bucket, linked up.
534  ConstantDataSequential *Next;
535  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
536  ConstantDataSequential(const ConstantDataSequential &) LLVM_DELETED_FUNCTION;
537protected:
538  explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
539    : Constant(ty, VT, nullptr, 0), DataElements(Data), Next(nullptr) {}
540  ~ConstantDataSequential() { delete Next; }
541
542  static Constant *getImpl(StringRef Bytes, Type *Ty);
543
544protected:
545  // allocate space for exactly zero operands.
546  void *operator new(size_t s) {
547    return User::operator new(s, 0);
548  }
549public:
550
551  /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
552  /// formed with a vector or array of the specified element type.
553  /// ConstantDataArray only works with normal float and int types that are
554  /// stored densely in memory, not with things like i42 or x86_f80.
555  static bool isElementTypeCompatible(const Type *Ty);
556
557  /// getElementAsInteger - If this is a sequential container of integers (of
558  /// any size), return the specified element in the low bits of a uint64_t.
559  uint64_t getElementAsInteger(unsigned i) const;
560
561  /// getElementAsAPFloat - If this is a sequential container of floating point
562  /// type, return the specified element as an APFloat.
563  APFloat getElementAsAPFloat(unsigned i) const;
564
565  /// getElementAsFloat - If this is an sequential container of floats, return
566  /// the specified element as a float.
567  float getElementAsFloat(unsigned i) const;
568
569  /// getElementAsDouble - If this is an sequential container of doubles, return
570  /// the specified element as a double.
571  double getElementAsDouble(unsigned i) const;
572
573  /// getElementAsConstant - Return a Constant for a specified index's element.
574  /// Note that this has to compute a new constant to return, so it isn't as
575  /// efficient as getElementAsInteger/Float/Double.
576  Constant *getElementAsConstant(unsigned i) const;
577
578  /// getType - Specialize the getType() method to always return a
579  /// SequentialType, which reduces the amount of casting needed in parts of the
580  /// compiler.
581  inline SequentialType *getType() const {
582    return cast<SequentialType>(Value::getType());
583  }
584
585  /// getElementType - Return the element type of the array/vector.
586  Type *getElementType() const;
587
588  /// getNumElements - Return the number of elements in the array or vector.
589  unsigned getNumElements() const;
590
591  /// getElementByteSize - Return the size (in bytes) of each element in the
592  /// array/vector.  The size of the elements is known to be a multiple of one
593  /// byte.
594  uint64_t getElementByteSize() const;
595
596
597  /// isString - This method returns true if this is an array of i8.
598  bool isString() const;
599
600  /// isCString - This method returns true if the array "isString", ends with a
601  /// nul byte, and does not contains any other nul bytes.
602  bool isCString() const;
603
604  /// getAsString - If this array is isString(), then this method returns the
605  /// array as a StringRef.  Otherwise, it asserts out.
606  ///
607  StringRef getAsString() const {
608    assert(isString() && "Not a string");
609    return getRawDataValues();
610  }
611
612  /// getAsCString - If this array is isCString(), then this method returns the
613  /// array (without the trailing null byte) as a StringRef. Otherwise, it
614  /// asserts out.
615  ///
616  StringRef getAsCString() const {
617    assert(isCString() && "Isn't a C string");
618    StringRef Str = getAsString();
619    return Str.substr(0, Str.size()-1);
620  }
621
622  /// getRawDataValues - Return the raw, underlying, bytes of this data.  Note
623  /// that this is an extremely tricky thing to work with, as it exposes the
624  /// host endianness of the data elements.
625  StringRef getRawDataValues() const;
626
627  void destroyConstant() override;
628
629  /// Methods for support type inquiry through isa, cast, and dyn_cast:
630  ///
631  static bool classof(const Value *V) {
632    return V->getValueID() == ConstantDataArrayVal ||
633           V->getValueID() == ConstantDataVectorVal;
634  }
635private:
636  const char *getElementPointer(unsigned Elt) const;
637};
638
639//===----------------------------------------------------------------------===//
640/// ConstantDataArray - An array constant whose element type is a simple
641/// 1/2/4/8-byte integer or float/double, and whose elements are just simple
642/// data values (i.e. ConstantInt/ConstantFP).  This Constant node has no
643/// operands because it stores all of the elements of the constant as densely
644/// packed data, instead of as Value*'s.
645class ConstantDataArray : public ConstantDataSequential {
646  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
647  ConstantDataArray(const ConstantDataArray &) LLVM_DELETED_FUNCTION;
648  void anchor() override;
649  friend class ConstantDataSequential;
650  explicit ConstantDataArray(Type *ty, const char *Data)
651    : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
652protected:
653  // allocate space for exactly zero operands.
654  void *operator new(size_t s) {
655    return User::operator new(s, 0);
656  }
657public:
658
659  /// get() constructors - Return a constant with array type with an element
660  /// count and element type matching the ArrayRef passed in.  Note that this
661  /// can return a ConstantAggregateZero object.
662  static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
663  static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
664  static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
665  static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
666  static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
667  static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
668
669  /// getString - This method constructs a CDS and initializes it with a text
670  /// string. The default behavior (AddNull==true) causes a null terminator to
671  /// be placed at the end of the array (increasing the length of the string by
672  /// one more than the StringRef would normally indicate.  Pass AddNull=false
673  /// to disable this behavior.
674  static Constant *getString(LLVMContext &Context, StringRef Initializer,
675                             bool AddNull = true);
676
677  /// getType - Specialize the getType() method to always return an ArrayType,
678  /// which reduces the amount of casting needed in parts of the compiler.
679  ///
680  inline ArrayType *getType() const {
681    return cast<ArrayType>(Value::getType());
682  }
683
684  /// Methods for support type inquiry through isa, cast, and dyn_cast:
685  ///
686  static bool classof(const Value *V) {
687    return V->getValueID() == ConstantDataArrayVal;
688  }
689};
690
691//===----------------------------------------------------------------------===//
692/// ConstantDataVector - A vector constant whose element type is a simple
693/// 1/2/4/8-byte integer or float/double, and whose elements are just simple
694/// data values (i.e. ConstantInt/ConstantFP).  This Constant node has no
695/// operands because it stores all of the elements of the constant as densely
696/// packed data, instead of as Value*'s.
697class ConstantDataVector : public ConstantDataSequential {
698  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
699  ConstantDataVector(const ConstantDataVector &) LLVM_DELETED_FUNCTION;
700  void anchor() override;
701  friend class ConstantDataSequential;
702  explicit ConstantDataVector(Type *ty, const char *Data)
703  : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
704protected:
705  // allocate space for exactly zero operands.
706  void *operator new(size_t s) {
707    return User::operator new(s, 0);
708  }
709public:
710
711  /// get() constructors - Return a constant with vector type with an element
712  /// count and element type matching the ArrayRef passed in.  Note that this
713  /// can return a ConstantAggregateZero object.
714  static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
715  static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
716  static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
717  static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
718  static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
719  static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
720
721  /// getSplat - Return a ConstantVector with the specified constant in each
722  /// element.  The specified constant has to be a of a compatible type (i8/i16/
723  /// i32/i64/float/double) and must be a ConstantFP or ConstantInt.
724  static Constant *getSplat(unsigned NumElts, Constant *Elt);
725
726  /// getSplatValue - If this is a splat constant, meaning that all of the
727  /// elements have the same value, return that value. Otherwise return NULL.
728  Constant *getSplatValue() const;
729
730  /// getType - Specialize the getType() method to always return a VectorType,
731  /// which reduces the amount of casting needed in parts of the compiler.
732  ///
733  inline VectorType *getType() const {
734    return cast<VectorType>(Value::getType());
735  }
736
737  /// Methods for support type inquiry through isa, cast, and dyn_cast:
738  ///
739  static bool classof(const Value *V) {
740    return V->getValueID() == ConstantDataVectorVal;
741  }
742};
743
744
745
746/// BlockAddress - The address of a basic block.
747///
748class BlockAddress : public Constant {
749  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
750  void *operator new(size_t s) { return User::operator new(s, 2); }
751  BlockAddress(Function *F, BasicBlock *BB);
752public:
753  /// get - Return a BlockAddress for the specified function and basic block.
754  static BlockAddress *get(Function *F, BasicBlock *BB);
755
756  /// get - Return a BlockAddress for the specified basic block.  The basic
757  /// block must be embedded into a function.
758  static BlockAddress *get(BasicBlock *BB);
759
760  /// \brief Lookup an existing \c BlockAddress constant for the given
761  /// BasicBlock.
762  ///
763  /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
764  static BlockAddress *lookup(const BasicBlock *BB);
765
766  /// Transparently provide more efficient getOperand methods.
767  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
768
769  Function *getFunction() const { return (Function*)Op<0>().get(); }
770  BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); }
771
772  void destroyConstant() override;
773  void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
774
775  /// Methods for support type inquiry through isa, cast, and dyn_cast:
776  static inline bool classof(const Value *V) {
777    return V->getValueID() == BlockAddressVal;
778  }
779};
780
781template <>
782struct OperandTraits<BlockAddress> :
783  public FixedNumOperandTraits<BlockAddress, 2> {
784};
785
786DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
787
788
789//===----------------------------------------------------------------------===//
790/// ConstantExpr - a constant value that is initialized with an expression using
791/// other constant values.
792///
793/// This class uses the standard Instruction opcodes to define the various
794/// constant expressions.  The Opcode field for the ConstantExpr class is
795/// maintained in the Value::SubclassData field.
796class ConstantExpr : public Constant {
797  friend struct ConstantCreator<ConstantExpr,Type,
798                            std::pair<unsigned, std::vector<Constant*> > >;
799  friend struct ConvertConstantType<ConstantExpr, Type>;
800
801protected:
802  ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
803    : Constant(ty, ConstantExprVal, Ops, NumOps) {
804    // Operation type (an Instruction opcode) is stored as the SubclassData.
805    setValueSubclassData(Opcode);
806  }
807
808public:
809  // Static methods to construct a ConstantExpr of different kinds.  Note that
810  // these methods may return a object that is not an instance of the
811  // ConstantExpr class, because they will attempt to fold the constant
812  // expression into something simpler if possible.
813
814  /// getAlignOf constant expr - computes the alignment of a type in a target
815  /// independent way (Note: the return type is an i64).
816  static Constant *getAlignOf(Type *Ty);
817
818  /// getSizeOf constant expr - computes the (alloc) size of a type (in
819  /// address-units, not bits) in a target independent way (Note: the return
820  /// type is an i64).
821  ///
822  static Constant *getSizeOf(Type *Ty);
823
824  /// getOffsetOf constant expr - computes the offset of a struct field in a
825  /// target independent way (Note: the return type is an i64).
826  ///
827  static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
828
829  /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
830  /// which supports any aggregate type, and any Constant index.
831  ///
832  static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
833
834  static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false);
835  static Constant *getFNeg(Constant *C);
836  static Constant *getNot(Constant *C);
837  static Constant *getAdd(Constant *C1, Constant *C2,
838                          bool HasNUW = false, bool HasNSW = false);
839  static Constant *getFAdd(Constant *C1, Constant *C2);
840  static Constant *getSub(Constant *C1, Constant *C2,
841                          bool HasNUW = false, bool HasNSW = false);
842  static Constant *getFSub(Constant *C1, Constant *C2);
843  static Constant *getMul(Constant *C1, Constant *C2,
844                          bool HasNUW = false, bool HasNSW = false);
845  static Constant *getFMul(Constant *C1, Constant *C2);
846  static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
847  static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
848  static Constant *getFDiv(Constant *C1, Constant *C2);
849  static Constant *getURem(Constant *C1, Constant *C2);
850  static Constant *getSRem(Constant *C1, Constant *C2);
851  static Constant *getFRem(Constant *C1, Constant *C2);
852  static Constant *getAnd(Constant *C1, Constant *C2);
853  static Constant *getOr(Constant *C1, Constant *C2);
854  static Constant *getXor(Constant *C1, Constant *C2);
855  static Constant *getShl(Constant *C1, Constant *C2,
856                          bool HasNUW = false, bool HasNSW = false);
857  static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
858  static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
859  static Constant *getTrunc   (Constant *C, Type *Ty);
860  static Constant *getSExt    (Constant *C, Type *Ty);
861  static Constant *getZExt    (Constant *C, Type *Ty);
862  static Constant *getFPTrunc (Constant *C, Type *Ty);
863  static Constant *getFPExtend(Constant *C, Type *Ty);
864  static Constant *getUIToFP  (Constant *C, Type *Ty);
865  static Constant *getSIToFP  (Constant *C, Type *Ty);
866  static Constant *getFPToUI  (Constant *C, Type *Ty);
867  static Constant *getFPToSI  (Constant *C, Type *Ty);
868  static Constant *getPtrToInt(Constant *C, Type *Ty);
869  static Constant *getIntToPtr(Constant *C, Type *Ty);
870  static Constant *getBitCast (Constant *C, Type *Ty);
871  static Constant *getAddrSpaceCast(Constant *C, Type *Ty);
872
873  static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
874  static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
875  static Constant *getNSWAdd(Constant *C1, Constant *C2) {
876    return getAdd(C1, C2, false, true);
877  }
878  static Constant *getNUWAdd(Constant *C1, Constant *C2) {
879    return getAdd(C1, C2, true, false);
880  }
881  static Constant *getNSWSub(Constant *C1, Constant *C2) {
882    return getSub(C1, C2, false, true);
883  }
884  static Constant *getNUWSub(Constant *C1, Constant *C2) {
885    return getSub(C1, C2, true, false);
886  }
887  static Constant *getNSWMul(Constant *C1, Constant *C2) {
888    return getMul(C1, C2, false, true);
889  }
890  static Constant *getNUWMul(Constant *C1, Constant *C2) {
891    return getMul(C1, C2, true, false);
892  }
893  static Constant *getNSWShl(Constant *C1, Constant *C2) {
894    return getShl(C1, C2, false, true);
895  }
896  static Constant *getNUWShl(Constant *C1, Constant *C2) {
897    return getShl(C1, C2, true, false);
898  }
899  static Constant *getExactSDiv(Constant *C1, Constant *C2) {
900    return getSDiv(C1, C2, true);
901  }
902  static Constant *getExactUDiv(Constant *C1, Constant *C2) {
903    return getUDiv(C1, C2, true);
904  }
905  static Constant *getExactAShr(Constant *C1, Constant *C2) {
906    return getAShr(C1, C2, true);
907  }
908  static Constant *getExactLShr(Constant *C1, Constant *C2) {
909    return getLShr(C1, C2, true);
910  }
911
912  /// getBinOpIdentity - Return the identity for the given binary operation,
913  /// i.e. a constant C such that X op C = X and C op X = X for every X.  It
914  /// returns null if the operator doesn't have an identity.
915  static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty);
916
917  /// getBinOpAbsorber - Return the absorbing element for the given binary
918  /// operation, i.e. a constant C such that X op C = C and C op X = C for
919  /// every X.  For example, this returns zero for integer multiplication.
920  /// It returns null if the operator doesn't have an absorbing element.
921  static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
922
923  /// Transparently provide more efficient getOperand methods.
924  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
925
926  // @brief Convenience function for getting one of the casting operations
927  // using a CastOps opcode.
928  static Constant *getCast(
929    unsigned ops,  ///< The opcode for the conversion
930    Constant *C,   ///< The constant to be converted
931    Type *Ty ///< The type to which the constant is converted
932  );
933
934  // @brief Create a ZExt or BitCast cast constant expression
935  static Constant *getZExtOrBitCast(
936    Constant *C,   ///< The constant to zext or bitcast
937    Type *Ty ///< The type to zext or bitcast C to
938  );
939
940  // @brief Create a SExt or BitCast cast constant expression
941  static Constant *getSExtOrBitCast(
942    Constant *C,   ///< The constant to sext or bitcast
943    Type *Ty ///< The type to sext or bitcast C to
944  );
945
946  // @brief Create a Trunc or BitCast cast constant expression
947  static Constant *getTruncOrBitCast(
948    Constant *C,   ///< The constant to trunc or bitcast
949    Type *Ty ///< The type to trunc or bitcast C to
950  );
951
952  /// @brief Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
953  /// expression.
954  static Constant *getPointerCast(
955    Constant *C,   ///< The pointer value to be casted (operand 0)
956    Type *Ty ///< The type to which cast should be made
957  );
958
959  /// @brief Create a BitCast or AddrSpaceCast for a pointer type depending on
960  /// the address space.
961  static Constant *getPointerBitCastOrAddrSpaceCast(
962    Constant *C,   ///< The constant to addrspacecast or bitcast
963    Type *Ty ///< The type to bitcast or addrspacecast C to
964  );
965
966  /// @brief Create a ZExt, Bitcast or Trunc for integer -> integer casts
967  static Constant *getIntegerCast(
968    Constant *C,    ///< The integer constant to be casted
969    Type *Ty, ///< The integer type to cast to
970    bool isSigned   ///< Whether C should be treated as signed or not
971  );
972
973  /// @brief Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
974  static Constant *getFPCast(
975    Constant *C,    ///< The integer constant to be casted
976    Type *Ty ///< The integer type to cast to
977  );
978
979  /// @brief Return true if this is a convert constant expression
980  bool isCast() const;
981
982  /// @brief Return true if this is a compare constant expression
983  bool isCompare() const;
984
985  /// @brief Return true if this is an insertvalue or extractvalue expression,
986  /// and the getIndices() method may be used.
987  bool hasIndices() const;
988
989  /// @brief Return true if this is a getelementptr expression and all
990  /// the index operands are compile-time known integers within the
991  /// corresponding notional static array extents. Note that this is
992  /// not equivalant to, a subset of, or a superset of the "inbounds"
993  /// property.
994  bool isGEPWithNoNotionalOverIndexing() const;
995
996  /// Select constant expr
997  ///
998  static Constant *getSelect(Constant *C, Constant *V1, Constant *V2);
999
1000  /// get - Return a binary or shift operator constant expression,
1001  /// folding if possible.
1002  ///
1003  static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1004                       unsigned Flags = 0);
1005
1006  /// @brief Return an ICmp or FCmp comparison operator constant expression.
1007  static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2);
1008
1009  /// get* - Return some common constants without having to
1010  /// specify the full Instruction::OPCODE identifier.
1011  ///
1012  static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS);
1013  static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS);
1014
1015  /// Getelementptr form.  Value* is only accepted for convenience;
1016  /// all elements must be Constant's.
1017  ///
1018  static Constant *getGetElementPtr(Constant *C,
1019                                    ArrayRef<Constant *> IdxList,
1020                                    bool InBounds = false) {
1021    return getGetElementPtr(C, makeArrayRef((Value * const *)IdxList.data(),
1022                                            IdxList.size()),
1023                            InBounds);
1024  }
1025  static Constant *getGetElementPtr(Constant *C,
1026                                    Constant *Idx,
1027                                    bool InBounds = false) {
1028    // This form of the function only exists to avoid ambiguous overload
1029    // warnings about whether to convert Idx to ArrayRef<Constant *> or
1030    // ArrayRef<Value *>.
1031    return getGetElementPtr(C, cast<Value>(Idx), InBounds);
1032  }
1033  static Constant *getGetElementPtr(Constant *C,
1034                                    ArrayRef<Value *> IdxList,
1035                                    bool InBounds = false);
1036
1037  /// Create an "inbounds" getelementptr. See the documentation for the
1038  /// "inbounds" flag in LangRef.html for details.
1039  static Constant *getInBoundsGetElementPtr(Constant *C,
1040                                            ArrayRef<Constant *> IdxList) {
1041    return getGetElementPtr(C, IdxList, true);
1042  }
1043  static Constant *getInBoundsGetElementPtr(Constant *C,
1044                                            Constant *Idx) {
1045    // This form of the function only exists to avoid ambiguous overload
1046    // warnings about whether to convert Idx to ArrayRef<Constant *> or
1047    // ArrayRef<Value *>.
1048    return getGetElementPtr(C, Idx, true);
1049  }
1050  static Constant *getInBoundsGetElementPtr(Constant *C,
1051                                            ArrayRef<Value *> IdxList) {
1052    return getGetElementPtr(C, IdxList, true);
1053  }
1054
1055  static Constant *getExtractElement(Constant *Vec, Constant *Idx);
1056  static Constant *getInsertElement(Constant *Vec, Constant *Elt,Constant *Idx);
1057  static Constant *getShuffleVector(Constant *V1, Constant *V2, Constant *Mask);
1058  static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs);
1059  static Constant *getInsertValue(Constant *Agg, Constant *Val,
1060                                  ArrayRef<unsigned> Idxs);
1061
1062  /// getOpcode - Return the opcode at the root of this constant expression
1063  unsigned getOpcode() const { return getSubclassDataFromValue(); }
1064
1065  /// getPredicate - Return the ICMP or FCMP predicate value. Assert if this is
1066  /// not an ICMP or FCMP constant expression.
1067  unsigned getPredicate() const;
1068
1069  /// getIndices - Assert that this is an insertvalue or exactvalue
1070  /// expression and return the list of indices.
1071  ArrayRef<unsigned> getIndices() const;
1072
1073  /// getOpcodeName - Return a string representation for an opcode.
1074  const char *getOpcodeName() const;
1075
1076  /// getWithOperandReplaced - Return a constant expression identical to this
1077  /// one, but with the specified operand set to the specified value.
1078  Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1079
1080  /// getWithOperands - This returns the current constant expression with the
1081  /// operands replaced with the specified values.  The specified array must
1082  /// have the same number of operands as our current one.
1083  Constant *getWithOperands(ArrayRef<Constant*> Ops) const {
1084    return getWithOperands(Ops, getType());
1085  }
1086
1087  /// getWithOperands - This returns the current constant expression with the
1088  /// operands replaced with the specified values and with the specified result
1089  /// type.  The specified array must have the same number of operands as our
1090  /// current one.
1091  Constant *getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const;
1092
1093  /// getAsInstruction - Returns an Instruction which implements the same operation
1094  /// as this ConstantExpr. The instruction is not linked to any basic block.
1095  ///
1096  /// A better approach to this could be to have a constructor for Instruction
1097  /// which would take a ConstantExpr parameter, but that would have spread
1098  /// implementation details of ConstantExpr outside of Constants.cpp, which
1099  /// would make it harder to remove ConstantExprs altogether.
1100  Instruction *getAsInstruction();
1101
1102  void destroyConstant() override;
1103  void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) override;
1104
1105  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1106  static inline bool classof(const Value *V) {
1107    return V->getValueID() == ConstantExprVal;
1108  }
1109
1110private:
1111  // Shadow Value::setValueSubclassData with a private forwarding method so that
1112  // subclasses cannot accidentally use it.
1113  void setValueSubclassData(unsigned short D) {
1114    Value::setValueSubclassData(D);
1115  }
1116};
1117
1118template <>
1119struct OperandTraits<ConstantExpr> :
1120  public VariadicOperandTraits<ConstantExpr, 1> {
1121};
1122
1123DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
1124
1125//===----------------------------------------------------------------------===//
1126/// UndefValue - 'undef' values are things that do not have specified contents.
1127/// These are used for a variety of purposes, including global variable
1128/// initializers and operands to instructions.  'undef' values can occur with
1129/// any first-class type.
1130///
1131/// Undef values aren't exactly constants; if they have multiple uses, they
1132/// can appear to have different bit patterns at each use. See
1133/// LangRef.html#undefvalues for details.
1134///
1135class UndefValue : public Constant {
1136  void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
1137  UndefValue(const UndefValue &) LLVM_DELETED_FUNCTION;
1138protected:
1139  explicit UndefValue(Type *T) : Constant(T, UndefValueVal, nullptr, 0) {}
1140protected:
1141  // allocate space for exactly zero operands
1142  void *operator new(size_t s) {
1143    return User::operator new(s, 0);
1144  }
1145public:
1146  /// get() - Static factory methods - Return an 'undef' object of the specified
1147  /// type.
1148  ///
1149  static UndefValue *get(Type *T);
1150
1151  /// getSequentialElement - If this Undef has array or vector type, return a
1152  /// undef with the right element type.
1153  UndefValue *getSequentialElement() const;
1154
1155  /// getStructElement - If this undef has struct type, return a undef with the
1156  /// right element type for the specified element.
1157  UndefValue *getStructElement(unsigned Elt) const;
1158
1159  /// getElementValue - Return an undef of the right value for the specified GEP
1160  /// index.
1161  UndefValue *getElementValue(Constant *C) const;
1162
1163  /// getElementValue - Return an undef of the right value for the specified GEP
1164  /// index.
1165  UndefValue *getElementValue(unsigned Idx) const;
1166
1167  void destroyConstant() override;
1168
1169  /// Methods for support type inquiry through isa, cast, and dyn_cast:
1170  static bool classof(const Value *V) {
1171    return V->getValueID() == UndefValueVal;
1172  }
1173};
1174
1175} // End llvm namespace
1176
1177#endif
1178