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 //===----------------------------------------------------------------------===//
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/LLVMContext.h"
16 #include "llvm/Support/Casting.h"
17 #include "llvm/Support/DataTypes.h"
18 #include "llvm/System/Atomic.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/ADT/iterator.h"
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 /// bitcode 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!
70 /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
73 // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
74 VoidTyID = 0, ///< 0: type with no size
75 FloatTyID, ///< 1: 32 bit floating point type
76 DoubleTyID, ///< 2: 64 bit floating point type
77 X86_FP80TyID, ///< 3: 80 bit floating point type (X87)
78 FP128TyID, ///< 4: 128 bit floating point type (112-bit mantissa)
79 PPC_FP128TyID, ///< 5: 128 bit floating point type (two 64-bits)
80 LabelTyID, ///< 6: Labels
81 MetadataTyID, ///< 7: Metadata
83 // Derived types... see DerivedTypes.h file...
84 // Make sure FirstDerivedTyID stays up to date!!!
85 IntegerTyID, ///< 8: Arbitrary bit width integers
86 FunctionTyID, ///< 9: Functions
87 StructTyID, ///< 10: Structures
88 ArrayTyID, ///< 11: Arrays
89 PointerTyID, ///< 12: Pointers
90 OpaqueTyID, ///< 13: Opaque: type with unknown structure
91 VectorTyID, ///< 14: SIMD 'packed' format, or other vector type
93 NumTypeIDs, // Must remain as last defined ID
94 LastPrimitiveTyID = LabelTyID,
95 FirstDerivedTyID = IntegerTyID
99 TypeID ID : 8; // The current base type of this type.
100 bool Abstract : 1; // True if type contains an OpaqueType
101 unsigned SubclassData : 23; //Space for subclasses to store data
103 /// RefCount - This counts the number of PATypeHolders that are pointing to
104 /// this type. When this number falls to zero, if the type is abstract and
105 /// has no AbstractTypeUsers, the type is deleted. This is only sensical for
108 mutable sys::cas_flag RefCount;
110 /// Context - This refers to the LLVMContext in which this type was uniqued.
111 LLVMContext &Context;
112 friend class LLVMContextImpl;
114 const Type *getForwardedTypeInternal() const;
116 // Some Type instances are allocated as arrays, some aren't. So we provide
117 // this method to get the right kind of destruction for the type of Type.
118 void destroy() const; // const is a lie, this does "delete this"!
121 explicit Type(LLVMContext &C, TypeID id) :
122 ID(id), Abstract(false), SubclassData(0),
123 RefCount(0), Context(C),
124 ForwardType(0), NumContainedTys(0),
127 assert(AbstractTypeUsers.empty() && "Abstract types remain");
130 /// Types can become nonabstract later, if they are refined.
132 inline void setAbstract(bool Val) { Abstract = Val; }
134 unsigned getRefCount() const { return RefCount; }
136 unsigned getSubclassData() const { return SubclassData; }
137 void setSubclassData(unsigned val) { SubclassData = val; }
139 /// ForwardType - This field is used to implement the union find scheme for
140 /// abstract types. When types are refined to other types, this field is set
141 /// to the more refined type. Only abstract types can be forwarded.
142 mutable const Type *ForwardType;
145 /// AbstractTypeUsers - Implement a list of the users that need to be notified
146 /// if I am a type, and I get resolved into a more concrete type.
148 mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
150 /// NumContainedTys - Keeps track of how many PATypeHandle instances there
151 /// are at the end of this type instance for the list of contained types. It
152 /// is the subclasses responsibility to set this up. Set to 0 if there are no
153 /// contained types in this type.
154 unsigned NumContainedTys;
156 /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained
157 /// by this Type. For example, this includes the arguments of a function
158 /// type, the elements of a structure, the pointee of a pointer, the element
159 /// type of an array, etc. This pointer may be 0 for types that don't
160 /// contain other types (Integer, Double, Float). In general, the subclass
161 /// should arrange for space for the PATypeHandles to be included in the
162 /// allocation of the type object and set this pointer to the address of the
163 /// first element. This allows the Type class to manipulate the ContainedTys
164 /// without understanding the subclass's placement for this array. keeping
165 /// it here also allows the subtype_* members to be implemented MUCH more
166 /// efficiently, and dynamically very few types do not contain any elements.
167 PATypeHandle *ContainedTys;
170 void print(raw_ostream &O) const;
171 void print(std::ostream &O) const;
173 /// @brief Debugging support: print to stderr
176 /// @brief Debugging support: print to stderr (use type names from context
178 void dump(const Module *Context) const;
180 /// getContext - Fetch the LLVMContext in which this type was uniqued.
181 LLVMContext &getContext() const { return Context; }
183 //===--------------------------------------------------------------------===//
184 // Property accessors for dealing with types... Some of these virtual methods
185 // are defined in private classes defined in Type.cpp for primitive types.
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 /// getDescription - Return the string representation of the type.
194 std::string getDescription() const;
196 /// isInteger - True if this is an instance of IntegerType.
198 bool isInteger() const { return ID == IntegerTyID; }
200 /// isIntOrIntVector - Return true if this is an integer type or a vector of
203 bool isIntOrIntVector() const;
205 /// isFloatingPoint - Return true if this is one of the five floating point
207 bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID ||
208 ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
210 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
212 bool isFPOrFPVector() const;
214 /// isAbstract - True if the type is either an Opaque type, or is a derived
215 /// type that includes an opaque type somewhere in it.
217 inline bool isAbstract() const { return Abstract; }
219 /// canLosslesslyBitCastTo - Return true if this type could be converted
220 /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts
221 /// are valid for types of the same size only where no re-interpretation of
222 /// the bits is done.
223 /// @brief Determine if this type could be losslessly bitcast to Ty
224 bool canLosslesslyBitCastTo(const Type *Ty) const;
227 /// Here are some useful little methods to query what type derived types are
228 /// Note that all other types can just compare to see if this == Type::xxxTy;
230 inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
231 inline bool isDerivedType() const { return ID >= FirstDerivedTyID; }
233 /// isFirstClassType - Return true if the type is "first class", meaning it
234 /// is a valid type for a Value.
236 inline bool isFirstClassType() const {
237 // There are more first-class kinds than non-first-class kinds, so a
238 // negative test is simpler than a positive one.
239 return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
242 /// isSingleValueType - Return true if the type is a valid type for a
243 /// virtual register in codegen. This includes all first-class types
244 /// except struct and array types.
246 inline bool isSingleValueType() const {
247 return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
248 ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
251 /// isAggregateType - Return true if the type is an aggregate type. This
252 /// means it is valid as the first operand of an insertvalue or
253 /// extractvalue instruction. This includes struct and array types, but
254 /// does not include vector types.
256 inline bool isAggregateType() const {
257 return ID == StructTyID || ID == ArrayTyID;
260 /// isSized - Return true if it makes sense to take the size of this type. To
261 /// get the actual size for a particular target, it is reasonable to use the
262 /// TargetData subsystem to do this.
264 bool isSized() const {
265 // If it's a primitive, it is always sized.
266 if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
268 // If it is not something that can have a size (e.g. a function or label),
269 // it doesn't have a size.
270 if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
272 // If it is something that can have a size and it's concrete, it definitely
273 // has a size, otherwise we have to try harder to decide.
274 return !isAbstract() || isSizedDerivedType();
277 /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
278 /// primitive type. These are fixed by LLVM and are not target dependent.
279 /// This will return zero if the type does not have a size or is not a
282 /// Note that this may not reflect the size of memory allocated for an
283 /// instance of the type or the number of bytes that are written when an
284 /// instance of the type is stored to memory. The TargetData class provides
285 /// additional query functions to provide this information.
287 unsigned getPrimitiveSizeInBits() const;
289 /// getScalarSizeInBits - If this is a vector type, return the
290 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
291 /// getPrimitiveSizeInBits value for this type.
292 unsigned getScalarSizeInBits() const;
294 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
295 /// is only valid on floating point types. If the FP type does not
296 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
297 int getFPMantissaWidth() const;
299 /// getForwardedType - Return the type that this type has been resolved to if
300 /// it has been resolved to anything. This is used to implement the
301 /// union-find algorithm for type resolution, and shouldn't be used by general
303 const Type *getForwardedType() const {
304 if (!ForwardType) return 0;
305 return getForwardedTypeInternal();
308 /// getVAArgsPromotedType - Return the type an argument of this type
309 /// will be promoted to if passed through a variable argument
311 const Type *getVAArgsPromotedType(LLVMContext &C) const;
313 /// getScalarType - If this is a vector type, return the element type,
314 /// otherwise return this.
315 const Type *getScalarType() const;
317 //===--------------------------------------------------------------------===//
318 // Type Iteration support
320 typedef PATypeHandle *subtype_iterator;
321 subtype_iterator subtype_begin() const { return ContainedTys; }
322 subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
324 /// getContainedType - This method is used to implement the type iterator
325 /// (defined a the end of the file). For derived types, this returns the
326 /// types 'contained' in the derived type.
328 const Type *getContainedType(unsigned i) const {
329 assert(i < NumContainedTys && "Index out of range!");
330 return ContainedTys[i].get();
333 /// getNumContainedTypes - Return the number of types in the derived type.
335 unsigned getNumContainedTypes() const { return NumContainedTys; }
337 //===--------------------------------------------------------------------===//
338 // Static members exported by the Type class itself. Useful for getting
339 // instances of Type.
342 /// getPrimitiveType - Return a type based on an identifier.
343 static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
345 //===--------------------------------------------------------------------===//
346 // These are the builtin types that are always available...
348 static const Type *getVoidTy(LLVMContext &C);
349 static const Type *getLabelTy(LLVMContext &C);
350 static const Type *getFloatTy(LLVMContext &C);
351 static const Type *getDoubleTy(LLVMContext &C);
352 static const Type *getMetadataTy(LLVMContext &C);
353 static const Type *getX86_FP80Ty(LLVMContext &C);
354 static const Type *getFP128Ty(LLVMContext &C);
355 static const Type *getPPC_FP128Ty(LLVMContext &C);
356 static const IntegerType *getInt1Ty(LLVMContext &C);
357 static const IntegerType *getInt8Ty(LLVMContext &C);
358 static const IntegerType *getInt16Ty(LLVMContext &C);
359 static const IntegerType *getInt32Ty(LLVMContext &C);
360 static const IntegerType *getInt64Ty(LLVMContext &C);
362 /// Methods for support type inquiry through isa, cast, and dyn_cast:
363 static inline bool classof(const Type *) { return true; }
365 void addRef() const {
366 assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
367 sys::AtomicIncrement(&RefCount);
370 void dropRef() const {
371 assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
372 assert(RefCount && "No objects are currently referencing this object!");
374 // If this is the last PATypeHolder using this object, and there are no
375 // PATypeHandles using it, the type is dead, delete it now.
376 sys::cas_flag OldCount = sys::AtomicDecrement(&RefCount);
377 if (OldCount == 0 && AbstractTypeUsers.empty())
381 /// addAbstractTypeUser - Notify an abstract type that there is a new user of
382 /// it. This function is called primarily by the PATypeHandle class.
384 void addAbstractTypeUser(AbstractTypeUser *U) const;
386 /// removeAbstractTypeUser - Notify an abstract type that a user of the class
387 /// no longer has a handle to the type. This function is called primarily by
388 /// the PATypeHandle class. When there are no users of the abstract type, it
389 /// is annihilated, because there is no way to get a reference to it ever
392 void removeAbstractTypeUser(AbstractTypeUser *U) const;
394 /// getPointerTo - Return a pointer to the current type. This is equivalent
395 /// to PointerType::get(Foo, AddrSpace).
396 PointerType *getPointerTo(unsigned AddrSpace = 0) const;
399 /// isSizedDerivedType - Derived types like structures and arrays are sized
400 /// iff all of the members of the type are sized as well. Since asking for
401 /// their size is relatively uncommon, move this operation out of line.
402 bool isSizedDerivedType() const;
404 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
405 virtual void typeBecameConcrete(const DerivedType *AbsTy);
408 // PromoteAbstractToConcrete - This is an internal method used to calculate
409 // change "Abstract" from true to false when types are refined.
410 void PromoteAbstractToConcrete();
411 friend class TypeMapBase;
414 //===----------------------------------------------------------------------===//
415 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
416 // These are defined here because they MUST be inlined, yet are dependent on
417 // the definition of the Type class.
419 inline void PATypeHandle::addUser() {
420 assert(Ty && "Type Handle has a null type!");
421 if (Ty->isAbstract())
422 Ty->addAbstractTypeUser(User);
424 inline void PATypeHandle::removeUser() {
425 if (Ty->isAbstract())
426 Ty->removeAbstractTypeUser(User);
429 // Define inline methods for PATypeHolder.
431 /// get - This implements the forwarding part of the union-find algorithm for
432 /// abstract types. Before every access to the Type*, we check to see if the
433 /// type we are pointing to is forwarding to a new type. If so, we drop our
434 /// reference to the type.
436 inline Type* PATypeHolder::get() const {
437 const Type *NewTy = Ty->getForwardedType();
438 if (!NewTy) return const_cast<Type*>(Ty);
439 return *const_cast<PATypeHolder*>(this) = NewTy;
442 inline void PATypeHolder::addRef() {
443 assert(Ty && "Type Holder has a null type!");
444 if (Ty->isAbstract())
448 inline void PATypeHolder::dropRef() {
449 if (Ty->isAbstract())
454 //===----------------------------------------------------------------------===//
455 // Provide specializations of GraphTraits to be able to treat a type as a
456 // graph of sub types...
458 template <> struct GraphTraits<Type*> {
459 typedef Type NodeType;
460 typedef Type::subtype_iterator ChildIteratorType;
462 static inline NodeType *getEntryNode(Type *T) { return T; }
463 static inline ChildIteratorType child_begin(NodeType *N) {
464 return N->subtype_begin();
466 static inline ChildIteratorType child_end(NodeType *N) {
467 return N->subtype_end();
471 template <> struct GraphTraits<const Type*> {
472 typedef const Type NodeType;
473 typedef Type::subtype_iterator ChildIteratorType;
475 static inline NodeType *getEntryNode(const Type *T) { return T; }
476 static inline ChildIteratorType child_begin(NodeType *N) {
477 return N->subtype_begin();
479 static inline ChildIteratorType child_end(NodeType *N) {
480 return N->subtype_end();
484 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
485 return Ty.getTypeID() == Type::PointerTyID;
488 std::ostream &operator<<(std::ostream &OS, const Type &T);
489 raw_ostream &operator<<(raw_ostream &OS, const Type &T);
491 } // End llvm namespace