1 //===- llvm/Type.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 declaration of the Type class.  For more "Type"
10 // stuff, look in DerivedTypes.h.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_TYPE_H
15 #define LLVM_IR_TYPE_H
16 
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/TypeSize.h"
25 #include <cassert>
26 #include <cstdint>
27 #include <iterator>
28 
29 namespace llvm {
30 
31 class IntegerType;
32 class LLVMContext;
33 class PointerType;
34 class raw_ostream;
35 class StringRef;
36 
37 /// The instances of the Type class are immutable: once they are created,
38 /// they are never changed.  Also note that only one instance of a particular
39 /// type is ever created.  Thus seeing if two types are equal is a matter of
40 /// doing a trivial pointer comparison. To enforce that no two equal instances
41 /// are created, Type instances can only be created via static factory methods
42 /// in class Type and in derived classes.  Once allocated, Types are never
43 /// free'd.
44 ///
45 class Type {
46 public:
47   //===--------------------------------------------------------------------===//
48   /// Definitions of all of the base types for the Type system.  Based on this
49   /// value, you can cast to a class defined in DerivedTypes.h.
50   /// Note: If you add an element to this, you need to add an element to the
51   /// Type::getPrimitiveType function, or else things will break!
52   /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
53   ///
54   enum TypeID {
55     // PrimitiveTypes
56     HalfTyID = 0,  ///< 16-bit floating point type
57     BFloatTyID,    ///< 16-bit floating point type (7-bit significand)
58     FloatTyID,     ///< 32-bit floating point type
59     DoubleTyID,    ///< 64-bit floating point type
60     X86_FP80TyID,  ///< 80-bit floating point type (X87)
61     FP128TyID,     ///< 128-bit floating point type (112-bit significand)
62     PPC_FP128TyID, ///< 128-bit floating point type (two 64-bits, PowerPC)
63     VoidTyID,      ///< type with no size
64     LabelTyID,     ///< Labels
65     MetadataTyID,  ///< Metadata
66     X86_MMXTyID,   ///< MMX vectors (64 bits, X86 specific)
67     X86_AMXTyID,   ///< AMX vectors (8192 bits, X86 specific)
68     TokenTyID,     ///< Tokens
69 
70     // Derived types... see DerivedTypes.h file.
71     IntegerTyID,       ///< Arbitrary bit width integers
72     FunctionTyID,      ///< Functions
73     PointerTyID,       ///< Pointers
74     StructTyID,        ///< Structures
75     ArrayTyID,         ///< Arrays
76     FixedVectorTyID,   ///< Fixed width SIMD vector type
77     ScalableVectorTyID ///< Scalable SIMD vector type
78   };
79 
80 private:
81   /// This refers to the LLVMContext in which this type was uniqued.
82   LLVMContext &Context;
83 
84   TypeID   ID : 8;            // The current base type of this type.
85   unsigned SubclassData : 24; // Space for subclasses to store data.
86                               // Note that this should be synchronized with
87                               // MAX_INT_BITS value in IntegerType class.
88 
89 protected:
90   friend class LLVMContextImpl;
91 
Type(LLVMContext & C,TypeID tid)92   explicit Type(LLVMContext &C, TypeID tid)
93     : Context(C), ID(tid), SubclassData(0) {}
94   ~Type() = default;
95 
getSubclassData()96   unsigned getSubclassData() const { return SubclassData; }
97 
setSubclassData(unsigned val)98   void setSubclassData(unsigned val) {
99     SubclassData = val;
100     // Ensure we don't have any accidental truncation.
101     assert(getSubclassData() == val && "Subclass data too large for field");
102   }
103 
104   /// Keeps track of how many Type*'s there are in the ContainedTys list.
105   unsigned NumContainedTys = 0;
106 
107   /// A pointer to the array of Types contained by this Type. For example, this
108   /// includes the arguments of a function type, the elements of a structure,
109   /// the pointee of a pointer, the element type of an array, etc. This pointer
110   /// may be 0 for types that don't contain other types (Integer, Double,
111   /// Float).
112   Type * const *ContainedTys = nullptr;
113 
114 public:
115   /// Print the current type.
116   /// Omit the type details if \p NoDetails == true.
117   /// E.g., let %st = type { i32, i16 }
118   /// When \p NoDetails is true, we only print %st.
119   /// Put differently, \p NoDetails prints the type as if
120   /// inlined with the operands when printing an instruction.
121   void print(raw_ostream &O, bool IsForDebug = false,
122              bool NoDetails = false) const;
123 
124   void dump() const;
125 
126   /// Return the LLVMContext in which this type was uniqued.
getContext()127   LLVMContext &getContext() const { return Context; }
128 
129   //===--------------------------------------------------------------------===//
130   // Accessors for working with types.
131   //
132 
133   /// Return the type id for the type. This will return one of the TypeID enum
134   /// elements defined above.
getTypeID()135   TypeID getTypeID() const { return ID; }
136 
137   /// Return true if this is 'void'.
isVoidTy()138   bool isVoidTy() const { return getTypeID() == VoidTyID; }
139 
140   /// Return true if this is 'half', a 16-bit IEEE fp type.
isHalfTy()141   bool isHalfTy() const { return getTypeID() == HalfTyID; }
142 
143   /// Return true if this is 'bfloat', a 16-bit bfloat type.
isBFloatTy()144   bool isBFloatTy() const { return getTypeID() == BFloatTyID; }
145 
146   /// Return true if this is 'float', a 32-bit IEEE fp type.
isFloatTy()147   bool isFloatTy() const { return getTypeID() == FloatTyID; }
148 
149   /// Return true if this is 'double', a 64-bit IEEE fp type.
isDoubleTy()150   bool isDoubleTy() const { return getTypeID() == DoubleTyID; }
151 
152   /// Return true if this is x86 long double.
isX86_FP80Ty()153   bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; }
154 
155   /// Return true if this is 'fp128'.
isFP128Ty()156   bool isFP128Ty() const { return getTypeID() == FP128TyID; }
157 
158   /// Return true if this is powerpc long double.
isPPC_FP128Ty()159   bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; }
160 
161   /// Return true if this is one of the six floating-point types
isFloatingPointTy()162   bool isFloatingPointTy() const {
163     return getTypeID() == HalfTyID || getTypeID() == BFloatTyID ||
164            getTypeID() == FloatTyID || getTypeID() == DoubleTyID ||
165            getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID ||
166            getTypeID() == PPC_FP128TyID;
167   }
168 
getFltSemantics()169   const fltSemantics &getFltSemantics() const {
170     switch (getTypeID()) {
171     case HalfTyID: return APFloat::IEEEhalf();
172     case BFloatTyID: return APFloat::BFloat();
173     case FloatTyID: return APFloat::IEEEsingle();
174     case DoubleTyID: return APFloat::IEEEdouble();
175     case X86_FP80TyID: return APFloat::x87DoubleExtended();
176     case FP128TyID: return APFloat::IEEEquad();
177     case PPC_FP128TyID: return APFloat::PPCDoubleDouble();
178     default: llvm_unreachable("Invalid floating type");
179     }
180   }
181 
182   /// Return true if this is X86 MMX.
isX86_MMXTy()183   bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; }
184 
185   /// Return true if this is X86 AMX.
isX86_AMXTy()186   bool isX86_AMXTy() const { return getTypeID() == X86_AMXTyID; }
187 
188   /// Return true if this is a FP type or a vector of FP.
isFPOrFPVectorTy()189   bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); }
190 
191   /// Return true if this is 'label'.
isLabelTy()192   bool isLabelTy() const { return getTypeID() == LabelTyID; }
193 
194   /// Return true if this is 'metadata'.
isMetadataTy()195   bool isMetadataTy() const { return getTypeID() == MetadataTyID; }
196 
197   /// Return true if this is 'token'.
isTokenTy()198   bool isTokenTy() const { return getTypeID() == TokenTyID; }
199 
200   /// True if this is an instance of IntegerType.
isIntegerTy()201   bool isIntegerTy() const { return getTypeID() == IntegerTyID; }
202 
203   /// Return true if this is an IntegerType of the given width.
204   bool isIntegerTy(unsigned Bitwidth) const;
205 
206   /// Return true if this is an integer type or a vector of integer types.
isIntOrIntVectorTy()207   bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); }
208 
209   /// Return true if this is an integer type or a vector of integer types of
210   /// the given width.
isIntOrIntVectorTy(unsigned BitWidth)211   bool isIntOrIntVectorTy(unsigned BitWidth) const {
212     return getScalarType()->isIntegerTy(BitWidth);
213   }
214 
215   /// Return true if this is an integer type or a pointer type.
isIntOrPtrTy()216   bool isIntOrPtrTy() const { return isIntegerTy() || isPointerTy(); }
217 
218   /// True if this is an instance of FunctionType.
isFunctionTy()219   bool isFunctionTy() const { return getTypeID() == FunctionTyID; }
220 
221   /// True if this is an instance of StructType.
isStructTy()222   bool isStructTy() const { return getTypeID() == StructTyID; }
223 
224   /// True if this is an instance of ArrayType.
isArrayTy()225   bool isArrayTy() const { return getTypeID() == ArrayTyID; }
226 
227   /// True if this is an instance of PointerType.
isPointerTy()228   bool isPointerTy() const { return getTypeID() == PointerTyID; }
229 
230   /// True if this is an instance of an opaque PointerType.
231   bool isOpaquePointerTy() const;
232 
233   /// Return true if this is a pointer type or a vector of pointer types.
isPtrOrPtrVectorTy()234   bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); }
235 
236   /// True if this is an instance of VectorType.
isVectorTy()237   inline bool isVectorTy() const {
238     return getTypeID() == ScalableVectorTyID || getTypeID() == FixedVectorTyID;
239   }
240 
241   /// Return true if this type could be converted with a lossless BitCast to
242   /// type 'Ty'. For example, i8* to i32*. BitCasts are valid for types of the
243   /// same size only where no re-interpretation of the bits is done.
244   /// Determine if this type could be losslessly bitcast to Ty
245   bool canLosslesslyBitCastTo(Type *Ty) const;
246 
247   /// Return true if this type is empty, that is, it has no elements or all of
248   /// its elements are empty.
249   bool isEmptyTy() const;
250 
251   /// Return true if the type is "first class", meaning it is a valid type for a
252   /// Value.
isFirstClassType()253   bool isFirstClassType() const {
254     return getTypeID() != FunctionTyID && getTypeID() != VoidTyID;
255   }
256 
257   /// Return true if the type is a valid type for a register in codegen. This
258   /// includes all first-class types except struct and array types.
isSingleValueType()259   bool isSingleValueType() const {
260     return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() ||
261            isPointerTy() || isVectorTy() || isX86_AMXTy();
262   }
263 
264   /// Return true if the type is an aggregate type. This means it is valid as
265   /// the first operand of an insertvalue or extractvalue instruction. This
266   /// includes struct and array types, but does not include vector types.
isAggregateType()267   bool isAggregateType() const {
268     return getTypeID() == StructTyID || getTypeID() == ArrayTyID;
269   }
270 
271   /// Return true if it makes sense to take the size of this type. To get the
272   /// actual size for a particular target, it is reasonable to use the
273   /// DataLayout subsystem to do this.
274   bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const {
275     // If it's a primitive, it is always sized.
276     if (getTypeID() == IntegerTyID || isFloatingPointTy() ||
277         getTypeID() == PointerTyID || getTypeID() == X86_MMXTyID ||
278         getTypeID() == X86_AMXTyID)
279       return true;
280     // If it is not something that can have a size (e.g. a function or label),
281     // it doesn't have a size.
282     if (getTypeID() != StructTyID && getTypeID() != ArrayTyID && !isVectorTy())
283       return false;
284     // Otherwise we have to try harder to decide.
285     return isSizedDerivedType(Visited);
286   }
287 
288   /// Return the basic size of this type if it is a primitive type. These are
289   /// fixed by LLVM and are not target-dependent.
290   /// This will return zero if the type does not have a size or is not a
291   /// primitive type.
292   ///
293   /// If this is a scalable vector type, the scalable property will be set and
294   /// the runtime size will be a positive integer multiple of the base size.
295   ///
296   /// Note that this may not reflect the size of memory allocated for an
297   /// instance of the type or the number of bytes that are written when an
298   /// instance of the type is stored to memory. The DataLayout class provides
299   /// additional query functions to provide this information.
300   ///
301   TypeSize getPrimitiveSizeInBits() const LLVM_READONLY;
302 
303   /// If this is a vector type, return the getPrimitiveSizeInBits value for the
304   /// element type. Otherwise return the getPrimitiveSizeInBits value for this
305   /// type.
306   unsigned getScalarSizeInBits() const LLVM_READONLY;
307 
308   /// Return the width of the mantissa of this type. This is only valid on
309   /// floating-point types. If the FP type does not have a stable mantissa (e.g.
310   /// ppc long double), this method returns -1.
311   int getFPMantissaWidth() const;
312 
313   /// Return whether the type is IEEE compatible, as defined by the eponymous
314   /// method in APFloat.
isIEEE()315   bool isIEEE() const { return APFloat::getZero(getFltSemantics()).isIEEE(); }
316 
317   /// If this is a vector type, return the element type, otherwise return
318   /// 'this'.
getScalarType()319   inline Type *getScalarType() const {
320     if (isVectorTy())
321       return getContainedType(0);
322     return const_cast<Type *>(this);
323   }
324 
325   //===--------------------------------------------------------------------===//
326   // Type Iteration support.
327   //
328   using subtype_iterator = Type * const *;
329 
subtype_begin()330   subtype_iterator subtype_begin() const { return ContainedTys; }
subtype_end()331   subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
subtypes()332   ArrayRef<Type*> subtypes() const {
333     return makeArrayRef(subtype_begin(), subtype_end());
334   }
335 
336   using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>;
337 
subtype_rbegin()338   subtype_reverse_iterator subtype_rbegin() const {
339     return subtype_reverse_iterator(subtype_end());
340   }
subtype_rend()341   subtype_reverse_iterator subtype_rend() const {
342     return subtype_reverse_iterator(subtype_begin());
343   }
344 
345   /// This method is used to implement the type iterator (defined at the end of
346   /// the file). For derived types, this returns the types 'contained' in the
347   /// derived type.
getContainedType(unsigned i)348   Type *getContainedType(unsigned i) const {
349     assert(i < NumContainedTys && "Index out of range!");
350     return ContainedTys[i];
351   }
352 
353   /// Return the number of types in the derived type.
getNumContainedTypes()354   unsigned getNumContainedTypes() const { return NumContainedTys; }
355 
356   //===--------------------------------------------------------------------===//
357   // Helper methods corresponding to subclass methods.  This forces a cast to
358   // the specified subclass and calls its accessor.  "getArrayNumElements" (for
359   // example) is shorthand for cast<ArrayType>(Ty)->getNumElements().  This is
360   // only intended to cover the core methods that are frequently used, helper
361   // methods should not be added here.
362 
363   inline unsigned getIntegerBitWidth() const;
364 
365   inline Type *getFunctionParamType(unsigned i) const;
366   inline unsigned getFunctionNumParams() const;
367   inline bool isFunctionVarArg() const;
368 
369   inline StringRef getStructName() const;
370   inline unsigned getStructNumElements() const;
371   inline Type *getStructElementType(unsigned N) const;
372 
373   inline uint64_t getArrayNumElements() const;
374 
getArrayElementType()375   Type *getArrayElementType() const {
376     assert(getTypeID() == ArrayTyID);
377     return ContainedTys[0];
378   }
379 
getPointerElementType()380   Type *getPointerElementType() const {
381     assert(getTypeID() == PointerTyID);
382     return ContainedTys[0];
383   }
384 
385   /// Given vector type, change the element type,
386   /// whilst keeping the old number of elements.
387   /// For non-vectors simply returns \p EltTy.
388   inline Type *getWithNewType(Type *EltTy) const;
389 
390   /// Given an integer or vector type, change the lane bitwidth to NewBitwidth,
391   /// whilst keeping the old number of lanes.
392   inline Type *getWithNewBitWidth(unsigned NewBitWidth) const;
393 
394   /// Given scalar/vector integer type, returns a type with elements twice as
395   /// wide as in the original type. For vectors, preserves element count.
396   inline Type *getExtendedType() const;
397 
398   /// Get the address space of this pointer or pointer vector type.
399   inline unsigned getPointerAddressSpace() const;
400 
401   //===--------------------------------------------------------------------===//
402   // Static members exported by the Type class itself.  Useful for getting
403   // instances of Type.
404   //
405 
406   /// Return a type based on an identifier.
407   static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
408 
409   //===--------------------------------------------------------------------===//
410   // These are the builtin types that are always available.
411   //
412   static Type *getVoidTy(LLVMContext &C);
413   static Type *getLabelTy(LLVMContext &C);
414   static Type *getHalfTy(LLVMContext &C);
415   static Type *getBFloatTy(LLVMContext &C);
416   static Type *getFloatTy(LLVMContext &C);
417   static Type *getDoubleTy(LLVMContext &C);
418   static Type *getMetadataTy(LLVMContext &C);
419   static Type *getX86_FP80Ty(LLVMContext &C);
420   static Type *getFP128Ty(LLVMContext &C);
421   static Type *getPPC_FP128Ty(LLVMContext &C);
422   static Type *getX86_MMXTy(LLVMContext &C);
423   static Type *getX86_AMXTy(LLVMContext &C);
424   static Type *getTokenTy(LLVMContext &C);
425   static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
426   static IntegerType *getInt1Ty(LLVMContext &C);
427   static IntegerType *getInt8Ty(LLVMContext &C);
428   static IntegerType *getInt16Ty(LLVMContext &C);
429   static IntegerType *getInt32Ty(LLVMContext &C);
430   static IntegerType *getInt64Ty(LLVMContext &C);
431   static IntegerType *getInt128Ty(LLVMContext &C);
getScalarTy(LLVMContext & C)432   template <typename ScalarTy> static Type *getScalarTy(LLVMContext &C) {
433     int noOfBits = sizeof(ScalarTy) * CHAR_BIT;
434     if (std::is_integral<ScalarTy>::value) {
435       return (Type*) Type::getIntNTy(C, noOfBits);
436     } else if (std::is_floating_point<ScalarTy>::value) {
437       switch (noOfBits) {
438       case 32:
439         return Type::getFloatTy(C);
440       case 64:
441         return Type::getDoubleTy(C);
442       }
443     }
444     llvm_unreachable("Unsupported type in Type::getScalarTy");
445   }
getFloatingPointTy(LLVMContext & C,const fltSemantics & S)446   static Type *getFloatingPointTy(LLVMContext &C, const fltSemantics &S) {
447     Type *Ty;
448     if (&S == &APFloat::IEEEhalf())
449       Ty = Type::getHalfTy(C);
450     else if (&S == &APFloat::BFloat())
451       Ty = Type::getBFloatTy(C);
452     else if (&S == &APFloat::IEEEsingle())
453       Ty = Type::getFloatTy(C);
454     else if (&S == &APFloat::IEEEdouble())
455       Ty = Type::getDoubleTy(C);
456     else if (&S == &APFloat::x87DoubleExtended())
457       Ty = Type::getX86_FP80Ty(C);
458     else if (&S == &APFloat::IEEEquad())
459       Ty = Type::getFP128Ty(C);
460     else {
461       assert(&S == &APFloat::PPCDoubleDouble() && "Unknown FP format");
462       Ty = Type::getPPC_FP128Ty(C);
463     }
464     return Ty;
465   }
466 
467   //===--------------------------------------------------------------------===//
468   // Convenience methods for getting pointer types with one of the above builtin
469   // types as pointee.
470   //
471   static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0);
472   static PointerType *getBFloatPtrTy(LLVMContext &C, unsigned AS = 0);
473   static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
474   static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
475   static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
476   static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
477   static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
478   static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
479   static PointerType *getX86_AMXPtrTy(LLVMContext &C, unsigned AS = 0);
480   static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
481   static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
482   static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
483   static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
484   static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
485   static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
486 
487   /// Return a pointer to the current type. This is equivalent to
488   /// PointerType::get(Foo, AddrSpace).
489   /// TODO: Remove this after opaque pointer transition is complete.
490   PointerType *getPointerTo(unsigned AddrSpace = 0) const;
491 
492 private:
493   /// Derived types like structures and arrays are sized iff all of the members
494   /// of the type are sized as well. Since asking for their size is relatively
495   /// uncommon, move this operation out-of-line.
496   bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const;
497 };
498 
499 // Printing of types.
500 inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
501   T.print(OS);
502   return OS;
503 }
504 
505 // allow isa<PointerType>(x) to work without DerivedTypes.h included.
506 template <> struct isa_impl<PointerType, Type> {
507   static inline bool doit(const Type &Ty) {
508     return Ty.getTypeID() == Type::PointerTyID;
509   }
510 };
511 
512 // Create wrappers for C Binding types (see CBindingWrapping.h).
513 DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)
514 
515 /* Specialized opaque type conversions.
516  */
517 inline Type **unwrap(LLVMTypeRef* Tys) {
518   return reinterpret_cast<Type**>(Tys);
519 }
520 
521 inline LLVMTypeRef *wrap(Type **Tys) {
522   return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys));
523 }
524 
525 } // end namespace llvm
526 
527 #endif // LLVM_IR_TYPE_H
528