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