439ac18bf4cecafb0cbb576e8f2428d8f4f1e6a9
[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 DerivedType;
26 class PointerType;
27 class IntegerType;
28 class TypeMapBase;
29
30 /// This file contains the declaration of the Type class.  For more "Type" type
31 /// stuff, look in DerivedTypes.h.
32 ///
33 /// The instances of the Type class are immutable: once they are created,
34 /// they are never changed.  Also note that only one instance of a particular
35 /// type is ever created.  Thus seeing if two types are equal is a matter of
36 /// doing a trivial pointer comparison. To enforce that no two equal instances
37 /// are created, Type instances can only be created via static factory methods 
38 /// in class Type and in derived classes.
39 /// 
40 /// Once allocated, Types are never free'd, unless they are an abstract type
41 /// that is resolved to a more concrete type.
42 /// 
43 /// Types themself don't have a name, and can be named either by:
44 /// - using SymbolTable instance, typically from some Module,
45 /// - using convenience methods in the Module class (which uses module's 
46 ///    SymbolTable too).
47 ///
48 /// Opaque types are simple derived types with no state.  There may be many
49 /// different Opaque type objects floating around, but two are only considered
50 /// identical if they are pointer equals of each other.  This allows us to have
51 /// two opaque types that end up resolving to different concrete types later.
52 ///
53 /// Opaque types are also kinda weird and scary and different because they have
54 /// to keep a list of uses of the type.  When, through linking, parsing, or
55 /// bytecode reading, they become resolved, they need to find and update all
56 /// users of the unknown type, causing them to reference a new, more concrete
57 /// type.  Opaque types are deleted when their use list dwindles to zero users.
58 ///
59 /// @brief Root of type hierarchy
60 class Type : public AbstractTypeUser {
61 public:
62   //===-------------------------------------------------------------------===//
63   /// Definitions of all of the base types for the Type system.  Based on this
64   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
65   /// Note: If you add an element to this, you need to add an element to the
66   /// Type::getPrimitiveType function, or else things will break!
67   ///
68   enum TypeID {
69     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
70     VoidTyID = 0,    ///<  0: type with no size
71     FloatTyID,       ///<  1: 32 bit floating point type
72     DoubleTyID,      ///<  2: 64 bit floating point type
73     LabelTyID,       ///<  3: Labels
74
75     // Derived types... see DerivedTypes.h file...
76     // Make sure FirstDerivedTyID stays up to date!!!
77     IntegerTyID,     ///<  4: Arbitrary bit width integers
78     FunctionTyID,    ///<  5: Functions
79     StructTyID,      ///<  6: Structures
80     PackedStructTyID,///<  7: Packed Structure. This is for bytecode only
81     ArrayTyID,       ///<  8: Arrays
82     PointerTyID,     ///<  9: Pointers
83     OpaqueTyID,      ///< 10: Opaque: type with unknown structure
84     VectorTyID,      ///< 11: SIMD 'packed' format, or other vector type
85
86     NumTypeIDs,                         // Must remain as last defined ID
87     LastPrimitiveTyID = LabelTyID,
88     FirstDerivedTyID = IntegerTyID
89   };
90
91 private:
92   TypeID   ID : 8;    // The current base type of this type.
93   bool     Abstract : 1;  // True if type contains an OpaqueType
94   unsigned SubclassData : 23; //Space for subclasses to store data
95
96   /// RefCount - This counts the number of PATypeHolders that are pointing to
97   /// this type.  When this number falls to zero, if the type is abstract and
98   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
99   /// derived types.
100   ///
101   mutable unsigned RefCount;
102
103   const Type *getForwardedTypeInternal() const;
104 protected:
105   Type(const char *Name, TypeID id);
106   explicit Type(TypeID id) : ID(id), Abstract(false), SubclassData(0),
107                              RefCount(0), ForwardType(0) {}
108   virtual ~Type() {
109     assert(AbstractTypeUsers.empty());
110   }
111
112   /// Types can become nonabstract later, if they are refined.
113   ///
114   inline void setAbstract(bool Val) { Abstract = Val; }
115
116   unsigned getRefCount() const { return RefCount; }
117
118   unsigned getSubclassData() const { return SubclassData; }
119   void setSubclassData(unsigned val) { SubclassData = val; }
120
121   /// ForwardType - This field is used to implement the union find scheme for
122   /// abstract types.  When types are refined to other types, this field is set
123   /// to the more refined type.  Only abstract types can be forwarded.
124   mutable const Type *ForwardType;
125
126   /// ContainedTys - The list of types contained by this one.  For example, this
127   /// includes the arguments of a function type, the elements of the structure,
128   /// the pointee of a pointer, etc.  Note that keeping this vector in the Type
129   /// class wastes some space for types that do not contain anything (such as
130   /// primitive types).  However, keeping it here allows the subtype_* members
131   /// to be implemented MUCH more efficiently, and dynamically very few types do
132   /// not contain any elements (most are derived).
133   std::vector<PATypeHandle> ContainedTys;
134
135   /// AbstractTypeUsers - Implement a list of the users that need to be notified
136   /// if I am a type, and I get resolved into a more concrete type.
137   ///
138   mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
139 public:
140   void print(std::ostream &O) const;
141   void print(std::ostream *O) const { if (O) print(*O); }
142
143   /// @brief Debugging support: print to stderr
144   void dump() const;
145
146   //===--------------------------------------------------------------------===//
147   // Property accessors for dealing with types... Some of these virtual methods
148   // are defined in private classes defined in Type.cpp for primitive types.
149   //
150
151   /// getTypeID - Return the type id for the type.  This will return one
152   /// of the TypeID enum elements defined above.
153   ///
154   inline TypeID getTypeID() const { return ID; }
155
156   /// getDescription - Return the string representation of the type...
157   const std::string &getDescription() const;
158
159   /// isInteger - True if this is an instance of IntegerType.
160   ///
161   bool isInteger() const { return ID == IntegerTyID; } 
162
163   /// isFloatingPoint - Return true if this is one of the two floating point
164   /// types
165   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID; }
166
167   /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
168   ///
169   bool isFPOrFPVector() const;
170   
171   /// isAbstract - True if the type is either an Opaque type, or is a derived
172   /// type that includes an opaque type somewhere in it.
173   ///
174   inline bool isAbstract() const { return Abstract; }
175
176   /// canLosslesslyBitCastTo - Return true if this type could be converted 
177   /// with a lossless BitCast to type 'Ty'. For example, uint to int. BitCasts 
178   /// are valid for types of the same size only where no re-interpretation of 
179   /// the bits is done.
180   /// @brief Determine if this type could be losslessly bitcast to Ty
181   bool canLosslesslyBitCastTo(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   ///
192   inline bool isFirstClassType() const {
193     return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
194             ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
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     // If it's a primitive, it is always sized.
203     if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
204       return true;
205     // If it is not something that can have a size (e.g. a function or label),
206     // it doesn't have a size.
207     if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID &&
208         ID != PackedStructTyID)
209       return false;
210     // If it is something that can have a size and it's concrete, it definitely
211     // has a size, otherwise we have to try harder to decide.
212     return !isAbstract() || isSizedDerivedType();
213   }
214
215   /// getPrimitiveSize - Return the basic size of this type if it is a primitive
216   /// type.  These are fixed by LLVM and are not target dependent.  This will
217   /// return zero if the type does not have a size or is not a primitive type.
218   ///
219   unsigned getPrimitiveSizeInBits() const;
220
221   /// getForwaredType - Return the type that this type has been resolved to if
222   /// it has been resolved to anything.  This is used to implement the
223   /// union-find algorithm for type resolution, and shouldn't be used by general
224   /// purpose clients.
225   const Type *getForwardedType() const {
226     if (!ForwardType) return 0;
227     return getForwardedTypeInternal();
228   }
229
230   /// getVAArgsPromotedType - Return the type an argument of this type
231   /// will be promoted to if passed through a variable argument
232   /// function.
233   const Type *getVAArgsPromotedType() const; 
234
235   //===--------------------------------------------------------------------===//
236   // Type Iteration support
237   //
238   typedef std::vector<PATypeHandle>::const_iterator subtype_iterator;
239   subtype_iterator subtype_begin() const { return ContainedTys.begin(); }
240   subtype_iterator subtype_end() const { return ContainedTys.end(); }
241
242   /// getContainedType - This method is used to implement the type iterator
243   /// (defined a the end of the file).  For derived types, this returns the
244   /// types 'contained' in the derived type.
245   ///
246   const Type *getContainedType(unsigned i) const {
247     assert(i < ContainedTys.size() && "Index out of range!");
248     return ContainedTys[i];
249   }
250
251   /// getNumContainedTypes - Return the number of types in the derived type.
252   ///
253   typedef std::vector<PATypeHandle>::size_type size_type;
254   size_type getNumContainedTypes() const { return ContainedTys.size(); }
255
256   //===--------------------------------------------------------------------===//
257   // Static members exported by the Type class itself.  Useful for getting
258   // instances of Type.
259   //
260
261   /// getPrimitiveType - Return a type based on an identifier.
262   static const Type *getPrimitiveType(TypeID IDNumber);
263
264   //===--------------------------------------------------------------------===//
265   // These are the builtin types that are always available...
266   //
267   static const Type *VoidTy, *LabelTy, *FloatTy, *DoubleTy;
268   static const IntegerType *Int1Ty, *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
269
270   /// Methods for support type inquiry through isa, cast, and dyn_cast:
271   static inline bool classof(const Type *T) { return true; }
272
273   void addRef() const {
274     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
275     ++RefCount;
276   }
277
278   void dropRef() const {
279     assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
280     assert(RefCount && "No objects are currently referencing this object!");
281
282     // If this is the last PATypeHolder using this object, and there are no
283     // PATypeHandles using it, the type is dead, delete it now.
284     if (--RefCount == 0 && AbstractTypeUsers.empty())
285       delete this;
286   }
287   
288   /// addAbstractTypeUser - Notify an abstract type that there is a new user of
289   /// it.  This function is called primarily by the PATypeHandle class.
290   ///
291   void addAbstractTypeUser(AbstractTypeUser *U) const {
292     assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
293     AbstractTypeUsers.push_back(U);
294   }
295   
296   /// removeAbstractTypeUser - Notify an abstract type that a user of the class
297   /// no longer has a handle to the type.  This function is called primarily by
298   /// the PATypeHandle class.  When there are no users of the abstract type, it
299   /// is annihilated, because there is no way to get a reference to it ever
300   /// again.
301   ///
302   void removeAbstractTypeUser(AbstractTypeUser *U) const;
303
304 private:
305   /// isSizedDerivedType - Derived types like structures and arrays are sized
306   /// iff all of the members of the type are sized as well.  Since asking for
307   /// their size is relatively uncommon, move this operation out of line.
308   bool isSizedDerivedType() const;
309
310   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
311   virtual void typeBecameConcrete(const DerivedType *AbsTy);
312
313 protected:
314   // PromoteAbstractToConcrete - This is an internal method used to calculate
315   // change "Abstract" from true to false when types are refined.
316   void PromoteAbstractToConcrete();
317   friend class TypeMapBase;
318 };
319
320 //===----------------------------------------------------------------------===//
321 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
322 // These are defined here because they MUST be inlined, yet are dependent on
323 // the definition of the Type class.
324 //
325 inline void PATypeHandle::addUser() {
326   assert(Ty && "Type Handle has a null type!");
327   if (Ty->isAbstract())
328     Ty->addAbstractTypeUser(User);
329 }
330 inline void PATypeHandle::removeUser() {
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
348 //===----------------------------------------------------------------------===//
349 // Provide specializations of GraphTraits to be able to treat a type as a
350 // graph of sub types...
351
352 template <> struct GraphTraits<Type*> {
353   typedef Type NodeType;
354   typedef Type::subtype_iterator ChildIteratorType;
355
356   static inline NodeType *getEntryNode(Type *T) { return T; }
357   static inline ChildIteratorType child_begin(NodeType *N) {
358     return N->subtype_begin();
359   }
360   static inline ChildIteratorType child_end(NodeType *N) {
361     return N->subtype_end();
362   }
363 };
364
365 template <> struct GraphTraits<const Type*> {
366   typedef const Type NodeType;
367   typedef Type::subtype_iterator ChildIteratorType;
368
369   static inline NodeType *getEntryNode(const Type *T) { return T; }
370   static inline ChildIteratorType child_begin(NodeType *N) {
371     return N->subtype_begin();
372   }
373   static inline ChildIteratorType child_end(NodeType *N) {
374     return N->subtype_end();
375   }
376 };
377
378 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
379   return Ty.getTypeID() == Type::PointerTyID;
380 }
381
382 std::ostream &operator<<(std::ostream &OS, const Type &T);
383
384 } // End llvm namespace
385
386 #endif