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/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/Constant.h"
29#include "llvm/IR/ConstantRange.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Intrinsics.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#include <optional>
42
43namespace llvm {
44
45template <class ConstantClass> struct ConstantAggrKeyType;
46
47/// Base class for constants with no operands.
48///
49/// These constants have no operands; they represent their data directly.
50/// Since they can be in use by unrelated modules (and are never based on
51/// GlobalValues), it never makes sense to RAUW them.
52class ConstantData : public Constant {
53 friend class Constant;
54
55 Value *handleOperandChangeImpl(Value *From, Value *To) {
56 llvm_unreachable("Constant data does not have operands!");
57 }
58
59protected:
60 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
61
62 void *operator new(size_t S) { return User::operator new(Size: S, Us: 0); }
63
64public:
65 void operator delete(void *Ptr) { User::operator delete(Usr: Ptr); }
66
67 ConstantData(const ConstantData &) = delete;
68
69 /// Methods to support type inquiry through isa, cast, and dyn_cast.
70 static bool classof(const Value *V) {
71 return V->getValueID() >= ConstantDataFirstVal &&
72 V->getValueID() <= ConstantDataLastVal;
73 }
74};
75
76//===----------------------------------------------------------------------===//
77/// This is the shared class of boolean and integer constants. This class
78/// represents both boolean and integral constants.
79/// Class for constant integers.
80class ConstantInt final : public ConstantData {
81 friend class Constant;
82 friend class ConstantVector;
83
84 APInt Val;
85
86 ConstantInt(Type *Ty, const APInt &V);
87
88 void destroyConstantImpl();
89
90 /// Return a ConstantInt with the specified value and an implied Type. The
91 /// type is the vector type whose integer element type corresponds to the bit
92 /// width of the value.
93 static ConstantInt *get(LLVMContext &Context, ElementCount EC,
94 const APInt &V);
95
96public:
97 ConstantInt(const ConstantInt &) = delete;
98
99 static ConstantInt *getTrue(LLVMContext &Context);
100 static ConstantInt *getFalse(LLVMContext &Context);
101 static ConstantInt *getBool(LLVMContext &Context, bool V);
102 static Constant *getTrue(Type *Ty);
103 static Constant *getFalse(Type *Ty);
104 static Constant *getBool(Type *Ty, bool V);
105
106 /// If Ty is a vector type, return a Constant with a splat of the given
107 /// value. Otherwise return a ConstantInt for the given value.
108 static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false);
109
110 /// Return a ConstantInt with the specified integer value for the specified
111 /// type. If the type is wider than 64 bits, the value will be zero-extended
112 /// to fit the type, unless IsSigned is true, in which case the value will
113 /// be interpreted as a 64-bit signed integer and sign-extended to fit
114 /// the type.
115 /// Get a ConstantInt for a specific value.
116 static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false);
117
118 /// Return a ConstantInt with the specified value for the specified type. The
119 /// value V will be canonicalized to a an unsigned APInt. Accessing it with
120 /// either getSExtValue() or getZExtValue() will yield a correctly sized and
121 /// signed value for the type Ty.
122 /// Get a ConstantInt for a specific signed value.
123 static ConstantInt *getSigned(IntegerType *Ty, int64_t V) {
124 return get(Ty, V, IsSigned: true);
125 }
126 static Constant *getSigned(Type *Ty, int64_t V) {
127 return get(Ty, V, IsSigned: true);
128 }
129
130 /// Return a ConstantInt with the specified value and an implied Type. The
131 /// type is the integer type that corresponds to the bit width of the value.
132 static ConstantInt *get(LLVMContext &Context, const APInt &V);
133
134 /// Return a ConstantInt constructed from the string strStart with the given
135 /// radix.
136 static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix);
137
138 /// If Ty is a vector type, return a Constant with a splat of the given
139 /// value. Otherwise return a ConstantInt for the given value.
140 static Constant *get(Type *Ty, const APInt &V);
141
142 /// Return the constant as an APInt value reference. This allows clients to
143 /// obtain a full-precision copy of the value.
144 /// Return the constant's value.
145 inline const APInt &getValue() const { return Val; }
146
147 /// getBitWidth - Return the scalar bitwidth of this constant.
148 unsigned getBitWidth() const { return Val.getBitWidth(); }
149
150 /// Return the constant as a 64-bit unsigned integer value after it
151 /// has been zero extended as appropriate for the type of this constant. Note
152 /// that this method can assert if the value does not fit in 64 bits.
153 /// Return the zero extended value.
154 inline uint64_t getZExtValue() const { return Val.getZExtValue(); }
155
156 /// Return the constant as a 64-bit integer value after it has been sign
157 /// extended as appropriate for the type of this constant. Note that
158 /// this method can assert if the value does not fit in 64 bits.
159 /// Return the sign extended value.
160 inline int64_t getSExtValue() const { return Val.getSExtValue(); }
161
162 /// Return the constant as an llvm::MaybeAlign.
163 /// Note that this method can assert if the value does not fit in 64 bits or
164 /// is not a power of two.
165 inline MaybeAlign getMaybeAlignValue() const {
166 return MaybeAlign(getZExtValue());
167 }
168
169 /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`.
170 /// Note that this method can assert if the value does not fit in 64 bits or
171 /// is not a power of two.
172 inline Align getAlignValue() const {
173 return getMaybeAlignValue().valueOrOne();
174 }
175
176 /// A helper method that can be used to determine if the constant contained
177 /// within is equal to a constant. This only works for very small values,
178 /// because this is all that can be represented with all types.
179 /// Determine if this constant's value is same as an unsigned char.
180 bool equalsInt(uint64_t V) const { return Val == V; }
181
182 /// Variant of the getType() method to always return an IntegerType, which
183 /// reduces the amount of casting needed in parts of the compiler.
184 inline IntegerType *getIntegerType() const {
185 return cast<IntegerType>(Val: Value::getType());
186 }
187
188 /// This static method returns true if the type Ty is big enough to
189 /// represent the value V. This can be used to avoid having the get method
190 /// assert when V is larger than Ty can represent. Note that there are two
191 /// versions of this method, one for unsigned and one for signed integers.
192 /// Although ConstantInt canonicalizes everything to an unsigned integer,
193 /// the signed version avoids callers having to convert a signed quantity
194 /// to the appropriate unsigned type before calling the method.
195 /// @returns true if V is a valid value for type Ty
196 /// Determine if the value is in range for the given type.
197 static bool isValueValidForType(Type *Ty, uint64_t V);
198 static bool isValueValidForType(Type *Ty, int64_t V);
199
200 bool isNegative() const { return Val.isNegative(); }
201
202 /// This is just a convenience method to make client code smaller for a
203 /// common code. It also correctly performs the comparison without the
204 /// potential for an assertion from getZExtValue().
205 bool isZero() const { return Val.isZero(); }
206
207 /// This is just a convenience method to make client code smaller for a
208 /// common case. It also correctly performs the comparison without the
209 /// potential for an assertion from getZExtValue().
210 /// Determine if the value is one.
211 bool isOne() const { return Val.isOne(); }
212
213 /// This function will return true iff every bit in this constant is set
214 /// to true.
215 /// @returns true iff this constant's bits are all set to true.
216 /// Determine if the value is all ones.
217 bool isMinusOne() const { return Val.isAllOnes(); }
218
219 /// This function will return true iff this constant represents the largest
220 /// value that may be represented by the constant's type.
221 /// @returns true iff this is the largest value that may be represented
222 /// by this type.
223 /// Determine if the value is maximal.
224 bool isMaxValue(bool IsSigned) const {
225 if (IsSigned)
226 return Val.isMaxSignedValue();
227 else
228 return Val.isMaxValue();
229 }
230
231 /// This function will return true iff this constant represents the smallest
232 /// value that may be represented by this constant's type.
233 /// @returns true if this is the smallest value that may be represented by
234 /// this type.
235 /// Determine if the value is minimal.
236 bool isMinValue(bool IsSigned) const {
237 if (IsSigned)
238 return Val.isMinSignedValue();
239 else
240 return Val.isMinValue();
241 }
242
243 /// This function will return true iff this constant represents a value with
244 /// active bits bigger than 64 bits or a value greater than the given uint64_t
245 /// value.
246 /// @returns true iff this constant is greater or equal to the given number.
247 /// Determine if the value is greater or equal to the given number.
248 bool uge(uint64_t Num) const { return Val.uge(RHS: Num); }
249
250 /// getLimitedValue - If the value is smaller than the specified limit,
251 /// return it, otherwise return the limit value. This causes the value
252 /// to saturate to the limit.
253 /// @returns the min of the value of the constant and the specified value
254 /// Get the constant's value with a saturation limit
255 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
256 return Val.getLimitedValue(Limit);
257 }
258
259 /// Methods to support type inquiry through isa, cast, and dyn_cast.
260 static bool classof(const Value *V) {
261 return V->getValueID() == ConstantIntVal;
262 }
263};
264
265//===----------------------------------------------------------------------===//
266/// ConstantFP - Floating Point Values [float, double]
267///
268class ConstantFP final : public ConstantData {
269 friend class Constant;
270 friend class ConstantVector;
271
272 APFloat Val;
273
274 ConstantFP(Type *Ty, const APFloat &V);
275
276 void destroyConstantImpl();
277
278 /// Return a ConstantFP with the specified value and an implied Type. The
279 /// type is the vector type whose element type has the same floating point
280 /// semantics as the value.
281 static ConstantFP *get(LLVMContext &Context, ElementCount EC,
282 const APFloat &V);
283
284public:
285 ConstantFP(const ConstantFP &) = delete;
286
287 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
288 /// for the specified value in the specified type. This should only be used
289 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
290 /// host double and as the target format.
291 static Constant *get(Type *Ty, double V);
292
293 /// If Ty is a vector type, return a Constant with a splat of the given
294 /// value. Otherwise return a ConstantFP for the given value.
295 static Constant *get(Type *Ty, const APFloat &V);
296
297 static Constant *get(Type *Ty, StringRef Str);
298 static ConstantFP *get(LLVMContext &Context, const APFloat &V);
299 static Constant *getNaN(Type *Ty, bool Negative = false,
300 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 *getZero(Type *Ty, bool Negative = false);
306 static Constant *getNegativeZero(Type *Ty) { return getZero(Ty, Negative: true); }
307 static Constant *getInfinity(Type *Ty, bool Negative = false);
308
309 /// Return true if Ty is big enough to represent V.
310 static bool isValueValidForType(Type *Ty, const APFloat &V);
311 inline const APFloat &getValueAPF() const { return Val; }
312 inline const APFloat &getValue() const { return Val; }
313
314 /// Return true if the value is positive or negative zero.
315 bool isZero() const { return Val.isZero(); }
316
317 /// Return true if the sign bit is set.
318 bool isNegative() const { return Val.isNegative(); }
319
320 /// Return true if the value is infinity
321 bool isInfinity() const { return Val.isInfinity(); }
322
323 /// Return true if the value is a NaN.
324 bool isNaN() const { return Val.isNaN(); }
325
326 /// We don't rely on operator== working on double values, as it returns true
327 /// for things that are clearly not equal, like -0.0 and 0.0.
328 /// As such, this method can be used to do an exact bit-for-bit comparison of
329 /// two floating point values. The version with a double operand is retained
330 /// because it's so convenient to write isExactlyValue(2.0), but please use
331 /// it only for simple constants.
332 bool isExactlyValue(const APFloat &V) const;
333
334 bool isExactlyValue(double V) const {
335 bool ignored;
336 APFloat FV(V);
337 FV.convert(ToSemantics: Val.getSemantics(), RM: APFloat::rmNearestTiesToEven, losesInfo: &ignored);
338 return isExactlyValue(V: FV);
339 }
340
341 /// Methods for support type inquiry through isa, cast, and dyn_cast:
342 static bool classof(const Value *V) {
343 return V->getValueID() == ConstantFPVal;
344 }
345};
346
347//===----------------------------------------------------------------------===//
348/// All zero aggregate value
349///
350class ConstantAggregateZero final : public ConstantData {
351 friend class Constant;
352
353 explicit ConstantAggregateZero(Type *Ty)
354 : ConstantData(Ty, ConstantAggregateZeroVal) {}
355
356 void destroyConstantImpl();
357
358public:
359 ConstantAggregateZero(const ConstantAggregateZero &) = delete;
360
361 static ConstantAggregateZero *get(Type *Ty);
362
363 /// If this CAZ has array or vector type, return a zero with the right element
364 /// type.
365 Constant *getSequentialElement() const;
366
367 /// If this CAZ has struct type, return a zero with the right element type for
368 /// the specified element.
369 Constant *getStructElement(unsigned Elt) const;
370
371 /// Return a zero of the right value for the specified GEP index if we can,
372 /// otherwise return null (e.g. if C is a ConstantExpr).
373 Constant *getElementValue(Constant *C) const;
374
375 /// Return a zero of the right value for the specified GEP index.
376 Constant *getElementValue(unsigned Idx) const;
377
378 /// Return the number of elements in the array, vector, or struct.
379 ElementCount getElementCount() const;
380
381 /// Methods for support type inquiry through isa, cast, and dyn_cast:
382 ///
383 static bool classof(const Value *V) {
384 return V->getValueID() == ConstantAggregateZeroVal;
385 }
386};
387
388/// Base class for aggregate constants (with operands).
389///
390/// These constants are aggregates of other constants, which are stored as
391/// operands.
392///
393/// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
394/// ConstantVector.
395///
396/// \note Some subclasses of \a ConstantData are semantically aggregates --
397/// such as \a ConstantDataArray -- but are not subclasses of this because they
398/// use operands.
399class ConstantAggregate : public Constant {
400protected:
401 ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V);
402
403public:
404 /// Transparently provide more efficient getOperand methods.
405 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
406
407 /// Methods for support type inquiry through isa, cast, and dyn_cast:
408 static bool classof(const Value *V) {
409 return V->getValueID() >= ConstantAggregateFirstVal &&
410 V->getValueID() <= ConstantAggregateLastVal;
411 }
412};
413
414template <>
415struct OperandTraits<ConstantAggregate>
416 : public VariadicOperandTraits<ConstantAggregate> {};
417
418DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)
419
420//===----------------------------------------------------------------------===//
421/// ConstantArray - Constant Array Declarations
422///
423class ConstantArray final : public ConstantAggregate {
424 friend struct ConstantAggrKeyType<ConstantArray>;
425 friend class Constant;
426
427 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
428
429 void destroyConstantImpl();
430 Value *handleOperandChangeImpl(Value *From, Value *To);
431
432public:
433 // ConstantArray accessors
434 static Constant *get(ArrayType *T, ArrayRef<Constant *> V);
435
436private:
437 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
438
439public:
440 /// Specialize the getType() method to always return an ArrayType,
441 /// which reduces the amount of casting needed in parts of the compiler.
442 inline ArrayType *getType() const {
443 return cast<ArrayType>(Val: Value::getType());
444 }
445
446 /// Methods for support type inquiry through isa, cast, and dyn_cast:
447 static bool classof(const Value *V) {
448 return V->getValueID() == ConstantArrayVal;
449 }
450};
451
452//===----------------------------------------------------------------------===//
453// Constant Struct Declarations
454//
455class ConstantStruct final : public ConstantAggregate {
456 friend struct ConstantAggrKeyType<ConstantStruct>;
457 friend class Constant;
458
459 ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
460
461 void destroyConstantImpl();
462 Value *handleOperandChangeImpl(Value *From, Value *To);
463
464public:
465 // ConstantStruct accessors
466 static Constant *get(StructType *T, ArrayRef<Constant *> V);
467
468 template <typename... Csts>
469 static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *>
470 get(StructType *T, Csts *...Vs) {
471 return get(T, V: ArrayRef<Constant *>({Vs...}));
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(T: getTypeForElements(V, Packed), V);
478 }
479 static Constant *getAnon(LLVMContext &Ctx, ArrayRef<Constant *> V,
480 bool Packed = false) {
481 return get(T: 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>(Val: 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///
507class 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
516public:
517 // ConstantVector accessors
518 static Constant *get(ArrayRef<Constant *> V);
519
520private:
521 static Constant *getImpl(ArrayRef<Constant *> V);
522
523public:
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>(Val: Value::getType());
532 }
533
534 /// If all elements of the vector constant have the same value, return that
535 /// value. Otherwise, return nullptr. Ignore poison elements by setting
536 /// AllowPoison to true.
537 Constant *getSplatValue(bool AllowPoison = 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///
548class ConstantPointerNull final : public ConstantData {
549 friend class Constant;
550
551 explicit ConstantPointerNull(PointerType *T)
552 : ConstantData(T, Value::ConstantPointerNullVal) {}
553
554 void destroyConstantImpl();
555
556public:
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>(Val: 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 half/bfloat/float/double, and whose elements
577/// are just simple data values (i.e. ConstantInt/ConstantFP). This Constant
578/// node has no operands because it stores all of the elements of the constant
579/// as densely packed data, instead of as Value*'s.
580///
581/// This is the common base class of ConstantDataArray and ConstantDataVector.
582///
583class 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
599protected:
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
605public:
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(Start: 0, N: 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
682private:
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.
692class ConstantDataArray final : public ConstantDataSequential {
693 friend class ConstantDataSequential;
694
695 explicit ConstantDataArray(Type *ty, const char *Data)
696 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
697
698public:
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(Data: StringRef(Data, Elts.size() * sizeof(ElementTy)), NumElements: Elts.size(),
708 ElementTy: 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, ArrayRef(Elts));
716 }
717
718 /// getRaw() 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 must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
722 /// the 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,
725 Type *ElementTy) {
726 Type *Ty = ArrayType::get(ElementType: ElementTy, NumElements);
727 return getImpl(Bytes: Data, Ty);
728 }
729
730 /// getFP() constructors - Return a constant of array type with a float
731 /// element type taken from argument `ElementType', and count taken from
732 /// argument `Elts'. The amount of bits of the contained type must match the
733 /// number of bits of the type contained in the passed in ArrayRef.
734 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
735 /// that this can return a ConstantAggregateZero object.
736 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
737 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
738 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
739
740 /// This method constructs a CDS and initializes it with a text string.
741 /// The default behavior (AddNull==true) causes a null terminator to
742 /// be placed at the end of the array (increasing the length of the string by
743 /// one more than the StringRef would normally indicate. Pass AddNull=false
744 /// to disable this behavior.
745 static Constant *getString(LLVMContext &Context, StringRef Initializer,
746 bool AddNull = true);
747
748 /// Specialize the getType() method to always return an ArrayType,
749 /// which reduces the amount of casting needed in parts of the compiler.
750 inline ArrayType *getType() const {
751 return cast<ArrayType>(Val: Value::getType());
752 }
753
754 /// Methods for support type inquiry through isa, cast, and dyn_cast:
755 static bool classof(const Value *V) {
756 return V->getValueID() == ConstantDataArrayVal;
757 }
758};
759
760//===----------------------------------------------------------------------===//
761/// A vector constant whose element type is a simple 1/2/4/8-byte integer or
762/// float/double, and whose elements are just simple data values
763/// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
764/// stores all of the elements of the constant as densely packed data, instead
765/// of as Value*'s.
766class ConstantDataVector final : public ConstantDataSequential {
767 friend class ConstantDataSequential;
768
769 explicit ConstantDataVector(Type *ty, const char *Data)
770 : ConstantDataSequential(ty, ConstantDataVectorVal, Data),
771 IsSplatSet(false) {}
772 // Cache whether or not the constant is a splat.
773 mutable bool IsSplatSet : 1;
774 mutable bool IsSplat : 1;
775 bool isSplatData() const;
776
777public:
778 ConstantDataVector(const ConstantDataVector &) = delete;
779
780 /// get() constructors - Return a constant with vector type with an element
781 /// count and element type matching the ArrayRef passed in. Note that this
782 /// can return a ConstantAggregateZero object.
783 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
784 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
785 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
786 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
787 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
788 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
789
790 /// getRaw() constructor - Return a constant with vector type with an element
791 /// count and element type matching the NumElements and ElementTy parameters
792 /// passed in. Note that this can return a ConstantAggregateZero object.
793 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
794 /// the buffer containing the elements. Be careful to make sure Data uses the
795 /// right endianness, the buffer will be used as-is.
796 static Constant *getRaw(StringRef Data, uint64_t NumElements,
797 Type *ElementTy) {
798 Type *Ty = VectorType::get(ElementType: ElementTy, EC: ElementCount::getFixed(MinVal: NumElements));
799 return getImpl(Bytes: Data, Ty);
800 }
801
802 /// getFP() constructors - Return a constant of vector type with a float
803 /// element type taken from argument `ElementType', and count taken from
804 /// argument `Elts'. The amount of bits of the contained type must match the
805 /// number of bits of the type contained in the passed in ArrayRef.
806 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
807 /// that this can return a ConstantAggregateZero object.
808 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
809 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
810 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
811
812 /// Return a ConstantVector with the specified constant in each element.
813 /// The specified constant has to be a of a compatible type (i8/i16/
814 /// i32/i64/half/bfloat/float/double) and must be a ConstantFP or ConstantInt.
815 static Constant *getSplat(unsigned NumElts, Constant *Elt);
816
817 /// Returns true if this is a splat constant, meaning that all elements have
818 /// the same value.
819 bool isSplat() const;
820
821 /// If this is a splat constant, meaning that all of the elements have the
822 /// same value, return that value. Otherwise return NULL.
823 Constant *getSplatValue() const;
824
825 /// Specialize the getType() method to always return a FixedVectorType,
826 /// which reduces the amount of casting needed in parts of the compiler.
827 inline FixedVectorType *getType() const {
828 return cast<FixedVectorType>(Val: Value::getType());
829 }
830
831 /// Methods for support type inquiry through isa, cast, and dyn_cast:
832 static bool classof(const Value *V) {
833 return V->getValueID() == ConstantDataVectorVal;
834 }
835};
836
837//===----------------------------------------------------------------------===//
838/// A constant token which is empty
839///
840class ConstantTokenNone final : public ConstantData {
841 friend class Constant;
842
843 explicit ConstantTokenNone(LLVMContext &Context)
844 : ConstantData(Type::getTokenTy(C&: Context), ConstantTokenNoneVal) {}
845
846 void destroyConstantImpl();
847
848public:
849 ConstantTokenNone(const ConstantTokenNone &) = delete;
850
851 /// Return the ConstantTokenNone.
852 static ConstantTokenNone *get(LLVMContext &Context);
853
854 /// Methods to support type inquiry through isa, cast, and dyn_cast.
855 static bool classof(const Value *V) {
856 return V->getValueID() == ConstantTokenNoneVal;
857 }
858};
859
860/// A constant target extension type default initializer
861class ConstantTargetNone final : public ConstantData {
862 friend class Constant;
863
864 explicit ConstantTargetNone(TargetExtType *T)
865 : ConstantData(T, Value::ConstantTargetNoneVal) {}
866
867 void destroyConstantImpl();
868
869public:
870 ConstantTargetNone(const ConstantTargetNone &) = delete;
871
872 /// Static factory methods - Return objects of the specified value.
873 static ConstantTargetNone *get(TargetExtType *T);
874
875 /// Specialize the getType() method to always return an TargetExtType,
876 /// which reduces the amount of casting needed in parts of the compiler.
877 inline TargetExtType *getType() const {
878 return cast<TargetExtType>(Val: Value::getType());
879 }
880
881 /// Methods for support type inquiry through isa, cast, and dyn_cast.
882 static bool classof(const Value *V) {
883 return V->getValueID() == ConstantTargetNoneVal;
884 }
885};
886
887/// The address of a basic block.
888///
889class BlockAddress final : public Constant {
890 friend class Constant;
891
892 BlockAddress(Function *F, BasicBlock *BB);
893
894 void *operator new(size_t S) { return User::operator new(Size: S, Us: 2); }
895
896 void destroyConstantImpl();
897 Value *handleOperandChangeImpl(Value *From, Value *To);
898
899public:
900 void operator delete(void *Ptr) { User::operator delete(Usr: Ptr); }
901
902 /// Return a BlockAddress for the specified function and basic block.
903 static BlockAddress *get(Function *F, BasicBlock *BB);
904
905 /// Return a BlockAddress for the specified basic block. The basic
906 /// block must be embedded into a function.
907 static BlockAddress *get(BasicBlock *BB);
908
909 /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
910 ///
911 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
912 static BlockAddress *lookup(const BasicBlock *BB);
913
914 /// Transparently provide more efficient getOperand methods.
915 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
916
917 Function *getFunction() const { return (Function *)Op<0>().get(); }
918 BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); }
919
920 /// Methods for support type inquiry through isa, cast, and dyn_cast:
921 static bool classof(const Value *V) {
922 return V->getValueID() == BlockAddressVal;
923 }
924};
925
926template <>
927struct OperandTraits<BlockAddress>
928 : public FixedNumOperandTraits<BlockAddress, 2> {};
929
930DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)
931
932/// Wrapper for a function that represents a value that
933/// functionally represents the original function. This can be a function,
934/// global alias to a function, or an ifunc.
935class DSOLocalEquivalent final : public Constant {
936 friend class Constant;
937
938 DSOLocalEquivalent(GlobalValue *GV);
939
940 void *operator new(size_t S) { return User::operator new(Size: S, Us: 1); }
941
942 void destroyConstantImpl();
943 Value *handleOperandChangeImpl(Value *From, Value *To);
944
945public:
946 void operator delete(void *Ptr) { User::operator delete(Usr: Ptr); }
947
948 /// Return a DSOLocalEquivalent for the specified global value.
949 static DSOLocalEquivalent *get(GlobalValue *GV);
950
951 /// Transparently provide more efficient getOperand methods.
952 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
953
954 GlobalValue *getGlobalValue() const {
955 return cast<GlobalValue>(Val: Op<0>().get());
956 }
957
958 /// Methods for support type inquiry through isa, cast, and dyn_cast:
959 static bool classof(const Value *V) {
960 return V->getValueID() == DSOLocalEquivalentVal;
961 }
962};
963
964template <>
965struct OperandTraits<DSOLocalEquivalent>
966 : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {};
967
968DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value)
969
970/// Wrapper for a value that won't be replaced with a CFI jump table
971/// pointer in LowerTypeTestsModule.
972class NoCFIValue final : public Constant {
973 friend class Constant;
974
975 NoCFIValue(GlobalValue *GV);
976
977 void *operator new(size_t S) { return User::operator new(Size: S, Us: 1); }
978
979 void destroyConstantImpl();
980 Value *handleOperandChangeImpl(Value *From, Value *To);
981
982public:
983 /// Return a NoCFIValue for the specified function.
984 static NoCFIValue *get(GlobalValue *GV);
985
986 /// Transparently provide more efficient getOperand methods.
987 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
988
989 GlobalValue *getGlobalValue() const {
990 return cast<GlobalValue>(Val: Op<0>().get());
991 }
992
993 /// NoCFIValue is always a pointer.
994 PointerType *getType() const {
995 return cast<PointerType>(Val: Value::getType());
996 }
997
998 /// Methods for support type inquiry through isa, cast, and dyn_cast:
999 static bool classof(const Value *V) {
1000 return V->getValueID() == NoCFIValueVal;
1001 }
1002};
1003
1004template <>
1005struct OperandTraits<NoCFIValue> : public FixedNumOperandTraits<NoCFIValue, 1> {
1006};
1007
1008DEFINE_TRANSPARENT_OPERAND_ACCESSORS(NoCFIValue, Value)
1009
1010//===----------------------------------------------------------------------===//
1011/// A constant value that is initialized with an expression using
1012/// other constant values.
1013///
1014/// This class uses the standard Instruction opcodes to define the various
1015/// constant expressions. The Opcode field for the ConstantExpr class is
1016/// maintained in the Value::SubclassData field.
1017class ConstantExpr : public Constant {
1018 friend struct ConstantExprKeyType;
1019 friend class Constant;
1020
1021 void destroyConstantImpl();
1022 Value *handleOperandChangeImpl(Value *From, Value *To);
1023
1024protected:
1025 ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
1026 : Constant(ty, ConstantExprVal, Ops, NumOps) {
1027 // Operation type (an Instruction opcode) is stored as the SubclassData.
1028 setValueSubclassData(Opcode);
1029 }
1030
1031 ~ConstantExpr() = default;
1032
1033public:
1034 // Static methods to construct a ConstantExpr of different kinds. Note that
1035 // these methods may return a object that is not an instance of the
1036 // ConstantExpr class, because they will attempt to fold the constant
1037 // expression into something simpler if possible.
1038
1039 /// getAlignOf constant expr - computes the alignment of a type in a target
1040 /// independent way (Note: the return type is an i64).
1041 static Constant *getAlignOf(Type *Ty);
1042
1043 /// getSizeOf constant expr - computes the (alloc) size of a type (in
1044 /// address-units, not bits) in a target independent way (Note: the return
1045 /// type is an i64).
1046 ///
1047 static Constant *getSizeOf(Type *Ty);
1048
1049 static Constant *getNeg(Constant *C, bool HasNSW = false);
1050 static Constant *getNot(Constant *C);
1051 static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false,
1052 bool HasNSW = false);
1053 static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false,
1054 bool HasNSW = false);
1055 static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false,
1056 bool HasNSW = false);
1057 static Constant *getXor(Constant *C1, Constant *C2);
1058 static Constant *getShl(Constant *C1, Constant *C2, bool HasNUW = false,
1059 bool HasNSW = false);
1060 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1061 static Constant *getPtrToInt(Constant *C, Type *Ty,
1062 bool OnlyIfReduced = false);
1063 static Constant *getIntToPtr(Constant *C, Type *Ty,
1064 bool OnlyIfReduced = false);
1065 static Constant *getBitCast(Constant *C, Type *Ty,
1066 bool OnlyIfReduced = false);
1067 static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
1068 bool OnlyIfReduced = false);
1069
1070 static Constant *getNSWNeg(Constant *C) { return getNeg(C, /*HasNSW=*/HasNSW: true); }
1071
1072 static Constant *getNSWAdd(Constant *C1, Constant *C2) {
1073 return getAdd(C1, C2, HasNUW: false, HasNSW: true);
1074 }
1075
1076 static Constant *getNUWAdd(Constant *C1, Constant *C2) {
1077 return getAdd(C1, C2, HasNUW: true, HasNSW: false);
1078 }
1079
1080 static Constant *getNSWSub(Constant *C1, Constant *C2) {
1081 return getSub(C1, C2, HasNUW: false, HasNSW: true);
1082 }
1083
1084 static Constant *getNUWSub(Constant *C1, Constant *C2) {
1085 return getSub(C1, C2, HasNUW: true, HasNSW: false);
1086 }
1087
1088 static Constant *getNSWMul(Constant *C1, Constant *C2) {
1089 return getMul(C1, C2, HasNUW: false, HasNSW: true);
1090 }
1091
1092 static Constant *getNUWMul(Constant *C1, Constant *C2) {
1093 return getMul(C1, C2, HasNUW: true, HasNSW: false);
1094 }
1095
1096 static Constant *getNSWShl(Constant *C1, Constant *C2) {
1097 return getShl(C1, C2, HasNUW: false, HasNSW: true);
1098 }
1099
1100 static Constant *getNUWShl(Constant *C1, Constant *C2) {
1101 return getShl(C1, C2, HasNUW: true, HasNSW: false);
1102 }
1103
1104 /// If C is a scalar/fixed width vector of known powers of 2, then this
1105 /// function returns a new scalar/fixed width vector obtained from logBase2
1106 /// of C. Undef vector elements are set to zero.
1107 /// Return a null pointer otherwise.
1108 static Constant *getExactLogBase2(Constant *C);
1109
1110 /// Return the identity constant for a binary opcode.
1111 /// If the binop is not commutative, callers can acquire the operand 1
1112 /// identity constant by setting AllowRHSConstant to true. For example, any
1113 /// shift has a zero identity constant for operand 1: X shift 0 = X. If this
1114 /// is a fadd/fsub operation and we don't care about signed zeros, then
1115 /// setting NSZ to true returns the identity +0.0 instead of -0.0. Return
1116 /// nullptr if the operator does not have an identity constant.
1117 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty,
1118 bool AllowRHSConstant = false,
1119 bool NSZ = false);
1120
1121 static Constant *getIntrinsicIdentity(Intrinsic::ID, Type *Ty);
1122
1123 /// Return the identity constant for a binary or intrinsic Instruction.
1124 /// The identity constant C is defined as X op C = X and C op X = X where C
1125 /// and X are the first two operands, and the operation is commutative.
1126 static Constant *getIdentity(Instruction *I, Type *Ty,
1127 bool AllowRHSConstant = false, bool NSZ = false);
1128
1129 /// Return the absorbing element for the given binary
1130 /// operation, i.e. a constant C such that X op C = C and C op X = C for
1131 /// every X. For example, this returns zero for integer multiplication.
1132 /// It returns null if the operator doesn't have an absorbing element.
1133 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
1134
1135 /// Transparently provide more efficient getOperand methods.
1136 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
1137
1138 /// Convenience function for getting a Cast operation.
1139 ///
1140 /// \param ops The opcode for the conversion
1141 /// \param C The constant to be converted
1142 /// \param Ty The type to which the constant is converted
1143 /// \param OnlyIfReduced see \a getWithOperands() docs.
1144 static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
1145 bool OnlyIfReduced = false);
1146
1147 // Create a Trunc or BitCast cast constant expression
1148 static Constant *
1149 getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast
1150 Type *Ty ///< The type to trunc or bitcast C to
1151 );
1152
1153 /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
1154 /// expression.
1155 static Constant *
1156 getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0)
1157 Type *Ty ///< The type to which cast should be made
1158 );
1159
1160 /// Create a BitCast or AddrSpaceCast for a pointer type depending on
1161 /// the address space.
1162 static Constant *getPointerBitCastOrAddrSpaceCast(
1163 Constant *C, ///< The constant to addrspacecast or bitcast
1164 Type *Ty ///< The type to bitcast or addrspacecast C to
1165 );
1166
1167 /// Return true if this is a convert constant expression
1168 bool isCast() const;
1169
1170 /// Return true if this is a compare constant expression
1171 bool isCompare() const;
1172
1173 /// get - Return a binary or shift operator constant expression,
1174 /// folding if possible.
1175 ///
1176 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1177 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1178 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
1179
1180 /// Return an ICmp or FCmp comparison operator constant expression.
1181 ///
1182 /// \param OnlyIfReduced see \a getWithOperands() docs.
1183 static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
1184 bool OnlyIfReduced = false);
1185
1186 /// get* - Return some common constants without having to
1187 /// specify the full Instruction::OPCODE identifier.
1188 ///
1189 static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
1190 bool OnlyIfReduced = false);
1191 static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
1192 bool OnlyIfReduced = false);
1193
1194 /// Getelementptr form. Value* is only accepted for convenience;
1195 /// all elements must be Constants.
1196 ///
1197 /// \param InRange the inrange range if present or std::nullopt.
1198 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1199 static Constant *
1200 getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Constant *> IdxList,
1201 bool InBounds = false,
1202 std::optional<ConstantRange> InRange = std::nullopt,
1203 Type *OnlyIfReducedTy = nullptr) {
1204 return getGetElementPtr(
1205 Ty, C, IdxList: ArrayRef((Value *const *)IdxList.data(), IdxList.size()),
1206 InBounds, InRange, OnlyIfReducedTy);
1207 }
1208 static Constant *
1209 getGetElementPtr(Type *Ty, Constant *C, Constant *Idx, bool InBounds = false,
1210 std::optional<ConstantRange> InRange = std::nullopt,
1211 Type *OnlyIfReducedTy = nullptr) {
1212 // This form of the function only exists to avoid ambiguous overload
1213 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1214 // ArrayRef<Value *>.
1215 return getGetElementPtr(Ty, C, IdxList: cast<Value>(Val: Idx), InBounds, InRange,
1216 OnlyIfReducedTy);
1217 }
1218 static Constant *
1219 getGetElementPtr(Type *Ty, Constant *C, ArrayRef<Value *> IdxList,
1220 bool InBounds = false,
1221 std::optional<ConstantRange> InRange = std::nullopt,
1222 Type *OnlyIfReducedTy = nullptr);
1223
1224 /// Create an "inbounds" getelementptr. See the documentation for the
1225 /// "inbounds" flag in LangRef.html for details.
1226 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1227 ArrayRef<Constant *> IdxList) {
1228 return getGetElementPtr(Ty, C, IdxList, InBounds: true);
1229 }
1230 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1231 Constant *Idx) {
1232 // This form of the function only exists to avoid ambiguous overload
1233 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1234 // ArrayRef<Value *>.
1235 return getGetElementPtr(Ty, C, Idx, InBounds: true);
1236 }
1237 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1238 ArrayRef<Value *> IdxList) {
1239 return getGetElementPtr(Ty, C, IdxList, InBounds: true);
1240 }
1241
1242 static Constant *getExtractElement(Constant *Vec, Constant *Idx,
1243 Type *OnlyIfReducedTy = nullptr);
1244 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
1245 Type *OnlyIfReducedTy = nullptr);
1246 static Constant *getShuffleVector(Constant *V1, Constant *V2,
1247 ArrayRef<int> Mask,
1248 Type *OnlyIfReducedTy = nullptr);
1249
1250 /// Return the opcode at the root of this constant expression
1251 unsigned getOpcode() const { return getSubclassDataFromValue(); }
1252
1253 /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
1254 /// FCMP constant expression.
1255 unsigned getPredicate() const;
1256
1257 /// Assert that this is a shufflevector and return the mask. See class
1258 /// ShuffleVectorInst for a description of the mask representation.
1259 ArrayRef<int> getShuffleMask() const;
1260
1261 /// Assert that this is a shufflevector and return the mask.
1262 ///
1263 /// TODO: This is a temporary hack until we update the bitcode format for
1264 /// shufflevector.
1265 Constant *getShuffleMaskForBitcode() const;
1266
1267 /// Return a string representation for an opcode.
1268 const char *getOpcodeName() const;
1269
1270 /// This returns the current constant expression with the operands replaced
1271 /// with the specified values. The specified array must have the same number
1272 /// of operands as our current one.
1273 Constant *getWithOperands(ArrayRef<Constant *> Ops) const {
1274 return getWithOperands(Ops, Ty: getType());
1275 }
1276
1277 /// Get the current expression with the operands replaced.
1278 ///
1279 /// Return the current constant expression with the operands replaced with \c
1280 /// Ops and the type with \c Ty. The new operands must have the same number
1281 /// as the current ones.
1282 ///
1283 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
1284 /// gets constant-folded, the type changes, or the expression is otherwise
1285 /// canonicalized. This parameter should almost always be \c false.
1286 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1287 bool OnlyIfReduced = false,
1288 Type *SrcTy = nullptr) const;
1289
1290 /// Returns an Instruction which implements the same operation as this
1291 /// ConstantExpr. It is not inserted into any basic block.
1292 ///
1293 /// A better approach to this could be to have a constructor for Instruction
1294 /// which would take a ConstantExpr parameter, but that would have spread
1295 /// implementation details of ConstantExpr outside of Constants.cpp, which
1296 /// would make it harder to remove ConstantExprs altogether.
1297 Instruction *getAsInstruction() const;
1298
1299 /// Whether creating a constant expression for this binary operator is
1300 /// desirable.
1301 static bool isDesirableBinOp(unsigned Opcode);
1302
1303 /// Whether creating a constant expression for this binary operator is
1304 /// supported.
1305 static bool isSupportedBinOp(unsigned Opcode);
1306
1307 /// Whether creating a constant expression for this cast is desirable.
1308 static bool isDesirableCastOp(unsigned Opcode);
1309
1310 /// Whether creating a constant expression for this cast is supported.
1311 static bool isSupportedCastOp(unsigned Opcode);
1312
1313 /// Whether creating a constant expression for this getelementptr type is
1314 /// supported.
1315 static bool isSupportedGetElementPtr(const Type *SrcElemTy) {
1316 return !SrcElemTy->isScalableTy();
1317 }
1318
1319 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1320 static bool classof(const Value *V) {
1321 return V->getValueID() == ConstantExprVal;
1322 }
1323
1324private:
1325 // Shadow Value::setValueSubclassData with a private forwarding method so that
1326 // subclasses cannot accidentally use it.
1327 void setValueSubclassData(unsigned short D) {
1328 Value::setValueSubclassData(D);
1329 }
1330};
1331
1332template <>
1333struct OperandTraits<ConstantExpr>
1334 : public VariadicOperandTraits<ConstantExpr, 1> {};
1335
1336DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)
1337
1338//===----------------------------------------------------------------------===//
1339/// 'undef' values are things that do not have specified contents.
1340/// These are used for a variety of purposes, including global variable
1341/// initializers and operands to instructions. 'undef' values can occur with
1342/// any first-class type.
1343///
1344/// Undef values aren't exactly constants; if they have multiple uses, they
1345/// can appear to have different bit patterns at each use. See
1346/// LangRef.html#undefvalues for details.
1347///
1348class UndefValue : public ConstantData {
1349 friend class Constant;
1350
1351 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
1352
1353 void destroyConstantImpl();
1354
1355protected:
1356 explicit UndefValue(Type *T, ValueTy vty) : ConstantData(T, vty) {}
1357
1358public:
1359 UndefValue(const UndefValue &) = delete;
1360
1361 /// Static factory methods - Return an 'undef' object of the specified type.
1362 static UndefValue *get(Type *T);
1363
1364 /// If this Undef has array or vector type, return a undef with the right
1365 /// element type.
1366 UndefValue *getSequentialElement() const;
1367
1368 /// If this undef has struct type, return a undef with the right element type
1369 /// for the specified element.
1370 UndefValue *getStructElement(unsigned Elt) const;
1371
1372 /// Return an undef of the right value for the specified GEP index if we can,
1373 /// otherwise return null (e.g. if C is a ConstantExpr).
1374 UndefValue *getElementValue(Constant *C) const;
1375
1376 /// Return an undef of the right value for the specified GEP index.
1377 UndefValue *getElementValue(unsigned Idx) const;
1378
1379 /// Return the number of elements in the array, vector, or struct.
1380 unsigned getNumElements() const;
1381
1382 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1383 static bool classof(const Value *V) {
1384 return V->getValueID() == UndefValueVal ||
1385 V->getValueID() == PoisonValueVal;
1386 }
1387};
1388
1389//===----------------------------------------------------------------------===//
1390/// In order to facilitate speculative execution, many instructions do not
1391/// invoke immediate undefined behavior when provided with illegal operands,
1392/// and return a poison value instead.
1393///
1394/// see LangRef.html#poisonvalues for details.
1395///
1396class PoisonValue final : public UndefValue {
1397 friend class Constant;
1398
1399 explicit PoisonValue(Type *T) : UndefValue(T, PoisonValueVal) {}
1400
1401 void destroyConstantImpl();
1402
1403public:
1404 PoisonValue(const PoisonValue &) = delete;
1405
1406 /// Static factory methods - Return an 'poison' object of the specified type.
1407 static PoisonValue *get(Type *T);
1408
1409 /// If this poison has array or vector type, return a poison with the right
1410 /// element type.
1411 PoisonValue *getSequentialElement() const;
1412
1413 /// If this poison has struct type, return a poison with the right element
1414 /// type for the specified element.
1415 PoisonValue *getStructElement(unsigned Elt) const;
1416
1417 /// Return an poison of the right value for the specified GEP index if we can,
1418 /// otherwise return null (e.g. if C is a ConstantExpr).
1419 PoisonValue *getElementValue(Constant *C) const;
1420
1421 /// Return an poison of the right value for the specified GEP index.
1422 PoisonValue *getElementValue(unsigned Idx) const;
1423
1424 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1425 static bool classof(const Value *V) {
1426 return V->getValueID() == PoisonValueVal;
1427 }
1428};
1429
1430} // end namespace llvm
1431
1432#endif // LLVM_IR_CONSTANTS_H
1433

source code of llvm/include/llvm/IR/Constants.h