ASTContext.h revision fe8ec01bba74f6841576a2ee93d2c62cdfa4eff2
1//===--- ASTContext.h - Context to hold long-lived AST nodes ----*- 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 defines the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/OperatorKinds.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/PrettyPrinter.h"
25#include "clang/AST/TemplateName.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/CanonicalType.h"
28#include "clang/AST/UsuallyTinyPtrVector.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/FoldingSet.h"
31#include "llvm/ADT/OwningPtr.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/Support/Allocator.h"
34#include <vector>
35
36namespace llvm {
37  struct fltSemantics;
38  class raw_ostream;
39}
40
41namespace clang {
42  class FileManager;
43  class ASTRecordLayout;
44  class BlockExpr;
45  class CharUnits;
46  class Diagnostic;
47  class Expr;
48  class ExternalASTSource;
49  class IdentifierTable;
50  class SelectorTable;
51  class SourceManager;
52  class TargetInfo;
53  // Decls
54  class DeclContext;
55  class CXXMethodDecl;
56  class CXXRecordDecl;
57  class Decl;
58  class FieldDecl;
59  class ObjCIvarDecl;
60  class ObjCIvarRefExpr;
61  class ObjCPropertyDecl;
62  class RecordDecl;
63  class StoredDeclsMap;
64  class TagDecl;
65  class TemplateTemplateParmDecl;
66  class TemplateTypeParmDecl;
67  class TranslationUnitDecl;
68  class TypeDecl;
69  class TypedefDecl;
70  class UsingDecl;
71  class UsingShadowDecl;
72  class UnresolvedSetIterator;
73
74  namespace Builtin { class Context; }
75
76/// ASTContext - This class holds long-lived AST nodes (such as types and
77/// decls) that can be referred to throughout the semantic analysis of a file.
78class ASTContext {
79  ASTContext &this_() { return *this; }
80
81  std::vector<Type*> Types;
82  llvm::FoldingSet<ExtQuals> ExtQualNodes;
83  llvm::FoldingSet<ComplexType> ComplexTypes;
84  llvm::FoldingSet<PointerType> PointerTypes;
85  llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
86  llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
87  llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
88  llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
89  llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
90  llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
91  std::vector<VariableArrayType*> VariableArrayTypes;
92  llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
93  llvm::FoldingSet<DependentSizedExtVectorType> DependentSizedExtVectorTypes;
94  llvm::FoldingSet<VectorType> VectorTypes;
95  llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
96  llvm::FoldingSet<FunctionProtoType> FunctionProtoTypes;
97  llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
98  llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
99  llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
100  llvm::FoldingSet<SubstTemplateTypeParmType> SubstTemplateTypeParmTypes;
101  llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
102    TemplateSpecializationTypes;
103  llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
104  llvm::FoldingSet<DependentNameType> DependentNameTypes;
105  llvm::ContextualFoldingSet<DependentTemplateSpecializationType, ASTContext&>
106    DependentTemplateSpecializationTypes;
107  llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
108  llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
109
110  llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
111  llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
112
113  /// \brief The set of nested name specifiers.
114  ///
115  /// This set is managed by the NestedNameSpecifier class.
116  llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
117  NestedNameSpecifier *GlobalNestedNameSpecifier;
118  friend class NestedNameSpecifier;
119
120  /// ASTRecordLayouts - A cache mapping from RecordDecls to ASTRecordLayouts.
121  ///  This is lazily created.  This is intentionally not serialized.
122  llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*> ASTRecordLayouts;
123  llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*> ObjCLayouts;
124
125  /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
126  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
127
128  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
129  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
130
131  /// \brief Representation of a "canonical" template template parameter that
132  /// is used in canonical template names.
133  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
134    TemplateTemplateParmDecl *Parm;
135
136  public:
137    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
138      : Parm(Parm) { }
139
140    TemplateTemplateParmDecl *getParam() const { return Parm; }
141
142    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
143
144    static void Profile(llvm::FoldingSetNodeID &ID,
145                        TemplateTemplateParmDecl *Parm);
146  };
147  llvm::FoldingSet<CanonicalTemplateTemplateParm> CanonTemplateTemplateParms;
148
149  TemplateTemplateParmDecl *getCanonicalTemplateTemplateParmDecl(
150                                               TemplateTemplateParmDecl *TTP);
151
152  /// BuiltinVaListType - built-in va list type.
153  /// This is initially null and set by Sema::LazilyCreateBuiltin when
154  /// a builtin that takes a valist is encountered.
155  QualType BuiltinVaListType;
156
157  /// ObjCIdType - a pseudo built-in typedef type (set by Sema).
158  QualType ObjCIdTypedefType;
159
160  /// ObjCSelType - another pseudo built-in typedef type (set by Sema).
161  QualType ObjCSelTypedefType;
162
163  /// ObjCProtoType - another pseudo built-in typedef type (set by Sema).
164  QualType ObjCProtoType;
165  const RecordType *ProtoStructType;
166
167  /// ObjCClassType - another pseudo built-in typedef type (set by Sema).
168  QualType ObjCClassTypedefType;
169
170  QualType ObjCConstantStringType;
171  RecordDecl *CFConstantStringTypeDecl;
172
173  RecordDecl *NSConstantStringTypeDecl;
174
175  RecordDecl *ObjCFastEnumerationStateTypeDecl;
176
177  /// \brief The type for the C FILE type.
178  TypeDecl *FILEDecl;
179
180  /// \brief The type for the C jmp_buf type.
181  TypeDecl *jmp_bufDecl;
182
183  /// \brief The type for the C sigjmp_buf type.
184  TypeDecl *sigjmp_bufDecl;
185
186  /// \brief Type for the Block descriptor for Blocks CodeGen.
187  RecordDecl *BlockDescriptorType;
188
189  /// \brief Type for the Block descriptor for Blocks CodeGen.
190  RecordDecl *BlockDescriptorExtendedType;
191
192  TypeSourceInfo NullTypeSourceInfo;
193
194  /// \brief Keeps track of all declaration attributes.
195  ///
196  /// Since so few decls have attrs, we keep them in a hash map instead of
197  /// wasting space in the Decl class.
198  llvm::DenseMap<const Decl*, Attr*> DeclAttrs;
199
200  /// \brief Keeps track of the static data member templates from which
201  /// static data members of class template specializations were instantiated.
202  ///
203  /// This data structure stores the mapping from instantiations of static
204  /// data members to the static data member representations within the
205  /// class template from which they were instantiated along with the kind
206  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
207  ///
208  /// Given the following example:
209  ///
210  /// \code
211  /// template<typename T>
212  /// struct X {
213  ///   static T value;
214  /// };
215  ///
216  /// template<typename T>
217  ///   T X<T>::value = T(17);
218  ///
219  /// int *x = &X<int>::value;
220  /// \endcode
221  ///
222  /// This mapping will contain an entry that maps from the VarDecl for
223  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
224  /// class template X) and will be marked TSK_ImplicitInstantiation.
225  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
226    InstantiatedFromStaticDataMember;
227
228  /// \brief Keeps track of the declaration from which a UsingDecl was
229  /// created during instantiation.  The source declaration is always
230  /// a UsingDecl, an UnresolvedUsingValueDecl, or an
231  /// UnresolvedUsingTypenameDecl.
232  ///
233  /// For example:
234  /// \code
235  /// template<typename T>
236  /// struct A {
237  ///   void f();
238  /// };
239  ///
240  /// template<typename T>
241  /// struct B : A<T> {
242  ///   using A<T>::f;
243  /// };
244  ///
245  /// template struct B<int>;
246  /// \endcode
247  ///
248  /// This mapping will contain an entry that maps from the UsingDecl in
249  /// B<int> to the UnresolvedUsingDecl in B<T>.
250  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
251
252  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
253    InstantiatedFromUsingShadowDecl;
254
255  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
256
257  /// \brief Mapping that stores the methods overridden by a given C++
258  /// member function.
259  ///
260  /// Since most C++ member functions aren't virtual and therefore
261  /// don't override anything, we store the overridden functions in
262  /// this map on the side rather than within the CXXMethodDecl structure.
263  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
264  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
265
266  TranslationUnitDecl *TUDecl;
267
268  /// SourceMgr - The associated SourceManager object.
269  SourceManager &SourceMgr;
270
271  /// LangOpts - The language options used to create the AST associated with
272  ///  this ASTContext object.
273  LangOptions LangOpts;
274
275  /// MallocAlloc/BumpAlloc - The allocator objects used to create AST objects.
276  bool FreeMemory;
277  llvm::MallocAllocator MallocAlloc;
278  llvm::BumpPtrAllocator BumpAlloc;
279
280  /// \brief Allocator for partial diagnostics.
281  PartialDiagnostic::StorageAllocator DiagAllocator;
282
283public:
284  const TargetInfo &Target;
285  IdentifierTable &Idents;
286  SelectorTable &Selectors;
287  Builtin::Context &BuiltinInfo;
288  DeclarationNameTable DeclarationNames;
289  llvm::OwningPtr<ExternalASTSource> ExternalSource;
290  clang::PrintingPolicy PrintingPolicy;
291
292  // Typedefs which may be provided defining the structure of Objective-C
293  // pseudo-builtins
294  QualType ObjCIdRedefinitionType;
295  QualType ObjCClassRedefinitionType;
296  QualType ObjCSelRedefinitionType;
297
298  SourceManager& getSourceManager() { return SourceMgr; }
299  const SourceManager& getSourceManager() const { return SourceMgr; }
300  void *Allocate(unsigned Size, unsigned Align = 8) {
301    return FreeMemory ? MallocAlloc.Allocate(Size, Align) :
302                        BumpAlloc.Allocate(Size, Align);
303  }
304  void Deallocate(void *Ptr) {
305    if (FreeMemory)
306      MallocAlloc.Deallocate(Ptr);
307  }
308
309  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
310    return DiagAllocator;
311  }
312
313  const LangOptions& getLangOptions() const { return LangOpts; }
314
315  FullSourceLoc getFullLoc(SourceLocation Loc) const {
316    return FullSourceLoc(Loc,SourceMgr);
317  }
318
319  /// \brief Retrieve the attributes for the given declaration.
320  Attr*& getDeclAttrs(const Decl *D) { return DeclAttrs[D]; }
321
322  /// \brief Erase the attributes corresponding to the given declaration.
323  void eraseDeclAttrs(const Decl *D) { DeclAttrs.erase(D); }
324
325  /// \brief If this variable is an instantiated static data member of a
326  /// class template specialization, returns the templated static data member
327  /// from which it was instantiated.
328  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
329                                                           const VarDecl *Var);
330
331  /// \brief Note that the static data member \p Inst is an instantiation of
332  /// the static data member template \p Tmpl of a class template.
333  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
334                                           TemplateSpecializationKind TSK);
335
336  /// \brief If the given using decl is an instantiation of a
337  /// (possibly unresolved) using decl from a template instantiation,
338  /// return it.
339  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
340
341  /// \brief Remember that the using decl \p Inst is an instantiation
342  /// of the using decl \p Pattern of a class template.
343  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
344
345  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
346                                          UsingShadowDecl *Pattern);
347  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
348
349  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
350
351  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
352
353  // Access to the set of methods overridden by the given C++ method.
354  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
355  overridden_cxx_method_iterator
356  overridden_methods_begin(const CXXMethodDecl *Method) const;
357
358  overridden_cxx_method_iterator
359  overridden_methods_end(const CXXMethodDecl *Method) const;
360
361  /// \brief Note that the given C++ \p Method overrides the given \p
362  /// Overridden method.
363  void addOverriddenMethod(const CXXMethodDecl *Method,
364                           const CXXMethodDecl *Overridden);
365
366  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
367
368
369  // Builtin Types.
370  CanQualType VoidTy;
371  CanQualType BoolTy;
372  CanQualType CharTy;
373  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
374  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
375  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
376  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
377  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
378  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
379  CanQualType FloatTy, DoubleTy, LongDoubleTy;
380  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
381  CanQualType VoidPtrTy, NullPtrTy;
382  CanQualType OverloadTy;
383  CanQualType DependentTy;
384  CanQualType UndeducedAutoTy;
385  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
386
387  ASTContext(const LangOptions& LOpts, SourceManager &SM, const TargetInfo &t,
388             IdentifierTable &idents, SelectorTable &sels,
389             Builtin::Context &builtins,
390             bool FreeMemory = true, unsigned size_reserve=0);
391
392  ~ASTContext();
393
394  /// \brief Attach an external AST source to the AST context.
395  ///
396  /// The external AST source provides the ability to load parts of
397  /// the abstract syntax tree as needed from some external storage,
398  /// e.g., a precompiled header.
399  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
400
401  /// \brief Retrieve a pointer to the external AST source associated
402  /// with this AST context, if any.
403  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
404
405  void PrintStats() const;
406  const std::vector<Type*>& getTypes() const { return Types; }
407
408  //===--------------------------------------------------------------------===//
409  //                           Type Constructors
410  //===--------------------------------------------------------------------===//
411
412private:
413  /// getExtQualType - Return a type with extended qualifiers.
414  QualType getExtQualType(const Type *Base, Qualifiers Quals);
415
416  QualType getTypeDeclTypeSlow(const TypeDecl *Decl);
417
418public:
419  /// getAddSpaceQualType - Return the uniqued reference to the type for an
420  /// address space qualified type with the specified type and address space.
421  /// The resulting type has a union of the qualifiers from T and the address
422  /// space. If T already has an address space specifier, it is silently
423  /// replaced.
424  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace);
425
426  /// getObjCGCQualType - Returns the uniqued reference to the type for an
427  /// objc gc qualified type. The retulting type has a union of the qualifiers
428  /// from T and the gc attribute.
429  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr);
430
431  /// getRestrictType - Returns the uniqued reference to the type for a
432  /// 'restrict' qualified type.  The resulting type has a union of the
433  /// qualifiers from T and 'restrict'.
434  QualType getRestrictType(QualType T) {
435    return T.withFastQualifiers(Qualifiers::Restrict);
436  }
437
438  /// getVolatileType - Returns the uniqued reference to the type for a
439  /// 'volatile' qualified type.  The resulting type has a union of the
440  /// qualifiers from T and 'volatile'.
441  QualType getVolatileType(QualType T);
442
443  /// getConstType - Returns the uniqued reference to the type for a
444  /// 'const' qualified type.  The resulting type has a union of the
445  /// qualifiers from T and 'const'.
446  ///
447  /// It can be reasonably expected that this will always be
448  /// equivalent to calling T.withConst().
449  QualType getConstType(QualType T) { return T.withConst(); }
450
451  /// getNoReturnType - Add or remove the noreturn attribute to the given type
452  /// which must be a FunctionType or a pointer to an allowable type or a
453  /// BlockPointer.
454  QualType getNoReturnType(QualType T, bool AddNoReturn = true);
455
456  /// getCallConvType - Adds the specified calling convention attribute to
457  /// the given type, which must be a FunctionType or a pointer to an
458  /// allowable type.
459  QualType getCallConvType(QualType T, CallingConv CallConv);
460
461  /// getRegParmType - Sets the specified regparm attribute to
462  /// the given type, which must be a FunctionType or a pointer to an
463  /// allowable type.
464  QualType getRegParmType(QualType T, unsigned RegParm);
465
466  /// getComplexType - Return the uniqued reference to the type for a complex
467  /// number with the specified element type.
468  QualType getComplexType(QualType T);
469  CanQualType getComplexType(CanQualType T) {
470    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
471  }
472
473  /// getPointerType - Return the uniqued reference to the type for a pointer to
474  /// the specified type.
475  QualType getPointerType(QualType T);
476  CanQualType getPointerType(CanQualType T) {
477    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
478  }
479
480  /// getBlockPointerType - Return the uniqued reference to the type for a block
481  /// of the specified type.
482  QualType getBlockPointerType(QualType T);
483
484  /// This gets the struct used to keep track of the descriptor for pointer to
485  /// blocks.
486  QualType getBlockDescriptorType();
487
488  // Set the type for a Block descriptor type.
489  void setBlockDescriptorType(QualType T);
490  /// Get the BlockDescriptorType type, or NULL if it hasn't yet been built.
491  QualType getRawBlockdescriptorType() {
492    if (BlockDescriptorType)
493      return getTagDeclType(BlockDescriptorType);
494    return QualType();
495  }
496
497  /// This gets the struct used to keep track of the extended descriptor for
498  /// pointer to blocks.
499  QualType getBlockDescriptorExtendedType();
500
501  // Set the type for a Block descriptor extended type.
502  void setBlockDescriptorExtendedType(QualType T);
503  /// Get the BlockDescriptorExtendedType type, or NULL if it hasn't yet been
504  /// built.
505  QualType getRawBlockdescriptorExtendedType() {
506    if (BlockDescriptorExtendedType)
507      return getTagDeclType(BlockDescriptorExtendedType);
508    return QualType();
509  }
510
511  /// This gets the struct used to keep track of pointer to blocks, complete
512  /// with captured variables.
513  QualType getBlockParmType(bool BlockHasCopyDispose,
514                            llvm::SmallVectorImpl<const Expr *> &Layout);
515
516  /// This builds the struct used for __block variables.
517  QualType BuildByRefType(const char *DeclName, QualType Ty);
518
519  /// Returns true iff we need copy/dispose helpers for the given type.
520  bool BlockRequiresCopying(QualType Ty);
521
522  /// getLValueReferenceType - Return the uniqued reference to the type for an
523  /// lvalue reference to the specified type.
524  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true);
525
526  /// getRValueReferenceType - Return the uniqued reference to the type for an
527  /// rvalue reference to the specified type.
528  QualType getRValueReferenceType(QualType T);
529
530  /// getMemberPointerType - Return the uniqued reference to the type for a
531  /// member pointer to the specified type in the specified class. The class
532  /// is a Type because it could be a dependent name.
533  QualType getMemberPointerType(QualType T, const Type *Cls);
534
535  /// getVariableArrayType - Returns a non-unique reference to the type for a
536  /// variable array of the specified element type.
537  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
538                                ArrayType::ArraySizeModifier ASM,
539                                unsigned EltTypeQuals,
540                                SourceRange Brackets);
541
542  /// getDependentSizedArrayType - Returns a non-unique reference to
543  /// the type for a dependently-sized array of the specified element
544  /// type. FIXME: We will need these to be uniqued, or at least
545  /// comparable, at some point.
546  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
547                                      ArrayType::ArraySizeModifier ASM,
548                                      unsigned EltTypeQuals,
549                                      SourceRange Brackets);
550
551  /// getIncompleteArrayType - Returns a unique reference to the type for a
552  /// incomplete array of the specified element type.
553  QualType getIncompleteArrayType(QualType EltTy,
554                                  ArrayType::ArraySizeModifier ASM,
555                                  unsigned EltTypeQuals);
556
557  /// getConstantArrayType - Return the unique reference to the type for a
558  /// constant array of the specified element type.
559  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
560                                ArrayType::ArraySizeModifier ASM,
561                                unsigned EltTypeQuals);
562
563  /// getVectorType - Return the unique reference to a vector type of
564  /// the specified element type and size. VectorType must be a built-in type.
565  QualType getVectorType(QualType VectorType, unsigned NumElts,
566                         VectorType::AltiVecSpecific AltiVecSpec);
567
568  /// getExtVectorType - Return the unique reference to an extended vector type
569  /// of the specified element type and size.  VectorType must be a built-in
570  /// type.
571  QualType getExtVectorType(QualType VectorType, unsigned NumElts);
572
573  /// getDependentSizedExtVectorType - Returns a non-unique reference to
574  /// the type for a dependently-sized vector of the specified element
575  /// type. FIXME: We will need these to be uniqued, or at least
576  /// comparable, at some point.
577  QualType getDependentSizedExtVectorType(QualType VectorType,
578                                          Expr *SizeExpr,
579                                          SourceLocation AttrLoc);
580
581  /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
582  ///
583  QualType getFunctionNoProtoType(QualType ResultTy,
584                                  const FunctionType::ExtInfo &Info);
585
586  QualType getFunctionNoProtoType(QualType ResultTy) {
587    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
588  }
589
590  /// getFunctionType - Return a normal function type with a typed argument
591  /// list.  isVariadic indicates whether the argument list includes '...'.
592  QualType getFunctionType(QualType ResultTy, const QualType *ArgArray,
593                           unsigned NumArgs, bool isVariadic,
594                           unsigned TypeQuals, bool hasExceptionSpec,
595                           bool hasAnyExceptionSpec,
596                           unsigned NumExs, const QualType *ExArray,
597                           const FunctionType::ExtInfo &Info);
598
599  /// getTypeDeclType - Return the unique reference to the type for
600  /// the specified type declaration.
601  QualType getTypeDeclType(const TypeDecl *Decl,
602                           const TypeDecl *PrevDecl = 0) {
603    assert(Decl && "Passed null for Decl param");
604    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
605
606    if (PrevDecl) {
607      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
608      Decl->TypeForDecl = PrevDecl->TypeForDecl;
609      return QualType(PrevDecl->TypeForDecl, 0);
610    }
611
612    return getTypeDeclTypeSlow(Decl);
613  }
614
615  /// getTypedefType - Return the unique reference to the type for the
616  /// specified typename decl.
617  QualType getTypedefType(const TypedefDecl *Decl);
618
619  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST);
620
621  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
622                                        QualType Replacement);
623
624  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
625                                   bool ParameterPack,
626                                   IdentifierInfo *Name = 0);
627
628  QualType getTemplateSpecializationType(TemplateName T,
629                                         const TemplateArgument *Args,
630                                         unsigned NumArgs,
631                                         QualType Canon = QualType());
632
633  QualType getTemplateSpecializationType(TemplateName T,
634                                         const TemplateArgumentListInfo &Args,
635                                         QualType Canon = QualType());
636
637  TypeSourceInfo *
638  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
639                                    const TemplateArgumentListInfo &Args,
640                                    QualType Canon = QualType());
641
642  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
643                             NestedNameSpecifier *NNS,
644                             QualType NamedType);
645  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
646                                NestedNameSpecifier *NNS,
647                                const IdentifierInfo *Name,
648                                QualType Canon = QualType());
649
650  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
651                                                  NestedNameSpecifier *NNS,
652                                                  const IdentifierInfo *Name,
653                                          const TemplateArgumentListInfo &Args);
654  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
655                                                  NestedNameSpecifier *NNS,
656                                                  const IdentifierInfo *Name,
657                                                  unsigned NumArgs,
658                                                  const TemplateArgument *Args);
659
660  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl);
661
662  QualType getObjCObjectType(QualType Base,
663                             ObjCProtocolDecl * const *Protocols,
664                             unsigned NumProtocols);
665
666  /// getObjCObjectPointerType - Return a ObjCObjectPointerType type
667  /// for the given ObjCObjectType.
668  QualType getObjCObjectPointerType(QualType OIT);
669
670  /// getTypeOfType - GCC extension.
671  QualType getTypeOfExprType(Expr *e);
672  QualType getTypeOfType(QualType t);
673
674  /// getDecltypeType - C++0x decltype.
675  QualType getDecltypeType(Expr *e);
676
677  /// getTagDeclType - Return the unique reference to the type for the
678  /// specified TagDecl (struct/union/class/enum) decl.
679  QualType getTagDeclType(const TagDecl *Decl);
680
681  /// getSizeType - Return the unique type for "size_t" (C99 7.17), defined
682  /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
683  CanQualType getSizeType() const;
684
685  /// getWCharType - In C++, this returns the unique wchar_t type.  In C99, this
686  /// returns a type compatible with the type defined in <stddef.h> as defined
687  /// by the target.
688  QualType getWCharType() const { return WCharTy; }
689
690  /// getSignedWCharType - Return the type of "signed wchar_t".
691  /// Used when in C++, as a GCC extension.
692  QualType getSignedWCharType() const;
693
694  /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
695  /// Used when in C++, as a GCC extension.
696  QualType getUnsignedWCharType() const;
697
698  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
699  /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
700  QualType getPointerDiffType() const;
701
702  // getCFConstantStringType - Return the C structure type used to represent
703  // constant CFStrings.
704  QualType getCFConstantStringType();
705
706  // getNSConstantStringType - Return the C structure type used to represent
707  // constant NSStrings.
708  QualType getNSConstantStringType();
709  /// Get the structure type used to representation NSStrings, or NULL
710  /// if it hasn't yet been built.
711  QualType getRawNSConstantStringType() {
712    if (NSConstantStringTypeDecl)
713      return getTagDeclType(NSConstantStringTypeDecl);
714    return QualType();
715  }
716  void setNSConstantStringType(QualType T);
717
718
719  /// Get the structure type used to representation CFStrings, or NULL
720  /// if it hasn't yet been built.
721  QualType getRawCFConstantStringType() {
722    if (CFConstantStringTypeDecl)
723      return getTagDeclType(CFConstantStringTypeDecl);
724    return QualType();
725  }
726  void setCFConstantStringType(QualType T);
727
728  // This setter/getter represents the ObjC type for an NSConstantString.
729  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
730  QualType getObjCConstantStringInterface() const {
731    return ObjCConstantStringType;
732  }
733
734  //// This gets the struct used to keep track of fast enumerations.
735  QualType getObjCFastEnumerationStateType();
736
737  /// Get the ObjCFastEnumerationState type, or NULL if it hasn't yet
738  /// been built.
739  QualType getRawObjCFastEnumerationStateType() {
740    if (ObjCFastEnumerationStateTypeDecl)
741      return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
742    return QualType();
743  }
744
745  void setObjCFastEnumerationStateType(QualType T);
746
747  /// \brief Set the type for the C FILE type.
748  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
749
750  /// \brief Retrieve the C FILE type.
751  QualType getFILEType() {
752    if (FILEDecl)
753      return getTypeDeclType(FILEDecl);
754    return QualType();
755  }
756
757  /// \brief Set the type for the C jmp_buf type.
758  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
759    this->jmp_bufDecl = jmp_bufDecl;
760  }
761
762  /// \brief Retrieve the C jmp_buf type.
763  QualType getjmp_bufType() {
764    if (jmp_bufDecl)
765      return getTypeDeclType(jmp_bufDecl);
766    return QualType();
767  }
768
769  /// \brief Set the type for the C sigjmp_buf type.
770  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
771    this->sigjmp_bufDecl = sigjmp_bufDecl;
772  }
773
774  /// \brief Retrieve the C sigjmp_buf type.
775  QualType getsigjmp_bufType() {
776    if (sigjmp_bufDecl)
777      return getTypeDeclType(sigjmp_bufDecl);
778    return QualType();
779  }
780
781  /// getObjCEncodingForType - Emit the ObjC type encoding for the
782  /// given type into \arg S. If \arg NameFields is specified then
783  /// record field names are also encoded.
784  void getObjCEncodingForType(QualType t, std::string &S,
785                              const FieldDecl *Field=0);
786
787  void getLegacyIntegralTypeEncoding(QualType &t) const;
788
789  // Put the string version of type qualifiers into S.
790  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
791                                       std::string &S) const;
792
793  /// getObjCEncodingForMethodDecl - Return the encoded type for this method
794  /// declaration.
795  void getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S);
796
797  /// getObjCEncodingForBlockDecl - Return the encoded type for this block
798  /// declaration.
799  void getObjCEncodingForBlock(const BlockExpr *Expr, std::string& S);
800
801  /// getObjCEncodingForPropertyDecl - Return the encoded type for
802  /// this method declaration. If non-NULL, Container must be either
803  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
804  /// only be NULL when getting encodings for protocol properties.
805  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
806                                      const Decl *Container,
807                                      std::string &S);
808
809  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
810                                      ObjCProtocolDecl *rProto);
811
812  /// getObjCEncodingTypeSize returns size of type for objective-c encoding
813  /// purpose in characters.
814  CharUnits getObjCEncodingTypeSize(QualType t);
815
816  /// This setter/getter represents the ObjC 'id' type. It is setup lazily, by
817  /// Sema.  id is always a (typedef for a) pointer type, a pointer to a struct.
818  QualType getObjCIdType() const { return ObjCIdTypedefType; }
819  void setObjCIdType(QualType T);
820
821  void setObjCSelType(QualType T);
822  QualType getObjCSelType() const { return ObjCSelTypedefType; }
823
824  void setObjCProtoType(QualType QT);
825  QualType getObjCProtoType() const { return ObjCProtoType; }
826
827  /// This setter/getter repreents the ObjC 'Class' type. It is setup lazily, by
828  /// Sema.  'Class' is always a (typedef for a) pointer type, a pointer to a
829  /// struct.
830  QualType getObjCClassType() const { return ObjCClassTypedefType; }
831  void setObjCClassType(QualType T);
832
833  void setBuiltinVaListType(QualType T);
834  QualType getBuiltinVaListType() const { return BuiltinVaListType; }
835
836  /// getCVRQualifiedType - Returns a type with additional const,
837  /// volatile, or restrict qualifiers.
838  QualType getCVRQualifiedType(QualType T, unsigned CVR) {
839    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
840  }
841
842  /// getQualifiedType - Returns a type with additional qualifiers.
843  QualType getQualifiedType(QualType T, Qualifiers Qs) {
844    if (!Qs.hasNonFastQualifiers())
845      return T.withFastQualifiers(Qs.getFastQualifiers());
846    QualifierCollector Qc(Qs);
847    const Type *Ptr = Qc.strip(T);
848    return getExtQualType(Ptr, Qc);
849  }
850
851  /// getQualifiedType - Returns a type with additional qualifiers.
852  QualType getQualifiedType(const Type *T, Qualifiers Qs) {
853    if (!Qs.hasNonFastQualifiers())
854      return QualType(T, Qs.getFastQualifiers());
855    return getExtQualType(T, Qs);
856  }
857
858  DeclarationName getNameForTemplate(TemplateName Name);
859
860  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
861                                         UnresolvedSetIterator End);
862
863  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
864                                        bool TemplateKeyword,
865                                        TemplateDecl *Template);
866
867  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
868                                        const IdentifierInfo *Name);
869  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
870                                        OverloadedOperatorKind Operator);
871
872  enum GetBuiltinTypeError {
873    GE_None,              //< No error
874    GE_Missing_stdio,     //< Missing a type from <stdio.h>
875    GE_Missing_setjmp     //< Missing a type from <setjmp.h>
876  };
877
878  /// GetBuiltinType - Return the type for the specified builtin.
879  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error);
880
881private:
882  CanQualType getFromTargetType(unsigned Type) const;
883
884  //===--------------------------------------------------------------------===//
885  //                         Type Predicates.
886  //===--------------------------------------------------------------------===//
887
888public:
889  /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
890  /// garbage collection attribute.
891  ///
892  Qualifiers::GC getObjCGCAttrKind(const QualType &Ty) const;
893
894  /// isObjCNSObjectType - Return true if this is an NSObject object with
895  /// its NSObject attribute set.
896  bool isObjCNSObjectType(QualType Ty) const;
897
898  //===--------------------------------------------------------------------===//
899  //                         Type Sizing and Analysis
900  //===--------------------------------------------------------------------===//
901
902  /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
903  /// scalar floating point type.
904  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
905
906  /// getTypeInfo - Get the size and alignment of the specified complete type in
907  /// bits.
908  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T);
909  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) {
910    return getTypeInfo(T.getTypePtr());
911  }
912
913  /// getTypeSize - Return the size of the specified type, in bits.  This method
914  /// does not work on incomplete types.
915  uint64_t getTypeSize(QualType T) {
916    return getTypeInfo(T).first;
917  }
918  uint64_t getTypeSize(const Type *T) {
919    return getTypeInfo(T).first;
920  }
921
922  /// getCharWidth - Return the size of the character type, in bits
923  uint64_t getCharWidth() {
924    return getTypeSize(CharTy);
925  }
926
927  /// getTypeSizeInChars - Return the size of the specified type, in characters.
928  /// This method does not work on incomplete types.
929  CharUnits getTypeSizeInChars(QualType T);
930  CharUnits getTypeSizeInChars(const Type *T);
931
932  /// getTypeAlign - Return the ABI-specified alignment of a type, in bits.
933  /// This method does not work on incomplete types.
934  unsigned getTypeAlign(QualType T) {
935    return getTypeInfo(T).second;
936  }
937  unsigned getTypeAlign(const Type *T) {
938    return getTypeInfo(T).second;
939  }
940
941  /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
942  /// characters. This method does not work on incomplete types.
943  CharUnits getTypeAlignInChars(QualType T);
944  CharUnits getTypeAlignInChars(const Type *T);
945
946  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T);
947  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T);
948
949  /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
950  /// type for the current target in bits.  This can be different than the ABI
951  /// alignment in cases where it is beneficial for performance to overalign
952  /// a data type.
953  unsigned getPreferredTypeAlign(const Type *T);
954
955  /// getDeclAlign - Return a conservative estimate of the alignment of
956  /// the specified decl.  Note that bitfields do not have a valid alignment, so
957  /// this method will assert on them.
958  /// If @p RefAsPointee, references are treated like their underlying type
959  /// (for alignof), else they're treated like pointers (for CodeGen).
960  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false);
961
962  /// getASTRecordLayout - Get or compute information about the layout of the
963  /// specified record (struct/union/class), which indicates its size and field
964  /// position information.
965  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D);
966
967  /// getASTObjCInterfaceLayout - Get or compute information about the
968  /// layout of the specified Objective-C interface.
969  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D);
970
971  void DumpRecordLayout(const RecordDecl *RD, llvm::raw_ostream &OS);
972
973  /// getASTObjCImplementationLayout - Get or compute information about
974  /// the layout of the specified Objective-C implementation. This may
975  /// differ from the interface if synthesized ivars are present.
976  const ASTRecordLayout &
977  getASTObjCImplementationLayout(const ObjCImplementationDecl *D);
978
979  /// getKeyFunction - Get the key function for the given record decl, or NULL
980  /// if there isn't one.  The key function is, according to the Itanium C++ ABI
981  /// section 5.2.3:
982  ///
983  /// ...the first non-pure virtual function that is not inline at the point
984  /// of class definition.
985  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
986
987  void CollectObjCIvars(const ObjCInterfaceDecl *OI,
988                        llvm::SmallVectorImpl<FieldDecl*> &Fields);
989
990  void ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
991                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
992  void CollectNonClassIvars(const ObjCInterfaceDecl *OI,
993                               llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars);
994  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI);
995  void CollectInheritedProtocols(const Decl *CDecl,
996                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
997
998  //===--------------------------------------------------------------------===//
999  //                            Type Operators
1000  //===--------------------------------------------------------------------===//
1001
1002  /// getCanonicalType - Return the canonical (structural) type corresponding to
1003  /// the specified potentially non-canonical type.  The non-canonical version
1004  /// of a type may have many "decorated" versions of types.  Decorators can
1005  /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1006  /// to be free of any of these, allowing two canonical types to be compared
1007  /// for exact equality with a simple pointer comparison.
1008  CanQualType getCanonicalType(QualType T);
1009  const Type *getCanonicalType(const Type *T) {
1010    return T->getCanonicalTypeInternal().getTypePtr();
1011  }
1012
1013  /// getCanonicalParamType - Return the canonical parameter type
1014  /// corresponding to the specific potentially non-canonical one.
1015  /// Qualifiers are stripped off, functions are turned into function
1016  /// pointers, and arrays decay one level into pointers.
1017  CanQualType getCanonicalParamType(QualType T);
1018
1019  /// \brief Determine whether the given types are equivalent.
1020  bool hasSameType(QualType T1, QualType T2) {
1021    return getCanonicalType(T1) == getCanonicalType(T2);
1022  }
1023
1024  /// \brief Returns this type as a completely-unqualified array type,
1025  /// capturing the qualifiers in Quals. This will remove the minimal amount of
1026  /// sugaring from the types, similar to the behavior of
1027  /// QualType::getUnqualifiedType().
1028  ///
1029  /// \param T is the qualified type, which may be an ArrayType
1030  ///
1031  /// \param Quals will receive the full set of qualifiers that were
1032  /// applied to the array.
1033  ///
1034  /// \returns if this is an array type, the completely unqualified array type
1035  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1036  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1037
1038  /// \brief Determine whether the given types are equivalent after
1039  /// cvr-qualifiers have been removed.
1040  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
1041    CanQualType CT1 = getCanonicalType(T1);
1042    CanQualType CT2 = getCanonicalType(T2);
1043
1044    Qualifiers Quals;
1045    QualType UnqualT1 = getUnqualifiedArrayType(CT1, Quals);
1046    QualType UnqualT2 = getUnqualifiedArrayType(CT2, Quals);
1047    return UnqualT1 == UnqualT2;
1048  }
1049
1050  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1051
1052  /// \brief Retrieves the "canonical" declaration of
1053
1054  /// \brief Retrieves the "canonical" nested name specifier for a
1055  /// given nested name specifier.
1056  ///
1057  /// The canonical nested name specifier is a nested name specifier
1058  /// that uniquely identifies a type or namespace within the type
1059  /// system. For example, given:
1060  ///
1061  /// \code
1062  /// namespace N {
1063  ///   struct S {
1064  ///     template<typename T> struct X { typename T* type; };
1065  ///   };
1066  /// }
1067  ///
1068  /// template<typename T> struct Y {
1069  ///   typename N::S::X<T>::type member;
1070  /// };
1071  /// \endcode
1072  ///
1073  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1074  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1075  /// by declarations in the type system and the canonical type for
1076  /// the template type parameter 'T' is template-param-0-0.
1077  NestedNameSpecifier *
1078  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS);
1079
1080  /// \brief Retrieves the canonical representation of the given
1081  /// calling convention.
1082  CallingConv getCanonicalCallConv(CallingConv CC) {
1083    if (CC == CC_C)
1084      return CC_Default;
1085    return CC;
1086  }
1087
1088  /// \brief Determines whether two calling conventions name the same
1089  /// calling convention.
1090  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1091    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1092  }
1093
1094  /// \brief Retrieves the "canonical" template name that refers to a
1095  /// given template.
1096  ///
1097  /// The canonical template name is the simplest expression that can
1098  /// be used to refer to a given template. For most templates, this
1099  /// expression is just the template declaration itself. For example,
1100  /// the template std::vector can be referred to via a variety of
1101  /// names---std::vector, ::std::vector, vector (if vector is in
1102  /// scope), etc.---but all of these names map down to the same
1103  /// TemplateDecl, which is used to form the canonical template name.
1104  ///
1105  /// Dependent template names are more interesting. Here, the
1106  /// template name could be something like T::template apply or
1107  /// std::allocator<T>::template rebind, where the nested name
1108  /// specifier itself is dependent. In this case, the canonical
1109  /// template name uses the shortest form of the dependent
1110  /// nested-name-specifier, which itself contains all canonical
1111  /// types, values, and templates.
1112  TemplateName getCanonicalTemplateName(TemplateName Name);
1113
1114  /// \brief Determine whether the given template names refer to the same
1115  /// template.
1116  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1117
1118  /// \brief Retrieve the "canonical" template argument.
1119  ///
1120  /// The canonical template argument is the simplest template argument
1121  /// (which may be a type, value, expression, or declaration) that
1122  /// expresses the value of the argument.
1123  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg);
1124
1125  /// Type Query functions.  If the type is an instance of the specified class,
1126  /// return the Type pointer for the underlying maximally pretty type.  This
1127  /// is a member of ASTContext because this may need to do some amount of
1128  /// canonicalization, e.g. to move type qualifiers into the element type.
1129  const ArrayType *getAsArrayType(QualType T);
1130  const ConstantArrayType *getAsConstantArrayType(QualType T) {
1131    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1132  }
1133  const VariableArrayType *getAsVariableArrayType(QualType T) {
1134    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1135  }
1136  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) {
1137    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1138  }
1139  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T) {
1140    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1141  }
1142
1143  /// getBaseElementType - Returns the innermost element type of an array type.
1144  /// For example, will return "int" for int[m][n]
1145  QualType getBaseElementType(const ArrayType *VAT);
1146
1147  /// getBaseElementType - Returns the innermost element type of a type
1148  /// (which needn't actually be an array type).
1149  QualType getBaseElementType(QualType QT);
1150
1151  /// getConstantArrayElementCount - Returns number of constant array elements.
1152  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1153
1154  /// getArrayDecayedType - Return the properly qualified result of decaying the
1155  /// specified array type to a pointer.  This operation is non-trivial when
1156  /// handling typedefs etc.  The canonical type of "T" must be an array type,
1157  /// this returns a pointer to a properly qualified element of the array.
1158  ///
1159  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1160  QualType getArrayDecayedType(QualType T);
1161
1162  /// getPromotedIntegerType - Returns the type that Promotable will
1163  /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
1164  /// integer type.
1165  QualType getPromotedIntegerType(QualType PromotableType);
1166
1167  /// \brief Whether this is a promotable bitfield reference according
1168  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1169  ///
1170  /// \returns the type this bit-field will promote to, or NULL if no
1171  /// promotion occurs.
1172  QualType isPromotableBitField(Expr *E);
1173
1174  /// getIntegerTypeOrder - Returns the highest ranked integer type:
1175  /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1176  /// LHS < RHS, return -1.
1177  int getIntegerTypeOrder(QualType LHS, QualType RHS);
1178
1179  /// getFloatingTypeOrder - Compare the rank of the two specified floating
1180  /// point types, ignoring the domain of the type (i.e. 'double' ==
1181  /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1182  /// LHS < RHS, return -1.
1183  int getFloatingTypeOrder(QualType LHS, QualType RHS);
1184
1185  /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1186  /// point or a complex type (based on typeDomain/typeSize).
1187  /// 'typeDomain' is a real floating point or complex type.
1188  /// 'typeSize' is a real floating point or complex type.
1189  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1190                                             QualType typeDomain) const;
1191
1192private:
1193  // Helper for integer ordering
1194  unsigned getIntegerRank(Type* T);
1195
1196public:
1197
1198  //===--------------------------------------------------------------------===//
1199  //                    Type Compatibility Predicates
1200  //===--------------------------------------------------------------------===//
1201
1202  /// Compatibility predicates used to check assignment expressions.
1203  bool typesAreCompatible(QualType, QualType); // C99 6.2.7p1
1204
1205  bool typesAreBlockPointerCompatible(QualType, QualType);
1206
1207  bool isObjCIdType(QualType T) const {
1208    return T == ObjCIdTypedefType;
1209  }
1210  bool isObjCClassType(QualType T) const {
1211    return T == ObjCClassTypedefType;
1212  }
1213  bool isObjCSelType(QualType T) const {
1214    return T == ObjCSelTypedefType;
1215  }
1216  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1217  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1218                                         bool ForCompare);
1219
1220  // Check the safety of assignment from LHS to RHS
1221  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1222                               const ObjCObjectPointerType *RHSOPT);
1223  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1224                               const ObjCObjectType *RHS);
1225  bool canAssignObjCInterfacesInBlockPointer(
1226                                          const ObjCObjectPointerType *LHSOPT,
1227                                          const ObjCObjectPointerType *RHSOPT);
1228  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1229  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1230                                   const ObjCObjectPointerType *RHSOPT);
1231
1232  // Functions for calculating composite types
1233  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false);
1234  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false);
1235
1236  QualType mergeObjCGCQualifiers(QualType, QualType);
1237
1238  /// UsualArithmeticConversionsType - handles the various conversions
1239  /// that are common to binary operators (C99 6.3.1.8, C++ [expr]p9)
1240  /// and returns the result type of that conversion.
1241  QualType UsualArithmeticConversionsType(QualType lhs, QualType rhs);
1242
1243  //===--------------------------------------------------------------------===//
1244  //                    Integer Predicates
1245  //===--------------------------------------------------------------------===//
1246
1247  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1248  // of bits in an integer type excluding any padding bits.
1249  unsigned getIntWidth(QualType T);
1250
1251  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1252  // unsigned integer type.  This method takes a signed type, and returns the
1253  // corresponding unsigned integer type.
1254  QualType getCorrespondingUnsignedType(QualType T);
1255
1256  //===--------------------------------------------------------------------===//
1257  //                    Type Iterators.
1258  //===--------------------------------------------------------------------===//
1259
1260  typedef std::vector<Type*>::iterator       type_iterator;
1261  typedef std::vector<Type*>::const_iterator const_type_iterator;
1262
1263  type_iterator types_begin() { return Types.begin(); }
1264  type_iterator types_end() { return Types.end(); }
1265  const_type_iterator types_begin() const { return Types.begin(); }
1266  const_type_iterator types_end() const { return Types.end(); }
1267
1268  //===--------------------------------------------------------------------===//
1269  //                    Integer Values
1270  //===--------------------------------------------------------------------===//
1271
1272  /// MakeIntValue - Make an APSInt of the appropriate width and
1273  /// signedness for the given \arg Value and integer \arg Type.
1274  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) {
1275    llvm::APSInt Res(getIntWidth(Type), !Type->isSignedIntegerType());
1276    Res = Value;
1277    return Res;
1278  }
1279
1280  /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1281  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1282  /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1283  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1284
1285  /// \brief Set the implementation of ObjCInterfaceDecl.
1286  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1287                             ObjCImplementationDecl *ImplD);
1288  /// \brief Set the implementation of ObjCCategoryDecl.
1289  void setObjCImplementation(ObjCCategoryDecl *CatD,
1290                             ObjCCategoryImplDecl *ImplD);
1291
1292  /// \brief Allocate an uninitialized TypeSourceInfo.
1293  ///
1294  /// The caller should initialize the memory held by TypeSourceInfo using
1295  /// the TypeLoc wrappers.
1296  ///
1297  /// \param T the type that will be the basis for type source info. This type
1298  /// should refer to how the declarator was written in source code, not to
1299  /// what type semantic analysis resolved the declarator to.
1300  ///
1301  /// \param Size the size of the type info to create, or 0 if the size
1302  /// should be calculated based on the type.
1303  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0);
1304
1305  /// \brief Allocate a TypeSourceInfo where all locations have been
1306  /// initialized to a given location, which defaults to the empty
1307  /// location.
1308  TypeSourceInfo *
1309  getTrivialTypeSourceInfo(QualType T, SourceLocation Loc = SourceLocation());
1310
1311  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1312
1313  /// \brief Add a deallocation callback that will be invoked when the
1314  /// ASTContext is destroyed.
1315  ///
1316  /// \brief Callback A callback function that will be invoked on destruction.
1317  ///
1318  /// \brief Data Pointer data that will be provided to the callback function
1319  /// when it is called.
1320  void AddDeallocation(void (*Callback)(void*), void *Data);
1321
1322private:
1323  ASTContext(const ASTContext&); // DO NOT IMPLEMENT
1324  void operator=(const ASTContext&); // DO NOT IMPLEMENT
1325
1326  void InitBuiltinTypes();
1327  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
1328
1329  // Return the ObjC type encoding for a given type.
1330  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
1331                                  bool ExpandPointedToStructures,
1332                                  bool ExpandStructures,
1333                                  const FieldDecl *Field,
1334                                  bool OutermostType = false,
1335                                  bool EncodingProperty = false);
1336
1337  const ASTRecordLayout &getObjCLayout(const ObjCInterfaceDecl *D,
1338                                       const ObjCImplementationDecl *Impl);
1339
1340private:
1341  /// \brief A set of deallocations that should be performed when the
1342  /// ASTContext is destroyed.
1343  llvm::SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
1344
1345  // FIXME: This currently contains the set of StoredDeclMaps used
1346  // by DeclContext objects.  This probably should not be in ASTContext,
1347  // but we include it here so that ASTContext can quickly deallocate them.
1348  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
1349
1350  /// \brief A counter used to uniquely identify "blocks".
1351  unsigned int UniqueBlockByRefTypeID;
1352  unsigned int UniqueBlockParmTypeID;
1353
1354  friend class DeclContext;
1355  friend class DeclarationNameTable;
1356  void ReleaseDeclContextMaps();
1357};
1358
1359/// @brief Utility function for constructing a nullary selector.
1360static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
1361  IdentifierInfo* II = &Ctx.Idents.get(name);
1362  return Ctx.Selectors.getSelector(0, &II);
1363}
1364
1365/// @brief Utility function for constructing an unary selector.
1366static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
1367  IdentifierInfo* II = &Ctx.Idents.get(name);
1368  return Ctx.Selectors.getSelector(1, &II);
1369}
1370
1371}  // end namespace clang
1372
1373// operator new and delete aren't allowed inside namespaces.
1374// The throw specifications are mandated by the standard.
1375/// @brief Placement new for using the ASTContext's allocator.
1376///
1377/// This placement form of operator new uses the ASTContext's allocator for
1378/// obtaining memory. It is a non-throwing new, which means that it returns
1379/// null on error. (If that is what the allocator does. The current does, so if
1380/// this ever changes, this operator will have to be changed, too.)
1381/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1382/// @code
1383/// // Default alignment (8)
1384/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
1385/// // Specific alignment
1386/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
1387/// @endcode
1388/// Please note that you cannot use delete on the pointer; it must be
1389/// deallocated using an explicit destructor call followed by
1390/// @c Context.Deallocate(Ptr).
1391///
1392/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1393/// @param C The ASTContext that provides the allocator.
1394/// @param Alignment The alignment of the allocated memory (if the underlying
1395///                  allocator supports it).
1396/// @return The allocated memory. Could be NULL.
1397inline void *operator new(size_t Bytes, clang::ASTContext &C,
1398                          size_t Alignment) throw () {
1399  return C.Allocate(Bytes, Alignment);
1400}
1401/// @brief Placement delete companion to the new above.
1402///
1403/// This operator is just a companion to the new above. There is no way of
1404/// invoking it directly; see the new operator for more details. This operator
1405/// is called implicitly by the compiler if a placement new expression using
1406/// the ASTContext throws in the object constructor.
1407inline void operator delete(void *Ptr, clang::ASTContext &C, size_t)
1408              throw () {
1409  C.Deallocate(Ptr);
1410}
1411
1412/// This placement form of operator new[] uses the ASTContext's allocator for
1413/// obtaining memory. It is a non-throwing new[], which means that it returns
1414/// null on error.
1415/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
1416/// @code
1417/// // Default alignment (8)
1418/// char *data = new (Context) char[10];
1419/// // Specific alignment
1420/// char *data = new (Context, 4) char[10];
1421/// @endcode
1422/// Please note that you cannot use delete on the pointer; it must be
1423/// deallocated using an explicit destructor call followed by
1424/// @c Context.Deallocate(Ptr).
1425///
1426/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
1427/// @param C The ASTContext that provides the allocator.
1428/// @param Alignment The alignment of the allocated memory (if the underlying
1429///                  allocator supports it).
1430/// @return The allocated memory. Could be NULL.
1431inline void *operator new[](size_t Bytes, clang::ASTContext& C,
1432                            size_t Alignment = 8) throw () {
1433  return C.Allocate(Bytes, Alignment);
1434}
1435
1436/// @brief Placement delete[] companion to the new[] above.
1437///
1438/// This operator is just a companion to the new[] above. There is no way of
1439/// invoking it directly; see the new[] operator for more details. This operator
1440/// is called implicitly by the compiler if a placement new[] expression using
1441/// the ASTContext throws in the object constructor.
1442inline void operator delete[](void *Ptr, clang::ASTContext &C, size_t)
1443              throw () {
1444  C.Deallocate(Ptr);
1445}
1446
1447#endif
1448