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