Type.h revision b5ebf15b2b2ce8989caf1a1114b05d80b0f9bd48
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 ArrayType;
26class DerivedType;
27class FunctionType;
28class OpaqueType;
29class PointerType;
30class StructType;
31class PackedType;
32class TypeMapBase;
33
34/// This file contains the declaration of the Type class.  For more "Type" type
35/// stuff, look in DerivedTypes.h.
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.
43///
44/// Once allocated, Types are never free'd, unless they are an abstract type
45/// that is resolved to a more concrete type.
46///
47/// Types themself don't have a name, and can be named either by:
48/// - using SymbolTable instance, typically from some Module,
49/// - using convenience methods in the Module class (which uses module's
50///    SymbolTable too).
51///
52/// Opaque types are simple derived types with no state.  There may be many
53/// different Opaque type objects floating around, but two are only considered
54/// identical if they are pointer equals of each other.  This allows us to have
55/// two opaque types that end up resolving to different concrete types later.
56///
57/// Opaque types are also kinda weird and scary and different because they have
58/// to keep a list of uses of the type.  When, through linking, parsing, or
59/// bytecode reading, they become resolved, they need to find and update all
60/// users of the unknown type, causing them to reference a new, more concrete
61/// type.  Opaque types are deleted when their use list dwindles to zero users.
62///
63/// @brief Root of type hierarchy
64class Type : public AbstractTypeUser {
65public:
66  ///===-------------------------------------------------------------------===//
67  /// Definitions of all of the base types for the Type system.  Based on this
68  /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
69  /// Note: If you add an element to this, you need to add an element to the
70  /// Type::getPrimitiveType function, or else things will break!
71  ///
72  enum TypeID {
73    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
74    VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
75    UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
76    UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
77    UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
78    ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
79    FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
80    LabelTyID     ,                     // 12   : Labels...
81
82    // Derived types... see DerivedTypes.h file...
83    // Make sure FirstDerivedTyID stays up to date!!!
84    FunctionTyID  , StructTyID,         // Functions... Structs...
85    ArrayTyID     , PointerTyID,        // Array... pointer...
86    OpaqueTyID,                         // Opaque type instances...
87    PackedTyID,                         // SIMD 'packed' format...
88    //...
89
90    NumTypeIDs,                         // Must remain as last defined ID
91    LastPrimitiveTyID = LabelTyID,
92    FirstDerivedTyID = FunctionTyID
93  };
94
95private:
96  TypeID   ID : 8;    // The current base type of this type.
97  bool     Abstract : 1;  // True if type contains an OpaqueType
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;
107protected:
108  Type(const char *Name, TypeID id);
109  Type(TypeID id) : ID(id), Abstract(false), RefCount(0), ForwardType(0) {}
110  virtual ~Type() {
111    assert(AbstractTypeUsers.empty());
112  }
113
114  /// Types can become nonabstract later, if they are refined.
115  ///
116  inline void setAbstract(bool Val) { Abstract = Val; }
117
118  unsigned getRefCount() const { return RefCount; }
119
120  /// ForwardType - This field is used to implement the union find scheme for
121  /// abstract types.  When types are refined to other types, this field is set
122  /// to the more refined type.  Only abstract types can be forwarded.
123  mutable const Type *ForwardType;
124
125  /// ContainedTys - The list of types contained by this one.  For example, this
126  /// includes the arguments of a function type, the elements of the structure,
127  /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
128  /// class wastes some space for types that do not contain anything (such as
129  /// primitive types).  However, keeping it here allows the subtype_* members
130  /// to be implemented MUCH more efficiently, and dynamically very few types do
131  /// not contain any elements (most are derived).
132  std::vector<PATypeHandle> ContainedTys;
133
134  /// AbstractTypeUsers - Implement a list of the users that need to be notified
135  /// if I am a type, and I get resolved into a more concrete type.
136  ///
137  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
138public:
139  void print(llvm_ostream &O) const {
140    if (O.stream()) print(*O.stream());
141  }
142  void print(std::ostream &O) const;
143
144  /// @brief Debugging support: print to stderr
145  void dump() const;
146
147  //===--------------------------------------------------------------------===//
148  // Property accessors for dealing with types... Some of these virtual methods
149  // are defined in private classes defined in Type.cpp for primitive types.
150  //
151
152  /// getTypeID - Return the type id for the type.  This will return one
153  /// of the TypeID enum elements defined above.
154  ///
155  inline TypeID getTypeID() const { return ID; }
156
157  /// getDescription - Return the string representation of the type...
158  const std::string &getDescription() const;
159
160  /// isSigned - Return whether an integral numeric type is signed.  This is
161  /// true for SByteTy, ShortTy, IntTy, LongTy.  Note that this is not true for
162  /// Float and Double.
163  ///
164  bool isSigned() const {
165    return ID == SByteTyID || ID == ShortTyID ||
166           ID == IntTyID || ID == LongTyID;
167  }
168
169  /// isUnsigned - Return whether a numeric type is unsigned.  This is not quite
170  /// the complement of isSigned... nonnumeric types return false as they do
171  /// with isSigned.  This returns true for UByteTy, UShortTy, UIntTy, and
172  /// ULongTy
173  ///
174  bool isUnsigned() const {
175    return ID == UByteTyID || ID == UShortTyID ||
176           ID == UIntTyID || ID == ULongTyID;
177  }
178
179  /// isInteger - Equivalent to isSigned() || isUnsigned()
180  ///
181  bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
182
183  /// isIntegral - Returns true if this is an integral type, which is either
184  /// BoolTy or one of the Integer types.
185  ///
186  bool isIntegral() const { return isInteger() || this == BoolTy; }
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
192  /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
193  ///
194  bool isFPOrFPVector() const;
195
196  /// isAbstract - True if the type is either an Opaque type, or is a derived
197  /// type that includes an opaque type somewhere in it.
198  ///
199  inline bool isAbstract() const { return Abstract; }
200
201  /// canLosslesslyBitCastTo - Return true if this type could be converted
202  /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts
203  /// are valid for types of the same size only where no re-interpretation of
204  /// the bits is done.
205  /// @brief Determine if this type could be losslessly bitcast to Ty
206  bool canLosslesslyBitCastTo(const Type *Ty) const;
207
208
209  /// Here are some useful little methods to query what type derived types are
210  /// Note that all other types can just compare to see if this == Type::xxxTy;
211  ///
212  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
213  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
214
215  /// isFirstClassType - Return true if the value is holdable in a register.
216  ///
217  inline bool isFirstClassType() const {
218    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
219            ID == PointerTyID || ID == PackedTyID;
220  }
221
222  /// isSized - Return true if it makes sense to take the size of this type.  To
223  /// get the actual size for a particular target, it is reasonable to use the
224  /// TargetData subsystem to do this.
225  ///
226  bool isSized() const {
227    // If it's a primitive, it is always sized.
228    if (ID >= BoolTyID && ID <= DoubleTyID || ID == PointerTyID)
229      return true;
230    // If it is not something that can have a size (e.g. a function or label),
231    // it doesn't have a size.
232    if (ID != StructTyID && ID != ArrayTyID && ID != PackedTyID)
233      return false;
234    // If it is something that can have a size and it's concrete, it definitely
235    // has a size, otherwise we have to try harder to decide.
236    return !isAbstract() || isSizedDerivedType();
237  }
238
239  /// getPrimitiveSize - Return the basic size of this type if it is a primitive
240  /// type.  These are fixed by LLVM and are not target dependent.  This will
241  /// return zero if the type does not have a size or is not a primitive type.
242  ///
243  unsigned getPrimitiveSize() const;
244  unsigned getPrimitiveSizeInBits() const;
245
246  /// getUnsignedVersion - If this is an integer type, return the unsigned
247  /// variant of this type.  For example int -> uint.
248  const Type *getUnsignedVersion() const;
249
250  /// getSignedVersion - If this is an integer type, return the signed variant
251  /// of this type.  For example uint -> int.
252  const Type *getSignedVersion() const;
253
254  /// getIntegralTypeMask - Return a bitmask with ones set for all of the bits
255  /// that can be set by an unsigned version of this type.  This is 0xFF for
256  /// sbyte/ubyte, 0xFFFF for shorts, etc.
257  uint64_t getIntegralTypeMask() const {
258    assert(isIntegral() && "This only works for integral types!");
259    return ~uint64_t(0UL) >> (64-getPrimitiveSizeInBits());
260  }
261
262  /// getForwaredType - Return the type that this type has been resolved to if
263  /// it has been resolved to anything.  This is used to implement the
264  /// union-find algorithm for type resolution, and shouldn't be used by general
265  /// purpose clients.
266  const Type *getForwardedType() const {
267    if (!ForwardType) return 0;
268    return getForwardedTypeInternal();
269  }
270
271  /// getVAArgsPromotedType - Return the type an argument of this type
272  /// will be promoted to if passed through a variable argument
273  /// function.
274  const Type *getVAArgsPromotedType() const {
275    if (ID == BoolTyID || ID == UByteTyID || ID == UShortTyID)
276      return Type::UIntTy;
277    else if (ID == SByteTyID || ID == ShortTyID)
278      return Type::IntTy;
279    else if (ID == FloatTyID)
280      return Type::DoubleTy;
281    else
282      return this;
283  }
284
285  //===--------------------------------------------------------------------===//
286  // Type Iteration support
287  //
288  typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
289  subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
290  subtype_iterator subtype_end() const { return ContainedTys.end(); }
291
292  /// getContainedType - This method is used to implement the type iterator
293  /// (defined a the end of the file).  For derived types, this returns the
294  /// types 'contained' in the derived type.
295  ///
296  const Type *getContainedType(unsigned i) const {
297    assert(i < ContainedTys.size() && "Index out of range!");
298    return ContainedTys[i];
299  }
300
301  /// getNumContainedTypes - Return the number of types in the derived type.
302  ///
303  typedef std::vector<PATypeHandle>::size_type size_type;
304  size_type getNumContainedTypes() const { return ContainedTys.size(); }
305
306  //===--------------------------------------------------------------------===//
307  // Static members exported by the Type class itself.  Useful for getting
308  // instances of Type.
309  //
310
311  /// getPrimitiveType - Return a type based on an identifier.
312  static const Type *getPrimitiveType(TypeID IDNumber);
313
314  //===--------------------------------------------------------------------===//
315  // These are the builtin types that are always available...
316  //
317  static Type *VoidTy , *BoolTy;
318  static Type *SByteTy, *UByteTy,
319              *ShortTy, *UShortTy,
320              *IntTy  , *UIntTy,
321              *LongTy , *ULongTy;
322  static Type *FloatTy, *DoubleTy;
323
324  static Type* LabelTy;
325
326  /// Methods for support type inquiry through isa, cast, and dyn_cast:
327  static inline bool classof(const Type *T) { return true; }
328
329  void addRef() const {
330    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
331    ++RefCount;
332  }
333
334  void dropRef() const {
335    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
336    assert(RefCount && "No objects are currently referencing this object!");
337
338    // If this is the last PATypeHolder using this object, and there are no
339    // PATypeHandles using it, the type is dead, delete it now.
340    if (--RefCount == 0 && AbstractTypeUsers.empty())
341      delete this;
342  }
343
344  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
345  /// it.  This function is called primarily by the PATypeHandle class.
346  ///
347  void addAbstractTypeUser(AbstractTypeUser *U) const {
348    assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
349    AbstractTypeUsers.push_back(U);
350  }
351
352  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
353  /// no longer has a handle to the type.  This function is called primarily by
354  /// the PATypeHandle class.  When there are no users of the abstract type, it
355  /// is annihilated, because there is no way to get a reference to it ever
356  /// again.
357  ///
358  void removeAbstractTypeUser(AbstractTypeUser *U) const;
359
360private:
361  /// isSizedDerivedType - Derived types like structures and arrays are sized
362  /// iff all of the members of the type are sized as well.  Since asking for
363  /// their size is relatively uncommon, move this operation out of line.
364  bool isSizedDerivedType() const;
365
366  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
367  virtual void typeBecameConcrete(const DerivedType *AbsTy);
368
369protected:
370  // PromoteAbstractToConcrete - This is an internal method used to calculate
371  // change "Abstract" from true to false when types are refined.
372  void PromoteAbstractToConcrete();
373  friend class TypeMapBase;
374};
375
376//===----------------------------------------------------------------------===//
377// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
378// These are defined here because they MUST be inlined, yet are dependent on
379// the definition of the Type class.
380//
381inline void PATypeHandle::addUser() {
382  assert(Ty && "Type Handle has a null type!");
383  if (Ty->isAbstract())
384    Ty->addAbstractTypeUser(User);
385}
386inline void PATypeHandle::removeUser() {
387  if (Ty->isAbstract())
388    Ty->removeAbstractTypeUser(User);
389}
390
391// Define inline methods for PATypeHolder...
392
393inline void PATypeHolder::addRef() {
394  if (Ty->isAbstract())
395    Ty->addRef();
396}
397
398inline void PATypeHolder::dropRef() {
399  if (Ty->isAbstract())
400    Ty->dropRef();
401}
402
403
404//===----------------------------------------------------------------------===//
405// Provide specializations of GraphTraits to be able to treat a type as a
406// graph of sub types...
407
408template <> struct GraphTraits<Type*> {
409  typedef Type NodeType;
410  typedef Type::subtype_iterator ChildIteratorType;
411
412  static inline NodeType *getEntryNode(Type *T) { return T; }
413  static inline ChildIteratorType child_begin(NodeType *N) {
414    return N->subtype_begin();
415  }
416  static inline ChildIteratorType child_end(NodeType *N) {
417    return N->subtype_end();
418  }
419};
420
421template <> struct GraphTraits<const Type*> {
422  typedef const Type NodeType;
423  typedef Type::subtype_iterator ChildIteratorType;
424
425  static inline NodeType *getEntryNode(const Type *T) { return T; }
426  static inline ChildIteratorType child_begin(NodeType *N) {
427    return N->subtype_begin();
428  }
429  static inline ChildIteratorType child_end(NodeType *N) {
430    return N->subtype_end();
431  }
432};
433
434template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
435  return Ty.getTypeID() == Type::PointerTyID;
436}
437
438std::ostream &operator<<(std::ostream &OS, const Type &T);
439
440} // End llvm namespace
441
442#endif
443