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