LLVM API Documentation

Type.h

Go to the documentation of this file.
00001 //===-- llvm/Type.h - Classes for handling data types -----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 
00011 #ifndef LLVM_TYPE_H
00012 #define LLVM_TYPE_H
00013 
00014 #include "llvm/AbstractTypeUser.h"
00015 #include "llvm/LLVMContext.h"
00016 #include "llvm/Support/Casting.h"
00017 #include "llvm/Support/DataTypes.h"
00018 #include "llvm/System/Atomic.h"
00019 #include "llvm/ADT/GraphTraits.h"
00020 #include "llvm/ADT/iterator.h"
00021 #include <string>
00022 #include <vector>
00023 
00024 namespace llvm {
00025 
00026 class DerivedType;
00027 class PointerType;
00028 class IntegerType;
00029 class TypeMapBase;
00030 class raw_ostream;
00031 class Module;
00032 
00033 /// This file contains the declaration of the Type class.  For more "Type" type
00034 /// stuff, look in DerivedTypes.h.
00035 ///
00036 /// The instances of the Type class are immutable: once they are created,
00037 /// they are never changed.  Also note that only one instance of a particular
00038 /// type is ever created.  Thus seeing if two types are equal is a matter of
00039 /// doing a trivial pointer comparison. To enforce that no two equal instances
00040 /// are created, Type instances can only be created via static factory methods 
00041 /// in class Type and in derived classes.
00042 /// 
00043 /// Once allocated, Types are never free'd, unless they are an abstract type
00044 /// that is resolved to a more concrete type.
00045 /// 
00046 /// Types themself don't have a name, and can be named either by:
00047 /// - using SymbolTable instance, typically from some Module,
00048 /// - using convenience methods in the Module class (which uses module's 
00049 ///    SymbolTable too).
00050 ///
00051 /// Opaque types are simple derived types with no state.  There may be many
00052 /// different Opaque type objects floating around, but two are only considered
00053 /// identical if they are pointer equals of each other.  This allows us to have
00054 /// two opaque types that end up resolving to different concrete types later.
00055 ///
00056 /// Opaque types are also kinda weird and scary and different because they have
00057 /// to keep a list of uses of the type.  When, through linking, parsing, or
00058 /// bitcode reading, they become resolved, they need to find and update all
00059 /// users of the unknown type, causing them to reference a new, more concrete
00060 /// type.  Opaque types are deleted when their use list dwindles to zero users.
00061 ///
00062 /// @brief Root of type hierarchy
00063 class Type : public AbstractTypeUser {
00064 public:
00065   //===-------------------------------------------------------------------===//
00066   /// Definitions of all of the base types for the Type system.  Based on this
00067   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
00068   /// Note: If you add an element to this, you need to add an element to the
00069   /// Type::getPrimitiveType function, or else things will break!
00070   /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
00071   ///
00072   enum TypeID {
00073     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
00074     VoidTyID = 0,    ///<  0: type with no size
00075     FloatTyID,       ///<  1: 32 bit floating point type
00076     DoubleTyID,      ///<  2: 64 bit floating point type
00077     X86_FP80TyID,    ///<  3: 80 bit floating point type (X87)
00078     FP128TyID,       ///<  4: 128 bit floating point type (112-bit mantissa)
00079     PPC_FP128TyID,   ///<  5: 128 bit floating point type (two 64-bits)
00080     LabelTyID,       ///<  6: Labels
00081     MetadataTyID,    ///<  7: Metadata
00082 
00083     // Derived types... see DerivedTypes.h file...
00084     // Make sure FirstDerivedTyID stays up to date!!!
00085     IntegerTyID,     ///<  8: Arbitrary bit width integers
00086     FunctionTyID,    ///<  9: Functions
00087     StructTyID,      ///< 10: Structures
00088     ArrayTyID,       ///< 11: Arrays
00089     PointerTyID,     ///< 12: Pointers
00090     OpaqueTyID,      ///< 13: Opaque: type with unknown structure
00091     VectorTyID,      ///< 14: SIMD 'packed' format, or other vector type
00092 
00093     NumTypeIDs,                         // Must remain as last defined ID
00094     LastPrimitiveTyID = LabelTyID,
00095     FirstDerivedTyID = IntegerTyID
00096   };
00097 
00098 private:
00099   TypeID   ID : 8;    // The current base type of this type.
00100   bool     Abstract : 1;  // True if type contains an OpaqueType
00101   unsigned SubclassData : 23; //Space for subclasses to store data
00102 
00103   /// RefCount - This counts the number of PATypeHolders that are pointing to
00104   /// this type.  When this number falls to zero, if the type is abstract and
00105   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
00106   /// derived types.
00107   ///
00108   mutable sys::cas_flag RefCount;
00109 
00110   /// Context - This refers to the LLVMContext in which this type was uniqued.
00111   LLVMContext &Context;
00112   friend class LLVMContextImpl;
00113 
00114   const Type *getForwardedTypeInternal() const;
00115 
00116   // Some Type instances are allocated as arrays, some aren't. So we provide
00117   // this method to get the right kind of destruction for the type of Type.
00118   void destroy() const; // const is a lie, this does "delete this"!
00119 
00120 protected:
00121   explicit Type(LLVMContext &C, TypeID id) :
00122                              ID(id), Abstract(false), SubclassData(0),
00123                              RefCount(0), Context(C),
00124                              ForwardType(0), NumContainedTys(0),
00125                              ContainedTys(0) {}
00126   virtual ~Type() {
00127     assert(AbstractTypeUsers.empty() && "Abstract types remain");
00128   }
00129 
00130   /// Types can become nonabstract later, if they are refined.
00131   ///
00132   inline void setAbstract(bool Val) { Abstract = Val; }
00133 
00134   unsigned getRefCount() const { return RefCount; }
00135 
00136   unsigned getSubclassData() const { return SubclassData; }
00137   void setSubclassData(unsigned val) { SubclassData = val; }
00138 
00139   /// ForwardType - This field is used to implement the union find scheme for
00140   /// abstract types.  When types are refined to other types, this field is set
00141   /// to the more refined type.  Only abstract types can be forwarded.
00142   mutable const Type *ForwardType;
00143 
00144 
00145   /// AbstractTypeUsers - Implement a list of the users that need to be notified
00146   /// if I am a type, and I get resolved into a more concrete type.
00147   ///
00148   mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
00149 
00150   /// NumContainedTys - Keeps track of how many PATypeHandle instances there
00151   /// are at the end of this type instance for the list of contained types. It
00152   /// is the subclasses responsibility to set this up. Set to 0 if there are no
00153   /// contained types in this type.
00154   unsigned NumContainedTys;
00155 
00156   /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained 
00157   /// by this Type.  For example, this includes the arguments of a function 
00158   /// type, the elements of a structure, the pointee of a pointer, the element
00159   /// type of an array, etc.  This pointer may be 0 for types that don't 
00160   /// contain other types (Integer, Double, Float).  In general, the subclass 
00161   /// should arrange for space for the PATypeHandles to be included in the 
00162   /// allocation of the type object and set this pointer to the address of the 
00163   /// first element. This allows the Type class to manipulate the ContainedTys 
00164   /// without understanding the subclass's placement for this array.  keeping 
00165   /// it here also allows the subtype_* members to be implemented MUCH more 
00166   /// efficiently, and dynamically very few types do not contain any elements.
00167   PATypeHandle *ContainedTys;
00168 
00169 public:
00170   void print(raw_ostream &O) const;
00171   void print(std::ostream &O) const;
00172 
00173   /// @brief Debugging support: print to stderr
00174   void dump() const;
00175 
00176   /// @brief Debugging support: print to stderr (use type names from context
00177   /// module).
00178   void dump(const Module *Context) const;
00179 
00180   /// getContext - Fetch the LLVMContext in which this type was uniqued.
00181   LLVMContext &getContext() const { return Context; }
00182 
00183   //===--------------------------------------------------------------------===//
00184   // Property accessors for dealing with types... Some of these virtual methods
00185   // are defined in private classes defined in Type.cpp for primitive types.
00186   //
00187 
00188   /// getTypeID - Return the type id for the type.  This will return one
00189   /// of the TypeID enum elements defined above.
00190   ///
00191   inline TypeID getTypeID() const { return ID; }
00192 
00193   /// getDescription - Return the string representation of the type.
00194   std::string getDescription() const;
00195 
00196   /// isInteger - True if this is an instance of IntegerType.
00197   ///
00198   bool isInteger() const { return ID == IntegerTyID; } 
00199 
00200   /// isIntOrIntVector - Return true if this is an integer type or a vector of
00201   /// integer types.
00202   ///
00203   bool isIntOrIntVector() const;
00204   
00205   /// isFloatingPoint - Return true if this is one of the five floating point
00206   /// types
00207   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID ||
00208       ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
00209 
00210   /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
00211   ///
00212   bool isFPOrFPVector() const;
00213   
00214   /// isAbstract - True if the type is either an Opaque type, or is a derived
00215   /// type that includes an opaque type somewhere in it.
00216   ///
00217   inline bool isAbstract() const { return Abstract; }
00218 
00219   /// canLosslesslyBitCastTo - Return true if this type could be converted 
00220   /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts 
00221   /// are valid for types of the same size only where no re-interpretation of 
00222   /// the bits is done.
00223   /// @brief Determine if this type could be losslessly bitcast to Ty
00224   bool canLosslesslyBitCastTo(const Type *Ty) const;
00225 
00226 
00227   /// Here are some useful little methods to query what type derived types are
00228   /// Note that all other types can just compare to see if this == Type::xxxTy;
00229   ///
00230   inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
00231   inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
00232 
00233   /// isFirstClassType - Return true if the type is "first class", meaning it
00234   /// is a valid type for a Value.
00235   ///
00236   inline bool isFirstClassType() const {
00237     // There are more first-class kinds than non-first-class kinds, so a
00238     // negative test is simpler than a positive one.
00239     return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
00240   }
00241 
00242   /// isSingleValueType - Return true if the type is a valid type for a
00243   /// virtual register in codegen.  This includes all first-class types
00244   /// except struct and array types.
00245   ///
00246   inline bool isSingleValueType() const {
00247     return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
00248             ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
00249   }
00250 
00251   /// isAggregateType - Return true if the type is an aggregate type. This
00252   /// means it is valid as the first operand of an insertvalue or
00253   /// extractvalue instruction. This includes struct and array types, but
00254   /// does not include vector types.
00255   ///
00256   inline bool isAggregateType() const {
00257     return ID == StructTyID || ID == ArrayTyID;
00258   }
00259 
00260   /// isSized - Return true if it makes sense to take the size of this type.  To
00261   /// get the actual size for a particular target, it is reasonable to use the
00262   /// TargetData subsystem to do this.
00263   ///
00264   bool isSized() const {
00265     // If it's a primitive, it is always sized.
00266     if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
00267       return true;
00268     // If it is not something that can have a size (e.g. a function or label),
00269     // it doesn't have a size.
00270     if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
00271       return false;
00272     // If it is something that can have a size and it's concrete, it definitely
00273     // has a size, otherwise we have to try harder to decide.
00274     return !isAbstract() || isSizedDerivedType();
00275   }
00276 
00277   /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
00278   /// primitive type.  These are fixed by LLVM and are not target dependent.
00279   /// This will return zero if the type does not have a size or is not a
00280   /// primitive type.
00281   ///
00282   /// Note that this may not reflect the size of memory allocated for an
00283   /// instance of the type or the number of bytes that are written when an
00284   /// instance of the type is stored to memory. The TargetData class provides
00285   /// additional query functions to provide this information.
00286   ///
00287   unsigned getPrimitiveSizeInBits() const;
00288 
00289   /// getScalarSizeInBits - If this is a vector type, return the
00290   /// getPrimitiveSizeInBits value for the element type. Otherwise return the
00291   /// getPrimitiveSizeInBits value for this type.
00292   unsigned getScalarSizeInBits() const;
00293 
00294   /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
00295   /// is only valid on floating point types.  If the FP type does not
00296   /// have a stable mantissa (e.g. ppc long double), this method returns -1.
00297   int getFPMantissaWidth() const;
00298 
00299   /// getForwardedType - Return the type that this type has been resolved to if
00300   /// it has been resolved to anything.  This is used to implement the
00301   /// union-find algorithm for type resolution, and shouldn't be used by general
00302   /// purpose clients.
00303   const Type *getForwardedType() const {
00304     if (!ForwardType) return 0;
00305     return getForwardedTypeInternal();
00306   }
00307 
00308   /// getVAArgsPromotedType - Return the type an argument of this type
00309   /// will be promoted to if passed through a variable argument
00310   /// function.
00311   const Type *getVAArgsPromotedType(LLVMContext &C) const; 
00312 
00313   /// getScalarType - If this is a vector type, return the element type,
00314   /// otherwise return this.
00315   const Type *getScalarType() const;
00316 
00317   //===--------------------------------------------------------------------===//
00318   // Type Iteration support
00319   //
00320   typedef PATypeHandle *subtype_iterator;
00321   subtype_iterator subtype_begin() const { return ContainedTys; }
00322   subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
00323 
00324   /// getContainedType - This method is used to implement the type iterator
00325   /// (defined a the end of the file).  For derived types, this returns the
00326   /// types 'contained' in the derived type.
00327   ///
00328   const Type *getContainedType(unsigned i) const {
00329     assert(i < NumContainedTys && "Index out of range!");
00330     return ContainedTys[i].get();
00331   }
00332 
00333   /// getNumContainedTypes - Return the number of types in the derived type.
00334   ///
00335   unsigned getNumContainedTypes() const { return NumContainedTys; }
00336 
00337   //===--------------------------------------------------------------------===//
00338   // Static members exported by the Type class itself.  Useful for getting
00339   // instances of Type.
00340   //
00341 
00342   /// getPrimitiveType - Return a type based on an identifier.
00343   static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
00344 
00345   //===--------------------------------------------------------------------===//
00346   // These are the builtin types that are always available...
00347   //
00348   static const Type *getVoidTy(LLVMContext &C);
00349   static const Type *getLabelTy(LLVMContext &C);
00350   static const Type *getFloatTy(LLVMContext &C);
00351   static const Type *getDoubleTy(LLVMContext &C);
00352   static const Type *getMetadataTy(LLVMContext &C);
00353   static const Type *getX86_FP80Ty(LLVMContext &C);
00354   static const Type *getFP128Ty(LLVMContext &C);
00355   static const Type *getPPC_FP128Ty(LLVMContext &C);
00356   static const IntegerType *getInt1Ty(LLVMContext &C);
00357   static const IntegerType *getInt8Ty(LLVMContext &C);
00358   static const IntegerType *getInt16Ty(LLVMContext &C);
00359   static const IntegerType *getInt32Ty(LLVMContext &C);
00360   static const IntegerType *getInt64Ty(LLVMContext &C);
00361 
00362   /// Methods for support type inquiry through isa, cast, and dyn_cast:
00363   static inline bool classof(const Type *) { return true; }
00364 
00365   void addRef() const {
00366     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
00367     sys::AtomicIncrement(&RefCount);
00368   }
00369 
00370   void dropRef() const {
00371     assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
00372     assert(RefCount && "No objects are currently referencing this object!");
00373 
00374     // If this is the last PATypeHolder using this object, and there are no
00375     // PATypeHandles using it, the type is dead, delete it now.
00376     sys::cas_flag OldCount = sys::AtomicDecrement(&RefCount);
00377     if (OldCount == 0 && AbstractTypeUsers.empty())
00378       this->destroy();
00379   }
00380   
00381   /// addAbstractTypeUser - Notify an abstract type that there is a new user of
00382   /// it.  This function is called primarily by the PATypeHandle class.
00383   ///
00384   void addAbstractTypeUser(AbstractTypeUser *U) const;
00385   
00386   /// removeAbstractTypeUser - Notify an abstract type that a user of the class
00387   /// no longer has a handle to the type.  This function is called primarily by
00388   /// the PATypeHandle class.  When there are no users of the abstract type, it
00389   /// is annihilated, because there is no way to get a reference to it ever
00390   /// again.
00391   ///
00392   void removeAbstractTypeUser(AbstractTypeUser *U) const;
00393 
00394   /// getPointerTo - Return a pointer to the current type.  This is equivalent
00395   /// to PointerType::get(Foo, AddrSpace).
00396   PointerType *getPointerTo(unsigned AddrSpace = 0) const;
00397 
00398 private:
00399   /// isSizedDerivedType - Derived types like structures and arrays are sized
00400   /// iff all of the members of the type are sized as well.  Since asking for
00401   /// their size is relatively uncommon, move this operation out of line.
00402   bool isSizedDerivedType() const;
00403 
00404   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
00405   virtual void typeBecameConcrete(const DerivedType *AbsTy);
00406 
00407 protected:
00408   // PromoteAbstractToConcrete - This is an internal method used to calculate
00409   // change "Abstract" from true to false when types are refined.
00410   void PromoteAbstractToConcrete();
00411   friend class TypeMapBase;
00412 };
00413 
00414 //===----------------------------------------------------------------------===//
00415 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
00416 // These are defined here because they MUST be inlined, yet are dependent on
00417 // the definition of the Type class.
00418 //
00419 inline void PATypeHandle::addUser() {
00420   assert(Ty && "Type Handle has a null type!");
00421   if (Ty->isAbstract())
00422     Ty->addAbstractTypeUser(User);
00423 }
00424 inline void PATypeHandle::removeUser() {
00425   if (Ty->isAbstract())
00426     Ty->removeAbstractTypeUser(User);
00427 }
00428 
00429 // Define inline methods for PATypeHolder.
00430 
00431 /// get - This implements the forwarding part of the union-find algorithm for
00432 /// abstract types.  Before every access to the Type*, we check to see if the
00433 /// type we are pointing to is forwarding to a new type.  If so, we drop our
00434 /// reference to the type.
00435 ///
00436 inline Type* PATypeHolder::get() const {
00437   const Type *NewTy = Ty->getForwardedType();
00438   if (!NewTy) return const_cast<Type*>(Ty);
00439   return *const_cast<PATypeHolder*>(this) = NewTy;
00440 }
00441 
00442 inline void PATypeHolder::addRef() {
00443   assert(Ty && "Type Holder has a null type!");
00444   if (Ty->isAbstract())
00445     Ty->addRef();
00446 }
00447 
00448 inline void PATypeHolder::dropRef() {
00449   if (Ty->isAbstract())
00450     Ty->dropRef();
00451 }
00452 
00453 
00454 //===----------------------------------------------------------------------===//
00455 // Provide specializations of GraphTraits to be able to treat a type as a
00456 // graph of sub types...
00457 
00458 template <> struct GraphTraits<Type*> {
00459   typedef Type NodeType;
00460   typedef Type::subtype_iterator ChildIteratorType;
00461 
00462   static inline NodeType *getEntryNode(Type *T) { return T; }
00463   static inline ChildIteratorType child_begin(NodeType *N) {
00464     return N->subtype_begin();
00465   }
00466   static inline ChildIteratorType child_end(NodeType *N) {
00467     return N->subtype_end();
00468   }
00469 };
00470 
00471 template <> struct GraphTraits<const Type*> {
00472   typedef const Type NodeType;
00473   typedef Type::subtype_iterator ChildIteratorType;
00474 
00475   static inline NodeType *getEntryNode(const Type *T) { return T; }
00476   static inline ChildIteratorType child_begin(NodeType *N) {
00477     return N->subtype_begin();
00478   }
00479   static inline ChildIteratorType child_end(NodeType *N) {
00480     return N->subtype_end();
00481   }
00482 };
00483 
00484 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
00485   return Ty.getTypeID() == Type::PointerTyID;
00486 }
00487 
00488 std::ostream &operator<<(std::ostream &OS, const Type &T);
00489 raw_ostream &operator<<(raw_ostream &OS, const Type &T);
00490 
00491 } // End llvm namespace
00492 
00493 #endif