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