1 //===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declarations for the subclasses of Constant,
12 /// which represent the different flavors of constant values that live in LLVM.
13 /// Note that Constants are immutable (once created they never change) and are
14 /// fully shared by structural equivalence. This means that two structurally
15 /// equivalent constants will always have the same address. Constants are
16 /// created on demand as needed and never deleted: thus clients don't have to
17 /// worry about the lifetime of the objects.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_IR_CONSTANTS_H
22 #define LLVM_IR_CONSTANTS_H
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/IR/Constant.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/OperandTraits.h"
40 struct ConstantExprKeyType;
41 template <class ConstantClass> struct ConstantAggrKeyType;
43 /// Base class for constants with no operands.
45 /// These constants have no operands; they represent their data directly.
46 /// Since they can be in use by unrelated modules (and are never based on
47 /// GlobalValues), it never makes sense to RAUW them.
48 class ConstantData : public Constant {
49 void anchor() override;
50 void *operator new(size_t, unsigned) = delete;
51 ConstantData() = delete;
52 ConstantData(const ConstantData &) = delete;
54 friend class Constant;
55 Value *handleOperandChangeImpl(Value *From, Value *To) {
56 llvm_unreachable("Constant data does not have operands!");
60 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
61 void *operator new(size_t s) { return User::operator new(s, 0); }
64 /// Methods to support type inquiry through isa, cast, and dyn_cast.
65 static bool classof(const Value *V) {
66 return V->getValueID() >= ConstantDataFirstVal &&
67 V->getValueID() <= ConstantDataLastVal;
71 //===----------------------------------------------------------------------===//
72 /// This is the shared class of boolean and integer constants. This class
73 /// represents both boolean and integral constants.
74 /// @brief Class for constant integers.
75 class ConstantInt final : public ConstantData {
76 void anchor() override;
77 ConstantInt(const ConstantInt &) = delete;
78 ConstantInt(IntegerType *Ty, const APInt& V);
81 friend class Constant;
82 void destroyConstantImpl();
85 static ConstantInt *getTrue(LLVMContext &Context);
86 static ConstantInt *getFalse(LLVMContext &Context);
87 static Constant *getTrue(Type *Ty);
88 static Constant *getFalse(Type *Ty);
90 /// If Ty is a vector type, return a Constant with a splat of the given
91 /// value. Otherwise return a ConstantInt for the given value.
92 static Constant *get(Type *Ty, uint64_t V, bool isSigned = false);
94 /// Return a ConstantInt with the specified integer value for the specified
95 /// type. If the type is wider than 64 bits, the value will be zero-extended
96 /// to fit the type, unless isSigned is true, in which case the value will
97 /// be interpreted as a 64-bit signed integer and sign-extended to fit
99 /// @brief Get a ConstantInt for a specific value.
100 static ConstantInt *get(IntegerType *Ty, uint64_t V,
101 bool isSigned = false);
103 /// Return a ConstantInt with the specified value for the specified type. The
104 /// value V will be canonicalized to a an unsigned APInt. Accessing it with
105 /// either getSExtValue() or getZExtValue() will yield a correctly sized and
106 /// signed value for the type Ty.
107 /// @brief Get a ConstantInt for a specific signed value.
108 static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
109 static Constant *getSigned(Type *Ty, int64_t V);
111 /// Return a ConstantInt with the specified value and an implied Type. The
112 /// type is the integer type that corresponds to the bit width of the value.
113 static ConstantInt *get(LLVMContext &Context, const APInt &V);
115 /// Return a ConstantInt constructed from the string strStart with the given
117 static ConstantInt *get(IntegerType *Ty, StringRef Str,
120 /// If Ty is a vector type, return a Constant with a splat of the given
121 /// value. Otherwise return a ConstantInt for the given value.
122 static Constant *get(Type* Ty, const APInt& V);
124 /// Return the constant as an APInt value reference. This allows clients to
125 /// obtain a copy of the value, with all its precision in tact.
126 /// @brief Return the constant's value.
127 inline const APInt &getValue() const {
131 /// getBitWidth - Return the bitwidth of this constant.
132 unsigned getBitWidth() const { return Val.getBitWidth(); }
134 /// Return the constant as a 64-bit unsigned integer value after it
135 /// has been zero extended as appropriate for the type of this constant. Note
136 /// that this method can assert if the value does not fit in 64 bits.
137 /// @brief Return the zero extended value.
138 inline uint64_t getZExtValue() const {
139 return Val.getZExtValue();
142 /// Return the constant as a 64-bit integer value after it has been sign
143 /// extended as appropriate for the type of this constant. Note that
144 /// this method can assert if the value does not fit in 64 bits.
145 /// @brief Return the sign extended value.
146 inline int64_t getSExtValue() const {
147 return Val.getSExtValue();
150 /// A helper method that can be used to determine if the constant contained
151 /// within is equal to a constant. This only works for very small values,
152 /// because this is all that can be represented with all types.
153 /// @brief Determine if this constant's value is same as an unsigned char.
154 bool equalsInt(uint64_t V) const {
158 /// getType - Specialize the getType() method to always return an IntegerType,
159 /// which reduces the amount of casting needed in parts of the compiler.
161 inline IntegerType *getType() const {
162 return cast<IntegerType>(Value::getType());
165 /// This static method returns true if the type Ty is big enough to
166 /// represent the value V. This can be used to avoid having the get method
167 /// assert when V is larger than Ty can represent. Note that there are two
168 /// versions of this method, one for unsigned and one for signed integers.
169 /// Although ConstantInt canonicalizes everything to an unsigned integer,
170 /// the signed version avoids callers having to convert a signed quantity
171 /// to the appropriate unsigned type before calling the method.
172 /// @returns true if V is a valid value for type Ty
173 /// @brief Determine if the value is in range for the given type.
174 static bool isValueValidForType(Type *Ty, uint64_t V);
175 static bool isValueValidForType(Type *Ty, int64_t V);
177 bool isNegative() const { return Val.isNegative(); }
179 /// This is just a convenience method to make client code smaller for a
180 /// common code. It also correctly performs the comparison without the
181 /// potential for an assertion from getZExtValue().
182 bool isZero() const {
186 /// This is just a convenience method to make client code smaller for a
187 /// common case. It also correctly performs the comparison without the
188 /// potential for an assertion from getZExtValue().
189 /// @brief Determine if the value is one.
194 /// This function will return true iff every bit in this constant is set
196 /// @returns true iff this constant's bits are all set to true.
197 /// @brief Determine if the value is all ones.
198 bool isMinusOne() const {
199 return Val.isAllOnesValue();
202 /// This function will return true iff this constant represents the largest
203 /// value that may be represented by the constant's type.
204 /// @returns true iff this is the largest value that may be represented
206 /// @brief Determine if the value is maximal.
207 bool isMaxValue(bool isSigned) const {
209 return Val.isMaxSignedValue();
211 return Val.isMaxValue();
214 /// This function will return true iff this constant represents the smallest
215 /// value that may be represented by this constant's type.
216 /// @returns true if this is the smallest value that may be represented by
218 /// @brief Determine if the value is minimal.
219 bool isMinValue(bool isSigned) const {
221 return Val.isMinSignedValue();
223 return Val.isMinValue();
226 /// This function will return true iff this constant represents a value with
227 /// active bits bigger than 64 bits or a value greater than the given uint64_t
229 /// @returns true iff this constant is greater or equal to the given number.
230 /// @brief Determine if the value is greater or equal to the given number.
231 bool uge(uint64_t Num) const {
232 return Val.getActiveBits() > 64 || Val.getZExtValue() >= Num;
235 /// getLimitedValue - If the value is smaller than the specified limit,
236 /// return it, otherwise return the limit value. This causes the value
237 /// to saturate to the limit.
238 /// @returns the min of the value of the constant and the specified value
239 /// @brief Get the constant's value with a saturation limit
240 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
241 return Val.getLimitedValue(Limit);
244 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
245 static bool classof(const Value *V) {
246 return V->getValueID() == ConstantIntVal;
251 //===----------------------------------------------------------------------===//
252 /// ConstantFP - Floating Point Values [float, double]
254 class ConstantFP final : public ConstantData {
256 void anchor() override;
257 ConstantFP(const ConstantFP &) = delete;
259 friend class Constant;
260 void destroyConstantImpl();
262 ConstantFP(Type *Ty, const APFloat& V);
265 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
266 /// method returns the negative zero constant for floating point or vector
267 /// floating point types; for all other types, it returns the null value.
268 static Constant *getZeroValueForNegation(Type *Ty);
270 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
271 /// for the specified value in the specified type. This should only be used
272 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
273 /// host double and as the target format.
274 static Constant *get(Type* Ty, double V);
275 static Constant *get(Type* Ty, StringRef Str);
276 static ConstantFP *get(LLVMContext &Context, const APFloat &V);
277 static Constant *getNaN(Type *Ty, bool Negative = false, unsigned type = 0);
278 static Constant *getNegativeZero(Type *Ty);
279 static Constant *getInfinity(Type *Ty, bool Negative = false);
281 /// Return true if Ty is big enough to represent V.
282 static bool isValueValidForType(Type *Ty, const APFloat &V);
283 inline const APFloat &getValueAPF() const { return Val; }
285 /// Return true if the value is positive or negative zero.
286 bool isZero() const { return Val.isZero(); }
288 /// Return true if the sign bit is set.
289 bool isNegative() const { return Val.isNegative(); }
291 /// Return true if the value is infinity
292 bool isInfinity() const { return Val.isInfinity(); }
294 /// Return true if the value is a NaN.
295 bool isNaN() const { return Val.isNaN(); }
297 /// We don't rely on operator== working on double values, as it returns true
298 /// for things that are clearly not equal, like -0.0 and 0.0.
299 /// As such, this method can be used to do an exact bit-for-bit comparison of
300 /// two floating point values. The version with a double operand is retained
301 /// because it's so convenient to write isExactlyValue(2.0), but please use
302 /// it only for simple constants.
303 bool isExactlyValue(const APFloat &V) const;
305 bool isExactlyValue(double V) const {
308 FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
309 return isExactlyValue(FV);
311 /// Methods for support type inquiry through isa, cast, and dyn_cast:
312 static bool classof(const Value *V) {
313 return V->getValueID() == ConstantFPVal;
317 //===----------------------------------------------------------------------===//
318 /// All zero aggregate value
320 class ConstantAggregateZero final : public ConstantData {
321 ConstantAggregateZero(const ConstantAggregateZero &) = delete;
323 friend class Constant;
324 void destroyConstantImpl();
326 explicit ConstantAggregateZero(Type *Ty)
327 : ConstantData(Ty, ConstantAggregateZeroVal) {}
330 static ConstantAggregateZero *get(Type *Ty);
332 /// If this CAZ has array or vector type, return a zero with the right element
334 Constant *getSequentialElement() const;
336 /// If this CAZ has struct type, return a zero with the right element type for
337 /// the specified element.
338 Constant *getStructElement(unsigned Elt) const;
340 /// Return a zero of the right value for the specified GEP index if we can,
341 /// otherwise return null (e.g. if C is a ConstantExpr).
342 Constant *getElementValue(Constant *C) const;
344 /// Return a zero of the right value for the specified GEP index.
345 Constant *getElementValue(unsigned Idx) const;
347 /// Return the number of elements in the array, vector, or struct.
348 unsigned getNumElements() const;
350 /// Methods for support type inquiry through isa, cast, and dyn_cast:
352 static bool classof(const Value *V) {
353 return V->getValueID() == ConstantAggregateZeroVal;
357 /// Base class for aggregate constants (with operands).
359 /// These constants are aggregates of other constants, which are stored as
362 /// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
365 /// \note Some subclasses of \a ConstantData are semantically aggregates --
366 /// such as \a ConstantDataArray -- but are not subclasses of this because they
368 class ConstantAggregate : public Constant {
370 ConstantAggregate(CompositeType *T, ValueTy VT, ArrayRef<Constant *> V);
373 /// Transparently provide more efficient getOperand methods.
374 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
376 /// Methods for support type inquiry through isa, cast, and dyn_cast:
377 static bool classof(const Value *V) {
378 return V->getValueID() >= ConstantAggregateFirstVal &&
379 V->getValueID() <= ConstantAggregateLastVal;
384 struct OperandTraits<ConstantAggregate>
385 : public VariadicOperandTraits<ConstantAggregate> {};
387 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)
389 //===----------------------------------------------------------------------===//
390 /// ConstantArray - Constant Array Declarations
392 class ConstantArray final : public ConstantAggregate {
393 friend struct ConstantAggrKeyType<ConstantArray>;
394 friend class Constant;
395 void destroyConstantImpl();
396 Value *handleOperandChangeImpl(Value *From, Value *To);
398 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
401 // ConstantArray accessors
402 static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
405 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
408 /// Specialize the getType() method to always return an ArrayType,
409 /// which reduces the amount of casting needed in parts of the compiler.
410 inline ArrayType *getType() const {
411 return cast<ArrayType>(Value::getType());
414 /// Methods for support type inquiry through isa, cast, and dyn_cast:
415 static bool classof(const Value *V) {
416 return V->getValueID() == ConstantArrayVal;
420 //===----------------------------------------------------------------------===//
421 // Constant Struct Declarations
423 class ConstantStruct final : public ConstantAggregate {
424 friend struct ConstantAggrKeyType<ConstantStruct>;
425 friend class Constant;
426 void destroyConstantImpl();
427 Value *handleOperandChangeImpl(Value *From, Value *To);
429 ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
432 // ConstantStruct accessors
433 static Constant *get(StructType *T, ArrayRef<Constant*> V);
434 static Constant *get(StructType *T, ...) LLVM_END_WITH_NULL;
436 /// Return an anonymous struct that has the specified elements.
437 /// If the struct is possibly empty, then you must specify a context.
438 static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) {
439 return get(getTypeForElements(V, Packed), V);
441 static Constant *getAnon(LLVMContext &Ctx,
442 ArrayRef<Constant*> V, bool Packed = false) {
443 return get(getTypeForElements(Ctx, V, Packed), V);
446 /// Return an anonymous struct type to use for a constant with the specified
447 /// set of elements. The list must not be empty.
448 static StructType *getTypeForElements(ArrayRef<Constant*> V,
449 bool Packed = false);
450 /// This version of the method allows an empty list.
451 static StructType *getTypeForElements(LLVMContext &Ctx,
452 ArrayRef<Constant*> V,
453 bool Packed = false);
455 /// Specialization - reduce amount of casting.
456 inline StructType *getType() const {
457 return cast<StructType>(Value::getType());
460 /// Methods for support type inquiry through isa, cast, and dyn_cast:
461 static bool classof(const Value *V) {
462 return V->getValueID() == ConstantStructVal;
467 //===----------------------------------------------------------------------===//
468 /// Constant Vector Declarations
470 class ConstantVector final : public ConstantAggregate {
471 friend struct ConstantAggrKeyType<ConstantVector>;
472 friend class Constant;
473 void destroyConstantImpl();
474 Value *handleOperandChangeImpl(Value *From, Value *To);
476 ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
479 // ConstantVector accessors
480 static Constant *get(ArrayRef<Constant*> V);
483 static Constant *getImpl(ArrayRef<Constant *> V);
486 /// Return a ConstantVector with the specified constant in each element.
487 static Constant *getSplat(unsigned NumElts, Constant *Elt);
489 /// Specialize the getType() method to always return a VectorType,
490 /// which reduces the amount of casting needed in parts of the compiler.
491 inline VectorType *getType() const {
492 return cast<VectorType>(Value::getType());
495 /// If this is a splat constant, meaning that all of the elements have the
496 /// same value, return that value. Otherwise return NULL.
497 Constant *getSplatValue() const;
499 /// Methods for support type inquiry through isa, cast, and dyn_cast:
500 static bool classof(const Value *V) {
501 return V->getValueID() == ConstantVectorVal;
505 //===----------------------------------------------------------------------===//
506 /// A constant pointer value that points to null
508 class ConstantPointerNull final : public ConstantData {
509 ConstantPointerNull(const ConstantPointerNull &) = delete;
511 friend class Constant;
512 void destroyConstantImpl();
514 explicit ConstantPointerNull(PointerType *T)
515 : ConstantData(T, Value::ConstantPointerNullVal) {}
518 /// Static factory methods - Return objects of the specified value
519 static ConstantPointerNull *get(PointerType *T);
521 /// Specialize the getType() method to always return an PointerType,
522 /// which reduces the amount of casting needed in parts of the compiler.
523 inline PointerType *getType() const {
524 return cast<PointerType>(Value::getType());
527 /// Methods for support type inquiry through isa, cast, and dyn_cast:
528 static bool classof(const Value *V) {
529 return V->getValueID() == ConstantPointerNullVal;
533 //===----------------------------------------------------------------------===//
534 /// ConstantDataSequential - A vector or array constant whose element type is a
535 /// simple 1/2/4/8-byte integer or float/double, and whose elements are just
536 /// simple data values (i.e. ConstantInt/ConstantFP). This Constant node has no
537 /// operands because it stores all of the elements of the constant as densely
538 /// packed data, instead of as Value*'s.
540 /// This is the common base class of ConstantDataArray and ConstantDataVector.
542 class ConstantDataSequential : public ConstantData {
543 friend class LLVMContextImpl;
544 /// A pointer to the bytes underlying this constant (which is owned by the
545 /// uniquing StringMap).
546 const char *DataElements;
548 /// This forms a link list of ConstantDataSequential nodes that have
549 /// the same value but different type. For example, 0,0,0,1 could be a 4
550 /// element array of i8, or a 1-element array of i32. They'll both end up in
551 /// the same StringMap bucket, linked up.
552 ConstantDataSequential *Next;
553 ConstantDataSequential(const ConstantDataSequential &) = delete;
555 friend class Constant;
556 void destroyConstantImpl();
559 explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
560 : ConstantData(ty, VT), DataElements(Data), Next(nullptr) {}
561 ~ConstantDataSequential() override { delete Next; }
563 static Constant *getImpl(StringRef Bytes, Type *Ty);
566 /// Return true if a ConstantDataSequential can be formed with a vector or
567 /// array of the specified element type.
568 /// ConstantDataArray only works with normal float and int types that are
569 /// stored densely in memory, not with things like i42 or x86_f80.
570 static bool isElementTypeCompatible(Type *Ty);
572 /// If this is a sequential container of integers (of any size), return the
573 /// specified element in the low bits of a uint64_t.
574 uint64_t getElementAsInteger(unsigned i) const;
576 /// If this is a sequential container of floating point type, return the
577 /// specified element as an APFloat.
578 APFloat getElementAsAPFloat(unsigned i) const;
580 /// If this is an sequential container of floats, return the specified element
582 float getElementAsFloat(unsigned i) const;
584 /// If this is an sequential container of doubles, return the specified
585 /// element as a double.
586 double getElementAsDouble(unsigned i) const;
588 /// Return a Constant for a specified index's element.
589 /// Note that this has to compute a new constant to return, so it isn't as
590 /// efficient as getElementAsInteger/Float/Double.
591 Constant *getElementAsConstant(unsigned i) const;
593 /// Specialize the getType() method to always return a SequentialType, which
594 /// reduces the amount of casting needed in parts of the compiler.
595 inline SequentialType *getType() const {
596 return cast<SequentialType>(Value::getType());
599 /// Return the element type of the array/vector.
600 Type *getElementType() const;
602 /// Return the number of elements in the array or vector.
603 unsigned getNumElements() const;
605 /// Return the size (in bytes) of each element in the array/vector.
606 /// The size of the elements is known to be a multiple of one byte.
607 uint64_t getElementByteSize() const;
609 /// This method returns true if this is an array of i8.
610 bool isString() const;
612 /// This method returns true if the array "isString", ends with a null byte,
613 /// and does not contains any other null bytes.
614 bool isCString() const;
616 /// If this array is isString(), then this method returns the array as a
617 /// StringRef. Otherwise, it asserts out.
618 StringRef getAsString() const {
619 assert(isString() && "Not a string");
620 return getRawDataValues();
623 /// If this array is isCString(), then this method returns the array (without
624 /// the trailing null byte) as a StringRef. Otherwise, it asserts out.
625 StringRef getAsCString() const {
626 assert(isCString() && "Isn't a C string");
627 StringRef Str = getAsString();
628 return Str.substr(0, Str.size()-1);
631 /// Return the raw, underlying, bytes of this data. Note that this is an
632 /// extremely tricky thing to work with, as it exposes the host endianness of
633 /// the data elements.
634 StringRef getRawDataValues() const;
636 /// Methods for support type inquiry through isa, cast, and dyn_cast:
637 static bool classof(const Value *V) {
638 return V->getValueID() == ConstantDataArrayVal ||
639 V->getValueID() == ConstantDataVectorVal;
642 const char *getElementPointer(unsigned Elt) const;
645 //===----------------------------------------------------------------------===//
646 /// An array constant whose element type is a simple 1/2/4/8-byte integer or
647 /// float/double, and whose elements are just simple data values
648 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
649 /// stores all of the elements of the constant as densely packed data, instead
651 class ConstantDataArray final : public ConstantDataSequential {
652 void *operator new(size_t, unsigned) = delete;
653 ConstantDataArray(const ConstantDataArray &) = delete;
654 void anchor() override;
655 friend class ConstantDataSequential;
656 explicit ConstantDataArray(Type *ty, const char *Data)
657 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
658 /// Allocate space for exactly zero operands.
659 void *operator new(size_t s) {
660 return User::operator new(s, 0);
664 /// get() constructors - Return a constant with array type with an element
665 /// count and element type matching the ArrayRef passed in. Note that this
666 /// can return a ConstantAggregateZero object.
667 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
668 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
669 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
670 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
671 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
672 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
674 /// getFP() constructors - Return a constant with array type with an element
675 /// count and element type of float with precision matching the number of
676 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
677 /// double for 64bits) Note that this can return a ConstantAggregateZero
679 static Constant *getFP(LLVMContext &Context, ArrayRef<uint16_t> Elts);
680 static Constant *getFP(LLVMContext &Context, ArrayRef<uint32_t> Elts);
681 static Constant *getFP(LLVMContext &Context, ArrayRef<uint64_t> Elts);
683 /// This method constructs a CDS and initializes it with a text string.
684 /// The default behavior (AddNull==true) causes a null terminator to
685 /// be placed at the end of the array (increasing the length of the string by
686 /// one more than the StringRef would normally indicate. Pass AddNull=false
687 /// to disable this behavior.
688 static Constant *getString(LLVMContext &Context, StringRef Initializer,
689 bool AddNull = true);
691 /// Specialize the getType() method to always return an ArrayType,
692 /// which reduces the amount of casting needed in parts of the compiler.
693 inline ArrayType *getType() const {
694 return cast<ArrayType>(Value::getType());
697 /// Methods for support type inquiry through isa, cast, and dyn_cast:
698 static bool classof(const Value *V) {
699 return V->getValueID() == ConstantDataArrayVal;
703 //===----------------------------------------------------------------------===//
704 /// A vector constant whose element type is a simple 1/2/4/8-byte integer or
705 /// float/double, and whose elements are just simple data values
706 /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
707 /// stores all of the elements of the constant as densely packed data, instead
709 class ConstantDataVector final : public ConstantDataSequential {
710 void *operator new(size_t, unsigned) = delete;
711 ConstantDataVector(const ConstantDataVector &) = delete;
712 void anchor() override;
713 friend class ConstantDataSequential;
714 explicit ConstantDataVector(Type *ty, const char *Data)
715 : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
716 // allocate space for exactly zero operands.
717 void *operator new(size_t s) {
718 return User::operator new(s, 0);
722 /// get() constructors - Return a constant with vector type with an element
723 /// count and element type matching the ArrayRef passed in. Note that this
724 /// can return a ConstantAggregateZero object.
725 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
726 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
727 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
728 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
729 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
730 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
732 /// getFP() constructors - Return a constant with vector type with an element
733 /// count and element type of float with the precision matching the number of
734 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
735 /// double for 64bits) Note that this can return a ConstantAggregateZero
737 static Constant *getFP(LLVMContext &Context, ArrayRef<uint16_t> Elts);
738 static Constant *getFP(LLVMContext &Context, ArrayRef<uint32_t> Elts);
739 static Constant *getFP(LLVMContext &Context, ArrayRef<uint64_t> Elts);
741 /// Return a ConstantVector with the specified constant in each element.
742 /// The specified constant has to be a of a compatible type (i8/i16/
743 /// i32/i64/float/double) and must be a ConstantFP or ConstantInt.
744 static Constant *getSplat(unsigned NumElts, Constant *Elt);
746 /// If this is a splat constant, meaning that all of the elements have the
747 /// same value, return that value. Otherwise return NULL.
748 Constant *getSplatValue() const;
750 /// Specialize the getType() method to always return a VectorType,
751 /// which reduces the amount of casting needed in parts of the compiler.
752 inline VectorType *getType() const {
753 return cast<VectorType>(Value::getType());
756 /// Methods for support type inquiry through isa, cast, and dyn_cast:
757 static bool classof(const Value *V) {
758 return V->getValueID() == ConstantDataVectorVal;
762 //===----------------------------------------------------------------------===//
763 /// A constant token which is empty
765 class ConstantTokenNone final : public ConstantData {
766 ConstantTokenNone(const ConstantTokenNone &) = delete;
768 friend class Constant;
769 void destroyConstantImpl();
771 explicit ConstantTokenNone(LLVMContext &Context)
772 : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {}
775 /// Return the ConstantTokenNone.
776 static ConstantTokenNone *get(LLVMContext &Context);
778 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
779 static bool classof(const Value *V) {
780 return V->getValueID() == ConstantTokenNoneVal;
784 /// The address of a basic block.
786 class BlockAddress final : public Constant {
787 void *operator new(size_t, unsigned) = delete;
788 void *operator new(size_t s) { return User::operator new(s, 2); }
789 BlockAddress(Function *F, BasicBlock *BB);
791 friend class Constant;
792 void destroyConstantImpl();
793 Value *handleOperandChangeImpl(Value *From, Value *To);
796 /// Return a BlockAddress for the specified function and basic block.
797 static BlockAddress *get(Function *F, BasicBlock *BB);
799 /// Return a BlockAddress for the specified basic block. The basic
800 /// block must be embedded into a function.
801 static BlockAddress *get(BasicBlock *BB);
803 /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
805 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
806 static BlockAddress *lookup(const BasicBlock *BB);
808 /// Transparently provide more efficient getOperand methods.
809 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
811 Function *getFunction() const { return (Function*)Op<0>().get(); }
812 BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); }
814 /// Methods for support type inquiry through isa, cast, and dyn_cast:
815 static inline bool classof(const Value *V) {
816 return V->getValueID() == BlockAddressVal;
821 struct OperandTraits<BlockAddress> :
822 public FixedNumOperandTraits<BlockAddress, 2> {
825 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
828 //===----------------------------------------------------------------------===//
829 /// A constant value that is initialized with an expression using
830 /// other constant values.
832 /// This class uses the standard Instruction opcodes to define the various
833 /// constant expressions. The Opcode field for the ConstantExpr class is
834 /// maintained in the Value::SubclassData field.
835 class ConstantExpr : public Constant {
836 friend struct ConstantExprKeyType;
838 friend class Constant;
839 void destroyConstantImpl();
840 Value *handleOperandChangeImpl(Value *From, Value *To);
843 ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
844 : Constant(ty, ConstantExprVal, Ops, NumOps) {
845 // Operation type (an Instruction opcode) is stored as the SubclassData.
846 setValueSubclassData(Opcode);
850 // Static methods to construct a ConstantExpr of different kinds. Note that
851 // these methods may return a object that is not an instance of the
852 // ConstantExpr class, because they will attempt to fold the constant
853 // expression into something simpler if possible.
855 /// getAlignOf constant expr - computes the alignment of a type in a target
856 /// independent way (Note: the return type is an i64).
857 static Constant *getAlignOf(Type *Ty);
859 /// getSizeOf constant expr - computes the (alloc) size of a type (in
860 /// address-units, not bits) in a target independent way (Note: the return
863 static Constant *getSizeOf(Type *Ty);
865 /// getOffsetOf constant expr - computes the offset of a struct field in a
866 /// target independent way (Note: the return type is an i64).
868 static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
870 /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
871 /// which supports any aggregate type, and any Constant index.
873 static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
875 static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false);
876 static Constant *getFNeg(Constant *C);
877 static Constant *getNot(Constant *C);
878 static Constant *getAdd(Constant *C1, Constant *C2,
879 bool HasNUW = false, bool HasNSW = false);
880 static Constant *getFAdd(Constant *C1, Constant *C2);
881 static Constant *getSub(Constant *C1, Constant *C2,
882 bool HasNUW = false, bool HasNSW = false);
883 static Constant *getFSub(Constant *C1, Constant *C2);
884 static Constant *getMul(Constant *C1, Constant *C2,
885 bool HasNUW = false, bool HasNSW = false);
886 static Constant *getFMul(Constant *C1, Constant *C2);
887 static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
888 static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
889 static Constant *getFDiv(Constant *C1, Constant *C2);
890 static Constant *getURem(Constant *C1, Constant *C2);
891 static Constant *getSRem(Constant *C1, Constant *C2);
892 static Constant *getFRem(Constant *C1, Constant *C2);
893 static Constant *getAnd(Constant *C1, Constant *C2);
894 static Constant *getOr(Constant *C1, Constant *C2);
895 static Constant *getXor(Constant *C1, Constant *C2);
896 static Constant *getShl(Constant *C1, Constant *C2,
897 bool HasNUW = false, bool HasNSW = false);
898 static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
899 static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
900 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
901 static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
902 static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
903 static Constant *getFPTrunc(Constant *C, Type *Ty,
904 bool OnlyIfReduced = false);
905 static Constant *getFPExtend(Constant *C, Type *Ty,
906 bool OnlyIfReduced = false);
907 static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
908 static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
909 static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
910 static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
911 static Constant *getPtrToInt(Constant *C, Type *Ty,
912 bool OnlyIfReduced = false);
913 static Constant *getIntToPtr(Constant *C, Type *Ty,
914 bool OnlyIfReduced = false);
915 static Constant *getBitCast(Constant *C, Type *Ty,
916 bool OnlyIfReduced = false);
917 static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
918 bool OnlyIfReduced = false);
920 static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
921 static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
922 static Constant *getNSWAdd(Constant *C1, Constant *C2) {
923 return getAdd(C1, C2, false, true);
925 static Constant *getNUWAdd(Constant *C1, Constant *C2) {
926 return getAdd(C1, C2, true, false);
928 static Constant *getNSWSub(Constant *C1, Constant *C2) {
929 return getSub(C1, C2, false, true);
931 static Constant *getNUWSub(Constant *C1, Constant *C2) {
932 return getSub(C1, C2, true, false);
934 static Constant *getNSWMul(Constant *C1, Constant *C2) {
935 return getMul(C1, C2, false, true);
937 static Constant *getNUWMul(Constant *C1, Constant *C2) {
938 return getMul(C1, C2, true, false);
940 static Constant *getNSWShl(Constant *C1, Constant *C2) {
941 return getShl(C1, C2, false, true);
943 static Constant *getNUWShl(Constant *C1, Constant *C2) {
944 return getShl(C1, C2, true, false);
946 static Constant *getExactSDiv(Constant *C1, Constant *C2) {
947 return getSDiv(C1, C2, true);
949 static Constant *getExactUDiv(Constant *C1, Constant *C2) {
950 return getUDiv(C1, C2, true);
952 static Constant *getExactAShr(Constant *C1, Constant *C2) {
953 return getAShr(C1, C2, true);
955 static Constant *getExactLShr(Constant *C1, Constant *C2) {
956 return getLShr(C1, C2, true);
959 /// Return the identity for the given binary operation,
960 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
961 /// returns null if the operator doesn't have an identity.
962 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty);
964 /// Return the absorbing element for the given binary
965 /// operation, i.e. a constant C such that X op C = C and C op X = C for
966 /// every X. For example, this returns zero for integer multiplication.
967 /// It returns null if the operator doesn't have an absorbing element.
968 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
970 /// Transparently provide more efficient getOperand methods.
971 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
973 /// \brief Convenience function for getting a Cast operation.
975 /// \param ops The opcode for the conversion
976 /// \param C The constant to be converted
977 /// \param Ty The type to which the constant is converted
978 /// \param OnlyIfReduced see \a getWithOperands() docs.
979 static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
980 bool OnlyIfReduced = false);
982 // @brief Create a ZExt or BitCast cast constant expression
983 static Constant *getZExtOrBitCast(
984 Constant *C, ///< The constant to zext or bitcast
985 Type *Ty ///< The type to zext or bitcast C to
988 // @brief Create a SExt or BitCast cast constant expression
989 static Constant *getSExtOrBitCast(
990 Constant *C, ///< The constant to sext or bitcast
991 Type *Ty ///< The type to sext or bitcast C to
994 // @brief Create a Trunc or BitCast cast constant expression
995 static Constant *getTruncOrBitCast(
996 Constant *C, ///< The constant to trunc or bitcast
997 Type *Ty ///< The type to trunc or bitcast C to
1000 /// @brief Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
1002 static Constant *getPointerCast(
1003 Constant *C, ///< The pointer value to be casted (operand 0)
1004 Type *Ty ///< The type to which cast should be made
1007 /// @brief Create a BitCast or AddrSpaceCast for a pointer type depending on
1008 /// the address space.
1009 static Constant *getPointerBitCastOrAddrSpaceCast(
1010 Constant *C, ///< The constant to addrspacecast or bitcast
1011 Type *Ty ///< The type to bitcast or addrspacecast C to
1014 /// @brief Create a ZExt, Bitcast or Trunc for integer -> integer casts
1015 static Constant *getIntegerCast(
1016 Constant *C, ///< The integer constant to be casted
1017 Type *Ty, ///< The integer type to cast to
1018 bool isSigned ///< Whether C should be treated as signed or not
1021 /// @brief Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
1022 static Constant *getFPCast(
1023 Constant *C, ///< The integer constant to be casted
1024 Type *Ty ///< The integer type to cast to
1027 /// @brief Return true if this is a convert constant expression
1028 bool isCast() const;
1030 /// @brief Return true if this is a compare constant expression
1031 bool isCompare() const;
1033 /// @brief Return true if this is an insertvalue or extractvalue expression,
1034 /// and the getIndices() method may be used.
1035 bool hasIndices() const;
1037 /// @brief Return true if this is a getelementptr expression and all
1038 /// the index operands are compile-time known integers within the
1039 /// corresponding notional static array extents. Note that this is
1040 /// not equivalant to, a subset of, or a superset of the "inbounds"
1042 bool isGEPWithNoNotionalOverIndexing() const;
1044 /// Select constant expr
1046 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1047 static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
1048 Type *OnlyIfReducedTy = nullptr);
1050 /// get - Return a binary or shift operator constant expression,
1051 /// folding if possible.
1053 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1054 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1055 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
1057 /// \brief Return an ICmp or FCmp comparison operator constant expression.
1059 /// \param OnlyIfReduced see \a getWithOperands() docs.
1060 static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
1061 bool OnlyIfReduced = false);
1063 /// get* - Return some common constants without having to
1064 /// specify the full Instruction::OPCODE identifier.
1066 static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
1067 bool OnlyIfReduced = false);
1068 static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
1069 bool OnlyIfReduced = false);
1071 /// Getelementptr form. Value* is only accepted for convenience;
1072 /// all elements must be Constants.
1074 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1075 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1076 ArrayRef<Constant *> IdxList,
1077 bool InBounds = false,
1078 Type *OnlyIfReducedTy = nullptr) {
1079 return getGetElementPtr(
1080 Ty, C, makeArrayRef((Value * const *)IdxList.data(), IdxList.size()),
1081 InBounds, OnlyIfReducedTy);
1083 static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx,
1084 bool InBounds = false,
1085 Type *OnlyIfReducedTy = nullptr) {
1086 // This form of the function only exists to avoid ambiguous overload
1087 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1088 // ArrayRef<Value *>.
1089 return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, OnlyIfReducedTy);
1091 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1092 ArrayRef<Value *> IdxList,
1093 bool InBounds = false,
1094 Type *OnlyIfReducedTy = nullptr);
1096 /// Create an "inbounds" getelementptr. See the documentation for the
1097 /// "inbounds" flag in LangRef.html for details.
1098 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1099 ArrayRef<Constant *> IdxList) {
1100 return getGetElementPtr(Ty, C, IdxList, true);
1102 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1104 // This form of the function only exists to avoid ambiguous overload
1105 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1106 // ArrayRef<Value *>.
1107 return getGetElementPtr(Ty, C, Idx, true);
1109 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1110 ArrayRef<Value *> IdxList) {
1111 return getGetElementPtr(Ty, C, IdxList, true);
1114 static Constant *getExtractElement(Constant *Vec, Constant *Idx,
1115 Type *OnlyIfReducedTy = nullptr);
1116 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
1117 Type *OnlyIfReducedTy = nullptr);
1118 static Constant *getShuffleVector(Constant *V1, Constant *V2, Constant *Mask,
1119 Type *OnlyIfReducedTy = nullptr);
1120 static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
1121 Type *OnlyIfReducedTy = nullptr);
1122 static Constant *getInsertValue(Constant *Agg, Constant *Val,
1123 ArrayRef<unsigned> Idxs,
1124 Type *OnlyIfReducedTy = nullptr);
1126 /// Return the opcode at the root of this constant expression
1127 unsigned getOpcode() const { return getSubclassDataFromValue(); }
1129 /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
1130 /// FCMP constant expression.
1131 unsigned getPredicate() const;
1133 /// Assert that this is an insertvalue or exactvalue
1134 /// expression and return the list of indices.
1135 ArrayRef<unsigned> getIndices() const;
1137 /// Return a string representation for an opcode.
1138 const char *getOpcodeName() const;
1140 /// Return a constant expression identical to this one, but with the specified
1141 /// operand set to the specified value.
1142 Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1144 /// This returns the current constant expression with the operands replaced
1145 /// with the specified values. The specified array must have the same number
1146 /// of operands as our current one.
1147 Constant *getWithOperands(ArrayRef<Constant*> Ops) const {
1148 return getWithOperands(Ops, getType());
1151 /// Get the current expression with the operands replaced.
1153 /// Return the current constant expression with the operands replaced with \c
1154 /// Ops and the type with \c Ty. The new operands must have the same number
1155 /// as the current ones.
1157 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
1158 /// gets constant-folded, the type changes, or the expression is otherwise
1159 /// canonicalized. This parameter should almost always be \c false.
1160 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1161 bool OnlyIfReduced = false,
1162 Type *SrcTy = nullptr) const;
1164 /// Returns an Instruction which implements the same operation as this
1165 /// ConstantExpr. The instruction is not linked to any basic block.
1167 /// A better approach to this could be to have a constructor for Instruction
1168 /// which would take a ConstantExpr parameter, but that would have spread
1169 /// implementation details of ConstantExpr outside of Constants.cpp, which
1170 /// would make it harder to remove ConstantExprs altogether.
1171 Instruction *getAsInstruction();
1173 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1174 static inline bool classof(const Value *V) {
1175 return V->getValueID() == ConstantExprVal;
1179 // Shadow Value::setValueSubclassData with a private forwarding method so that
1180 // subclasses cannot accidentally use it.
1181 void setValueSubclassData(unsigned short D) {
1182 Value::setValueSubclassData(D);
1187 struct OperandTraits<ConstantExpr> :
1188 public VariadicOperandTraits<ConstantExpr, 1> {
1191 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
1193 //===----------------------------------------------------------------------===//
1194 /// 'undef' values are things that do not have specified contents.
1195 /// These are used for a variety of purposes, including global variable
1196 /// initializers and operands to instructions. 'undef' values can occur with
1197 /// any first-class type.
1199 /// Undef values aren't exactly constants; if they have multiple uses, they
1200 /// can appear to have different bit patterns at each use. See
1201 /// LangRef.html#undefvalues for details.
1203 class UndefValue final : public ConstantData {
1204 UndefValue(const UndefValue &) = delete;
1206 friend class Constant;
1207 void destroyConstantImpl();
1209 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
1212 /// Static factory methods - Return an 'undef' object of the specified type.
1213 static UndefValue *get(Type *T);
1215 /// If this Undef has array or vector type, return a undef with the right
1217 UndefValue *getSequentialElement() const;
1219 /// If this undef has struct type, return a undef with the right element type
1220 /// for the specified element.
1221 UndefValue *getStructElement(unsigned Elt) const;
1223 /// Return an undef of the right value for the specified GEP index if we can,
1224 /// otherwise return null (e.g. if C is a ConstantExpr).
1225 UndefValue *getElementValue(Constant *C) const;
1227 /// Return an undef of the right value for the specified GEP index.
1228 UndefValue *getElementValue(unsigned Idx) const;
1230 /// Return the number of elements in the array, vector, or struct.
1231 unsigned getNumElements() const;
1233 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1234 static bool classof(const Value *V) {
1235 return V->getValueID() == UndefValueVal;
1239 } // End llvm namespace