Reformat.
[oota-llvm.git] / include / llvm / IR / 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 // This file contains the declaration of the Type class.  For more "Type"
11 // stuff, look in DerivedTypes.h.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_IR_TYPE_H
16 #define LLVM_IR_TYPE_H
17
18 #include "llvm-c/Core.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/Support/CBindingWrapping.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/DataTypes.h"
24 #include "llvm/Support/ErrorHandling.h"
25
26 namespace llvm {
27
28 class PointerType;
29 class IntegerType;
30 class raw_ostream;
31 class Module;
32 class LLVMContext;
33 class LLVMContextImpl;
34 class StringRef;
35 template<class GraphType> struct GraphTraits;
36
37 /// The instances of the Type class are immutable: once they are created,
38 /// they are never changed.  Also note that only one instance of a particular
39 /// type is ever created.  Thus seeing if two types are equal is a matter of
40 /// doing a trivial pointer comparison. To enforce that no two equal instances
41 /// are created, Type instances can only be created via static factory methods 
42 /// in class Type and in derived classes.  Once allocated, Types are never
43 /// free'd.
44 /// 
45 class Type {
46 public:
47   //===--------------------------------------------------------------------===//
48   /// Definitions of all of the base types for the Type system.  Based on this
49   /// value, you can cast to a class defined in DerivedTypes.h.
50   /// Note: If you add an element to this, you need to add an element to the
51   /// Type::getPrimitiveType function, or else things will break!
52   /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
53   ///
54   enum TypeID {
55     // PrimitiveTypes - make sure LastPrimitiveTyID stays up to date.
56     VoidTyID = 0,    ///<  0: type with no size
57     HalfTyID,        ///<  1: 16-bit floating point type
58     FloatTyID,       ///<  2: 32-bit floating point type
59     DoubleTyID,      ///<  3: 64-bit floating point type
60     X86_FP80TyID,    ///<  4: 80-bit floating point type (X87)
61     FP128TyID,       ///<  5: 128-bit floating point type (112-bit mantissa)
62     PPC_FP128TyID,   ///<  6: 128-bit floating point type (two 64-bits, PowerPC)
63     LabelTyID,       ///<  7: Labels
64     MetadataTyID,    ///<  8: Metadata
65     X86_MMXTyID,     ///<  9: MMX vectors (64 bits, X86 specific)
66     TokenTyID,       ///< 10: Tokens
67
68     // Derived types... see DerivedTypes.h file.
69     // Make sure FirstDerivedTyID stays up to date!
70     IntegerTyID,     ///< 11: Arbitrary bit width integers
71     FunctionTyID,    ///< 12: Functions
72     StructTyID,      ///< 13: Structures
73     ArrayTyID,       ///< 14: Arrays
74     PointerTyID,     ///< 15: Pointers
75     VectorTyID       ///< 16: SIMD 'packed' format, or other vector type
76   };
77
78 private:
79   /// Context - This refers to the LLVMContext in which this type was uniqued.
80   LLVMContext &Context;
81
82   TypeID   ID : 8;            // The current base type of this type.
83   unsigned SubclassData : 24; // Space for subclasses to store data.
84
85 protected:
86   friend class LLVMContextImpl;
87   explicit Type(LLVMContext &C, TypeID tid)
88     : Context(C), ID(tid), SubclassData(0),
89       NumContainedTys(0), ContainedTys(nullptr) {}
90   ~Type() = default;
91
92   unsigned getSubclassData() const { return SubclassData; }
93
94   void setSubclassData(unsigned val) {
95     SubclassData = val;
96     // Ensure we don't have any accidental truncation.
97     assert(getSubclassData() == val && "Subclass data too large for field");
98   }
99
100   /// NumContainedTys - Keeps track of how many Type*'s there are in the
101   /// ContainedTys list.
102   unsigned NumContainedTys;
103
104   /// ContainedTys - A pointer to the array of Types contained by this Type.
105   /// For example, this includes the arguments of a function type, the elements
106   /// of a structure, the pointee of a pointer, the element type of an array,
107   /// etc.  This pointer may be 0 for types that don't contain other types
108   /// (Integer, Double, Float).
109   Type * const *ContainedTys;
110
111 public:
112   void print(raw_ostream &O) const;
113   void dump() const;
114
115   /// getContext - Return the LLVMContext in which this type was uniqued.
116   LLVMContext &getContext() const { return Context; }
117
118   //===--------------------------------------------------------------------===//
119   // Accessors for working with types.
120   //
121
122   /// getTypeID - Return the type id for the type.  This will return one
123   /// of the TypeID enum elements defined above.
124   ///
125   TypeID getTypeID() const { return ID; }
126
127   /// isVoidTy - Return true if this is 'void'.
128   bool isVoidTy() const { return getTypeID() == VoidTyID; }
129
130   /// isHalfTy - Return true if this is 'half', a 16-bit IEEE fp type.
131   bool isHalfTy() const { return getTypeID() == HalfTyID; }
132
133   /// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
134   bool isFloatTy() const { return getTypeID() == FloatTyID; }
135   
136   /// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
137   bool isDoubleTy() const { return getTypeID() == DoubleTyID; }
138
139   /// isX86_FP80Ty - Return true if this is x86 long double.
140   bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; }
141
142   /// isFP128Ty - Return true if this is 'fp128'.
143   bool isFP128Ty() const { return getTypeID() == FP128TyID; }
144
145   /// isPPC_FP128Ty - Return true if this is powerpc long double.
146   bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; }
147
148   /// isFloatingPointTy - Return true if this is one of the six floating point
149   /// types
150   bool isFloatingPointTy() const {
151     return getTypeID() == HalfTyID || getTypeID() == FloatTyID ||
152            getTypeID() == DoubleTyID ||
153            getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID ||
154            getTypeID() == PPC_FP128TyID;
155   }
156
157   const fltSemantics &getFltSemantics() const {
158     switch (getTypeID()) {
159     case HalfTyID: return APFloat::IEEEhalf;
160     case FloatTyID: return APFloat::IEEEsingle;
161     case DoubleTyID: return APFloat::IEEEdouble;
162     case X86_FP80TyID: return APFloat::x87DoubleExtended;
163     case FP128TyID: return APFloat::IEEEquad;
164     case PPC_FP128TyID: return APFloat::PPCDoubleDouble;
165     default: llvm_unreachable("Invalid floating type");
166     }
167   }
168
169   /// isX86_MMXTy - Return true if this is X86 MMX.
170   bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; }
171
172   /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP.
173   ///
174   bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); }
175  
176   /// isLabelTy - Return true if this is 'label'.
177   bool isLabelTy() const { return getTypeID() == LabelTyID; }
178
179   /// isMetadataTy - Return true if this is 'metadata'.
180   bool isMetadataTy() const { return getTypeID() == MetadataTyID; }
181
182   /// isTokenTy - Return true if this is 'token'.
183   bool isTokenTy() const { return getTypeID() == TokenTyID; }
184
185   /// isIntegerTy - True if this is an instance of IntegerType.
186   ///
187   bool isIntegerTy() const { return getTypeID() == IntegerTyID; } 
188
189   /// isIntegerTy - Return true if this is an IntegerType of the given width.
190   bool isIntegerTy(unsigned Bitwidth) const;
191
192   /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
193   /// integer types.
194   ///
195   bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); }
196   
197   /// isFunctionTy - True if this is an instance of FunctionType.
198   ///
199   bool isFunctionTy() const { return getTypeID() == FunctionTyID; }
200
201   /// isStructTy - True if this is an instance of StructType.
202   ///
203   bool isStructTy() const { return getTypeID() == StructTyID; }
204
205   /// isArrayTy - True if this is an instance of ArrayType.
206   ///
207   bool isArrayTy() const { return getTypeID() == ArrayTyID; }
208
209   /// isPointerTy - True if this is an instance of PointerType.
210   ///
211   bool isPointerTy() const { return getTypeID() == PointerTyID; }
212
213   /// isPtrOrPtrVectorTy - Return true if this is a pointer type or a vector of
214   /// pointer types.
215   ///
216   bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); }
217  
218   /// isVectorTy - True if this is an instance of VectorType.
219   ///
220   bool isVectorTy() const { return getTypeID() == VectorTyID; }
221
222   /// canLosslesslyBitCastTo - Return true if this type could be converted 
223   /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitCasts 
224   /// are valid for types of the same size only where no re-interpretation of 
225   /// the bits is done.
226   /// @brief Determine if this type could be losslessly bitcast to Ty
227   bool canLosslesslyBitCastTo(Type *Ty) const;
228
229   /// isEmptyTy - Return true if this type is empty, that is, it has no
230   /// elements or all its elements are empty.
231   bool isEmptyTy() const;
232
233   /// isFirstClassType - Return true if the type is "first class", meaning it
234   /// is a valid type for a Value.
235   ///
236   bool isFirstClassType() const {
237     return getTypeID() != FunctionTyID && getTypeID() != VoidTyID;
238   }
239
240   /// isSingleValueType - Return true if the type is a valid type for a
241   /// register in codegen.  This includes all first-class types except struct
242   /// and array types.
243   ///
244   bool isSingleValueType() const {
245     return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() ||
246            isPointerTy() || isVectorTy();
247   }
248
249   /// isAggregateType - Return true if the type is an aggregate type. This
250   /// means it is valid as the first operand of an insertvalue or
251   /// extractvalue instruction. This includes struct and array types, but
252   /// does not include vector types.
253   ///
254   bool isAggregateType() const {
255     return getTypeID() == StructTyID || getTypeID() == ArrayTyID;
256   }
257
258   /// isSized - Return true if it makes sense to take the size of this type.  To
259   /// get the actual size for a particular target, it is reasonable to use the
260   /// DataLayout subsystem to do this.
261   ///
262   bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const {
263     // If it's a primitive, it is always sized.
264     if (getTypeID() == IntegerTyID || isFloatingPointTy() ||
265         getTypeID() == PointerTyID ||
266         getTypeID() == X86_MMXTyID)
267       return true;
268     // If it is not something that can have a size (e.g. a function or label),
269     // it doesn't have a size.
270     if (getTypeID() != StructTyID && getTypeID() != ArrayTyID &&
271         getTypeID() != VectorTyID)
272       return false;
273     // Otherwise we have to try harder to decide.
274     return isSizedDerivedType(Visited);
275   }
276
277   /// getPrimitiveSizeInBits - Return the basic size of this type if it is a
278   /// primitive type.  These are fixed by LLVM and are not target dependent.
279   /// This will return zero if the type does not have a size or is not a
280   /// primitive type.
281   ///
282   /// Note that this may not reflect the size of memory allocated for an
283   /// instance of the type or the number of bytes that are written when an
284   /// instance of the type is stored to memory. The DataLayout class provides
285   /// additional query functions to provide this information.
286   ///
287   unsigned getPrimitiveSizeInBits() const LLVM_READONLY;
288
289   /// getScalarSizeInBits - If this is a vector type, return the
290   /// getPrimitiveSizeInBits value for the element type. Otherwise return the
291   /// getPrimitiveSizeInBits value for this type.
292   unsigned getScalarSizeInBits() const LLVM_READONLY;
293
294   /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
295   /// is only valid on floating point types.  If the FP type does not
296   /// have a stable mantissa (e.g. ppc long double), this method returns -1.
297   int getFPMantissaWidth() const;
298
299   /// getScalarType - If this is a vector type, return the element type,
300   /// otherwise return 'this'.
301   Type *getScalarType() const LLVM_READONLY;
302
303   //===--------------------------------------------------------------------===//
304   // Type Iteration support.
305   //
306   typedef Type * const *subtype_iterator;
307   subtype_iterator subtype_begin() const { return ContainedTys; }
308   subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
309   ArrayRef<Type*> subtypes() const {
310     return makeArrayRef(subtype_begin(), subtype_end());
311   }
312
313   typedef std::reverse_iterator<subtype_iterator> subtype_reverse_iterator;
314   subtype_reverse_iterator subtype_rbegin() const {
315     return subtype_reverse_iterator(subtype_end());
316   }
317   subtype_reverse_iterator subtype_rend() const {
318     return subtype_reverse_iterator(subtype_begin());
319   }
320
321   /// getContainedType - This method is used to implement the type iterator
322   /// (defined at the end of the file).  For derived types, this returns the
323   /// types 'contained' in the derived type.
324   ///
325   Type *getContainedType(unsigned i) const {
326     assert(i < NumContainedTys && "Index out of range!");
327     return ContainedTys[i];
328   }
329
330   /// getNumContainedTypes - Return the number of types in the derived type.
331   ///
332   unsigned getNumContainedTypes() const { return NumContainedTys; }
333
334   //===--------------------------------------------------------------------===//
335   // Helper methods corresponding to subclass methods.  This forces a cast to
336   // the specified subclass and calls its accessor.  "getVectorNumElements" (for
337   // example) is shorthand for cast<VectorType>(Ty)->getNumElements().  This is
338   // only intended to cover the core methods that are frequently used, helper
339   // methods should not be added here.
340   
341   unsigned getIntegerBitWidth() const;
342
343   Type *getFunctionParamType(unsigned i) const;
344   unsigned getFunctionNumParams() const;
345   bool isFunctionVarArg() const;
346   
347   StringRef getStructName() const;
348   unsigned getStructNumElements() const;
349   Type *getStructElementType(unsigned N) const;
350   
351   Type *getSequentialElementType() const;
352   
353   uint64_t getArrayNumElements() const;
354   Type *getArrayElementType() const { return getSequentialElementType(); }
355
356   unsigned getVectorNumElements() const;
357   Type *getVectorElementType() const { return getSequentialElementType(); }
358
359   Type *getPointerElementType() const { return getSequentialElementType(); }
360
361   /// \brief Get the address space of this pointer or pointer vector type.
362   unsigned getPointerAddressSpace() const;
363   
364   //===--------------------------------------------------------------------===//
365   // Static members exported by the Type class itself.  Useful for getting
366   // instances of Type.
367   //
368
369   /// getPrimitiveType - Return a type based on an identifier.
370   static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
371
372   //===--------------------------------------------------------------------===//
373   // These are the builtin types that are always available.
374   //
375   static Type *getVoidTy(LLVMContext &C);
376   static Type *getLabelTy(LLVMContext &C);
377   static Type *getHalfTy(LLVMContext &C);
378   static Type *getFloatTy(LLVMContext &C);
379   static Type *getDoubleTy(LLVMContext &C);
380   static Type *getMetadataTy(LLVMContext &C);
381   static Type *getX86_FP80Ty(LLVMContext &C);
382   static Type *getFP128Ty(LLVMContext &C);
383   static Type *getPPC_FP128Ty(LLVMContext &C);
384   static Type *getX86_MMXTy(LLVMContext &C);
385   static Type *getTokenTy(LLVMContext &C);
386   static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
387   static IntegerType *getInt1Ty(LLVMContext &C);
388   static IntegerType *getInt8Ty(LLVMContext &C);
389   static IntegerType *getInt16Ty(LLVMContext &C);
390   static IntegerType *getInt32Ty(LLVMContext &C);
391   static IntegerType *getInt64Ty(LLVMContext &C);
392   static IntegerType *getInt128Ty(LLVMContext &C);
393   
394   //===--------------------------------------------------------------------===//
395   // Convenience methods for getting pointer types with one of the above builtin
396   // types as pointee.
397   //
398   static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0);
399   static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
400   static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
401   static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
402   static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
403   static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
404   static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
405   static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
406   static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
407   static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
408   static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
409   static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
410   static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
411
412   /// getPointerTo - Return a pointer to the current type.  This is equivalent
413   /// to PointerType::get(Foo, AddrSpace).
414   PointerType *getPointerTo(unsigned AddrSpace = 0) const;
415
416 private:
417   /// isSizedDerivedType - Derived types like structures and arrays are sized
418   /// iff all of the members of the type are sized as well.  Since asking for
419   /// their size is relatively uncommon, move this operation out of line.
420   bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const;
421 };
422
423 // Printing of types.
424 static inline raw_ostream &operator<<(raw_ostream &OS, Type &T) {
425   T.print(OS);
426   return OS;
427 }
428
429 // allow isa<PointerType>(x) to work without DerivedTypes.h included.
430 template <> struct isa_impl<PointerType, Type> {
431   static inline bool doit(const Type &Ty) {
432     return Ty.getTypeID() == Type::PointerTyID;
433   }
434 };
435
436   
437 //===----------------------------------------------------------------------===//
438 // Provide specializations of GraphTraits to be able to treat a type as a
439 // graph of sub types.
440
441 template <> struct GraphTraits<Type *> {
442   typedef Type NodeType;
443   typedef Type::subtype_iterator ChildIteratorType;
444
445   static inline NodeType *getEntryNode(Type *T) { return T; }
446   static inline ChildIteratorType child_begin(NodeType *N) {
447     return N->subtype_begin();
448   }
449   static inline ChildIteratorType child_end(NodeType *N) {
450     return N->subtype_end();
451   }
452 };
453
454 template <> struct GraphTraits<const Type*> {
455   typedef const Type NodeType;
456   typedef Type::subtype_iterator ChildIteratorType;
457
458   static inline NodeType *getEntryNode(NodeType *T) { return T; }
459   static inline ChildIteratorType child_begin(NodeType *N) {
460     return N->subtype_begin();
461   }
462   static inline ChildIteratorType child_end(NodeType *N) {
463     return N->subtype_end();
464   }
465 };
466
467 // Create wrappers for C Binding types (see CBindingWrapping.h).
468 DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)
469
470 /* Specialized opaque type conversions.
471  */
472 inline Type **unwrap(LLVMTypeRef* Tys) {
473   return reinterpret_cast<Type**>(Tys);
474 }
475
476 inline LLVMTypeRef *wrap(Type **Tys) {
477   return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys));
478 }
479   
480 } // End llvm namespace
481
482 #endif