1 //===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/Support/Casting.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/iterator"
33 /// This file contains the declaration of the Type class. For more "Type" type
34 /// stuff, look in DerivedTypes.h.
36 /// The instances of the Type class are immutable: once they are created,
37 /// they are never changed. Also note that only one instance of a particular
38 /// type is ever created. Thus seeing if two types are equal is a matter of
39 /// doing a trivial pointer comparison. To enforce that no two equal instances
40 /// are created, Type instances can only be created via static factory methods
41 /// in class Type and in derived classes.
43 /// Once allocated, Types are never free'd, unless they are an abstract type
44 /// that is resolved to a more concrete type.
46 /// Types themself don't have a name, and can be named either by:
47 /// - using SymbolTable instance, typically from some Module,
48 /// - using convenience methods in the Module class (which uses module's
51 /// Opaque types are simple derived types with no state. There may be many
52 /// different Opaque type objects floating around, but two are only considered
53 /// identical if they are pointer equals of each other. This allows us to have
54 /// two opaque types that end up resolving to different concrete types later.
56 /// Opaque types are also kinda weird and scary and different because they have
57 /// to keep a list of uses of the type. When, through linking, parsing, or
58 /// bytecode reading, they become resolved, they need to find and update all
59 /// users of the unknown type, causing them to reference a new, more concrete
60 /// type. Opaque types are deleted when their use list dwindles to zero users.
62 /// @brief Root of type hierarchy
63 class Type : public AbstractTypeUser {
65 ///===-------------------------------------------------------------------===//
66 /// Definitions of all of the base types for the Type system. Based on this
67 /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
68 /// Note: If you add an element to this, you need to add an element to the
69 /// Type::getPrimitiveType function, or else things will break!
72 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
73 VoidTyID = 0 , BoolTyID, // 0, 1: Basics...
74 UByteTyID , SByteTyID, // 2, 3: 8 bit types...
75 UShortTyID , ShortTyID, // 4, 5: 16 bit types...
76 UIntTyID , IntTyID, // 6, 7: 32 bit types...
77 ULongTyID , LongTyID, // 8, 9: 64 bit types...
78 FloatTyID , DoubleTyID, // 10,11: Floating point types...
79 LabelTyID , // 12 : Labels...
81 // Derived types... see DerivedTypes.h file...
82 // Make sure FirstDerivedTyID stays up to date!!!
83 FunctionTyID , StructTyID, // Functions... Structs...
84 ArrayTyID , PointerTyID, // Array... pointer...
85 OpaqueTyID, // Opaque type instances...
86 PackedTyID, // SIMD 'packed' format...
89 NumTypeIDs, // Must remain as last defined ID
90 LastPrimitiveTyID = LabelTyID,
91 FirstDerivedTyID = FunctionTyID
95 TypeID ID : 8; // The current base type of this type.
96 bool Abstract : 1; // True if type contains an OpaqueType
98 /// RefCount - This counts the number of PATypeHolders that are pointing to
99 /// this type. When this number falls to zero, if the type is abstract and
100 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
103 mutable unsigned RefCount;
105 const Type *getForwardedTypeInternal() const;
107 Type(const char *Name, TypeID id);
108 Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
110 assert(AbstractTypeUsers.empty());
113 /// Types can become nonabstract later, if they are refined.
115 inline void setAbstract(bool Val) { Abstract = Val; }
117 unsigned getRefCount() const { return RefCount; }
119 /// ForwardType - This field is used to implement the union find scheme for
120 /// abstract types. When types are refined to other types, this field is set
121 /// to the more refined type. Only abstract types can be forwarded.
122 mutable const Type *ForwardType;
124 /// ContainedTys - The list of types contained by this one. For example, this
125 /// includes the arguments of a function type, the elements of the structure,
126 /// the pointee of a pointer, etc. Note that keeping this vector in the Type
127 /// class wastes some space for types that do not contain anything (such as
128 /// primitive types). However, keeping it here allows the subtype_* members
129 /// to be implemented MUCH more efficiently, and dynamically very few types do
130 /// not contain any elements (most are derived).
131 std::vector<PATypeHandle> ContainedTys;
133 /// AbstractTypeUsers - Implement a list of the users that need to be notified
134 /// if I am a type, and I get resolved into a more concrete type.
136 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
138 void print(std::ostream &O) const;
140 /// @brief Debugging support: print to stderr
143 //===--------------------------------------------------------------------===//
144 // Property accessors for dealing with types... Some of these virtual methods
145 // are defined in private classes defined in Type.cpp for primitive types.
148 /// getTypeID - Return the type id for the type. This will return one
149 /// of the TypeID enum elements defined above.
151 inline TypeID getTypeID() const { return ID; }
153 /// getDescription - Return the string representation of the type...
154 const std::string &getDescription() const;
156 /// isSigned - Return whether an integral numeric type is signed. This is
157 /// true for SByteTy, ShortTy, IntTy, LongTy. Note that this is not true for
158 /// Float and Double.
160 bool isSigned() const {
161 return ID == SByteTyID || ID == ShortTyID ||
162 ID == IntTyID || ID == LongTyID;
165 /// isUnsigned - Return whether a numeric type is unsigned. This is not quite
166 /// the complement of isSigned... nonnumeric types return false as they do
167 /// with isSigned. This returns true for UByteTy, UShortTy, UIntTy, and
170 bool isUnsigned() const {
171 return ID == UByteTyID || ID == UShortTyID ||
172 ID == UIntTyID || ID == ULongTyID;
175 /// isInteger - Equivalent to isSigned() || isUnsigned()
177 bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
179 /// isIntegral - Returns true if this is an integral type, which is either
180 /// BoolTy or one of the Integer types.
182 bool isIntegral() const { return isInteger() || this == BoolTy; }
184 /// isFloatingPoint - Return true if this is one of the two floating point
186 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
188 /// isAbstract - True if the type is either an Opaque type, or is a derived
189 /// type that includes an opaque type somewhere in it.
191 inline bool isAbstract() const { return Abstract; }
193 /// isLosslesslyConvertibleTo - Return true if this type can be converted to
194 /// 'Ty' without any reinterpretation of bits. For example, uint to int.
196 bool isLosslesslyConvertibleTo(const Type *Ty) const;
199 /// Here are some useful little methods to query what type derived types are
200 /// Note that all other types can just compare to see if this == Type::xxxTy;
202 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
203 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
205 /// isFirstClassType - Return true if the value is holdable in a register.
207 inline bool isFirstClassType() const {
208 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
209 ID == PointerTyID || ID == PackedTyID;
212 /// isSized - Return true if it makes sense to take the size of this type. To
213 /// get the actual size for a particular target, it is reasonable to use the
214 /// TargetData subsystem to do this.
216 bool isSized() const {
217 // If it's a primitive, it is always sized.
218 if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
220 // If it is not something that can have a size (e.g. a function or label),
221 // it doesn't have a size.
222 if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
224 // If it is something that can have a size and it's concrete, it definitely
225 // has a size, otherwise we have to try harder to decide.
226 return !isAbstract() || isSizedDerivedType();
229 /// getPrimitiveSize - Return the basic size of this type if it is a primitive
230 /// type. These are fixed by LLVM and are not target dependent. This will
231 /// return zero if the type does not have a size or is not a primitive type.
233 unsigned getPrimitiveSize() const;
234 unsigned getPrimitiveSizeInBits() const;
236 /// getUnsignedVersion - If this is an integer type, return the unsigned
237 /// variant of this type. For example int -> uint.
238 const Type *getUnsignedVersion() const;
240 /// getSignedVersion - If this is an integer type, return the signed variant
241 /// of this type. For example uint -> int.
242 const Type *getSignedVersion() const;
244 /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
245 /// that can be set by an unsigned version of this type. This is 0xFF for
246 /// sbyte/ubyte, 0xFFFF for shorts, etc.
247 uint64_t getIntegralTypeMask() const {
248 assert(isIntegral() && "This only works for integral types!");
249 return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
252 /// getForwaredType - Return the type that this type has been resolved to if
253 /// it has been resolved to anything. This is used to implement the
254 /// union-find algorithm for type resolution, and shouldn't be used by general
256 const Type *getForwardedType() const {
257 if (!ForwardType) return 0;
258 return getForwardedTypeInternal();
261 /// getVAArgsPromotedType - Return the type an argument of this type
262 /// will be promoted to if passed through a variable argument
264 const Type *getVAArgsPromotedType() const {
265 if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
267 else if (ID == SByteTyID || ID == ShortTyID)
269 else if (ID == FloatTyID)
270 return Type::DoubleTy;
275 //===--------------------------------------------------------------------===//
276 // Type Iteration support
278 typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
279 subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
280 subtype_iterator subtype_end() const { return ContainedTys.end(); }
282 /// getContainedType - This method is used to implement the type iterator
283 /// (defined a the end of the file). For derived types, this returns the
284 /// types 'contained' in the derived type.
286 const Type *getContainedType(unsigned i) const {
287 assert(i < ContainedTys.size() && "Index out of range!");
288 return ContainedTys[i];
291 /// getNumContainedTypes - Return the number of types in the derived type.
293 typedef std::vector<PATypeHandle>::size_type size_type;
294 size_type getNumContainedTypes() const { return ContainedTys.size(); }
296 //===--------------------------------------------------------------------===//
297 // Static members exported by the Type class itself. Useful for getting
298 // instances of Type.
301 /// getPrimitiveType - Return a type based on an identifier.
302 static const Type *getPrimitiveType(TypeID IDNumber);
304 //===--------------------------------------------------------------------===//
305 // These are the builtin types that are always available...
307 static Type *VoidTy , *BoolTy;
308 static Type *SByteTy, *UByteTy,
312 static Type *FloatTy, *DoubleTy;
314 static Type* LabelTy;
316 /// Methods for support type inquiry through isa, cast, and dyn_cast:
317 static inline bool classof(const Type *T) { return true; }
319 void addRef() const {
320 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
324 void dropRef() const {
325 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
326 assert(RefCount && "No objects are currently referencing this object!");
328 // If this is the last PATypeHolder using this object, and there are no
329 // PATypeHandles using it, the type is dead, delete it now.
330 if (--RefCount == 0 && AbstractTypeUsers.empty())
334 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
335 /// it. This function is called primarily by the PATypeHandle class.
337 void addAbstractTypeUser(AbstractTypeUser *U) const {
338 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
339 AbstractTypeUsers.push_back(U);
342 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
343 /// no longer has a handle to the type. This function is called primarily by
344 /// the PATypeHandle class. When there are no users of the abstract type, it
345 /// is annihilated, because there is no way to get a reference to it ever
348 void removeAbstractTypeUser(AbstractTypeUser *U) const;
350 /// clearAllTypeMaps - This method frees all internal memory used by the
351 /// type subsystem, which can be used in environments where this memory is
352 /// otherwise reported as a leak.
353 static void clearAllTypeMaps();
356 /// isSizedDerivedType - Derived types like structures and arrays are sized
357 /// iff all of the members of the type are sized as well. Since asking for
358 /// their size is relatively uncommon, move this operation out of line.
359 bool isSizedDerivedType() const;
361 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
362 virtual void typeBecameConcrete(const DerivedType *AbsTy);
365 // PromoteAbstractToConcrete - This is an internal method used to calculate
366 // change "Abstract" from true to false when types are refined.
367 void PromoteAbstractToConcrete();
368 friend class TypeMapBase;
371 //===----------------------------------------------------------------------===//
372 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
373 // These are defined here because they MUST be inlined, yet are dependent on
374 // the definition of the Type class.
376 inline void PATypeHandle::addUser() {
377 assert(Ty && "Type Handle has a null type!");
378 if (Ty->isAbstract())
379 Ty->addAbstractTypeUser(User);
381 inline void PATypeHandle::removeUser() {
382 if (Ty->isAbstract())
383 Ty->removeAbstractTypeUser(User);
386 // Define inline methods for PATypeHolder...
388 inline void PATypeHolder::addRef() {
389 if (Ty->isAbstract())
393 inline void PATypeHolder::dropRef() {
394 if (Ty->isAbstract())
399 //===----------------------------------------------------------------------===//
400 // Provide specializations of GraphTraits to be able to treat a type as a
401 // graph of sub types...
403 template <> struct GraphTraits<Type*> {
404 typedef Type NodeType;
405 typedef Type::subtype_iterator ChildIteratorType;
407 static inline NodeType *getEntryNode(Type *T) { return T; }
408 static inline ChildIteratorType child_begin(NodeType *N) {
409 return N->subtype_begin();
411 static inline ChildIteratorType child_end(NodeType *N) {
412 return N->subtype_end();
416 template <> struct GraphTraits<const Type*> {
417 typedef const Type NodeType;
418 typedef Type::subtype_iterator ChildIteratorType;
420 static inline NodeType *getEntryNode(const Type *T) { return T; }
421 static inline ChildIteratorType child_begin(NodeType *N) {
422 return N->subtype_begin();
424 static inline ChildIteratorType child_end(NodeType *N) {
425 return N->subtype_end();
429 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
430 return Ty.getTypeID() == Type::PointerTyID;
433 std::ostream &operator<<(std::ostream &OS, const Type &T);
435 } // End llvm namespace