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