Doxygen-ify comments
[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 // This file contains the declaration of the Type class.  For more "Type" type
11 // stuff, look in DerivedTypes.h.
12 //
13 // Note that instances of the Type class are immutable: once they are created,
14 // they are never changed.  Also note that only one instance of a particular 
15 // type is ever created.  Thus seeing if two types are equal is a matter of 
16 // doing a trivial pointer comparison.
17 //
18 // Types, once allocated, are never free'd, unless they are an abstract type
19 // that is resolved to a more concrete type.
20 //
21 // Opaque types are simple derived types with no state.  There may be many
22 // different Opaque type objects floating around, but two are only considered
23 // identical if they are pointer equals of each other.  This allows us to have 
24 // two opaque types that end up resolving to different concrete types later.
25 //
26 // Opaque types are also kinda wierd and scary and different because they have
27 // to keep a list of uses of the type.  When, through linking, parsing, or
28 // bytecode reading, they become resolved, they need to find and update all
29 // users of the unknown type, causing them to reference a new, more concrete
30 // type.  Opaque types are deleted when their use list dwindles to zero users.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #ifndef LLVM_TYPE_H
35 #define LLVM_TYPE_H
36
37 #include "AbstractTypeUser.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/ADT/GraphTraits.h"
40 #include "llvm/ADT/iterator"
41 #include <vector>
42
43 namespace llvm {
44
45 class ArrayType;
46 class DerivedType;
47 class FunctionType;
48 class OpaqueType;
49 class PointerType;
50 class StructType;
51 class PackedType;
52
53 class Type {
54 public:
55   ///===-------------------------------------------------------------------===//
56   /// Definitions of all of the base types for the Type system.  Based on this
57   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
58   /// Note: If you add an element to this, you need to add an element to the 
59   /// Type::getPrimitiveType function, or else things will break!
60   ///
61   enum TypeID {
62     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
63     VoidTyID = 0  , BoolTyID,           //  0, 1: Basics...
64     UByteTyID     , SByteTyID,          //  2, 3: 8 bit types...
65     UShortTyID    , ShortTyID,          //  4, 5: 16 bit types...
66     UIntTyID      , IntTyID,            //  6, 7: 32 bit types...
67     ULongTyID     , LongTyID,           //  8, 9: 64 bit types...
68     FloatTyID     , DoubleTyID,         // 10,11: Floating point types...
69     LabelTyID     ,                     // 12   : Labels... 
70
71     // Derived types... see DerivedTypes.h file...
72     // Make sure FirstDerivedTyID stays up to date!!!
73     FunctionTyID  , StructTyID,         // Functions... Structs...
74     ArrayTyID     , PointerTyID,        // Array... pointer...
75     OpaqueTyID,                         // Opaque type instances...
76     PackedTyID,                         // SIMD 'packed' format... 
77     //...
78
79     NumTypeIDs,                         // Must remain as last defined ID
80     LastPrimitiveTyID = LabelTyID,
81     FirstDerivedTyID = FunctionTyID,
82   };
83
84 private:
85   TypeID   ID : 8;    // The current base type of this type.
86   bool     Abstract;  // True if type contains an OpaqueType
87
88   /// RefCount - This counts the number of PATypeHolders that are pointing to
89   /// this type.  When this number falls to zero, if the type is abstract and
90   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
91   /// derived types.
92   ///
93   mutable unsigned RefCount;
94
95   const Type *getForwardedTypeInternal() const;
96 protected:
97   Type(const std::string& Name, TypeID id);
98   virtual ~Type() {}
99
100   /// Types can become nonabstract later, if they are refined.
101   ///
102   inline void setAbstract(bool Val) { Abstract = Val; }
103
104   /// PromoteAbstractToConcrete - This is an internal method used to calculate
105   /// change "Abstract" from true to false when types are refined.
106   ///
107   bool PromoteAbstractToConcrete(void *);
108
109   unsigned getRefCount() const { return RefCount; }
110
111   /// ForwardType - This field is used to implement the union find scheme for
112   /// abstract types.  When types are refined to other types, this field is set
113   /// to the more refined type.  Only abstract types can be forwarded.
114   mutable const Type *ForwardType;
115
116   /// ContainedTys - The list of types contained by this one.  For example, this
117   /// includes the arguments of a function type, the elements of the structure,
118   /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
119   /// class wastes some space for types that do not contain anything (such as
120   /// primitive types).  However, keeping it here allows the subtype_* members
121   /// to be implemented MUCH more efficiently, and dynamically very few types do
122   /// not contain any elements (most are derived).
123   std::vector<PATypeHandle> ContainedTys;
124
125 public:
126   virtual void print(std::ostream &O) const;
127
128   /// @brief Debugging support: print to stderr
129   virtual void dump() const;
130
131   //===--------------------------------------------------------------------===//
132   // Property accessors for dealing with types... Some of these virtual methods
133   // are defined in private classes defined in Type.cpp for primitive types.
134   //
135
136   /// getTypeID - Return the type id for the type.  This will return one
137   /// of the TypeID enum elements defined above.
138   ///
139   inline TypeID getTypeID() const { return ID; }
140
141   /// getDescription - Return the string representation of the type...
142   const std::string &getDescription() const;
143
144   /// isSigned - Return whether an integral numeric type is signed.  This is
145   /// true for SByteTy, ShortTy, IntTy, LongTy.  Note that this is not true for
146   /// Float and Double.
147   ///
148   bool isSigned() const {
149     return ID == SByteTyID || ID == ShortTyID || 
150            ID == IntTyID || ID == LongTyID; 
151   }
152   
153   /// isUnsigned - Return whether a numeric type is unsigned.  This is not quite
154   /// the complement of isSigned... nonnumeric types return false as they do
155   /// with isSigned.  This returns true for UByteTy, UShortTy, UIntTy, and
156   /// ULongTy
157   /// 
158   bool isUnsigned() const {
159     return ID == UByteTyID || ID == UShortTyID || 
160            ID == UIntTyID || ID == ULongTyID; 
161   }
162
163   /// isInteger - Equivalent to isSigned() || isUnsigned()
164   ///
165   bool isInteger() const { return ID >= UByteTyID && ID <= LongTyID; }
166
167   /// isIntegral - Returns true if this is an integral type, which is either
168   /// BoolTy or one of the Integer types.
169   ///
170   bool isIntegral() const { return isInteger() || this == BoolTy; }
171
172   /// isFloatingPoint - Return true if this is one of the two floating point
173   /// types
174   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
175
176   /// isAbstract - True if the type is either an Opaque type, or is a derived
177   /// type that includes an opaque type somewhere in it.  
178   ///
179   inline bool isAbstract() const { return Abstract; }
180
181   /// isLosslesslyConvertibleTo - Return true if this type can be converted to
182   /// 'Ty' without any reinterpretation of bits.  For example, uint to int.
183   ///
184   bool isLosslesslyConvertibleTo(const Type *Ty) const;
185
186
187   /// Here are some useful little methods to query what type derived types are
188   /// Note that all other types can just compare to see if this == Type::xxxTy;
189   ///
190   inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
191   inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
192
193   /// isFirstClassType - Return true if the value is holdable in a register.
194   inline bool isFirstClassType() const {
195     return (ID != VoidTyID && ID <= LastPrimitiveTyID) || 
196             ID == PointerTyID || ID == PackedTyID;
197   }
198
199   /// isSized - Return true if it makes sense to take the size of this type.  To
200   /// get the actual size for a particular target, it is reasonable to use the
201   /// TargetData subsystem to do this.
202   ///
203   bool isSized() const {
204     return (ID >= BoolTyID && ID <= DoubleTyID) || ID == PointerTyID || 
205            isSizedDerivedType();
206   }
207
208   /// getPrimitiveSize - Return the basic size of this type if it is a primitive
209   /// type.  These are fixed by LLVM and are not target dependent.  This will
210   /// return zero if the type does not have a size or is not a primitive type.
211   ///
212   unsigned getPrimitiveSize() const;
213
214   /// getUnsignedVersion - If this is an integer type, return the unsigned
215   /// variant of this type.  For example int -> uint.
216   const Type *getUnsignedVersion() const;
217
218   /// getSignedVersion - If this is an integer type, return the signed variant
219   /// of this type.  For example uint -> int.
220   const Type *getSignedVersion() const;
221
222   /// getForwaredType - Return the type that this type has been resolved to if
223   /// it has been resolved to anything.  This is used to implement the
224   /// union-find algorithm for type resolution, and shouldn't be used by general
225   /// purpose clients.
226   const Type *getForwardedType() const {
227     if (!ForwardType) return 0;
228     return getForwardedTypeInternal();
229   }
230
231   //===--------------------------------------------------------------------===//
232   // Type Iteration support
233   //
234   typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
235   subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
236   subtype_iterator subtype_end() const { return ContainedTys.end(); }
237
238   /// getContainedType - This method is used to implement the type iterator
239   /// (defined a the end of the file).  For derived types, this returns the
240   /// types 'contained' in the derived type.
241   ///
242   const Type *getContainedType(unsigned i) const {
243     assert(i < ContainedTys.size() && "Index out of range!");
244     return ContainedTys[i];
245   }
246
247   /// getNumContainedTypes - Return the number of types in the derived type.
248   ///
249   unsigned getNumContainedTypes() const { return ContainedTys.size(); }
250
251   //===--------------------------------------------------------------------===//
252   // Static members exported by the Type class itself.  Useful for getting
253   // instances of Type.
254   //
255
256   /// getPrimitiveType - Return a type based on an identifier.
257   static const Type *getPrimitiveType(TypeID IDNumber);
258
259   //===--------------------------------------------------------------------===//
260   // These are the builtin types that are always available...
261   //
262   static Type *VoidTy , *BoolTy;
263   static Type *SByteTy, *UByteTy,
264               *ShortTy, *UShortTy,
265               *IntTy  , *UIntTy, 
266               *LongTy , *ULongTy;
267   static Type *FloatTy, *DoubleTy;
268
269   static Type* LabelTy;
270
271   /// Methods for support type inquiry through isa, cast, and dyn_cast:
272   static inline bool classof(const Type *T) { return true; }
273
274 #include "llvm/Type.def"
275
276   // Virtual methods used by callbacks below.  These should only be implemented
277   // in the DerivedType class.
278   virtual void addAbstractTypeUser(AbstractTypeUser *U) const {
279     abort(); // Only on derived types!
280   }
281   virtual void removeAbstractTypeUser(AbstractTypeUser *U) const {
282     abort(); // Only on derived types!
283   }
284
285   void addRef() const {
286     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
287     ++RefCount;
288   }
289   
290   void dropRef() const {
291     assert(isAbstract() && "Cannot drop a refernce to a non-abstract type!");
292     assert(RefCount && "No objects are currently referencing this object!");
293
294     // If this is the last PATypeHolder using this object, and there are no
295     // PATypeHandles using it, the type is dead, delete it now.
296     if (--RefCount == 0)
297       RefCountIsZero();
298   }
299 private:
300   /// isSizedDerivedType - Derived types like structures and arrays are sized
301   /// iff all of the members of the type are sized as well.  Since asking for
302   /// their size is relatively uncommon, move this operation out of line.
303   bool isSizedDerivedType() const;
304
305   virtual void RefCountIsZero() const {
306     abort(); // only on derived types!
307   }
308
309 };
310
311 //===----------------------------------------------------------------------===//
312 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
313 // These are defined here because they MUST be inlined, yet are dependent on 
314 // the definition of the Type class.  Of course Type derives from Value, which
315 // contains an AbstractTypeUser instance, so there is no good way to factor out
316 // the code.  Hence this bit of uglyness.
317 //
318 // In the long term, Type should not derive from Value, allowing
319 // AbstractTypeUser.h to #include Type.h, allowing us to eliminate this
320 // nastyness entirely.
321 //
322 inline void PATypeHandle::addUser() {
323   assert(Ty && "Type Handle has a null type!");
324   if (Ty->isAbstract())
325     Ty->addAbstractTypeUser(User);
326 }
327 inline void PATypeHandle::removeUser() {
328   if (Ty->isAbstract())
329     Ty->removeAbstractTypeUser(User);
330 }
331
332 inline void PATypeHandle::removeUserFromConcrete() {
333   if (!Ty->isAbstract())
334     Ty->removeAbstractTypeUser(User);
335 }
336
337 // Define inline methods for PATypeHolder...
338
339 inline void PATypeHolder::addRef() {
340   if (Ty->isAbstract())
341     Ty->addRef();
342 }
343
344 inline void PATypeHolder::dropRef() {
345   if (Ty->isAbstract())
346     Ty->dropRef();
347 }
348
349 /// get - This implements the forwarding part of the union-find algorithm for
350 /// abstract types.  Before every access to the Type*, we check to see if the
351 /// type we are pointing to is forwarding to a new type.  If so, we drop our
352 /// reference to the type.
353 ///
354 inline Type* PATypeHolder::get() const {
355   const Type *NewTy = Ty->getForwardedType();
356   if (!NewTy) return const_cast<Type*>(Ty);
357   return *const_cast<PATypeHolder*>(this) = NewTy;
358 }
359
360
361
362 //===----------------------------------------------------------------------===//
363 // Provide specializations of GraphTraits to be able to treat a type as a 
364 // graph of sub types...
365
366 template <> struct GraphTraits<Type*> {
367   typedef Type NodeType;
368   typedef Type::subtype_iterator ChildIteratorType;
369
370   static inline NodeType *getEntryNode(Type *T) { return T; }
371   static inline ChildIteratorType child_begin(NodeType *N) { 
372     return N->subtype_begin(); 
373   }
374   static inline ChildIteratorType child_end(NodeType *N) { 
375     return N->subtype_end();
376   }
377 };
378
379 template <> struct GraphTraits<const Type*> {
380   typedef const Type NodeType;
381   typedef Type::subtype_iterator ChildIteratorType;
382
383   static inline NodeType *getEntryNode(const 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
392 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) { 
393   return Ty.getTypeID() == Type::PointerTyID;
394 }
395
396 std::ostream &operator<<(std::ostream &OS, const Type &T);
397
398 } // End llvm namespace
399
400 #endif