Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / DerivedTypes.h
blob5bf37294bb2ec837bbb350d185a75b4de95858e7
1 //===- llvm/DerivedTypes.h - Classes for handling data types ----*- 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 // This file contains the declarations of classes that represent "derived
10 // types". These are things like "arrays of x" or "structure of x, y, z" or
11 // "function returning x taking (y,z) as parameters", etc...
13 // The implementations of these classes live in the Type.cpp file.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_IR_DERIVEDTYPES_H
18 #define LLVM_IR_DERIVEDTYPES_H
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compiler.h"
26 #include <cassert>
27 #include <cstdint>
29 namespace llvm {
31 class Value;
32 class APInt;
33 class LLVMContext;
35 /// Class to represent integer types. Note that this class is also used to
36 /// represent the built-in integer types: Int1Ty, Int8Ty, Int16Ty, Int32Ty and
37 /// Int64Ty.
38 /// Integer representation type
39 class IntegerType : public Type {
40 friend class LLVMContextImpl;
42 protected:
43 explicit IntegerType(LLVMContext &C, unsigned NumBits) : Type(C, IntegerTyID){
44 setSubclassData(NumBits);
47 public:
48 /// This enum is just used to hold constants we need for IntegerType.
49 enum {
50 MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
51 MAX_INT_BITS = (1<<24)-1 ///< Maximum number of bits that can be specified
52 ///< Note that bit width is stored in the Type classes SubclassData field
53 ///< which has 24 bits. This yields a maximum bit width of 16,777,215
54 ///< bits.
57 /// This static method is the primary way of constructing an IntegerType.
58 /// If an IntegerType with the same NumBits value was previously instantiated,
59 /// that instance will be returned. Otherwise a new one will be created. Only
60 /// one instance with a given NumBits value is ever created.
61 /// Get or create an IntegerType instance.
62 static IntegerType *get(LLVMContext &C, unsigned NumBits);
64 /// Get the number of bits in this IntegerType
65 unsigned getBitWidth() const { return getSubclassData(); }
67 /// Return a bitmask with ones set for all of the bits that can be set by an
68 /// unsigned version of this type. This is 0xFF for i8, 0xFFFF for i16, etc.
69 uint64_t getBitMask() const {
70 return ~uint64_t(0UL) >> (64-getBitWidth());
73 /// Return a uint64_t with just the most significant bit set (the sign bit, if
74 /// the value is treated as a signed number).
75 uint64_t getSignBit() const {
76 return 1ULL << (getBitWidth()-1);
79 /// For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
80 /// @returns a bit mask with ones set for all the bits of this type.
81 /// Get a bit mask for this type.
82 APInt getMask() const;
84 /// This method determines if the width of this IntegerType is a power-of-2
85 /// in terms of 8 bit bytes.
86 /// @returns true if this is a power-of-2 byte width.
87 /// Is this a power-of-2 byte-width IntegerType ?
88 bool isPowerOf2ByteWidth() const;
90 /// Methods for support type inquiry through isa, cast, and dyn_cast.
91 static bool classof(const Type *T) {
92 return T->getTypeID() == IntegerTyID;
96 unsigned Type::getIntegerBitWidth() const {
97 return cast<IntegerType>(this)->getBitWidth();
100 /// Class to represent function types
102 class FunctionType : public Type {
103 FunctionType(Type *Result, ArrayRef<Type*> Params, bool IsVarArgs);
105 public:
106 FunctionType(const FunctionType &) = delete;
107 FunctionType &operator=(const FunctionType &) = delete;
109 /// This static method is the primary way of constructing a FunctionType.
110 static FunctionType *get(Type *Result,
111 ArrayRef<Type*> Params, bool isVarArg);
113 /// Create a FunctionType taking no parameters.
114 static FunctionType *get(Type *Result, bool isVarArg);
116 /// Return true if the specified type is valid as a return type.
117 static bool isValidReturnType(Type *RetTy);
119 /// Return true if the specified type is valid as an argument type.
120 static bool isValidArgumentType(Type *ArgTy);
122 bool isVarArg() const { return getSubclassData()!=0; }
123 Type *getReturnType() const { return ContainedTys[0]; }
125 using param_iterator = Type::subtype_iterator;
127 param_iterator param_begin() const { return ContainedTys + 1; }
128 param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
129 ArrayRef<Type *> params() const {
130 return makeArrayRef(param_begin(), param_end());
133 /// Parameter type accessors.
134 Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
136 /// Return the number of fixed parameters this function type requires.
137 /// This does not consider varargs.
138 unsigned getNumParams() const { return NumContainedTys - 1; }
140 /// Methods for support type inquiry through isa, cast, and dyn_cast.
141 static bool classof(const Type *T) {
142 return T->getTypeID() == FunctionTyID;
145 static_assert(alignof(FunctionType) >= alignof(Type *),
146 "Alignment sufficient for objects appended to FunctionType");
148 bool Type::isFunctionVarArg() const {
149 return cast<FunctionType>(this)->isVarArg();
152 Type *Type::getFunctionParamType(unsigned i) const {
153 return cast<FunctionType>(this)->getParamType(i);
156 unsigned Type::getFunctionNumParams() const {
157 return cast<FunctionType>(this)->getNumParams();
160 /// A handy container for a FunctionType+Callee-pointer pair, which can be
161 /// passed around as a single entity. This assists in replacing the use of
162 /// PointerType::getElementType() to access the function's type, since that's
163 /// slated for removal as part of the [opaque pointer types] project.
164 class FunctionCallee {
165 public:
166 // Allow implicit conversion from types which have a getFunctionType member
167 // (e.g. Function and InlineAsm).
168 template <typename T, typename U = decltype(&T::getFunctionType)>
169 FunctionCallee(T *Fn)
170 : FnTy(Fn ? Fn->getFunctionType() : nullptr), Callee(Fn) {}
172 FunctionCallee(FunctionType *FnTy, Value *Callee)
173 : FnTy(FnTy), Callee(Callee) {
174 assert((FnTy == nullptr) == (Callee == nullptr));
177 FunctionCallee(std::nullptr_t) {}
179 FunctionCallee() = default;
181 FunctionType *getFunctionType() { return FnTy; }
183 Value *getCallee() { return Callee; }
185 explicit operator bool() { return Callee; }
187 private:
188 FunctionType *FnTy = nullptr;
189 Value *Callee = nullptr;
192 /// Common super class of ArrayType, StructType and VectorType.
193 class CompositeType : public Type {
194 protected:
195 explicit CompositeType(LLVMContext &C, TypeID tid) : Type(C, tid) {}
197 public:
198 /// Given an index value into the type, return the type of the element.
199 Type *getTypeAtIndex(const Value *V) const;
200 Type *getTypeAtIndex(unsigned Idx) const;
201 bool indexValid(const Value *V) const;
202 bool indexValid(unsigned Idx) const;
204 /// Methods for support type inquiry through isa, cast, and dyn_cast.
205 static bool classof(const Type *T) {
206 return T->getTypeID() == ArrayTyID ||
207 T->getTypeID() == StructTyID ||
208 T->getTypeID() == VectorTyID;
212 /// Class to represent struct types. There are two different kinds of struct
213 /// types: Literal structs and Identified structs.
215 /// Literal struct types (e.g. { i32, i32 }) are uniqued structurally, and must
216 /// always have a body when created. You can get one of these by using one of
217 /// the StructType::get() forms.
219 /// Identified structs (e.g. %foo or %42) may optionally have a name and are not
220 /// uniqued. The names for identified structs are managed at the LLVMContext
221 /// level, so there can only be a single identified struct with a given name in
222 /// a particular LLVMContext. Identified structs may also optionally be opaque
223 /// (have no body specified). You get one of these by using one of the
224 /// StructType::create() forms.
226 /// Independent of what kind of struct you have, the body of a struct type are
227 /// laid out in memory consecutively with the elements directly one after the
228 /// other (if the struct is packed) or (if not packed) with padding between the
229 /// elements as defined by DataLayout (which is required to match what the code
230 /// generator for a target expects).
232 class StructType : public CompositeType {
233 StructType(LLVMContext &C) : CompositeType(C, StructTyID) {}
235 enum {
236 /// This is the contents of the SubClassData field.
237 SCDB_HasBody = 1,
238 SCDB_Packed = 2,
239 SCDB_IsLiteral = 4,
240 SCDB_IsSized = 8
243 /// For a named struct that actually has a name, this is a pointer to the
244 /// symbol table entry (maintained by LLVMContext) for the struct.
245 /// This is null if the type is an literal struct or if it is a identified
246 /// type that has an empty name.
247 void *SymbolTableEntry = nullptr;
249 public:
250 StructType(const StructType &) = delete;
251 StructType &operator=(const StructType &) = delete;
253 /// This creates an identified struct.
254 static StructType *create(LLVMContext &Context, StringRef Name);
255 static StructType *create(LLVMContext &Context);
257 static StructType *create(ArrayRef<Type *> Elements, StringRef Name,
258 bool isPacked = false);
259 static StructType *create(ArrayRef<Type *> Elements);
260 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements,
261 StringRef Name, bool isPacked = false);
262 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements);
263 template <class... Tys>
264 static typename std::enable_if<are_base_of<Type, Tys...>::value,
265 StructType *>::type
266 create(StringRef Name, Type *elt1, Tys *... elts) {
267 assert(elt1 && "Cannot create a struct type with no elements with this");
268 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
269 return create(StructFields, Name);
272 /// This static method is the primary way to create a literal StructType.
273 static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
274 bool isPacked = false);
276 /// Create an empty structure type.
277 static StructType *get(LLVMContext &Context, bool isPacked = false);
279 /// This static method is a convenience method for creating structure types by
280 /// specifying the elements as arguments. Note that this method always returns
281 /// a non-packed struct, and requires at least one element type.
282 template <class... Tys>
283 static typename std::enable_if<are_base_of<Type, Tys...>::value,
284 StructType *>::type
285 get(Type *elt1, Tys *... elts) {
286 assert(elt1 && "Cannot create a struct type with no elements with this");
287 LLVMContext &Ctx = elt1->getContext();
288 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
289 return llvm::StructType::get(Ctx, StructFields);
292 bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
294 /// Return true if this type is uniqued by structural equivalence, false if it
295 /// is a struct definition.
296 bool isLiteral() const { return (getSubclassData() & SCDB_IsLiteral) != 0; }
298 /// Return true if this is a type with an identity that has no body specified
299 /// yet. These prints as 'opaque' in .ll files.
300 bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
302 /// isSized - Return true if this is a sized type.
303 bool isSized(SmallPtrSetImpl<Type *> *Visited = nullptr) const;
305 /// Return true if this is a named struct that has a non-empty name.
306 bool hasName() const { return SymbolTableEntry != nullptr; }
308 /// Return the name for this struct type if it has an identity.
309 /// This may return an empty string for an unnamed struct type. Do not call
310 /// this on an literal type.
311 StringRef getName() const;
313 /// Change the name of this type to the specified name, or to a name with a
314 /// suffix if there is a collision. Do not call this on an literal type.
315 void setName(StringRef Name);
317 /// Specify a body for an opaque identified type.
318 void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
320 template <typename... Tys>
321 typename std::enable_if<are_base_of<Type, Tys...>::value, void>::type
322 setBody(Type *elt1, Tys *... elts) {
323 assert(elt1 && "Cannot create a struct type with no elements with this");
324 SmallVector<llvm::Type *, 8> StructFields({elt1, elts...});
325 setBody(StructFields);
328 /// Return true if the specified type is valid as a element type.
329 static bool isValidElementType(Type *ElemTy);
331 // Iterator access to the elements.
332 using element_iterator = Type::subtype_iterator;
334 element_iterator element_begin() const { return ContainedTys; }
335 element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
336 ArrayRef<Type *> const elements() const {
337 return makeArrayRef(element_begin(), element_end());
340 /// Return true if this is layout identical to the specified struct.
341 bool isLayoutIdentical(StructType *Other) const;
343 /// Random access to the elements
344 unsigned getNumElements() const { return NumContainedTys; }
345 Type *getElementType(unsigned N) const {
346 assert(N < NumContainedTys && "Element number out of range!");
347 return ContainedTys[N];
350 /// Methods for support type inquiry through isa, cast, and dyn_cast.
351 static bool classof(const Type *T) {
352 return T->getTypeID() == StructTyID;
356 StringRef Type::getStructName() const {
357 return cast<StructType>(this)->getName();
360 unsigned Type::getStructNumElements() const {
361 return cast<StructType>(this)->getNumElements();
364 Type *Type::getStructElementType(unsigned N) const {
365 return cast<StructType>(this)->getElementType(N);
368 /// This is the superclass of the array and vector type classes. Both of these
369 /// represent "arrays" in memory. The array type represents a specifically sized
370 /// array, and the vector type represents a specifically sized array that allows
371 /// for use of SIMD instructions. SequentialType holds the common features of
372 /// both, which stem from the fact that both lay their components out in memory
373 /// identically.
374 class SequentialType : public CompositeType {
375 Type *ContainedType; ///< Storage for the single contained type.
376 uint64_t NumElements;
378 protected:
379 SequentialType(TypeID TID, Type *ElType, uint64_t NumElements)
380 : CompositeType(ElType->getContext(), TID), ContainedType(ElType),
381 NumElements(NumElements) {
382 ContainedTys = &ContainedType;
383 NumContainedTys = 1;
386 public:
387 SequentialType(const SequentialType &) = delete;
388 SequentialType &operator=(const SequentialType &) = delete;
390 uint64_t getNumElements() const { return NumElements; }
391 Type *getElementType() const { return ContainedType; }
393 /// Methods for support type inquiry through isa, cast, and dyn_cast.
394 static bool classof(const Type *T) {
395 return T->getTypeID() == ArrayTyID || T->getTypeID() == VectorTyID;
399 /// Class to represent array types.
400 class ArrayType : public SequentialType {
401 ArrayType(Type *ElType, uint64_t NumEl);
403 public:
404 ArrayType(const ArrayType &) = delete;
405 ArrayType &operator=(const ArrayType &) = delete;
407 /// This static method is the primary way to construct an ArrayType
408 static ArrayType *get(Type *ElementType, uint64_t NumElements);
410 /// Return true if the specified type is valid as a element type.
411 static bool isValidElementType(Type *ElemTy);
413 /// Methods for support type inquiry through isa, cast, and dyn_cast.
414 static bool classof(const Type *T) {
415 return T->getTypeID() == ArrayTyID;
419 uint64_t Type::getArrayNumElements() const {
420 return cast<ArrayType>(this)->getNumElements();
423 /// Class to represent vector types.
424 class VectorType : public SequentialType {
425 VectorType(Type *ElType, unsigned NumEl);
427 public:
428 VectorType(const VectorType &) = delete;
429 VectorType &operator=(const VectorType &) = delete;
431 /// This static method is the primary way to construct an VectorType.
432 static VectorType *get(Type *ElementType, unsigned NumElements);
434 /// This static method gets a VectorType with the same number of elements as
435 /// the input type, and the element type is an integer type of the same width
436 /// as the input element type.
437 static VectorType *getInteger(VectorType *VTy) {
438 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
439 assert(EltBits && "Element size must be of a non-zero size");
440 Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
441 return VectorType::get(EltTy, VTy->getNumElements());
444 /// This static method is like getInteger except that the element types are
445 /// twice as wide as the elements in the input type.
446 static VectorType *getExtendedElementVectorType(VectorType *VTy) {
447 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
448 Type *EltTy = IntegerType::get(VTy->getContext(), EltBits * 2);
449 return VectorType::get(EltTy, VTy->getNumElements());
452 /// This static method is like getInteger except that the element types are
453 /// half as wide as the elements in the input type.
454 static VectorType *getTruncatedElementVectorType(VectorType *VTy) {
455 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
456 assert((EltBits & 1) == 0 &&
457 "Cannot truncate vector element with odd bit-width");
458 Type *EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
459 return VectorType::get(EltTy, VTy->getNumElements());
462 /// This static method returns a VectorType with half as many elements as the
463 /// input type and the same element type.
464 static VectorType *getHalfElementsVectorType(VectorType *VTy) {
465 unsigned NumElts = VTy->getNumElements();
466 assert ((NumElts & 1) == 0 &&
467 "Cannot halve vector with odd number of elements.");
468 return VectorType::get(VTy->getElementType(), NumElts/2);
471 /// This static method returns a VectorType with twice as many elements as the
472 /// input type and the same element type.
473 static VectorType *getDoubleElementsVectorType(VectorType *VTy) {
474 unsigned NumElts = VTy->getNumElements();
475 return VectorType::get(VTy->getElementType(), NumElts*2);
478 /// Return true if the specified type is valid as a element type.
479 static bool isValidElementType(Type *ElemTy);
481 /// Return the number of bits in the Vector type.
482 /// Returns zero when the vector is a vector of pointers.
483 unsigned getBitWidth() const {
484 return getNumElements() * getElementType()->getPrimitiveSizeInBits();
487 /// Methods for support type inquiry through isa, cast, and dyn_cast.
488 static bool classof(const Type *T) {
489 return T->getTypeID() == VectorTyID;
493 unsigned Type::getVectorNumElements() const {
494 return cast<VectorType>(this)->getNumElements();
497 /// Class to represent pointers.
498 class PointerType : public Type {
499 explicit PointerType(Type *ElType, unsigned AddrSpace);
501 Type *PointeeTy;
503 public:
504 PointerType(const PointerType &) = delete;
505 PointerType &operator=(const PointerType &) = delete;
507 /// This constructs a pointer to an object of the specified type in a numbered
508 /// address space.
509 static PointerType *get(Type *ElementType, unsigned AddressSpace);
511 /// This constructs a pointer to an object of the specified type in the
512 /// generic address space (address space zero).
513 static PointerType *getUnqual(Type *ElementType) {
514 return PointerType::get(ElementType, 0);
517 Type *getElementType() const { return PointeeTy; }
519 /// Return true if the specified type is valid as a element type.
520 static bool isValidElementType(Type *ElemTy);
522 /// Return true if we can load or store from a pointer to this type.
523 static bool isLoadableOrStorableType(Type *ElemTy);
525 /// Return the address space of the Pointer type.
526 inline unsigned getAddressSpace() const { return getSubclassData(); }
528 /// Implement support type inquiry through isa, cast, and dyn_cast.
529 static bool classof(const Type *T) {
530 return T->getTypeID() == PointerTyID;
534 unsigned Type::getPointerAddressSpace() const {
535 return cast<PointerType>(getScalarType())->getAddressSpace();
538 } // end namespace llvm
540 #endif // LLVM_IR_DERIVEDTYPES_H