Add another required #include for freestanding .h files.
[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 is distributed under the University of Illinois Open Source
6 // 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/LLVMContext.h"
16 #include "llvm/Support/Casting.h"
17 #include "llvm/Support/DataTypes.h"
18 #include "llvm/System/Atomic.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include <string>
21 #include <vector>
22
23 namespace llvm {
24
25 class DerivedType;
26 class PointerType;
27 class IntegerType;
28 class TypeMapBase;
29 class raw_ostream;
30 class Module;
31
32 /// This file contains the declaration of the Type class.  For more "Type" type
33 /// stuff, look in DerivedTypes.h.
34 ///
35 /// The instances of the Type class are immutable: once they are created,
36 /// they are never changed.  Also note that only one instance of a particular
37 /// type is ever created.  Thus seeing if two types are equal is a matter of
38 /// doing a trivial pointer comparison. To enforce that no two equal instances
39 /// are created, Type instances can only be created via static factory methods 
40 /// in class Type and in derived classes.
41 /// 
42 /// Once allocated, Types are never free'd, unless they are an abstract type
43 /// that is resolved to a more concrete type.
44 /// 
45 /// Types themself don't have a name, and can be named either by:
46 /// - using SymbolTable instance, typically from some Module,
47 /// - using convenience methods in the Module class (which uses module's 
48 ///    SymbolTable too).
49 ///
50 /// Opaque types are simple derived types with no state.  There may be many
51 /// different Opaque type objects floating around, but two are only considered
52 /// identical if they are pointer equals of each other.  This allows us to have
53 /// two opaque types that end up resolving to different concrete types later.
54 ///
55 /// Opaque types are also kinda weird and scary and different because they have
56 /// to keep a list of uses of the type.  When, through linking, parsing, or
57 /// bitcode reading, they become resolved, they need to find and update all
58 /// users of the unknown type, causing them to reference a new, more concrete
59 /// type.  Opaque types are deleted when their use list dwindles to zero users.
60 ///
61 /// @brief Root of type hierarchy
62 class Type : public AbstractTypeUser {
63 public:
64   //===-------------------------------------------------------------------===//
65   /// Definitions of all of the base types for the Type system.  Based on this
66   /// value, you can cast to a "DerivedType" subclass (see DerivedTypes.h)
67   /// Note: If you add an element to this, you need to add an element to the
68   /// Type::getPrimitiveType function, or else things will break!
69   /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
70   ///
71   enum TypeID {
72     // PrimitiveTypes .. make sure LastPrimitiveTyID stays up to date
73     VoidTyID = 0,    ///<  0: type with no size
74     FloatTyID,       ///<  1: 32 bit floating point type
75     DoubleTyID,      ///<  2: 64 bit floating point type
76     X86_FP80TyID,    ///<  3: 80 bit floating point type (X87)
77     FP128TyID,       ///<  4: 128 bit floating point type (112-bit mantissa)
78     PPC_FP128TyID,   ///<  5: 128 bit floating point type (two 64-bits)
79     LabelTyID,       ///<  6: Labels
80     MetadataTyID,    ///<  7: Metadata
81
82     // Derived types... see DerivedTypes.h file...
83     // Make sure FirstDerivedTyID stays up to date!!!
84     IntegerTyID,     ///<  8: Arbitrary bit width integers
85     FunctionTyID,    ///<  9: Functions
86     StructTyID,      ///< 10: Structures
87     ArrayTyID,       ///< 11: Arrays
88     PointerTyID,     ///< 12: Pointers
89     OpaqueTyID,      ///< 13: Opaque: type with unknown structure
90     VectorTyID,      ///< 14: SIMD 'packed' format, or other vector type
91
92     NumTypeIDs,                         // Must remain as last defined ID
93     LastPrimitiveTyID = LabelTyID,
94     FirstDerivedTyID = IntegerTyID
95   };
96
97 private:
98   TypeID   ID : 8;    // The current base type of this type.
99   bool     Abstract : 1;  // True if type contains an OpaqueType
100   unsigned SubclassData : 23; //Space for subclasses to store data
101
102   /// RefCount - This counts the number of PATypeHolders that are pointing to
103   /// this type.  When this number falls to zero, if the type is abstract and
104   /// has no AbstractTypeUsers, the type is deleted.  This is only sensical for
105   /// derived types.
106   ///
107   mutable sys::cas_flag RefCount;
108
109   /// Context - This refers to the LLVMContext in which this type was uniqued.
110   LLVMContext &Context;
111   friend class LLVMContextImpl;
112
113   const Type *getForwardedTypeInternal() const;
114
115   // Some Type instances are allocated as arrays, some aren't. So we provide
116   // this method to get the right kind of destruction for the type of Type.
117   void destroy() const; // const is a lie, this does "delete this"!
118
119 protected:
120   explicit Type(LLVMContext &C, TypeID id) :
121                              ID(id), Abstract(false), SubclassData(0),
122                              RefCount(0), Context(C),
123                              ForwardType(0), NumContainedTys(0),
124                              ContainedTys(0) {}
125   virtual ~Type() {
126     assert(AbstractTypeUsers.empty() && "Abstract types remain");
127   }
128
129   /// Types can become nonabstract later, if they are refined.
130   ///
131   inline void setAbstract(bool Val) { Abstract = Val; }
132
133   unsigned getRefCount() const { return RefCount; }
134
135   unsigned getSubclassData() const { return SubclassData; }
136   void setSubclassData(unsigned val) { SubclassData = val; }
137
138   /// ForwardType - This field is used to implement the union find scheme for
139   /// abstract types.  When types are refined to other types, this field is set
140   /// to the more refined type.  Only abstract types can be forwarded.
141   mutable const Type *ForwardType;
142
143
144   /// AbstractTypeUsers - Implement a list of the users that need to be notified
145   /// if I am a type, and I get resolved into a more concrete type.
146   ///
147   mutable std::vector<AbstractTypeUser *> AbstractTypeUsers;
148
149   /// NumContainedTys - Keeps track of how many PATypeHandle instances there
150   /// are at the end of this type instance for the list of contained types. It
151   /// is the subclasses responsibility to set this up. Set to 0 if there are no
152   /// contained types in this type.
153   unsigned NumContainedTys;
154
155   /// ContainedTys - A pointer to the array of Types (PATypeHandle) contained 
156   /// by this Type.  For example, this includes the arguments of a function 
157   /// type, the elements of a structure, the pointee of a pointer, the element
158   /// type of an array, etc.  This pointer may be 0 for types that don't 
159   /// contain other types (Integer, Double, Float).  In general, the subclass 
160   /// should arrange for space for the PATypeHandles to be included in the 
161   /// allocation of the type object and set this pointer to the address of the 
162   /// first element. This allows the Type class to manipulate the ContainedTys 
163   /// without understanding the subclass's placement for this array.  keeping 
164   /// it here also allows the subtype_* members to be implemented MUCH more 
165   /// efficiently, and dynamically very few types do not contain any elements.
166   PATypeHandle *ContainedTys;
167
168 public:
169   void print(raw_ostream &O) const;
170
171   /// @brief Debugging support: print to stderr
172   void dump() const;
173
174   /// @brief Debugging support: print to stderr (use type names from context
175   /// module).
176   void dump(const Module *Context) const;
177
178   /// getContext - Fetch the LLVMContext in which this type was uniqued.
179   LLVMContext &getContext() const { return Context; }
180
181   //===--------------------------------------------------------------------===//
182   // Property accessors for dealing with types... Some of these virtual methods
183   // are defined in private classes defined in Type.cpp for primitive types.
184   //
185
186   /// getTypeID - Return the type id for the type.  This will return one
187   /// of the TypeID enum elements defined above.
188   ///
189   inline TypeID getTypeID() const { return ID; }
190
191   /// isVoidTy - Return true if this is 'void'.
192   bool isVoidTy() const { return ID == VoidTyID; }
193
194   /// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
195   bool isFloatTy() const { return ID == FloatTyID; }
196   
197   /// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
198   bool isDoubleTy() const { return ID == DoubleTyID; }
199
200   /// isX86_FP80Ty - Return true if this is x86 long double.
201   bool isX86_FP80Ty() const { return ID == X86_FP80TyID; }
202
203   /// isFP128Ty - Return true if this is 'fp128'.
204   bool isFP128Ty() const { return ID == FP128TyID; }
205
206   /// isPPC_FP128Ty - Return true if this is powerpc long double.
207   bool isPPC_FP128Ty() const { return ID == PPC_FP128TyID; }
208
209   /// isLabelTy - Return true if this is 'label'.
210   bool isLabelTy() const { return ID == LabelTyID; }
211
212   /// isMetadataTy - Return true if this is 'metadata'.
213   bool isMetadataTy() const { return ID == MetadataTyID; }
214
215   /// getDescription - Return the string representation of the type.
216   std::string getDescription() const;
217
218   /// isInteger - True if this is an instance of IntegerType.
219   ///
220   bool isInteger() const { return ID == IntegerTyID; } 
221
222   /// isIntOrIntVector - Return true if this is an integer type or a vector of
223   /// integer types.
224   ///
225   bool isIntOrIntVector() const;
226   
227   /// isFloatingPoint - Return true if this is one of the five floating point
228   /// types
229   bool isFloatingPoint() const { return ID == FloatTyID || ID == DoubleTyID ||
230       ID == X86_FP80TyID || ID == FP128TyID || ID == PPC_FP128TyID; }
231
232   /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
233   ///
234   bool isFPOrFPVector() const;
235   
236   /// isAbstract - True if the type is either an Opaque type, or is a derived
237   /// type that includes an opaque type somewhere in it.
238   ///
239   inline bool isAbstract() const { return Abstract; }
240
241   /// canLosslesslyBitCastTo - Return true if this type could be converted 
242   /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts 
243   /// are valid for types of the same size only where no re-interpretation of 
244   /// the bits is done.
245   /// @brief Determine if this type could be losslessly bitcast to Ty
246   bool canLosslesslyBitCastTo(const Type *Ty) const;
247
248
249   /// Here are some useful little methods to query what type derived types are
250   /// Note that all other types can just compare to see if this == Type::xxxTy;
251   ///
252   inline bool isPrimitiveType() const { return ID <= LastPrimitiveTyID; }
253   inline bool isDerivedType()   const { return ID >= FirstDerivedTyID; }
254
255   /// isFirstClassType - Return true if the type is "first class", meaning it
256   /// is a valid type for a Value.
257   ///
258   inline bool isFirstClassType() const {
259     // There are more first-class kinds than non-first-class kinds, so a
260     // negative test is simpler than a positive one.
261     return ID != FunctionTyID && ID != VoidTyID && ID != OpaqueTyID;
262   }
263
264   /// isSingleValueType - Return true if the type is a valid type for a
265   /// virtual register in codegen.  This includes all first-class types
266   /// except struct and array types.
267   ///
268   inline bool isSingleValueType() const {
269     return (ID != VoidTyID && ID <= LastPrimitiveTyID) ||
270             ID == IntegerTyID || ID == PointerTyID || ID == VectorTyID;
271   }
272
273   /// isAggregateType - Return true if the type is an aggregate type. This
274   /// means it is valid as the first operand of an insertvalue or
275   /// extractvalue instruction. This includes struct and array types, but
276   /// does not include vector types.
277   ///
278   inline bool isAggregateType() const {
279     return ID == StructTyID || ID == ArrayTyID;
280   }
281
282   /// isSized - Return true if it makes sense to take the size of this type.  To
283   /// get the actual size for a particular target, it is reasonable to use the
284   /// TargetData subsystem to do this.
285   ///
286   bool isSized() const {
287     // If it's a primitive, it is always sized.
288     if (ID == IntegerTyID || isFloatingPoint() || ID == PointerTyID)
289       return true;
290     // If it is not something that can have a size (e.g. a function or label),
291     // it doesn't have a size.
292     if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
293       return false;
294     // If it is something that can have a size and it's concrete, it definitely
295     // has a size, otherwise we have to try harder to decide.
296     return !isAbstract() || isSizedDerivedType();
297   }
298
299   /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
300   /// primitive type.  These are fixed by LLVM and are not target dependent.
301   /// This will return zero if the type does not have a size or is not a
302   /// primitive type.
303   ///
304   /// Note that this may not reflect the size of memory allocated for an
305   /// instance of the type or the number of bytes that are written when an
306   /// instance of the type is stored to memory. The TargetData class provides
307   /// additional query functions to provide this information.
308   ///
309   unsigned getPrimitiveSizeInBits() const;
310
311   /// getScalarSizeInBits - If this is a vector type, return the
312   /// getPrimitiveSizeInBits value for the element type. Otherwise return the
313   /// getPrimitiveSizeInBits value for this type.
314   unsigned getScalarSizeInBits() const;
315
316   /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
317   /// is only valid on floating point types.  If the FP type does not
318   /// have a stable mantissa (e.g. ppc long double), this method returns -1.
319   int getFPMantissaWidth() const;
320
321   /// getForwardedType - Return the type that this type has been resolved to if
322   /// it has been resolved to anything.  This is used to implement the
323   /// union-find algorithm for type resolution, and shouldn't be used by general
324   /// purpose clients.
325   const Type *getForwardedType() const {
326     if (!ForwardType) return 0;
327     return getForwardedTypeInternal();
328   }
329
330   /// getVAArgsPromotedType - Return the type an argument of this type
331   /// will be promoted to if passed through a variable argument
332   /// function.
333   const Type *getVAArgsPromotedType(LLVMContext &C) const; 
334
335   /// getScalarType - If this is a vector type, return the element type,
336   /// otherwise return this.
337   const Type *getScalarType() const;
338
339   //===--------------------------------------------------------------------===//
340   // Type Iteration support
341   //
342   typedef PATypeHandle *subtype_iterator;
343   subtype_iterator subtype_begin() const { return ContainedTys; }
344   subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
345
346   /// getContainedType - This method is used to implement the type iterator
347   /// (defined a the end of the file).  For derived types, this returns the
348   /// types 'contained' in the derived type.
349   ///
350   const Type *getContainedType(unsigned i) const {
351     assert(i < NumContainedTys && "Index out of range!");
352     return ContainedTys[i].get();
353   }
354
355   /// getNumContainedTypes - Return the number of types in the derived type.
356   ///
357   unsigned getNumContainedTypes() const { return NumContainedTys; }
358
359   //===--------------------------------------------------------------------===//
360   // Static members exported by the Type class itself.  Useful for getting
361   // instances of Type.
362   //
363
364   /// getPrimitiveType - Return a type based on an identifier.
365   static const Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
366
367   //===--------------------------------------------------------------------===//
368   // These are the builtin types that are always available...
369   //
370   static const Type *getVoidTy(LLVMContext &C);
371   static const Type *getLabelTy(LLVMContext &C);
372   static const Type *getFloatTy(LLVMContext &C);
373   static const Type *getDoubleTy(LLVMContext &C);
374   static const Type *getMetadataTy(LLVMContext &C);
375   static const Type *getX86_FP80Ty(LLVMContext &C);
376   static const Type *getFP128Ty(LLVMContext &C);
377   static const Type *getPPC_FP128Ty(LLVMContext &C);
378   static const IntegerType *getInt1Ty(LLVMContext &C);
379   static const IntegerType *getInt8Ty(LLVMContext &C);
380   static const IntegerType *getInt16Ty(LLVMContext &C);
381   static const IntegerType *getInt32Ty(LLVMContext &C);
382   static const IntegerType *getInt64Ty(LLVMContext &C);
383
384   //===--------------------------------------------------------------------===//
385   // Convenience methods for getting pointer types with one of the above builtin
386   // types as pointee.
387   //
388   static const PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
389   static const PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
390   static const PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
391   static const PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
392   static const PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
393   static const PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
394   static const PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
395   static const PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
396   static const PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
397   static const PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
398
399   /// Methods for support type inquiry through isa, cast, and dyn_cast:
400   static inline bool classof(const Type *) { return true; }
401
402   void addRef() const {
403     assert(isAbstract() && "Cannot add a reference to a non-abstract type!");
404     sys::AtomicIncrement(&RefCount);
405   }
406
407   void dropRef() const {
408     assert(isAbstract() && "Cannot drop a reference to a non-abstract type!");
409     assert(RefCount && "No objects are currently referencing this object!");
410
411     // If this is the last PATypeHolder using this object, and there are no
412     // PATypeHandles using it, the type is dead, delete it now.
413     sys::cas_flag OldCount = sys::AtomicDecrement(&RefCount);
414     if (OldCount == 0 && AbstractTypeUsers.empty())
415       this->destroy();
416   }
417   
418   /// addAbstractTypeUser - Notify an abstract type that there is a new user of
419   /// it.  This function is called primarily by the PATypeHandle class.
420   ///
421   void addAbstractTypeUser(AbstractTypeUser *U) const;
422   
423   /// removeAbstractTypeUser - Notify an abstract type that a user of the class
424   /// no longer has a handle to the type.  This function is called primarily by
425   /// the PATypeHandle class.  When there are no users of the abstract type, it
426   /// is annihilated, because there is no way to get a reference to it ever
427   /// again.
428   ///
429   void removeAbstractTypeUser(AbstractTypeUser *U) const;
430
431   /// getPointerTo - Return a pointer to the current type.  This is equivalent
432   /// to PointerType::get(Foo, AddrSpace).
433   const PointerType *getPointerTo(unsigned AddrSpace = 0) const;
434
435 private:
436   /// isSizedDerivedType - Derived types like structures and arrays are sized
437   /// iff all of the members of the type are sized as well.  Since asking for
438   /// their size is relatively uncommon, move this operation out of line.
439   bool isSizedDerivedType() const;
440
441   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
442   virtual void typeBecameConcrete(const DerivedType *AbsTy);
443
444 protected:
445   // PromoteAbstractToConcrete - This is an internal method used to calculate
446   // change "Abstract" from true to false when types are refined.
447   void PromoteAbstractToConcrete();
448   friend class TypeMapBase;
449 };
450
451 //===----------------------------------------------------------------------===//
452 // Define some inline methods for the AbstractTypeUser.h:PATypeHandle class.
453 // These are defined here because they MUST be inlined, yet are dependent on
454 // the definition of the Type class.
455 //
456 inline void PATypeHandle::addUser() {
457   assert(Ty && "Type Handle has a null type!");
458   if (Ty->isAbstract())
459     Ty->addAbstractTypeUser(User);
460 }
461 inline void PATypeHandle::removeUser() {
462   if (Ty->isAbstract())
463     Ty->removeAbstractTypeUser(User);
464 }
465
466 // Define inline methods for PATypeHolder.
467
468 /// get - This implements the forwarding part of the union-find algorithm for
469 /// abstract types.  Before every access to the Type*, we check to see if the
470 /// type we are pointing to is forwarding to a new type.  If so, we drop our
471 /// reference to the type.
472 ///
473 inline Type* PATypeHolder::get() const {
474   const Type *NewTy = Ty->getForwardedType();
475   if (!NewTy) return const_cast<Type*>(Ty);
476   return *const_cast<PATypeHolder*>(this) = NewTy;
477 }
478
479 inline void PATypeHolder::addRef() {
480   assert(Ty && "Type Holder has a null type!");
481   if (Ty->isAbstract())
482     Ty->addRef();
483 }
484
485 inline void PATypeHolder::dropRef() {
486   if (Ty->isAbstract())
487     Ty->dropRef();
488 }
489
490
491 //===----------------------------------------------------------------------===//
492 // Provide specializations of GraphTraits to be able to treat a type as a
493 // graph of sub types...
494
495 template <> struct GraphTraits<Type*> {
496   typedef Type NodeType;
497   typedef Type::subtype_iterator ChildIteratorType;
498
499   static inline NodeType *getEntryNode(Type *T) { return T; }
500   static inline ChildIteratorType child_begin(NodeType *N) {
501     return N->subtype_begin();
502   }
503   static inline ChildIteratorType child_end(NodeType *N) {
504     return N->subtype_end();
505   }
506 };
507
508 template <> struct GraphTraits<const Type*> {
509   typedef const Type NodeType;
510   typedef Type::subtype_iterator ChildIteratorType;
511
512   static inline NodeType *getEntryNode(const Type *T) { return T; }
513   static inline ChildIteratorType child_begin(NodeType *N) {
514     return N->subtype_begin();
515   }
516   static inline ChildIteratorType child_end(NodeType *N) {
517     return N->subtype_end();
518   }
519 };
520
521 template <> inline bool isa_impl<PointerType, Type>(const Type &Ty) {
522   return Ty.getTypeID() == Type::PointerTyID;
523 }
524
525 raw_ostream &operator<<(raw_ostream &OS, const Type &T);
526
527 } // End llvm namespace
528
529 #endif