Type.h revision 47c5188789bc40671504ed1fa3a44765cefba44f
1//===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLVM_TYPE_H
11#define LLVM_TYPE_H
12
13#include "llvm/AbstractTypeUser.h"
14#include "llvm/Support/Casting.h"
15#include "llvm/System/DataTypes.h"
16#include "llvm/ADT/GraphTraits.h"
17#include <string>
18#include <vector>
19
20namespace llvm {
21
22class DerivedType;
23class PointerType;
24class IntegerType;
25class TypeMapBase;
26class raw_ostream;
27class Module;
28class LLVMContext;
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  /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
68  ///
69  enum TypeID {
70    // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
71    VoidTyID = 0,    ///<  0: type with no size
72    FloatTyID,       ///<  1: 32 bit floating point type
73    DoubleTyID,      ///<  2: 64 bit floating point type
74    X86_FP80TyID,    ///<  3: 80 bit floating point type (X87)
75    FP128TyID,       ///<  4: 128 bit floating point type (112-bit mantissa)
76    PPC_FP128TyID,   ///<  5: 128 bit floating point type (two 64-bits)
77    LabelTyID,       ///<  6: Labels
78    MetadataTyID,    ///<  7: Metadata
79
80    // Derived types... see DerivedTypes.h file...
81    // Make sure FirstDerivedTyID stays up to date!!!
82    IntegerTyID,     ///<  8: Arbitrary bit width integers
83    FunctionTyID,    ///<  9: Functions
84    StructTyID,      ///< 10: Structures
85    UnionTyID,       ///< 11: Unions
86    ArrayTyID,       ///< 12: Arrays
87    PointerTyID,     ///< 13: Pointers
88    OpaqueTyID,      ///< 14: Opaque: type with unknown structure
89    VectorTyID,      ///< 15: SIMD 'packed' format, or other vector type
90
91    NumTypeIDs,                         // Must remain as last defined ID
92    LastPrimitiveTyID = LabelTyID,
93    FirstDerivedTyID = IntegerTyID
94  };
95
96private:
97  TypeID   ID : 8;    // The current base type of this type.
98  bool     Abstract : 1;  // True if type contains an OpaqueType
99  unsigned SubclassData : 23; //Space for subclasses to store data
100
101  /// RefCount - This counts the number of PATypeHolders that are pointing to
102  /// this type.  When this number falls to zero, if the type is abstract and
103  /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
104  /// derived types.
105  ///
106  mutable unsigned RefCount;
107
108  /// Context - This refers to the LLVMContext in which this type was uniqued.
109  LLVMContext &Context;
110  friend class LLVMContextImpl;
111
112  const Type *getForwardedTypeInternal() const;
113
114  // Some Type instances are allocated as arrays, some aren't. So we provide
115  // this method to get the right kind of destruction for the type of Type.
116  void destroy() const; // const is a lie, this does "delete this"!
117
118protected:
119  explicit Type(LLVMContext &C, TypeID id) :
120                             ID(id), Abstract(false), SubclassData(0),
121                             RefCount(0), Context(C),
122                             ForwardType(0), NumContainedTys(0),
123                             ContainedTys(0) {}
124  virtual ~Type() {
125    assert(AbstractTypeUsers.empty() && "Abstract types remain");
126  }
127
128  /// Types can become nonabstract later, if they are refined.
129  ///
130  inline void setAbstract(bool Val) { Abstract = Val; }
131
132  unsigned getRefCount() const { return RefCount; }
133
134  unsigned getSubclassData() const { return SubclassData; }
135  void setSubclassData(unsigned val) { SubclassData = val; }
136
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;
141
142
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.
145  ///
146  mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
147
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;
153
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;
166
167public:
168  void print(raw_ostream &O) const;
169
170  /// @brief Debugging support: print to stderr
171  void dump() const;
172
173  /// @brief Debugging support: print to stderr (use type names from context
174  /// module).
175  void dump(const Module *Context) const;
176
177  /// getContext - Fetch the LLVMContext in which this type was uniqued.
178  LLVMContext &getContext() const { return Context; }
179
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.
183  //
184
185  /// getDescription - Return the string representation of the type.
186  std::string getDescription() const;
187
188  /// getTypeID - Return the type id for the type.  This will return one
189  /// of the TypeID enum elements defined above.
190  ///
191  inline TypeID getTypeID() const { return ID; }
192
193  /// isVoidTy - Return true if this is 'void'.
194  bool isVoidTy() const { return ID == VoidTyID; }
195
196  /// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
197  bool isFloatTy() const { return ID == FloatTyID; }
198
199  /// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
200  bool isDoubleTy() const { return ID == DoubleTyID; }
201
202  /// isX86_FP80Ty - Return true if this is x86 long double.
203  bool isX86_FP80Ty() const { return ID == X86_FP80TyID; }
204
205  /// isFP128Ty - Return true if this is 'fp128'.
206  bool isFP128Ty() const { return ID == FP128TyID; }
207
208  /// isPPC_FP128Ty - Return true if this is powerpc long double.
209  bool isPPC_FP128Ty() const { return ID == PPC_FP128TyID; }
210
211  /// isFloatingPointTy - Return true if this is one of the five floating point
212  /// types
213  bool isFloatingPointTy() const { return ID == FloatTyID || ID == DoubleTyID ||
214      ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
215
216  /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP.
217  ///
218  bool isFPOrFPVectorTy() const;
219
220  /// isLabelTy - Return true if this is 'label'.
221  bool isLabelTy() const { return ID == LabelTyID; }
222
223  /// isMetadataTy - Return true if this is 'metadata'.
224  bool isMetadataTy() const { return ID == MetadataTyID; }
225
226  /// isIntegerTy - True if this is an instance of IntegerType.
227  ///
228  bool isIntegerTy() const { return ID == IntegerTyID; }
229
230  /// isIntegerTy - Return true if this is an IntegerType of the given width.
231  bool isIntegerTy(unsigned Bitwidth) const;
232
233  /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
234  /// integer types.
235  ///
236  bool isIntOrIntVectorTy() const;
237
238  /// isFunctionTy - True if this is an instance of FunctionType.
239  ///
240  bool isFunctionTy() const { return ID == FunctionTyID; }
241
242  /// isStructTy - True if this is an instance of StructType.
243  ///
244  bool isStructTy() const { return ID == StructTyID; }
245
246  /// isUnionTy - True if this is an instance of UnionType.
247  ///
248  bool isUnionTy() const { return ID == UnionTyID; }
249
250  /// isArrayTy - True if this is an instance of ArrayType.
251  ///
252  bool isArrayTy() const { return ID == ArrayTyID; }
253
254  /// isPointerTy - True if this is an instance of PointerType.
255  ///
256  bool isPointerTy() const { return ID == PointerTyID; }
257
258  /// isOpaqueTy - True if this is an instance of OpaqueType.
259  ///
260  bool isOpaqueTy() const { return ID == OpaqueTyID; }
261
262  /// isVectorTy - True if this is an instance of VectorType.
263  ///
264  bool isVectorTy() const { return ID == VectorTyID; }
265
266  /// isAbstract - True if the type is either an Opaque type, or is a derived
267  /// type that includes an opaque type somewhere in it.
268  ///
269  inline bool isAbstract() const { return Abstract; }
270
271  /// canLosslesslyBitCastTo - Return true if this type could be converted
272  /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts
273  /// are valid for types of the same size only where no re-interpretation of
274  /// the bits is done.
275  /// @brief Determine if this type could be losslessly bitcast to Ty
276  bool canLosslesslyBitCastTo(const Type *Ty) const;
277
278
279  /// Here are some useful little methods to query what type derived types are
280  /// Note that all other types can just compare to see if this == Type::xxxTy;
281  ///
282  inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
283  inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
284
285  /// isFirstClassType - Return true if the type is "first class", meaning it
286  /// is a valid type for a Value.
287  ///
288  inline bool isFirstClassType() const {
289    // There are more first-class kinds than non-first-class kinds, so a
290    // negative test is simpler than a positive one.
291    return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
292  }
293
294  /// isSingleValueType - Return true if the type is a valid type for a
295  /// virtual register in codegen.  This includes all first-class types
296  /// except struct and array types.
297  ///
298  inline bool isSingleValueType() const {
299    return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
300            ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
301  }
302
303  /// isAggregateType - Return true if the type is an aggregate type. This
304  /// means it is valid as the first operand of an insertvalue or
305  /// extractvalue instruction. This includes struct and array types, but
306  /// does not include vector types.
307  ///
308  inline bool isAggregateType() const {
309    return ID == StructTyID || ID == ArrayTyID || ID == UnionTyID;
310  }
311
312  /// isSized - Return true if it makes sense to take the size of this type.  To
313  /// get the actual size for a particular target, it is reasonable to use the
314  /// TargetData subsystem to do this.
315  ///
316  bool isSized() const {
317    // If it's a primitive, it is always sized.
318    if (ID == IntegerTyID || isFloatingPointTy() || ID == PointerTyID)
319      return true;
320    // If it is not something that can have a size (e.g. a function or label),
321    // it doesn't have a size.
322    if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID &&
323        ID != UnionTyID)
324      return false;
325    // If it is something that can have a size and it's concrete, it definitely
326    // has a size, otherwise we have to try harder to decide.
327    return !isAbstract() || isSizedDerivedType();
328  }
329
330  /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
331  /// primitive type.  These are fixed by LLVM and are not target dependent.
332  /// This will return zero if the type does not have a size or is not a
333  /// primitive type.
334  ///
335  /// Note that this may not reflect the size of memory allocated for an
336  /// instance of the type or the number of bytes that are written when an
337  /// instance of the type is stored to memory. The TargetData class provides
338  /// additional query functions to provide this information.
339  ///
340  unsigned getPrimitiveSizeInBits() const;
341
342  /// getScalarSizeInBits - If this is a vector type, return the
343  /// getPrimitiveSizeInBits value for the element type. Otherwise return the
344  /// getPrimitiveSizeInBits value for this type.
345  unsigned getScalarSizeInBits() const;
346
347  /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
348  /// is only valid on floating point types.  If the FP type does not
349  /// have a stable mantissa (e.g. ppc long double), this method returns -1.
350  int getFPMantissaWidth() const;
351
352  /// getForwardedType - Return the type that this type has been resolved to if
353  /// it has been resolved to anything.  This is used to implement the
354  /// union-find algorithm for type resolution, and shouldn't be used by general
355  /// purpose clients.
356  const Type *getForwardedType() const {
357    if (!ForwardType) return 0;
358    return getForwardedTypeInternal();
359  }
360
361  /// getVAArgsPromotedType - Return the type an argument of this type
362  /// will be promoted to if passed through a variable argument
363  /// function.
364  const Type *getVAArgsPromotedType(LLVMContext &C) const;
365
366  /// getScalarType - If this is a vector type, return the element type,
367  /// otherwise return this.
368  const Type *getScalarType() const;
369
370  //===--------------------------------------------------------------------===//
371  // Type Iteration support
372  //
373  typedef PATypeHandle *subtype_iterator;
374  subtype_iterator subtype_begin() const { return ContainedTys; }
375  subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
376
377  /// getContainedType - This method is used to implement the type iterator
378  /// (defined a the end of the file).  For derived types, this returns the
379  /// types 'contained' in the derived type.
380  ///
381  const Type *getContainedType(unsigned i) const {
382    assert(i < NumContainedTys && "Index out of range!");
383    return ContainedTys[i].get();
384  }
385
386  /// getNumContainedTypes - Return the number of types in the derived type.
387  ///
388  unsigned getNumContainedTypes() const { return NumContainedTys; }
389
390  //===--------------------------------------------------------------------===//
391  // Static members exported by the Type class itself.  Useful for getting
392  // instances of Type.
393  //
394
395  /// getPrimitiveType - Return a type based on an identifier.
396  static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
397
398  //===--------------------------------------------------------------------===//
399  // These are the builtin types that are always available...
400  //
401  static const Type *getVoidTy(LLVMContext &C);
402  static const Type *getLabelTy(LLVMContext &C);
403  static const Type *getFloatTy(LLVMContext &C);
404  static const Type *getDoubleTy(LLVMContext &C);
405  static const Type *getMetadataTy(LLVMContext &C);
406  static const Type *getX86_FP80Ty(LLVMContext &C);
407  static const Type *getFP128Ty(LLVMContext &C);
408  static const Type *getPPC_FP128Ty(LLVMContext &C);
409  static const IntegerType *getInt1Ty(LLVMContext &C);
410  static const IntegerType *getInt8Ty(LLVMContext &C);
411  static const IntegerType *getInt16Ty(LLVMContext &C);
412  static const IntegerType *getInt32Ty(LLVMContext &C);
413  static const IntegerType *getInt64Ty(LLVMContext &C);
414
415  //===--------------------------------------------------------------------===//
416  // Convenience methods for getting pointer types with one of the above builtin
417  // types as pointee.
418  //
419  static const PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
420  static const PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
421  static const PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
422  static const PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
423  static const PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
424  static const PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
425  static const PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
426  static const PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
427  static const PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
428  static const PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
429
430  /// Methods for support type inquiry through isa, cast, and dyn_cast:
431  static inline bool classof(const Type *) { return true; }
432
433  void addRef() const {
434    assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
435    ++RefCount;
436  }
437
438  void dropRef() const {
439    assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
440    assert(RefCount && "No objects are currently referencing this object!");
441
442    // If this is the last PATypeHolder using this object, and there are no
443    // PATypeHandles using it, the type is dead, delete it now.
444    if (--RefCount == 0 && AbstractTypeUsers.empty())
445      this->destroy();
446  }
447
448  /// addAbstractTypeUser - Notify an abstract type that there is a new user of
449  /// it.  This function is called primarily by the PATypeHandle class.
450  ///
451  void addAbstractTypeUser(AbstractTypeUser *U) const;
452
453  /// removeAbstractTypeUser - Notify an abstract type that a user of the class
454  /// no longer has a handle to the type.  This function is called primarily by
455  /// the PATypeHandle class.  When there are no users of the abstract type, it
456  /// is annihilated, because there is no way to get a reference to it ever
457  /// again.
458  ///
459  void removeAbstractTypeUser(AbstractTypeUser *U) const;
460
461  /// getPointerTo - Return a pointer to the current type.  This is equivalent
462  /// to PointerType::get(Foo, AddrSpace).
463  const PointerType *getPointerTo(unsigned AddrSpace = 0) const;
464
465private:
466  /// isSizedDerivedType - Derived types like structures and arrays are sized
467  /// iff all of the members of the type are sized as well.  Since asking for
468  /// their size is relatively uncommon, move this operation out of line.
469  bool isSizedDerivedType() const;
470
471  virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
472  virtual void typeBecameConcrete(const DerivedType *AbsTy);
473
474protected:
475  // PromoteAbstractToConcrete - This is an internal method used to calculate
476  // change "Abstract" from true to false when types are refined.
477  void PromoteAbstractToConcrete();
478  friend class TypeMapBase;
479};
480
481//===----------------------------------------------------------------------===//
482// Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
483// These are defined here because they MUST be inlined, yet are dependent on
484// the definition of the Type class.
485//
486inline void PATypeHandle::addUser() {
487  assert(Ty && "Type Handle has a null type!");
488  if (Ty->isAbstract())
489    Ty->addAbstractTypeUser(User);
490}
491inline void PATypeHandle::removeUser() {
492  if (Ty->isAbstract())
493    Ty->removeAbstractTypeUser(User);
494}
495
496// Define inline methods for PATypeHolder.
497
498/// get - This implements the forwarding part of the union-find algorithm for
499/// abstract types.  Before every access to the Type*, we check to see if the
500/// type we are pointing to is forwarding to a new type.  If so, we drop our
501/// reference to the type.
502///
503inline Type* PATypeHolder::get() const {
504  const Type *NewTy = Ty->getForwardedType();
505  if (!NewTy) return const_cast<Type*>(Ty);
506  return *const_cast<PATypeHolder*>(this) = NewTy;
507}
508
509inline void PATypeHolder::addRef() {
510  assert(Ty && "Type Holder has a null type!");
511  if (Ty->isAbstract())
512    Ty->addRef();
513}
514
515inline void PATypeHolder::dropRef() {
516  if (Ty->isAbstract())
517    Ty->dropRef();
518}
519
520
521//===----------------------------------------------------------------------===//
522// Provide specializations of GraphTraits to be able to treat a type as a
523// graph of sub types...
524
525template <> struct GraphTraits<Type*> {
526  typedef Type NodeType;
527  typedef Type::subtype_iterator ChildIteratorType;
528
529  static inline NodeType *getEntryNode(Type *T) { return T; }
530  static inline ChildIteratorType child_begin(NodeType *N) {
531    return N->subtype_begin();
532  }
533  static inline ChildIteratorType child_end(NodeType *N) {
534    return N->subtype_end();
535  }
536};
537
538template <> struct GraphTraits<const Type*> {
539  typedef const Type NodeType;
540  typedef Type::subtype_iterator ChildIteratorType;
541
542  static inline NodeType *getEntryNode(const Type *T) { return T; }
543  static inline ChildIteratorType child_begin(NodeType *N) {
544    return N->subtype_begin();
545  }
546  static inline ChildIteratorType child_end(NodeType *N) {
547    return N->subtype_end();
548  }
549};
550
551template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
552  return Ty.getTypeID() == Type::PointerTyID;
553}
554
555raw_ostream &operator<<(raw_ostream &OS, const Type &T);
556
557} // End llvm namespace
558
559#endif
560