Type.h revision ef1af7d6d5be039e7eea46f8f3a2720fb5a1a153
1//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9
10
11#ifndef LLVM_TYPE_H
12#define LLVM_TYPE_H
13
14#include "llvm/AbstractTypeUser.h"
15#include "llvm/Support/Casting.h"
16#include "llvm/Support/DataTypes.h"
17#include "llvm/Support/Streams.h"
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/ADT/iterator"
20#include <string>
21#include <vector>
22
23namespace llvm {
24
25class DerivedType;
26class PointerType;
27class IntegerType;
28class TypeMapBase;
29
30/// This file contains the declaration of the Type class.  For more "Type" type
31/// stuff, look in DerivedTypes.h.
32///
33/// The instances of the Type class are immutable: once they are created,
34/// they are never changed.  Also note that only one instance of a particular
35/// type is ever created.  Thus seeing if two types are equal is a matter of
36/// doing a trivial pointer comparison. To enforce that no two equal instances
37/// are created, Type instances can only be created via static factory methods
38/// in class Type and in derived classes.
39///
40/// Once allocated, Types are never free'd, unless they are an abstract type
41/// that is resolved to a more concrete type.
42///
43/// Types themself don't have a name, and can be named either by:
44/// - using SymbolTable instance, typically from some Module,
45/// - using convenience methods in the Module class (which uses module's
46///    SymbolTable too).
47///
48/// Opaque types are simple derived types with no state.  There may be many
49/// different Opaque type objects floating around, but two are only considered
50/// identical if they are pointer equals of each other.  This allows us to have
51/// two opaque types that end up resolving to different concrete types later.
52///
53/// Opaque types are also kinda weird and scary and different because they have
54/// to keep a list of uses of the type.  When, through linking, parsing, or
55/// bitcode reading, they become resolved, they need to find and update all
56/// users of the unknown type, causing them to reference a new, more concrete
57/// type.  Opaque types are deleted when their use list dwindles to zero users.
58///
59/// @brief Root of type hierarchy
60class Type : public AbstractTypeUser {
61public:
62  //===-------------------------------------------------------------------===//
63  /// Definitions of all of the base types for the Type system.  Based on this
64  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
65  /// Note: If you add an element to this, you need to add an element to the
66  /// Type::getPrimitiveType function, or else things will break!
67  ///
68  enum TypeID {
69    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
70    VoidTyID = 0,    ///<  0: type with no size
71    FloatTyID,       ///<  1: 32 bit floating point type
72    DoubleTyID,      ///<  2: 64 bit floating point type
73    X86_FP80TyID,    ///<  3: 80 bit floating point type (X87)
74    FP128TyID,       ///<  4: 128 bit floating point type (112-bit mantissa)
75    PPC_FP128TyID,   ///<  5: 128 bit floating point type (two 64-bits)
76    LabelTyID,       ///<  6: Labels
77
78    // Derived types... see DerivedTypes.h file...
79    // Make sure FirstDerivedTyID stays up to date!!!
80    IntegerTyID,     ///<  7: Arbitrary bit width integers
81    FunctionTyID,    ///<  8: Functions
82    StructTyID,      ///<  9: Structures
83    PackedStructTyID,///< 10: Packed Structure. This is for bitcode only
84    ArrayTyID,       ///< 11: Arrays
85    PointerTyID,     ///< 12: Pointers
86    OpaqueTyID,      ///< 13: Opaque: type with unknown structure
87    VectorTyID,      ///< 14: SIMD 'packed' format, or other vector type
88
89    NumTypeIDs,                         // Must remain as last defined ID
90    LastPrimitiveTyID = LabelTyID,
91    FirstDerivedTyID = IntegerTyID
92  };
93
94private:
95  TypeID   ID : 8;    // The current base type of this type.
96  bool     Abstract : 1;  // True if type contains an OpaqueType
97  unsigned SubclassData : 23; //Space for subclasses to store data
98
99  /// RefCount - This counts the number of PATypeHolders that are pointing to
100  /// this type.  When this number falls to zero, if the type is abstract and
101  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
102  /// derived types.
103  ///
104  mutable unsigned RefCount;
105
106  const Type *getForwardedTypeInternal() const;
107
108  // Some Type instances are allocated as arrays, some aren't. So we provide
109  // this method to get the right kind of destruction for the type of Type.
110  void destroy() const; // const is a lie, this does "delete this"!
111
112protected:
113  explicit Type(TypeID id) : ID(id), Abstract(false), SubclassData(0),
114                             RefCount(0), ForwardType(0), NumContainedTys(0),
115                             ContainedTys(0) {}
116  virtual ~Type() {
117    assert(AbstractTypeUsers.empty() && "Abstract types remain");
118  }
119
120  /// Types can become nonabstract later, if they are refined.
121  ///
122  inline void setAbstract(bool Val) { Abstract = Val; }
123
124  unsigned getRefCount() const { return RefCount; }
125
126  unsigned getSubclassData() const { return SubclassData; }
127  void setSubclassData(unsigned val) { SubclassData = val; }
128
129  /// ForwardType - This field is used to implement the union find scheme for
130  /// abstract types.  When types are refined to other types, this field is set
131  /// to the more refined type.  Only abstract types can be forwarded.
132  mutable const Type *ForwardType;
133
134
135  /// AbstractTypeUsers - Implement a list of the users that need to be notified
136  /// if I am a type, and I get resolved into a more concrete type.
137  ///
138  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
139
140  /// NumContainedTys - Keeps track of how many PATypeHandle instances there
141  /// are at the end of this type instance for the list of contained types. It
142  /// is the subclasses responsibility to set this up. Set to 0 if there are no
143  /// contained types in this type.
144  unsigned NumContainedTys;
145
146  /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained
147  /// by this Type.  For example, this includes the arguments of a function
148  /// type, the elements of a structure, the pointee of a pointer, the element
149  /// type of an array, etc.  This pointer may be 0 for types that don't
150  /// contain other types (Integer, Double, Float).  In general, the subclass
151  /// should arrange for space for the PATypeHandles to be included in the
152  /// allocation of the type object and set this pointer to the address of the
153  /// first element. This allows the Type class to manipulate the ContainedTys
154  /// without understanding the subclass's placement for this array.  keeping
155  /// it here also allows the subtype_* members to be implemented MUCH more
156  /// efficiently, and dynamically very few types do not contain any elements.
157  PATypeHandle *ContainedTys;
158
159public:
160  void print(std::ostream &O) const;
161  void print(std::ostream *O) const { if (O) print(*O); }
162
163  /// @brief Debugging support: print to stderr
164  void dump() const;
165
166  //===--------------------------------------------------------------------===//
167  // Property accessors for dealing with types... Some of these virtual methods
168  // are defined in private classes defined in Type.cpp for primitive types.
169  //
170
171  /// getTypeID - Return the type id for the type.  This will return one
172  /// of the TypeID enum elements defined above.
173  ///
174  inline TypeID getTypeID() const { return ID; }
175
176  /// getDescription - Return the string representation of the type...
177  const std::string &getDescription() const;
178
179  /// isInteger - True if this is an instance of IntegerType.
180  ///
181  bool isInteger() const { return ID == IntegerTyID; }
182
183  /// isIntOrIntVector - Return true if this is an integer type or a vector of
184  /// integer types.
185  ///
186  bool isIntOrIntVector() const;
187
188  /// isFloatingPoint - Return true if this is one of the two floating point
189  /// types
190  bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID ||
191      ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
192
193  /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
194  ///
195  bool isFPOrFPVector() const;
196
197  /// isAbstract - True if the type is either an Opaque type, or is a derived
198  /// type that includes an opaque type somewhere in it.
199  ///
200  inline bool isAbstract() const { return Abstract; }
201
202  /// canLosslesslyBitCastTo - Return true if this type could be converted
203  /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
204  /// are valid for types of the same size only where no re-interpretation of
205  /// the bits is done.
206  /// @brief Determine if this type could be losslessly bitcast to Ty
207  bool canLosslesslyBitCastTo(const Type *Ty) const;
208
209
210  /// Here are some useful little methods to query what type derived types are
211  /// Note that all other types can just compare to see if this == Type::xxxTy;
212  ///
213  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
214  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
215
216  /// isFirstClassType - Return true if the value is holdable in a register.
217  ///
218  inline bool isFirstClassType() const {
219    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
220            ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
221  }
222
223  /// isSized - Return true if it makes sense to take the size of this type.  To
224  /// get the actual size for a particular target, it is reasonable to use the
225  /// TargetData subsystem to do this.
226  ///
227  bool isSized() const {
228    // If it's a primitive, it is always sized.
229    if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
230      return true;
231    // If it is not something that can have a size (e.g. a function or label),
232    // it doesn't have a size.
233    if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID &&
234        ID != PackedStructTyID)
235      return false;
236    // If it is something that can have a size and it's concrete, it definitely
237    // has a size, otherwise we have to try harder to decide.
238    return !isAbstract() || isSizedDerivedType();
239  }
240
241  /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
242  /// primitive type.  These are fixed by LLVM and are not target dependent.
243  /// This will return zero if the type does not have a size or is not a
244  /// primitive type.
245  ///
246  unsigned getPrimitiveSizeInBits() const;
247
248  /// getForwaredType - Return the type that this type has been resolved to if
249  /// it has been resolved to anything.  This is used to implement the
250  /// union-find algorithm for type resolution, and shouldn't be used by general
251  /// purpose clients.
252  const Type *getForwardedType() const {
253    if (!ForwardType) return 0;
254    return getForwardedTypeInternal();
255  }
256
257  /// getVAArgsPromotedType - Return the type an argument of this type
258  /// will be promoted to if passed through a variable argument
259  /// function.
260  const Type *getVAArgsPromotedType() const;
261
262  //===--------------------------------------------------------------------===//
263  // Type Iteration support
264  //
265  typedef PATypeHandle *subtype_iterator;
266  subtype_iterator subtype_begin() const { return ContainedTys; }
267  subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
268
269  /// getContainedType - This method is used to implement the type iterator
270  /// (defined a the end of the file).  For derived types, this returns the
271  /// types 'contained' in the derived type.
272  ///
273  const Type *getContainedType(unsigned i) const {
274    assert(i < NumContainedTys && "Index out of range!");
275    return ContainedTys[i].get();
276  }
277
278  /// getNumContainedTypes - Return the number of types in the derived type.
279  ///
280  unsigned getNumContainedTypes() const { return NumContainedTys; }
281
282  //===--------------------------------------------------------------------===//
283  // Static members exported by the Type class itself.  Useful for getting
284  // instances of Type.
285  //
286
287  /// getPrimitiveType - Return a type based on an identifier.
288  static const Type *getPrimitiveType(TypeID IDNumber);
289
290  //===--------------------------------------------------------------------===//
291  // These are the builtin types that are always available...
292  //
293  static const Type *VoidTy, *LabelTy, *FloatTy, *DoubleTy;
294  static const Type *X86_FP80Ty, *FP128Ty, *PPC_FP128Ty;
295  static const IntegerType *Int1Ty, *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
296
297  /// Methods for support type inquiry through isa, cast, and dyn_cast:
298  static inline bool classof(const Type *T) { return true; }
299
300  void addRef() const {
301    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
302    ++RefCount;
303  }
304
305  void dropRef() const {
306    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
307    assert(RefCount && "No objects are currently referencing this object!");
308
309    // If this is the last PATypeHolder using this object, and there are no
310    // PATypeHandles using it, the type is dead, delete it now.
311    if (--RefCount == 0 && AbstractTypeUsers.empty())
312      this->destroy();
313  }
314
315  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
316  /// it.  This function is called primarily by the PATypeHandle class.
317  ///
318  void addAbstractTypeUser(AbstractTypeUser *U) const {
319    assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
320    AbstractTypeUsers.push_back(U);
321  }
322
323  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
324  /// no longer has a handle to the type.  This function is called primarily by
325  /// the PATypeHandle class.  When there are no users of the abstract type, it
326  /// is annihilated, because there is no way to get a reference to it ever
327  /// again.
328  ///
329  void removeAbstractTypeUser(AbstractTypeUser *U) const;
330
331private:
332  /// isSizedDerivedType - Derived types like structures and arrays are sized
333  /// iff all of the members of the type are sized as well.  Since asking for
334  /// their size is relatively uncommon, move this operation out of line.
335  bool isSizedDerivedType() const;
336
337  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
338  virtual void typeBecameConcrete(const DerivedType *AbsTy);
339
340protected:
341  // PromoteAbstractToConcrete - This is an internal method used to calculate
342  // change "Abstract" from true to false when types are refined.
343  void PromoteAbstractToConcrete();
344  friend class TypeMapBase;
345};
346
347//===----------------------------------------------------------------------===//
348// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
349// These are defined here because they MUST be inlined, yet are dependent on
350// the definition of the Type class.
351//
352inline void PATypeHandle::addUser() {
353  assert(Ty && "Type Handle has a null type!");
354  if (Ty->isAbstract())
355    Ty->addAbstractTypeUser(User);
356}
357inline void PATypeHandle::removeUser() {
358  if (Ty->isAbstract())
359    Ty->removeAbstractTypeUser(User);
360}
361
362// Define inline methods for PATypeHolder...
363
364inline void PATypeHolder::addRef() {
365  if (Ty->isAbstract())
366    Ty->addRef();
367}
368
369inline void PATypeHolder::dropRef() {
370  if (Ty->isAbstract())
371    Ty->dropRef();
372}
373
374
375//===----------------------------------------------------------------------===//
376// Provide specializations of GraphTraits to be able to treat a type as a
377// graph of sub types...
378
379template <> struct GraphTraits<Type*> {
380  typedef Type NodeType;
381  typedef Type::subtype_iterator ChildIteratorType;
382
383  static inline NodeType *getEntryNode(Type *T) { return T; }
384  static inline ChildIteratorType child_begin(NodeType *N) {
385    return N->subtype_begin();
386  }
387  static inline ChildIteratorType child_end(NodeType *N) {
388    return N->subtype_end();
389  }
390};
391
392template <> struct GraphTraits<const Type*> {
393  typedef const Type NodeType;
394  typedef Type::subtype_iterator ChildIteratorType;
395
396  static inline NodeType *getEntryNode(const Type *T) { return T; }
397  static inline ChildIteratorType child_begin(NodeType *N) {
398    return N->subtype_begin();
399  }
400  static inline ChildIteratorType child_end(NodeType *N) {
401    return N->subtype_end();
402  }
403};
404
405template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
406  return Ty.getTypeID() == Type::PointerTyID;
407}
408
409std::ostream &operator<<(std::ostream &OS, const Type &T);
410
411} // End llvm namespace
412
413#endif
414