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