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