1 //===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the Type class. For more "Type"
11 // stuff, look in DerivedTypes.h.
13 //===----------------------------------------------------------------------===//
18 #include "llvm/AbstractTypeUser.h"
19 #include "llvm/Support/Casting.h"
32 template<class GraphType> struct GraphTraits;
34 /// The instances of the Type class are immutable: once they are created,
35 /// they are never changed. Also note that only one instance of a particular
36 /// type is ever created. Thus seeing if two types are equal is a matter of
37 /// doing a trivial pointer comparison. To enforce that no two equal instances
38 /// are created, Type instances can only be created via static factory methods
39 /// in class Type and in derived classes.
41 /// Once allocated, Types are never free'd, unless they are an abstract type
42 /// that is resolved to a more concrete type.
44 /// Types themself don't have a name, and can be named either by:
45 /// - using SymbolTable instance, typically from some Module,
46 /// - using convenience methods in the Module class (which uses module's
49 /// Opaque types are simple derived types with no state. There may be many
50 /// different Opaque type objects floating around, but two are only considered
51 /// identical if they are pointer equals of each other. This allows us to have
52 /// two opaque types that end up resolving to different concrete types later.
54 /// Opaque types are also kinda weird and scary and different because they have
55 /// to keep a list of uses of the type. When, through linking, parsing, or
56 /// bitcode reading, they become resolved, they need to find and update all
57 /// users of the unknown type, causing them to reference a new, more concrete
58 /// type. Opaque types are deleted when their use list dwindles to zero users.
60 /// @brief Root of type hierarchy
61 class Type : public AbstractTypeUser {
63 //===--------------------------------------------------------------------===//
64 /// Definitions of all of the base types for the Type system. Based on this
65 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
66 /// Note: If you add an element to this, you need to add an element to the
67 /// Type::getPrimitiveType function, or else things will break!
68 /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
71 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
72 VoidTyID = 0, ///< 0: type with no size
73 FloatTyID, ///< 1: 32-bit floating point type
74 DoubleTyID, ///< 2: 64-bit floating point type
75 X86_FP80TyID, ///< 3: 80-bit floating point type (X87)
76 FP128TyID, ///< 4: 128-bit floating point type (112-bit mantissa)
77 PPC_FP128TyID, ///< 5: 128-bit floating point type (two 64-bits, PowerPC)
78 LabelTyID, ///< 6: Labels
79 MetadataTyID, ///< 7: Metadata
80 X86_MMXTyID, ///< 8: MMX vectors (64 bits, X86 specific)
82 // Derived types... see DerivedTypes.h file.
83 // Make sure FirstDerivedTyID stays up to date!
84 IntegerTyID, ///< 9: Arbitrary bit width integers
85 FunctionTyID, ///< 10: Functions
86 StructTyID, ///< 11: Structures
87 ArrayTyID, ///< 12: Arrays
88 PointerTyID, ///< 13: Pointers
89 OpaqueTyID, ///< 14: Opaque: type with unknown structure
90 VectorTyID, ///< 15: SIMD 'packed' format, or other vector type
92 NumTypeIDs, // Must remain as last defined ID
93 LastPrimitiveTyID = X86_MMXTyID,
94 FirstDerivedTyID = IntegerTyID
98 TypeID ID : 8; // The current base type of this type.
99 bool Abstract : 1; // True if type contains an OpaqueType
100 unsigned SubclassData : 23; //Space for subclasses to store data
102 /// RefCount - This counts the number of PATypeHolders that are pointing to
103 /// this type. When this number falls to zero, if the type is abstract and
104 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
107 mutable unsigned RefCount;
109 /// Context - This refers to the LLVMContext in which this type was uniqued.
110 LLVMContext &Context;
111 friend class LLVMContextImpl;
113 const Type *getForwardedTypeInternal() const;
115 // When the last reference to a forwarded type is removed, it is destroyed.
116 void destroy() const;
119 explicit Type(LLVMContext &C, TypeID id) :
120 ID(id), Abstract(false), SubclassData(0),
121 RefCount(0), Context(C),
122 ForwardType(0), NumContainedTys(0),
125 assert(AbstractTypeUsers.empty() && "Abstract types remain");
128 /// Types can become nonabstract later, if they are refined.
130 inline void setAbstract(bool Val) { Abstract = Val; }
132 unsigned getRefCount() const { return RefCount; }
134 unsigned getSubclassData() const { return SubclassData; }
135 void setSubclassData(unsigned val) { SubclassData = val; }
137 /// ForwardType - This field is used to implement the union find scheme for
138 /// abstract types. When types are refined to other types, this field is set
139 /// to the more refined type. Only abstract types can be forwarded.
140 mutable const Type *ForwardType;
143 /// AbstractTypeUsers - Implement a list of the users that need to be notified
144 /// if I am a type, and I get resolved into a more concrete type.
146 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
148 /// NumContainedTys - Keeps track of how many PATypeHandle instances there
149 /// are at the end of this type instance for the list of contained types. It
150 /// is the subclasses responsibility to set this up. Set to 0 if there are no
151 /// contained types in this type.
152 unsigned NumContainedTys;
154 /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained
155 /// by this Type. For example, this includes the arguments of a function
156 /// type, the elements of a structure, the pointee of a pointer, the element
157 /// type of an array, etc. This pointer may be 0 for types that don't
158 /// contain other types (Integer, Double, Float). In general, the subclass
159 /// should arrange for space for the PATypeHandles to be included in the
160 /// allocation of the type object and set this pointer to the address of the
161 /// first element. This allows the Type class to manipulate the ContainedTys
162 /// without understanding the subclass's placement for this array. keeping
163 /// it here also allows the subtype_* members to be implemented MUCH more
164 /// efficiently, and dynamically very few types do not contain any elements.
165 PATypeHandle *ContainedTys;
168 void print(raw_ostream &O) const;
170 /// @brief Debugging support: print to stderr
173 /// @brief Debugging support: print to stderr (use type names from context
175 void dump(const Module *Context) const;
177 /// getContext - Fetch the LLVMContext in which this type was uniqued.
178 LLVMContext &getContext() const { return Context; }
180 //===--------------------------------------------------------------------===//
181 // Property accessors for dealing with types... Some of these virtual methods
182 // are defined in private classes defined in Type.cpp for primitive types.
185 /// getDescription - Return the string representation of the type.
186 std::string getDescription() const;
188 /// getTypeID - Return the type id for the type. This will return one
189 /// of the TypeID enum elements defined above.
191 inline TypeID getTypeID() const { return ID; }
193 /// isVoidTy - Return true if this is 'void'.
194 bool isVoidTy() const { return ID == VoidTyID; }
196 /// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
197 bool isFloatTy() const { return ID == FloatTyID; }
199 /// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
200 bool isDoubleTy() const { return ID == DoubleTyID; }
202 /// isX86_FP80Ty - Return true if this is x86 long double.
203 bool isX86_FP80Ty() const { return ID == X86_FP80TyID; }
205 /// isFP128Ty - Return true if this is 'fp128'.
206 bool isFP128Ty() const { return ID == FP128TyID; }
208 /// isPPC_FP128Ty - Return true if this is powerpc long double.
209 bool isPPC_FP128Ty() const { return ID == PPC_FP128TyID; }
211 /// isFloatingPointTy - Return true if this is one of the five floating point
213 bool isFloatingPointTy() const { return ID == FloatTyID || ID == DoubleTyID ||
214 ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
216 /// isX86_MMXTy - Return true if this is X86 MMX.
217 bool isX86_MMXTy() const { return ID == X86_MMXTyID; }
219 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP.
221 bool isFPOrFPVectorTy() const;
223 /// isLabelTy - Return true if this is 'label'.
224 bool isLabelTy() const { return ID == LabelTyID; }
226 /// isMetadataTy - Return true if this is 'metadata'.
227 bool isMetadataTy() const { return ID == MetadataTyID; }
229 /// isIntegerTy - True if this is an instance of IntegerType.
231 bool isIntegerTy() const { return ID == IntegerTyID; }
233 /// isIntegerTy - Return true if this is an IntegerType of the given width.
234 bool isIntegerTy(unsigned Bitwidth) const;
236 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
239 bool isIntOrIntVectorTy() const;
241 /// isFunctionTy - True if this is an instance of FunctionType.
243 bool isFunctionTy() const { return ID == FunctionTyID; }
245 /// isStructTy - True if this is an instance of StructType.
247 bool isStructTy() const { return ID == StructTyID; }
249 /// isArrayTy - True if this is an instance of ArrayType.
251 bool isArrayTy() const { return ID == ArrayTyID; }
253 /// isPointerTy - True if this is an instance of PointerType.
255 bool isPointerTy() const { return ID == PointerTyID; }
257 /// isOpaqueTy - True if this is an instance of OpaqueType.
259 bool isOpaqueTy() const { return ID == OpaqueTyID; }
261 /// isVectorTy - True if this is an instance of VectorType.
263 bool isVectorTy() const { return ID == VectorTyID; }
265 /// isAbstract - True if the type is either an Opaque type, or is a derived
266 /// type that includes an opaque type somewhere in it.
268 inline bool isAbstract() const { return Abstract; }
270 /// canLosslesslyBitCastTo - Return true if this type could be converted
271 /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts
272 /// are valid for types of the same size only where no re-interpretation of
273 /// the bits is done.
274 /// @brief Determine if this type could be losslessly bitcast to Ty
275 bool canLosslesslyBitCastTo(const Type *Ty) const;
277 /// isEmptyTy - Return true if this type is empty, that is, it has no
278 /// elements or all its elements are empty.
279 bool isEmptyTy() const;
281 /// Here are some useful little methods to query what type derived types are
282 /// Note that all other types can just compare to see if this == Type::xxxTy;
284 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
285 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
287 /// isFirstClassType - Return true if the type is "first class", meaning it
288 /// is a valid type for a Value.
290 inline bool isFirstClassType() const {
291 // There are more first-class kinds than non-first-class kinds, so a
292 // negative test is simpler than a positive one.
293 return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
296 /// isSingleValueType - Return true if the type is a valid type for a
297 /// virtual register in codegen. This includes all first-class types
298 /// except struct and array types.
300 inline bool isSingleValueType() const {
301 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
302 ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
305 /// isAggregateType - Return true if the type is an aggregate type. This
306 /// means it is valid as the first operand of an insertvalue or
307 /// extractvalue instruction. This includes struct and array types, but
308 /// does not include vector types.
310 inline bool isAggregateType() const {
311 return ID == StructTyID || ID == ArrayTyID;
314 /// isSized - Return true if it makes sense to take the size of this type. To
315 /// get the actual size for a particular target, it is reasonable to use the
316 /// TargetData subsystem to do this.
318 bool isSized() const {
319 // If it's a primitive, it is always sized.
320 if (ID == IntegerTyID || isFloatingPointTy() || ID == PointerTyID ||
323 // If it is not something that can have a size (e.g. a function or label),
324 // it doesn't have a size.
325 if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
327 // If it is something that can have a size and it's concrete, it definitely
328 // has a size, otherwise we have to try harder to decide.
329 return !isAbstract() || isSizedDerivedType();
332 /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
333 /// primitive type. These are fixed by LLVM and are not target dependent.
334 /// This will return zero if the type does not have a size or is not a
337 /// Note that this may not reflect the size of memory allocated for an
338 /// instance of the type or the number of bytes that are written when an
339 /// instance of the type is stored to memory. The TargetData class provides
340 /// additional query functions to provide this information.
342 unsigned getPrimitiveSizeInBits() const;
344 /// getScalarSizeInBits - If this is a vector type, return the
345 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
346 /// getPrimitiveSizeInBits value for this type.
347 unsigned getScalarSizeInBits() const;
349 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
350 /// is only valid on floating point types. If the FP type does not
351 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
352 int getFPMantissaWidth() const;
354 /// getForwardedType - Return the type that this type has been resolved to if
355 /// it has been resolved to anything. This is used to implement the
356 /// union-find algorithm for type resolution, and shouldn't be used by general
358 const Type *getForwardedType() const {
359 if (!ForwardType) return 0;
360 return getForwardedTypeInternal();
363 /// getScalarType - If this is a vector type, return the element type,
364 /// otherwise return this.
365 const Type *getScalarType() const;
367 //===--------------------------------------------------------------------===//
368 // Type Iteration support
370 typedef PATypeHandle *subtype_iterator;
371 subtype_iterator subtype_begin() const { return ContainedTys; }
372 subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
374 /// getContainedType - This method is used to implement the type iterator
375 /// (defined a the end of the file). For derived types, this returns the
376 /// types 'contained' in the derived type.
378 const Type *getContainedType(unsigned i) const {
379 assert(i < NumContainedTys && "Index out of range!");
380 return ContainedTys[i].get();
383 /// getNumContainedTypes - Return the number of types in the derived type.
385 unsigned getNumContainedTypes() const { return NumContainedTys; }
387 //===--------------------------------------------------------------------===//
388 // Static members exported by the Type class itself. Useful for getting
389 // instances of Type.
392 /// getPrimitiveType - Return a type based on an identifier.
393 static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
395 //===--------------------------------------------------------------------===//
396 // These are the builtin types that are always available...
398 static const Type *getVoidTy(LLVMContext &C);
399 static const Type *getLabelTy(LLVMContext &C);
400 static const Type *getFloatTy(LLVMContext &C);
401 static const Type *getDoubleTy(LLVMContext &C);
402 static const Type *getMetadataTy(LLVMContext &C);
403 static const Type *getX86_FP80Ty(LLVMContext &C);
404 static const Type *getFP128Ty(LLVMContext &C);
405 static const Type *getPPC_FP128Ty(LLVMContext &C);
406 static const Type *getX86_MMXTy(LLVMContext &C);
407 static const IntegerType *getIntNTy(LLVMContext &C, unsigned N);
408 static const IntegerType *getInt1Ty(LLVMContext &C);
409 static const IntegerType *getInt8Ty(LLVMContext &C);
410 static const IntegerType *getInt16Ty(LLVMContext &C);
411 static const IntegerType *getInt32Ty(LLVMContext &C);
412 static const IntegerType *getInt64Ty(LLVMContext &C);
414 //===--------------------------------------------------------------------===//
415 // Convenience methods for getting pointer types with one of the above builtin
418 static const PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
419 static const PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
420 static const PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
421 static const PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
422 static const PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
423 static const PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
424 static const PointerType *getIntNPtrTy(LLVMContext &C, unsigned N,
426 static const PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
427 static const PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
428 static const PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
429 static const PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
430 static const PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
432 /// Methods for support type inquiry through isa, cast, and dyn_cast:
433 static inline bool classof(const Type *) { return true; }
435 void addRef() const {
436 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
440 void dropRef() const {
441 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
442 assert(RefCount && "No objects are currently referencing this object!");
444 // If this is the last PATypeHolder using this object, and there are no
445 // PATypeHandles using it, the type is dead, delete it now.
446 if (--RefCount == 0 && AbstractTypeUsers.empty())
450 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
451 /// it. This function is called primarily by the PATypeHandle class.
453 void addAbstractTypeUser(AbstractTypeUser *U) const;
455 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
456 /// no longer has a handle to the type. This function is called primarily by
457 /// the PATypeHandle class. When there are no users of the abstract type, it
458 /// is annihilated, because there is no way to get a reference to it ever
461 void removeAbstractTypeUser(AbstractTypeUser *U) const;
463 /// getPointerTo - Return a pointer to the current type. This is equivalent
464 /// to PointerType::get(Foo, AddrSpace).
465 const PointerType *getPointerTo(unsigned AddrSpace = 0) const;
468 /// isSizedDerivedType - Derived types like structures and arrays are sized
469 /// iff all of the members of the type are sized as well. Since asking for
470 /// their size is relatively uncommon, move this operation out of line.
471 bool isSizedDerivedType() const;
473 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
474 virtual void typeBecameConcrete(const DerivedType *AbsTy);
477 // PromoteAbstractToConcrete - This is an internal method used to calculate
478 // change "Abstract" from true to false when types are refined.
479 void PromoteAbstractToConcrete();
480 friend class TypeMapBase;
483 //===----------------------------------------------------------------------===//
484 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
485 // These are defined here because they MUST be inlined, yet are dependent on
486 // the definition of the Type class.
488 inline void PATypeHandle::addUser() {
489 assert(Ty && "Type Handle has a null type!");
490 if (Ty->isAbstract())
491 Ty->addAbstractTypeUser(User);
493 inline void PATypeHandle::removeUser() {
494 if (Ty->isAbstract())
495 Ty->removeAbstractTypeUser(User);
498 // Define inline methods for PATypeHolder.
500 /// get - This implements the forwarding part of the union-find algorithm for
501 /// abstract types. Before every access to the Type*, we check to see if the
502 /// type we are pointing to is forwarding to a new type. If so, we drop our
503 /// reference to the type.
505 inline Type *PATypeHolder::get() const {
506 if (Ty == 0) return 0;
507 const Type *NewTy = Ty->getForwardedType();
508 if (!NewTy) return const_cast<Type*>(Ty);
509 return *const_cast<PATypeHolder*>(this) = NewTy;
512 inline void PATypeHolder::addRef() {
513 if (Ty && Ty->isAbstract())
517 inline void PATypeHolder::dropRef() {
518 if (Ty && Ty->isAbstract())
523 //===----------------------------------------------------------------------===//
524 // Provide specializations of GraphTraits to be able to treat a type as a
525 // graph of sub types.
527 template <> struct GraphTraits<Type*> {
528 typedef Type NodeType;
529 typedef Type::subtype_iterator ChildIteratorType;
531 static inline NodeType *getEntryNode(Type *T) { return T; }
532 static inline ChildIteratorType child_begin(NodeType *N) {
533 return N->subtype_begin();
535 static inline ChildIteratorType child_end(NodeType *N) {
536 return N->subtype_end();
540 template <> struct GraphTraits<const Type*> {
541 typedef const Type NodeType;
542 typedef Type::subtype_iterator ChildIteratorType;
544 static inline NodeType *getEntryNode(const Type *T) { return T; }
545 static inline ChildIteratorType child_begin(NodeType *N) {
546 return N->subtype_begin();
548 static inline ChildIteratorType child_end(NodeType *N) {
549 return N->subtype_end();
553 template <> struct isa_impl<PointerType, Type> {
554 static inline bool doit(const Type &Ty) {
555 return Ty.getTypeID() == Type::PointerTyID;
559 raw_ostream &operator<<(raw_ostream &OS, const Type &T);
561 } // End llvm namespace