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