ASTContext.h revision 749ace614b6ea1ae11d194a60b18e1e43e1db243
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/// \file
11/// \brief Defines the clang::ASTContext interface.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16#define LLVM_CLANG_AST_ASTCONTEXT_H
17
18#include "clang/Basic/AddressSpaces.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/OperatorKinds.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/VersionTuple.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/LambdaMangleContext.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/PrettyPrinter.h"
28#include "clang/AST/TemplateName.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/CanonicalType.h"
31#include "clang/AST/RawCommentList.h"
32#include "clang/AST/CommentCommandTraits.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/FoldingSet.h"
35#include "llvm/ADT/IntrusiveRefCntPtr.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/TinyPtrVector.h"
39#include "llvm/Support/Allocator.h"
40#include <vector>
41
42namespace llvm {
43  struct fltSemantics;
44}
45
46namespace clang {
47  class FileManager;
48  class ASTRecordLayout;
49  class BlockExpr;
50  class CharUnits;
51  class DiagnosticsEngine;
52  class Expr;
53  class ExternalASTSource;
54  class ASTMutationListener;
55  class IdentifierTable;
56  class SelectorTable;
57  class TargetInfo;
58  class CXXABI;
59  // Decls
60  class DeclContext;
61  class CXXConversionDecl;
62  class CXXMethodDecl;
63  class CXXRecordDecl;
64  class Decl;
65  class FieldDecl;
66  class MangleContext;
67  class ObjCIvarDecl;
68  class ObjCIvarRefExpr;
69  class ObjCPropertyDecl;
70  class ParmVarDecl;
71  class RecordDecl;
72  class StoredDeclsMap;
73  class TagDecl;
74  class TemplateTemplateParmDecl;
75  class TemplateTypeParmDecl;
76  class TranslationUnitDecl;
77  class TypeDecl;
78  class TypedefNameDecl;
79  class UsingDecl;
80  class UsingShadowDecl;
81  class UnresolvedSetIterator;
82
83  namespace Builtin { class Context; }
84
85  namespace comments {
86    class FullComment;
87  }
88
89/// \brief Holds long-lived AST nodes (such as types and decls) that can be
90/// referred to throughout the semantic analysis of a file.
91class ASTContext : public RefCountedBase<ASTContext> {
92  ASTContext &this_() { return *this; }
93
94  mutable std::vector<Type*> Types;
95  mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
96  mutable llvm::FoldingSet<ComplexType> ComplexTypes;
97  mutable llvm::FoldingSet<PointerType> PointerTypes;
98  mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
99  mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
100  mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
101  mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
102  mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
103  mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
104  mutable std::vector<VariableArrayType*> VariableArrayTypes;
105  mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
106  mutable llvm::FoldingSet<DependentSizedExtVectorType>
107    DependentSizedExtVectorTypes;
108  mutable llvm::FoldingSet<VectorType> VectorTypes;
109  mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
110  mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
111    FunctionProtoTypes;
112  mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
113  mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
114  mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
115  mutable llvm::FoldingSet<SubstTemplateTypeParmType>
116    SubstTemplateTypeParmTypes;
117  mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
118    SubstTemplateTypeParmPackTypes;
119  mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
120    TemplateSpecializationTypes;
121  mutable llvm::FoldingSet<ParenType> ParenTypes;
122  mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
123  mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
124  mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
125                                     ASTContext&>
126    DependentTemplateSpecializationTypes;
127  llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
128  mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
129  mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
130  mutable llvm::FoldingSet<AutoType> AutoTypes;
131  mutable llvm::FoldingSet<AtomicType> AtomicTypes;
132  llvm::FoldingSet<AttributedType> AttributedTypes;
133
134  mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
135  mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
136  mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
137    SubstTemplateTemplateParms;
138  mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
139                                     ASTContext&>
140    SubstTemplateTemplateParmPacks;
141
142  /// \brief The set of nested name specifiers.
143  ///
144  /// This set is managed by the NestedNameSpecifier class.
145  mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
146  mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
147  friend class NestedNameSpecifier;
148
149  /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
150  ///
151  /// This is lazily created.  This is intentionally not serialized.
152  mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
153    ASTRecordLayouts;
154  mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
155    ObjCLayouts;
156
157  /// \brief A cache from types to size and alignment information.
158  typedef llvm::DenseMap<const Type*,
159                         std::pair<uint64_t, unsigned> > TypeInfoMap;
160  mutable TypeInfoMap MemoizedTypeInfo;
161
162  /// \brief A cache mapping from CXXRecordDecls to key functions.
163  llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
164
165  /// \brief Mapping from ObjCContainers to their ObjCImplementations.
166  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
167
168  /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
169  /// interface.
170  llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
171
172  /// \brief Mapping from __block VarDecls to their copy initialization expr.
173  llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
174
175  /// \brief Mapping from class scope functions specialization to their
176  /// template patterns.
177  llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
178    ClassScopeSpecializationPattern;
179
180  /// \brief Representation of a "canonical" template template parameter that
181  /// is used in canonical template names.
182  class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
183    TemplateTemplateParmDecl *Parm;
184
185  public:
186    CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
187      : Parm(Parm) { }
188
189    TemplateTemplateParmDecl *getParam() const { return Parm; }
190
191    void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
192
193    static void Profile(llvm::FoldingSetNodeID &ID,
194                        TemplateTemplateParmDecl *Parm);
195  };
196  mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
197    CanonTemplateTemplateParms;
198
199  TemplateTemplateParmDecl *
200    getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
201
202  /// \brief The typedef for the __int128_t type.
203  mutable TypedefDecl *Int128Decl;
204
205  /// \brief The typedef for the __uint128_t type.
206  mutable TypedefDecl *UInt128Decl;
207
208  /// \brief The typedef for the target specific predefined
209  /// __builtin_va_list type.
210  mutable TypedefDecl *BuiltinVaListDecl;
211
212  /// \brief The typedef for the predefined \c id type.
213  mutable TypedefDecl *ObjCIdDecl;
214
215  /// \brief The typedef for the predefined \c SEL type.
216  mutable TypedefDecl *ObjCSelDecl;
217
218  /// \brief The typedef for the predefined \c Class type.
219  mutable TypedefDecl *ObjCClassDecl;
220
221  /// \brief The typedef for the predefined \c Protocol class in Objective-C.
222  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
223
224  /// \brief The typedef for the predefined 'BOOL' type.
225  mutable TypedefDecl *BOOLDecl;
226
227  // Typedefs which may be provided defining the structure of Objective-C
228  // pseudo-builtins
229  QualType ObjCIdRedefinitionType;
230  QualType ObjCClassRedefinitionType;
231  QualType ObjCSelRedefinitionType;
232
233  QualType ObjCConstantStringType;
234  mutable RecordDecl *CFConstantStringTypeDecl;
235
236  QualType ObjCNSStringType;
237
238  /// \brief The typedef declaration for the Objective-C "instancetype" type.
239  TypedefDecl *ObjCInstanceTypeDecl;
240
241  /// \brief The type for the C FILE type.
242  TypeDecl *FILEDecl;
243
244  /// \brief The type for the C jmp_buf type.
245  TypeDecl *jmp_bufDecl;
246
247  /// \brief The type for the C sigjmp_buf type.
248  TypeDecl *sigjmp_bufDecl;
249
250  /// \brief The type for the C ucontext_t type.
251  TypeDecl *ucontext_tDecl;
252
253  /// \brief Type for the Block descriptor for Blocks CodeGen.
254  ///
255  /// Since this is only used for generation of debug info, it is not
256  /// serialized.
257  mutable RecordDecl *BlockDescriptorType;
258
259  /// \brief Type for the Block descriptor for Blocks CodeGen.
260  ///
261  /// Since this is only used for generation of debug info, it is not
262  /// serialized.
263  mutable RecordDecl *BlockDescriptorExtendedType;
264
265  /// \brief Declaration for the CUDA cudaConfigureCall function.
266  FunctionDecl *cudaConfigureCallDecl;
267
268  TypeSourceInfo NullTypeSourceInfo;
269
270  /// \brief Keeps track of all declaration attributes.
271  ///
272  /// Since so few decls have attrs, we keep them in a hash map instead of
273  /// wasting space in the Decl class.
274  llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
275
276  /// \brief Keeps track of the static data member templates from which
277  /// static data members of class template specializations were instantiated.
278  ///
279  /// This data structure stores the mapping from instantiations of static
280  /// data members to the static data member representations within the
281  /// class template from which they were instantiated along with the kind
282  /// of instantiation or specialization (a TemplateSpecializationKind - 1).
283  ///
284  /// Given the following example:
285  ///
286  /// \code
287  /// template<typename T>
288  /// struct X {
289  ///   static T value;
290  /// };
291  ///
292  /// template<typename T>
293  ///   T X<T>::value = T(17);
294  ///
295  /// int *x = &X<int>::value;
296  /// \endcode
297  ///
298  /// This mapping will contain an entry that maps from the VarDecl for
299  /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
300  /// class template X) and will be marked TSK_ImplicitInstantiation.
301  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>
302    InstantiatedFromStaticDataMember;
303
304  /// \brief Keeps track of the declaration from which a UsingDecl was
305  /// created during instantiation.
306  ///
307  /// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
308  /// or an UnresolvedUsingTypenameDecl.
309  ///
310  /// For example:
311  /// \code
312  /// template<typename T>
313  /// struct A {
314  ///   void f();
315  /// };
316  ///
317  /// template<typename T>
318  /// struct B : A<T> {
319  ///   using A<T>::f;
320  /// };
321  ///
322  /// template struct B<int>;
323  /// \endcode
324  ///
325  /// This mapping will contain an entry that maps from the UsingDecl in
326  /// B<int> to the UnresolvedUsingDecl in B<T>.
327  llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
328
329  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
330    InstantiatedFromUsingShadowDecl;
331
332  llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
333
334  /// \brief Mapping that stores the methods overridden by a given C++
335  /// member function.
336  ///
337  /// Since most C++ member functions aren't virtual and therefore
338  /// don't override anything, we store the overridden functions in
339  /// this map on the side rather than within the CXXMethodDecl structure.
340  typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
341  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
342
343  /// \brief Mapping from each declaration context to its corresponding lambda
344  /// mangling context.
345  llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleContexts;
346
347  /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
348  /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
349  typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
350  ParameterIndexTable ParamIndices;
351
352  ImportDecl *FirstLocalImport;
353  ImportDecl *LastLocalImport;
354
355  TranslationUnitDecl *TUDecl;
356
357  /// \brief The associated SourceManager object.a
358  SourceManager &SourceMgr;
359
360  /// \brief The language options used to create the AST associated with
361  ///  this ASTContext object.
362  LangOptions &LangOpts;
363
364  /// \brief The allocator used to create AST objects.
365  ///
366  /// AST objects are never destructed; rather, all memory associated with the
367  /// AST objects will be released when the ASTContext itself is destroyed.
368  mutable llvm::BumpPtrAllocator BumpAlloc;
369
370  /// \brief Allocator for partial diagnostics.
371  PartialDiagnostic::StorageAllocator DiagAllocator;
372
373  /// \brief The current C++ ABI.
374  OwningPtr<CXXABI> ABI;
375  CXXABI *createCXXABI(const TargetInfo &T);
376
377  /// \brief The logical -> physical address space map.
378  const LangAS::Map *AddrSpaceMap;
379
380  friend class ASTDeclReader;
381  friend class ASTReader;
382  friend class ASTWriter;
383  friend class CXXRecordDecl;
384
385  const TargetInfo *Target;
386  clang::PrintingPolicy PrintingPolicy;
387
388public:
389  IdentifierTable &Idents;
390  SelectorTable &Selectors;
391  Builtin::Context &BuiltinInfo;
392  mutable DeclarationNameTable DeclarationNames;
393  OwningPtr<ExternalASTSource> ExternalSource;
394  ASTMutationListener *Listener;
395
396  const clang::PrintingPolicy &getPrintingPolicy() const {
397    return PrintingPolicy;
398  }
399
400  void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
401    PrintingPolicy = Policy;
402  }
403
404  SourceManager& getSourceManager() { return SourceMgr; }
405  const SourceManager& getSourceManager() const { return SourceMgr; }
406
407  llvm::BumpPtrAllocator &getAllocator() const {
408    return BumpAlloc;
409  }
410
411  void *Allocate(unsigned Size, unsigned Align = 8) const {
412    return BumpAlloc.Allocate(Size, Align);
413  }
414  void Deallocate(void *Ptr) const { }
415
416  /// Return the total amount of physical memory allocated for representing
417  /// AST nodes and type information.
418  size_t getASTAllocatedMemory() const {
419    return BumpAlloc.getTotalMemory();
420  }
421  /// Return the total memory used for various side tables.
422  size_t getSideTableAllocatedMemory() const;
423
424  PartialDiagnostic::StorageAllocator &getDiagAllocator() {
425    return DiagAllocator;
426  }
427
428  const TargetInfo &getTargetInfo() const { return *Target; }
429
430  const LangOptions& getLangOpts() const { return LangOpts; }
431
432  DiagnosticsEngine &getDiagnostics() const;
433
434  FullSourceLoc getFullLoc(SourceLocation Loc) const {
435    return FullSourceLoc(Loc,SourceMgr);
436  }
437
438  /// \brief All comments in this translation unit.
439  RawCommentList Comments;
440
441  /// \brief True if comments are already loaded from ExternalASTSource.
442  mutable bool CommentsLoaded;
443
444  class RawCommentAndCacheFlags {
445  public:
446    enum Kind {
447      /// We searched for a comment attached to the particular declaration, but
448      /// didn't find any.
449      ///
450      /// getRaw() == 0.
451      NoCommentInDecl = 0,
452
453      /// We have found a comment attached to this particular declaration.
454      ///
455      /// getRaw() != 0.
456      FromDecl,
457
458      /// This declaration does not have an attached comment, and we have
459      /// searched the redeclaration chain.
460      ///
461      /// If getRaw() == 0, the whole redeclaration chain does not have any
462      /// comments.
463      ///
464      /// If getRaw() != 0, it is a comment propagated from other
465      /// redeclaration.
466      FromRedecl
467    };
468
469    Kind getKind() const LLVM_READONLY {
470      return Data.getInt();
471    }
472
473    void setKind(Kind K) {
474      Data.setInt(K);
475    }
476
477    const RawComment *getRaw() const LLVM_READONLY {
478      return Data.getPointer();
479    }
480
481    void setRaw(const RawComment *RC) {
482      Data.setPointer(RC);
483    }
484
485    const Decl *getOriginalDecl() const LLVM_READONLY {
486      return OriginalDecl;
487    }
488
489    void setOriginalDecl(const Decl *Orig) {
490      OriginalDecl = Orig;
491    }
492
493  private:
494    llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
495    const Decl *OriginalDecl;
496  };
497
498  /// \brief Mapping from declarations to comments attached to any
499  /// redeclaration.
500  ///
501  /// Raw comments are owned by Comments list.  This mapping is populated
502  /// lazily.
503  mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
504
505  /// \brief Mapping from declarations to parsed comments attached to any
506  /// redeclaration.
507  mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
508
509  /// \brief Return the documentation comment attached to a given declaration,
510  /// without looking into cache.
511  RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
512
513public:
514  RawCommentList &getRawCommentList() {
515    return Comments;
516  }
517
518  void addComment(const RawComment &RC) {
519    assert(LangOpts.RetainCommentsFromSystemHeaders ||
520           !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
521    Comments.addComment(RC, BumpAlloc);
522  }
523
524  /// \brief Return the documentation comment attached to a given declaration.
525  /// Returns NULL if no comment is attached.
526  ///
527  /// \param OriginalDecl if not NULL, is set to declaration AST node that had
528  /// the comment, if the comment we found comes from a redeclaration.
529  const RawComment *getRawCommentForAnyRedecl(
530                                      const Decl *D,
531                                      const Decl **OriginalDecl = NULL) const;
532
533  /// Return parsed documentation comment attached to a given declaration.
534  /// Returns NULL if no comment is attached.
535  ///
536  /// \param PP the Preprocessor used with this TU.  Could be NULL if
537  /// preprocessor is not available.
538  comments::FullComment *getCommentForDecl(const Decl *D,
539                                           const Preprocessor *PP) const;
540
541  comments::FullComment *cloneFullComment(comments::FullComment *FC,
542                                         const Decl *D) const;
543
544private:
545  mutable comments::CommandTraits CommentCommandTraits;
546
547public:
548  comments::CommandTraits &getCommentCommandTraits() const {
549    return CommentCommandTraits;
550  }
551
552  /// \brief Retrieve the attributes for the given declaration.
553  AttrVec& getDeclAttrs(const Decl *D);
554
555  /// \brief Erase the attributes corresponding to the given declaration.
556  void eraseDeclAttrs(const Decl *D);
557
558  /// \brief If this variable is an instantiated static data member of a
559  /// class template specialization, returns the templated static data member
560  /// from which it was instantiated.
561  MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
562                                                           const VarDecl *Var);
563
564  FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
565
566  void setClassScopeSpecializationPattern(FunctionDecl *FD,
567                                          FunctionDecl *Pattern);
568
569  /// \brief Note that the static data member \p Inst is an instantiation of
570  /// the static data member template \p Tmpl of a class template.
571  void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
572                                           TemplateSpecializationKind TSK,
573                        SourceLocation PointOfInstantiation = SourceLocation());
574
575  /// \brief If the given using decl \p Inst is an instantiation of a
576  /// (possibly unresolved) using decl from a template instantiation,
577  /// return it.
578  NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
579
580  /// \brief Remember that the using decl \p Inst is an instantiation
581  /// of the using decl \p Pattern of a class template.
582  void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
583
584  void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
585                                          UsingShadowDecl *Pattern);
586  UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
587
588  FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
589
590  void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
591
592  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
593  /// the non-bitfield \p LastFD.
594  bool ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
595                                      const FieldDecl *LastFD) const;
596
597  /// \brief Return \c true if \p FD is a zero-length bitfield which follows
598  /// the bitfield \p LastFD.
599  bool ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
600                                   const FieldDecl *LastFD) const;
601
602  /// \brief Return \c true if \p FD is a bitfield which follows the bitfield
603  /// \p LastFD.
604  bool BitfieldFollowsBitfield(const FieldDecl *FD,
605                               const FieldDecl *LastFD) const;
606
607  /// \brief Return \c true if \p FD is not a bitfield which follows the
608  /// bitfield \p LastFD.
609  bool NonBitfieldFollowsBitfield(const FieldDecl *FD,
610                                  const FieldDecl *LastFD) const;
611
612  /// \brief Return \c true if \p FD is a bitfield which follows the
613  /// non-bitfield \p LastFD.
614  bool BitfieldFollowsNonBitfield(const FieldDecl *FD,
615                                  const FieldDecl *LastFD) const;
616
617  // Access to the set of methods overridden by the given C++ method.
618  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
619  overridden_cxx_method_iterator
620  overridden_methods_begin(const CXXMethodDecl *Method) const;
621
622  overridden_cxx_method_iterator
623  overridden_methods_end(const CXXMethodDecl *Method) const;
624
625  unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
626
627  /// \brief Note that the given C++ \p Method overrides the given \p
628  /// Overridden method.
629  void addOverriddenMethod(const CXXMethodDecl *Method,
630                           const CXXMethodDecl *Overridden);
631
632  /// \brief Return C++ or ObjC overridden methods for the given \p Method.
633  ///
634  /// An ObjC method is considered to override any method in the class's
635  /// base classes, its protocols, or its categories' protocols, that has
636  /// the same selector and is of the same kind (class or instance).
637  /// A method in an implementation is not considered as overriding the same
638  /// method in the interface or its categories.
639  void getOverriddenMethods(const NamedDecl *Method,
640                            SmallVectorImpl<const NamedDecl *> &Overridden);
641
642  /// \brief Notify the AST context that a new import declaration has been
643  /// parsed or implicitly created within this translation unit.
644  void addedLocalImportDecl(ImportDecl *Import);
645
646  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
647    return Import->NextLocalImport;
648  }
649
650  /// \brief Iterator that visits import declarations.
651  class import_iterator {
652    ImportDecl *Import;
653
654  public:
655    typedef ImportDecl               *value_type;
656    typedef ImportDecl               *reference;
657    typedef ImportDecl               *pointer;
658    typedef int                       difference_type;
659    typedef std::forward_iterator_tag iterator_category;
660
661    import_iterator() : Import() { }
662    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
663
664    reference operator*() const { return Import; }
665    pointer operator->() const { return Import; }
666
667    import_iterator &operator++() {
668      Import = ASTContext::getNextLocalImport(Import);
669      return *this;
670    }
671
672    import_iterator operator++(int) {
673      import_iterator Other(*this);
674      ++(*this);
675      return Other;
676    }
677
678    friend bool operator==(import_iterator X, import_iterator Y) {
679      return X.Import == Y.Import;
680    }
681
682    friend bool operator!=(import_iterator X, import_iterator Y) {
683      return X.Import != Y.Import;
684    }
685  };
686
687  import_iterator local_import_begin() const {
688    return import_iterator(FirstLocalImport);
689  }
690  import_iterator local_import_end() const { return import_iterator(); }
691
692  TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
693
694
695  // Builtin Types.
696  CanQualType VoidTy;
697  CanQualType BoolTy;
698  CanQualType CharTy;
699  CanQualType WCharTy;  // [C++ 3.9.1p5], integer type in C99.
700  CanQualType WIntTy;   // [C99 7.24.1], integer type unchanged by default promotions.
701  CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
702  CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
703  CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
704  CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
705  CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
706  CanQualType FloatTy, DoubleTy, LongDoubleTy;
707  CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
708  CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
709  CanQualType VoidPtrTy, NullPtrTy;
710  CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
711  CanQualType BuiltinFnTy;
712  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
713  CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
714  CanQualType ObjCBuiltinBoolTy;
715
716  // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
717  mutable QualType AutoDeductTy;     // Deduction against 'auto'.
718  mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
719
720  // Type used to help define __builtin_va_list for some targets.
721  // The type is built when constructing 'BuiltinVaListDecl'.
722  mutable QualType VaListTagTy;
723
724  ASTContext(LangOptions& LOpts, SourceManager &SM, const TargetInfo *t,
725             IdentifierTable &idents, SelectorTable &sels,
726             Builtin::Context &builtins,
727             unsigned size_reserve,
728             bool DelayInitialization = false);
729
730  ~ASTContext();
731
732  /// \brief Attach an external AST source to the AST context.
733  ///
734  /// The external AST source provides the ability to load parts of
735  /// the abstract syntax tree as needed from some external storage,
736  /// e.g., a precompiled header.
737  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
738
739  /// \brief Retrieve a pointer to the external AST source associated
740  /// with this AST context, if any.
741  ExternalASTSource *getExternalSource() const { return ExternalSource.get(); }
742
743  /// \brief Attach an AST mutation listener to the AST context.
744  ///
745  /// The AST mutation listener provides the ability to track modifications to
746  /// the abstract syntax tree entities committed after they were initially
747  /// created.
748  void setASTMutationListener(ASTMutationListener *Listener) {
749    this->Listener = Listener;
750  }
751
752  /// \brief Retrieve a pointer to the AST mutation listener associated
753  /// with this AST context, if any.
754  ASTMutationListener *getASTMutationListener() const { return Listener; }
755
756  void PrintStats() const;
757  const std::vector<Type*>& getTypes() const { return Types; }
758
759  /// \brief Retrieve the declaration for the 128-bit signed integer type.
760  TypedefDecl *getInt128Decl() const;
761
762  /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
763  TypedefDecl *getUInt128Decl() const;
764
765  //===--------------------------------------------------------------------===//
766  //                           Type Constructors
767  //===--------------------------------------------------------------------===//
768
769private:
770  /// \brief Return a type with extended qualifiers.
771  QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
772
773  QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
774
775public:
776  /// \brief Return the uniqued reference to the type for an address space
777  /// qualified type with the specified type and address space.
778  ///
779  /// The resulting type has a union of the qualifiers from T and the address
780  /// space. If T already has an address space specifier, it is silently
781  /// replaced.
782  QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
783
784  /// \brief Return the uniqued reference to the type for an Objective-C
785  /// gc-qualified type.
786  ///
787  /// The retulting type has a union of the qualifiers from T and the gc
788  /// attribute.
789  QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
790
791  /// \brief Return the uniqued reference to the type for a \c restrict
792  /// qualified type.
793  ///
794  /// The resulting type has a union of the qualifiers from \p T and
795  /// \c restrict.
796  QualType getRestrictType(QualType T) const {
797    return T.withFastQualifiers(Qualifiers::Restrict);
798  }
799
800  /// \brief Return the uniqued reference to the type for a \c volatile
801  /// qualified type.
802  ///
803  /// The resulting type has a union of the qualifiers from \p T and
804  /// \c volatile.
805  QualType getVolatileType(QualType T) const {
806    return T.withFastQualifiers(Qualifiers::Volatile);
807  }
808
809  /// \brief Return the uniqued reference to the type for a \c const
810  /// qualified type.
811  ///
812  /// The resulting type has a union of the qualifiers from \p T and \c const.
813  ///
814  /// It can be reasonably expected that this will always be equivalent to
815  /// calling T.withConst().
816  QualType getConstType(QualType T) const { return T.withConst(); }
817
818  /// \brief Change the ExtInfo on a function type.
819  const FunctionType *adjustFunctionType(const FunctionType *Fn,
820                                         FunctionType::ExtInfo EInfo);
821
822  /// \brief Return the uniqued reference to the type for a complex
823  /// number with the specified element type.
824  QualType getComplexType(QualType T) const;
825  CanQualType getComplexType(CanQualType T) const {
826    return CanQualType::CreateUnsafe(getComplexType((QualType) T));
827  }
828
829  /// \brief Return the uniqued reference to the type for a pointer to
830  /// the specified type.
831  QualType getPointerType(QualType T) const;
832  CanQualType getPointerType(CanQualType T) const {
833    return CanQualType::CreateUnsafe(getPointerType((QualType) T));
834  }
835
836  /// \brief Return the uniqued reference to the atomic type for the specified
837  /// type.
838  QualType getAtomicType(QualType T) const;
839
840  /// \brief Return the uniqued reference to the type for a block of the
841  /// specified type.
842  QualType getBlockPointerType(QualType T) const;
843
844  /// Gets the struct used to keep track of the descriptor for pointer to
845  /// blocks.
846  QualType getBlockDescriptorType() const;
847
848  /// Gets the struct used to keep track of the extended descriptor for
849  /// pointer to blocks.
850  QualType getBlockDescriptorExtendedType() const;
851
852  void setcudaConfigureCallDecl(FunctionDecl *FD) {
853    cudaConfigureCallDecl = FD;
854  }
855  FunctionDecl *getcudaConfigureCallDecl() {
856    return cudaConfigureCallDecl;
857  }
858
859  /// Builds the struct used for __block variables.
860  QualType BuildByRefType(StringRef DeclName, QualType Ty) const;
861
862  /// Returns true iff we need copy/dispose helpers for the given type.
863  bool BlockRequiresCopying(QualType Ty) const;
864
865  /// \brief Return the uniqued reference to the type for an lvalue reference
866  /// to the specified type.
867  QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
868    const;
869
870  /// \brief Return the uniqued reference to the type for an rvalue reference
871  /// to the specified type.
872  QualType getRValueReferenceType(QualType T) const;
873
874  /// \brief Return the uniqued reference to the type for a member pointer to
875  /// the specified type in the specified class.
876  ///
877  /// The class \p Cls is a \c Type because it could be a dependent name.
878  QualType getMemberPointerType(QualType T, const Type *Cls) const;
879
880  /// \brief Return a non-unique reference to the type for a variable array of
881  /// the specified element type.
882  QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
883                                ArrayType::ArraySizeModifier ASM,
884                                unsigned IndexTypeQuals,
885                                SourceRange Brackets) const;
886
887  /// \brief Return a non-unique reference to the type for a dependently-sized
888  /// array of the specified element type.
889  ///
890  /// FIXME: We will need these to be uniqued, or at least comparable, at some
891  /// point.
892  QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
893                                      ArrayType::ArraySizeModifier ASM,
894                                      unsigned IndexTypeQuals,
895                                      SourceRange Brackets) const;
896
897  /// \brief Return a unique reference to the type for an incomplete array of
898  /// the specified element type.
899  QualType getIncompleteArrayType(QualType EltTy,
900                                  ArrayType::ArraySizeModifier ASM,
901                                  unsigned IndexTypeQuals) const;
902
903  /// \brief Return the unique reference to the type for a constant array of
904  /// the specified element type.
905  QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
906                                ArrayType::ArraySizeModifier ASM,
907                                unsigned IndexTypeQuals) const;
908
909  /// \brief Returns a vla type where known sizes are replaced with [*].
910  QualType getVariableArrayDecayedType(QualType Ty) const;
911
912  /// \brief Return the unique reference to a vector type of the specified
913  /// element type and size.
914  ///
915  /// \pre \p VectorType must be a built-in type.
916  QualType getVectorType(QualType VectorType, unsigned NumElts,
917                         VectorType::VectorKind VecKind) const;
918
919  /// \brief Return the unique reference to an extended vector type
920  /// of the specified element type and size.
921  ///
922  /// \pre \p VectorType must be a built-in type.
923  QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
924
925  /// \pre Return a non-unique reference to the type for a dependently-sized
926  /// vector of the specified element type.
927  ///
928  /// FIXME: We will need these to be uniqued, or at least comparable, at some
929  /// point.
930  QualType getDependentSizedExtVectorType(QualType VectorType,
931                                          Expr *SizeExpr,
932                                          SourceLocation AttrLoc) const;
933
934  /// \brief Return a K&R style C function type like 'int()'.
935  QualType getFunctionNoProtoType(QualType ResultTy,
936                                  const FunctionType::ExtInfo &Info) const;
937
938  QualType getFunctionNoProtoType(QualType ResultTy) const {
939    return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
940  }
941
942  /// \brief Return a normal function type with a typed argument list.
943  QualType getFunctionType(QualType ResultTy,
944                           const QualType *Args, unsigned NumArgs,
945                           const FunctionProtoType::ExtProtoInfo &EPI) const;
946
947  /// \brief Return the unique reference to the type for the specified type
948  /// declaration.
949  QualType getTypeDeclType(const TypeDecl *Decl,
950                           const TypeDecl *PrevDecl = 0) const {
951    assert(Decl && "Passed null for Decl param");
952    if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
953
954    if (PrevDecl) {
955      assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
956      Decl->TypeForDecl = PrevDecl->TypeForDecl;
957      return QualType(PrevDecl->TypeForDecl, 0);
958    }
959
960    return getTypeDeclTypeSlow(Decl);
961  }
962
963  /// \brief Return the unique reference to the type for the specified
964  /// typedef-name decl.
965  QualType getTypedefType(const TypedefNameDecl *Decl,
966                          QualType Canon = QualType()) const;
967
968  QualType getRecordType(const RecordDecl *Decl) const;
969
970  QualType getEnumType(const EnumDecl *Decl) const;
971
972  QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
973
974  QualType getAttributedType(AttributedType::Kind attrKind,
975                             QualType modifiedType,
976                             QualType equivalentType);
977
978  QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
979                                        QualType Replacement) const;
980  QualType getSubstTemplateTypeParmPackType(
981                                          const TemplateTypeParmType *Replaced,
982                                            const TemplateArgument &ArgPack);
983
984  QualType getTemplateTypeParmType(unsigned Depth, unsigned Index,
985                                   bool ParameterPack,
986                                   TemplateTypeParmDecl *ParmDecl = 0) const;
987
988  QualType getTemplateSpecializationType(TemplateName T,
989                                         const TemplateArgument *Args,
990                                         unsigned NumArgs,
991                                         QualType Canon = QualType()) const;
992
993  QualType getCanonicalTemplateSpecializationType(TemplateName T,
994                                                  const TemplateArgument *Args,
995                                                  unsigned NumArgs) const;
996
997  QualType getTemplateSpecializationType(TemplateName T,
998                                         const TemplateArgumentListInfo &Args,
999                                         QualType Canon = QualType()) const;
1000
1001  TypeSourceInfo *
1002  getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1003                                    const TemplateArgumentListInfo &Args,
1004                                    QualType Canon = QualType()) const;
1005
1006  QualType getParenType(QualType NamedType) const;
1007
1008  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1009                             NestedNameSpecifier *NNS,
1010                             QualType NamedType) const;
1011  QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1012                                NestedNameSpecifier *NNS,
1013                                const IdentifierInfo *Name,
1014                                QualType Canon = QualType()) const;
1015
1016  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1017                                                  NestedNameSpecifier *NNS,
1018                                                  const IdentifierInfo *Name,
1019                                    const TemplateArgumentListInfo &Args) const;
1020  QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1021                                                  NestedNameSpecifier *NNS,
1022                                                  const IdentifierInfo *Name,
1023                                                  unsigned NumArgs,
1024                                            const TemplateArgument *Args) const;
1025
1026  QualType getPackExpansionType(QualType Pattern,
1027                                llvm::Optional<unsigned> NumExpansions);
1028
1029  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1030                                ObjCInterfaceDecl *PrevDecl = 0) const;
1031
1032  QualType getObjCObjectType(QualType Base,
1033                             ObjCProtocolDecl * const *Protocols,
1034                             unsigned NumProtocols) const;
1035
1036  /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1037  QualType getObjCObjectPointerType(QualType OIT) const;
1038
1039  /// \brief GCC extension.
1040  QualType getTypeOfExprType(Expr *e) const;
1041  QualType getTypeOfType(QualType t) const;
1042
1043  /// \brief C++11 decltype.
1044  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1045
1046  /// \brief Unary type transforms
1047  QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1048                                 UnaryTransformType::UTTKind UKind) const;
1049
1050  /// \brief C++11 deduced auto type.
1051  QualType getAutoType(QualType DeducedType) const;
1052
1053  /// \brief C++11 deduction pattern for 'auto' type.
1054  QualType getAutoDeductType() const;
1055
1056  /// \brief C++11 deduction pattern for 'auto &&' type.
1057  QualType getAutoRRefDeductType() const;
1058
1059  /// \brief Return the unique reference to the type for the specified TagDecl
1060  /// (struct/union/class/enum) decl.
1061  QualType getTagDeclType(const TagDecl *Decl) const;
1062
1063  /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1064  /// <stddef.h>.
1065  ///
1066  /// The sizeof operator requires this (C99 6.5.3.4p4).
1067  CanQualType getSizeType() const;
1068
1069  /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1070  /// <stdint.h>.
1071  CanQualType getIntMaxType() const;
1072
1073  /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1074  /// <stdint.h>.
1075  CanQualType getUIntMaxType() const;
1076
1077  /// \brief In C++, this returns the unique wchar_t type.  In C99, this
1078  /// returns a type compatible with the type defined in <stddef.h> as defined
1079  /// by the target.
1080  QualType getWCharType() const { return WCharTy; }
1081
1082  /// \brief Return the type of "signed wchar_t".
1083  ///
1084  /// Used when in C++, as a GCC extension.
1085  QualType getSignedWCharType() const;
1086
1087  /// \brief Return the type of "unsigned wchar_t".
1088  ///
1089  /// Used when in C++, as a GCC extension.
1090  QualType getUnsignedWCharType() const;
1091
1092  /// \brief In C99, this returns a type compatible with the type
1093  /// defined in <stddef.h> as defined by the target.
1094  QualType getWIntType() const { return WIntTy; }
1095
1096  /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1097  /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1098  QualType getPointerDiffType() const;
1099
1100  /// \brief Return the C structure type used to represent constant CFStrings.
1101  QualType getCFConstantStringType() const;
1102
1103  /// Get the structure type used to representation CFStrings, or NULL
1104  /// if it hasn't yet been built.
1105  QualType getRawCFConstantStringType() const {
1106    if (CFConstantStringTypeDecl)
1107      return getTagDeclType(CFConstantStringTypeDecl);
1108    return QualType();
1109  }
1110  void setCFConstantStringType(QualType T);
1111
1112  // This setter/getter represents the ObjC type for an NSConstantString.
1113  void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1114  QualType getObjCConstantStringInterface() const {
1115    return ObjCConstantStringType;
1116  }
1117
1118  QualType getObjCNSStringType() const {
1119    return ObjCNSStringType;
1120  }
1121
1122  void setObjCNSStringType(QualType T) {
1123    ObjCNSStringType = T;
1124  }
1125
1126  /// \brief Retrieve the type that \c id has been defined to, which may be
1127  /// different from the built-in \c id if \c id has been typedef'd.
1128  QualType getObjCIdRedefinitionType() const {
1129    if (ObjCIdRedefinitionType.isNull())
1130      return getObjCIdType();
1131    return ObjCIdRedefinitionType;
1132  }
1133
1134  /// \brief Set the user-written type that redefines \c id.
1135  void setObjCIdRedefinitionType(QualType RedefType) {
1136    ObjCIdRedefinitionType = RedefType;
1137  }
1138
1139  /// \brief Retrieve the type that \c Class has been defined to, which may be
1140  /// different from the built-in \c Class if \c Class has been typedef'd.
1141  QualType getObjCClassRedefinitionType() const {
1142    if (ObjCClassRedefinitionType.isNull())
1143      return getObjCClassType();
1144    return ObjCClassRedefinitionType;
1145  }
1146
1147  /// \brief Set the user-written type that redefines 'SEL'.
1148  void setObjCClassRedefinitionType(QualType RedefType) {
1149    ObjCClassRedefinitionType = RedefType;
1150  }
1151
1152  /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1153  /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1154  QualType getObjCSelRedefinitionType() const {
1155    if (ObjCSelRedefinitionType.isNull())
1156      return getObjCSelType();
1157    return ObjCSelRedefinitionType;
1158  }
1159
1160
1161  /// \brief Set the user-written type that redefines 'SEL'.
1162  void setObjCSelRedefinitionType(QualType RedefType) {
1163    ObjCSelRedefinitionType = RedefType;
1164  }
1165
1166  /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1167  /// otherwise, returns a NULL type;
1168  QualType getObjCInstanceType() {
1169    return getTypeDeclType(getObjCInstanceTypeDecl());
1170  }
1171
1172  /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1173  /// "instancetype" type.
1174  TypedefDecl *getObjCInstanceTypeDecl();
1175
1176  /// \brief Set the type for the C FILE type.
1177  void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1178
1179  /// \brief Retrieve the C FILE type.
1180  QualType getFILEType() const {
1181    if (FILEDecl)
1182      return getTypeDeclType(FILEDecl);
1183    return QualType();
1184  }
1185
1186  /// \brief Set the type for the C jmp_buf type.
1187  void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1188    this->jmp_bufDecl = jmp_bufDecl;
1189  }
1190
1191  /// \brief Retrieve the C jmp_buf type.
1192  QualType getjmp_bufType() const {
1193    if (jmp_bufDecl)
1194      return getTypeDeclType(jmp_bufDecl);
1195    return QualType();
1196  }
1197
1198  /// \brief Set the type for the C sigjmp_buf type.
1199  void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1200    this->sigjmp_bufDecl = sigjmp_bufDecl;
1201  }
1202
1203  /// \brief Retrieve the C sigjmp_buf type.
1204  QualType getsigjmp_bufType() const {
1205    if (sigjmp_bufDecl)
1206      return getTypeDeclType(sigjmp_bufDecl);
1207    return QualType();
1208  }
1209
1210  /// \brief Set the type for the C ucontext_t type.
1211  void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1212    this->ucontext_tDecl = ucontext_tDecl;
1213  }
1214
1215  /// \brief Retrieve the C ucontext_t type.
1216  QualType getucontext_tType() const {
1217    if (ucontext_tDecl)
1218      return getTypeDeclType(ucontext_tDecl);
1219    return QualType();
1220  }
1221
1222  /// \brief The result type of logical operations, '<', '>', '!=', etc.
1223  QualType getLogicalOperationType() const {
1224    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1225  }
1226
1227  /// \brief Emit the Objective-CC type encoding for the given type \p T into
1228  /// \p S.
1229  ///
1230  /// If \p Field is specified then record field names are also encoded.
1231  void getObjCEncodingForType(QualType T, std::string &S,
1232                              const FieldDecl *Field=0) const;
1233
1234  void getLegacyIntegralTypeEncoding(QualType &t) const;
1235
1236  /// \brief Put the string version of the type qualifiers \p QT into \p S.
1237  void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1238                                       std::string &S) const;
1239
1240  /// \brief Emit the encoded type for the function \p Decl into \p S.
1241  ///
1242  /// This is in the same format as Objective-C method encodings.
1243  ///
1244  /// \returns true if an error occurred (e.g., because one of the parameter
1245  /// types is incomplete), false otherwise.
1246  bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
1247
1248  /// \brief Emit the encoded type for the method declaration \p Decl into
1249  /// \p S.
1250  ///
1251  /// \returns true if an error occurred (e.g., because one of the parameter
1252  /// types is incomplete), false otherwise.
1253  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
1254                                    bool Extended = false)
1255    const;
1256
1257  /// \brief Return the encoded type for this block declaration.
1258  std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1259
1260  /// getObjCEncodingForPropertyDecl - Return the encoded type for
1261  /// this method declaration. If non-NULL, Container must be either
1262  /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1263  /// only be NULL when getting encodings for protocol properties.
1264  void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1265                                      const Decl *Container,
1266                                      std::string &S) const;
1267
1268  bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1269                                      ObjCProtocolDecl *rProto) const;
1270
1271  /// \brief Return the size of type \p T for Objective-C encoding purpose,
1272  /// in characters.
1273  CharUnits getObjCEncodingTypeSize(QualType T) const;
1274
1275  /// \brief Retrieve the typedef corresponding to the predefined \c id type
1276  /// in Objective-C.
1277  TypedefDecl *getObjCIdDecl() const;
1278
1279  /// \brief Represents the Objective-CC \c id type.
1280  ///
1281  /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1282  /// pointer type, a pointer to a struct.
1283  QualType getObjCIdType() const {
1284    return getTypeDeclType(getObjCIdDecl());
1285  }
1286
1287  /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1288  /// in Objective-C.
1289  TypedefDecl *getObjCSelDecl() const;
1290
1291  /// \brief Retrieve the type that corresponds to the predefined Objective-C
1292  /// 'SEL' type.
1293  QualType getObjCSelType() const {
1294    return getTypeDeclType(getObjCSelDecl());
1295  }
1296
1297  /// \brief Retrieve the typedef declaration corresponding to the predefined
1298  /// Objective-C 'Class' type.
1299  TypedefDecl *getObjCClassDecl() const;
1300
1301  /// \brief Represents the Objective-C \c Class type.
1302  ///
1303  /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1304  /// pointer type, a pointer to a struct.
1305  QualType getObjCClassType() const {
1306    return getTypeDeclType(getObjCClassDecl());
1307  }
1308
1309  /// \brief Retrieve the Objective-C class declaration corresponding to
1310  /// the predefined \c Protocol class.
1311  ObjCInterfaceDecl *getObjCProtocolDecl() const;
1312
1313  /// \brief Retrieve declaration of 'BOOL' typedef
1314  TypedefDecl *getBOOLDecl() const {
1315    return BOOLDecl;
1316  }
1317
1318  /// \brief Save declaration of 'BOOL' typedef
1319  void setBOOLDecl(TypedefDecl *TD) {
1320    BOOLDecl = TD;
1321  }
1322
1323  /// \brief type of 'BOOL' type.
1324  QualType getBOOLType() const {
1325    return getTypeDeclType(getBOOLDecl());
1326  }
1327
1328  /// \brief Retrieve the type of the Objective-C \c Protocol class.
1329  QualType getObjCProtoType() const {
1330    return getObjCInterfaceType(getObjCProtocolDecl());
1331  }
1332
1333  /// \brief Retrieve the C type declaration corresponding to the predefined
1334  /// \c __builtin_va_list type.
1335  TypedefDecl *getBuiltinVaListDecl() const;
1336
1337  /// \brief Retrieve the type of the \c __builtin_va_list type.
1338  QualType getBuiltinVaListType() const {
1339    return getTypeDeclType(getBuiltinVaListDecl());
1340  }
1341
1342  /// \brief Retrieve the C type declaration corresponding to the predefined
1343  /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1344  /// for some targets.
1345  QualType getVaListTagType() const;
1346
1347  /// \brief Return a type with additional \c const, \c volatile, or
1348  /// \c restrict qualifiers.
1349  QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1350    return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1351  }
1352
1353  /// \brief Un-split a SplitQualType.
1354  QualType getQualifiedType(SplitQualType split) const {
1355    return getQualifiedType(split.Ty, split.Quals);
1356  }
1357
1358  /// \brief Return a type with additional qualifiers.
1359  QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1360    if (!Qs.hasNonFastQualifiers())
1361      return T.withFastQualifiers(Qs.getFastQualifiers());
1362    QualifierCollector Qc(Qs);
1363    const Type *Ptr = Qc.strip(T);
1364    return getExtQualType(Ptr, Qc);
1365  }
1366
1367  /// \brief Return a type with additional qualifiers.
1368  QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1369    if (!Qs.hasNonFastQualifiers())
1370      return QualType(T, Qs.getFastQualifiers());
1371    return getExtQualType(T, Qs);
1372  }
1373
1374  /// \brief Return a type with the given lifetime qualifier.
1375  ///
1376  /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1377  QualType getLifetimeQualifiedType(QualType type,
1378                                    Qualifiers::ObjCLifetime lifetime) {
1379    assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1380    assert(lifetime != Qualifiers::OCL_None);
1381
1382    Qualifiers qs;
1383    qs.addObjCLifetime(lifetime);
1384    return getQualifiedType(type, qs);
1385  }
1386
1387  DeclarationNameInfo getNameForTemplate(TemplateName Name,
1388                                         SourceLocation NameLoc) const;
1389
1390  TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1391                                         UnresolvedSetIterator End) const;
1392
1393  TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1394                                        bool TemplateKeyword,
1395                                        TemplateDecl *Template) const;
1396
1397  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1398                                        const IdentifierInfo *Name) const;
1399  TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1400                                        OverloadedOperatorKind Operator) const;
1401  TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1402                                            TemplateName replacement) const;
1403  TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1404                                        const TemplateArgument &ArgPack) const;
1405
1406  enum GetBuiltinTypeError {
1407    GE_None,              ///< No error
1408    GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1409    GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1410    GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1411  };
1412
1413  /// \brief Return the type for the specified builtin.
1414  ///
1415  /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1416  /// arguments to the builtin that are required to be integer constant
1417  /// expressions.
1418  QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1419                          unsigned *IntegerConstantArgs = 0) const;
1420
1421private:
1422  CanQualType getFromTargetType(unsigned Type) const;
1423  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
1424
1425  //===--------------------------------------------------------------------===//
1426  //                         Type Predicates.
1427  //===--------------------------------------------------------------------===//
1428
1429public:
1430  /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1431  /// collection attributes.
1432  Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1433
1434  /// \brief Return true if the given vector types are of the same unqualified
1435  /// type or if they are equivalent to the same GCC vector type.
1436  ///
1437  /// \note This ignores whether they are target-specific (AltiVec or Neon)
1438  /// types.
1439  bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1440
1441  /// \brief Return true if this is an \c NSObject object with its \c NSObject
1442  /// attribute set.
1443  static bool isObjCNSObjectType(QualType Ty) {
1444    return Ty->isObjCNSObjectType();
1445  }
1446
1447  //===--------------------------------------------------------------------===//
1448  //                         Type Sizing and Analysis
1449  //===--------------------------------------------------------------------===//
1450
1451  /// \brief Return the APFloat 'semantics' for the specified scalar floating
1452  /// point type.
1453  const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1454
1455  /// \brief Get the size and alignment of the specified complete type in bits.
1456  std::pair<uint64_t, unsigned> getTypeInfo(const Type *T) const;
1457  std::pair<uint64_t, unsigned> getTypeInfo(QualType T) const {
1458    return getTypeInfo(T.getTypePtr());
1459  }
1460
1461  /// \brief Return the size of the specified (complete) type \p T, in bits.
1462  uint64_t getTypeSize(QualType T) const {
1463    return getTypeInfo(T).first;
1464  }
1465  uint64_t getTypeSize(const Type *T) const {
1466    return getTypeInfo(T).first;
1467  }
1468
1469  /// \brief Return the size of the character type, in bits.
1470  uint64_t getCharWidth() const {
1471    return getTypeSize(CharTy);
1472  }
1473
1474  /// \brief Convert a size in bits to a size in characters.
1475  CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1476
1477  /// \brief Convert a size in characters to a size in bits.
1478  int64_t toBits(CharUnits CharSize) const;
1479
1480  /// \brief Return the size of the specified (complete) type \p T, in
1481  /// characters.
1482  CharUnits getTypeSizeInChars(QualType T) const;
1483  CharUnits getTypeSizeInChars(const Type *T) const;
1484
1485  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1486  /// bits.
1487  unsigned getTypeAlign(QualType T) const {
1488    return getTypeInfo(T).second;
1489  }
1490  unsigned getTypeAlign(const Type *T) const {
1491    return getTypeInfo(T).second;
1492  }
1493
1494  /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1495  /// characters.
1496  CharUnits getTypeAlignInChars(QualType T) const;
1497  CharUnits getTypeAlignInChars(const Type *T) const;
1498
1499  // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1500  // type is a record, its data size is returned.
1501  std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1502
1503  std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1504  std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1505
1506  /// \brief Return the "preferred" alignment of the specified type \p T for
1507  /// the current target, in bits.
1508  ///
1509  /// This can be different than the ABI alignment in cases where it is
1510  /// beneficial for performance to overalign a data type.
1511  unsigned getPreferredTypeAlign(const Type *T) const;
1512
1513  /// \brief Return a conservative estimate of the alignment of the specified
1514  /// decl \p D.
1515  ///
1516  /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1517  /// alignment.
1518  ///
1519  /// If \p RefAsPointee, references are treated like their underlying type
1520  /// (for alignof), else they're treated like pointers (for CodeGen).
1521  CharUnits getDeclAlign(const Decl *D, bool RefAsPointee = false) const;
1522
1523  /// \brief Get or compute information about the layout of the specified
1524  /// record (struct/union/class) \p D, which indicates its size and field
1525  /// position information.
1526  const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
1527
1528  /// \brief Get or compute information about the layout of the specified
1529  /// Objective-C interface.
1530  const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
1531    const;
1532
1533  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
1534                        bool Simple = false) const;
1535
1536  /// \brief Get or compute information about the layout of the specified
1537  /// Objective-C implementation.
1538  ///
1539  /// This may differ from the interface if synthesized ivars are present.
1540  const ASTRecordLayout &
1541  getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
1542
1543  /// \brief Get the key function for the given record decl, or NULL if there
1544  /// isn't one.
1545  ///
1546  /// The key function is, according to the Itanium C++ ABI section 5.2.3:
1547  ///
1548  /// ...the first non-pure virtual function that is not inline at the point
1549  /// of class definition.
1550  const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
1551
1552  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
1553  uint64_t getFieldOffset(const ValueDecl *FD) const;
1554
1555  bool isNearlyEmpty(const CXXRecordDecl *RD) const;
1556
1557  MangleContext *createMangleContext();
1558
1559  void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
1560                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
1561
1562  unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
1563  void CollectInheritedProtocols(const Decl *CDecl,
1564                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
1565
1566  //===--------------------------------------------------------------------===//
1567  //                            Type Operators
1568  //===--------------------------------------------------------------------===//
1569
1570  /// \brief Return the canonical (structural) type corresponding to the
1571  /// specified potentially non-canonical type \p T.
1572  ///
1573  /// The non-canonical version of a type may have many "decorated" versions of
1574  /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
1575  /// returned type is guaranteed to be free of any of these, allowing two
1576  /// canonical types to be compared for exact equality with a simple pointer
1577  /// comparison.
1578  CanQualType getCanonicalType(QualType T) const {
1579    return CanQualType::CreateUnsafe(T.getCanonicalType());
1580  }
1581
1582  const Type *getCanonicalType(const Type *T) const {
1583    return T->getCanonicalTypeInternal().getTypePtr();
1584  }
1585
1586  /// \brief Return the canonical parameter type corresponding to the specific
1587  /// potentially non-canonical one.
1588  ///
1589  /// Qualifiers are stripped off, functions are turned into function
1590  /// pointers, and arrays decay one level into pointers.
1591  CanQualType getCanonicalParamType(QualType T) const;
1592
1593  /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
1594  bool hasSameType(QualType T1, QualType T2) const {
1595    return getCanonicalType(T1) == getCanonicalType(T2);
1596  }
1597
1598  /// \brief Return this type as a completely-unqualified array type,
1599  /// capturing the qualifiers in \p Quals.
1600  ///
1601  /// This will remove the minimal amount of sugaring from the types, similar
1602  /// to the behavior of QualType::getUnqualifiedType().
1603  ///
1604  /// \param T is the qualified type, which may be an ArrayType
1605  ///
1606  /// \param Quals will receive the full set of qualifiers that were
1607  /// applied to the array.
1608  ///
1609  /// \returns if this is an array type, the completely unqualified array type
1610  /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
1611  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
1612
1613  /// \brief Determine whether the given types are equivalent after
1614  /// cvr-qualifiers have been removed.
1615  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
1616    return getCanonicalType(T1).getTypePtr() ==
1617           getCanonicalType(T2).getTypePtr();
1618  }
1619
1620  bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
1621
1622  /// \brief Retrieves the "canonical" nested name specifier for a
1623  /// given nested name specifier.
1624  ///
1625  /// The canonical nested name specifier is a nested name specifier
1626  /// that uniquely identifies a type or namespace within the type
1627  /// system. For example, given:
1628  ///
1629  /// \code
1630  /// namespace N {
1631  ///   struct S {
1632  ///     template<typename T> struct X { typename T* type; };
1633  ///   };
1634  /// }
1635  ///
1636  /// template<typename T> struct Y {
1637  ///   typename N::S::X<T>::type member;
1638  /// };
1639  /// \endcode
1640  ///
1641  /// Here, the nested-name-specifier for N::S::X<T>:: will be
1642  /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
1643  /// by declarations in the type system and the canonical type for
1644  /// the template type parameter 'T' is template-param-0-0.
1645  NestedNameSpecifier *
1646  getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
1647
1648  /// \brief Retrieves the default calling convention to use for
1649  /// C++ instance methods.
1650  CallingConv getDefaultCXXMethodCallConv(bool isVariadic);
1651
1652  /// \brief Retrieves the canonical representation of the given
1653  /// calling convention.
1654  CallingConv getCanonicalCallConv(CallingConv CC) const;
1655
1656  /// \brief Determines whether two calling conventions name the same
1657  /// calling convention.
1658  bool isSameCallConv(CallingConv lcc, CallingConv rcc) {
1659    return (getCanonicalCallConv(lcc) == getCanonicalCallConv(rcc));
1660  }
1661
1662  /// \brief Retrieves the "canonical" template name that refers to a
1663  /// given template.
1664  ///
1665  /// The canonical template name is the simplest expression that can
1666  /// be used to refer to a given template. For most templates, this
1667  /// expression is just the template declaration itself. For example,
1668  /// the template std::vector can be referred to via a variety of
1669  /// names---std::vector, \::std::vector, vector (if vector is in
1670  /// scope), etc.---but all of these names map down to the same
1671  /// TemplateDecl, which is used to form the canonical template name.
1672  ///
1673  /// Dependent template names are more interesting. Here, the
1674  /// template name could be something like T::template apply or
1675  /// std::allocator<T>::template rebind, where the nested name
1676  /// specifier itself is dependent. In this case, the canonical
1677  /// template name uses the shortest form of the dependent
1678  /// nested-name-specifier, which itself contains all canonical
1679  /// types, values, and templates.
1680  TemplateName getCanonicalTemplateName(TemplateName Name) const;
1681
1682  /// \brief Determine whether the given template names refer to the same
1683  /// template.
1684  bool hasSameTemplateName(TemplateName X, TemplateName Y);
1685
1686  /// \brief Retrieve the "canonical" template argument.
1687  ///
1688  /// The canonical template argument is the simplest template argument
1689  /// (which may be a type, value, expression, or declaration) that
1690  /// expresses the value of the argument.
1691  TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
1692    const;
1693
1694  /// Type Query functions.  If the type is an instance of the specified class,
1695  /// return the Type pointer for the underlying maximally pretty type.  This
1696  /// is a member of ASTContext because this may need to do some amount of
1697  /// canonicalization, e.g. to move type qualifiers into the element type.
1698  const ArrayType *getAsArrayType(QualType T) const;
1699  const ConstantArrayType *getAsConstantArrayType(QualType T) const {
1700    return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
1701  }
1702  const VariableArrayType *getAsVariableArrayType(QualType T) const {
1703    return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
1704  }
1705  const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
1706    return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
1707  }
1708  const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
1709    const {
1710    return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
1711  }
1712
1713  /// \brief Return the innermost element type of an array type.
1714  ///
1715  /// For example, will return "int" for int[m][n]
1716  QualType getBaseElementType(const ArrayType *VAT) const;
1717
1718  /// \brief Return the innermost element type of a type (which needn't
1719  /// actually be an array type).
1720  QualType getBaseElementType(QualType QT) const;
1721
1722  /// \brief Return number of constant array elements.
1723  uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
1724
1725  /// \brief Perform adjustment on the parameter type of a function.
1726  ///
1727  /// This routine adjusts the given parameter type @p T to the actual
1728  /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
1729  /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
1730  QualType getAdjustedParameterType(QualType T) const;
1731
1732  /// \brief Retrieve the parameter type as adjusted for use in the signature
1733  /// of a function, decaying array and function types and removing top-level
1734  /// cv-qualifiers.
1735  QualType getSignatureParameterType(QualType T) const;
1736
1737  /// \brief Return the properly qualified result of decaying the specified
1738  /// array type to a pointer.
1739  ///
1740  /// This operation is non-trivial when handling typedefs etc.  The canonical
1741  /// type of \p T must be an array type, this returns a pointer to a properly
1742  /// qualified element of the array.
1743  ///
1744  /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1745  QualType getArrayDecayedType(QualType T) const;
1746
1747  /// \brief Return the type that \p PromotableType will promote to: C99
1748  /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
1749  QualType getPromotedIntegerType(QualType PromotableType) const;
1750
1751  /// \brief Recurses in pointer/array types until it finds an Objective-C
1752  /// retainable type and returns its ownership.
1753  Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
1754
1755  /// \brief Whether this is a promotable bitfield reference according
1756  /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
1757  ///
1758  /// \returns the type this bit-field will promote to, or NULL if no
1759  /// promotion occurs.
1760  QualType isPromotableBitField(Expr *E) const;
1761
1762  /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
1763  ///
1764  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1765  /// \p LHS < \p RHS, return -1.
1766  int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
1767
1768  /// \brief Compare the rank of the two specified floating point types,
1769  /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
1770  ///
1771  /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
1772  /// \p LHS < \p RHS, return -1.
1773  int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
1774
1775  /// \brief Return a real floating point or a complex type (based on
1776  /// \p typeDomain/\p typeSize).
1777  ///
1778  /// \param typeDomain a real floating point or complex type.
1779  /// \param typeSize a real floating point or complex type.
1780  QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
1781                                             QualType typeDomain) const;
1782
1783  unsigned getTargetAddressSpace(QualType T) const {
1784    return getTargetAddressSpace(T.getQualifiers());
1785  }
1786
1787  unsigned getTargetAddressSpace(Qualifiers Q) const {
1788    return getTargetAddressSpace(Q.getAddressSpace());
1789  }
1790
1791  unsigned getTargetAddressSpace(unsigned AS) const {
1792    if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
1793      return AS;
1794    else
1795      return (*AddrSpaceMap)[AS - LangAS::Offset];
1796  }
1797
1798private:
1799  // Helper for integer ordering
1800  unsigned getIntegerRank(const Type *T) const;
1801
1802public:
1803
1804  //===--------------------------------------------------------------------===//
1805  //                    Type Compatibility Predicates
1806  //===--------------------------------------------------------------------===//
1807
1808  /// Compatibility predicates used to check assignment expressions.
1809  bool typesAreCompatible(QualType T1, QualType T2,
1810                          bool CompareUnqualified = false); // C99 6.2.7p1
1811
1812  bool propertyTypesAreCompatible(QualType, QualType);
1813  bool typesAreBlockPointerCompatible(QualType, QualType);
1814
1815  bool isObjCIdType(QualType T) const {
1816    return T == getObjCIdType();
1817  }
1818  bool isObjCClassType(QualType T) const {
1819    return T == getObjCClassType();
1820  }
1821  bool isObjCSelType(QualType T) const {
1822    return T == getObjCSelType();
1823  }
1824  bool QualifiedIdConformsQualifiedId(QualType LHS, QualType RHS);
1825  bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
1826                                         bool ForCompare);
1827
1828  bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
1829
1830  // Check the safety of assignment from LHS to RHS
1831  bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
1832                               const ObjCObjectPointerType *RHSOPT);
1833  bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
1834                               const ObjCObjectType *RHS);
1835  bool canAssignObjCInterfacesInBlockPointer(
1836                                          const ObjCObjectPointerType *LHSOPT,
1837                                          const ObjCObjectPointerType *RHSOPT,
1838                                          bool BlockReturnType);
1839  bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
1840  QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
1841                                   const ObjCObjectPointerType *RHSOPT);
1842  bool canBindObjCObjectType(QualType To, QualType From);
1843
1844  // Functions for calculating composite types
1845  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
1846                      bool Unqualified = false, bool BlockReturnType = false);
1847  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
1848                              bool Unqualified = false);
1849  QualType mergeFunctionArgumentTypes(QualType, QualType,
1850                                      bool OfBlockPointer=false,
1851                                      bool Unqualified = false);
1852  QualType mergeTransparentUnionType(QualType, QualType,
1853                                     bool OfBlockPointer=false,
1854                                     bool Unqualified = false);
1855
1856  QualType mergeObjCGCQualifiers(QualType, QualType);
1857
1858  bool FunctionTypesMatchOnNSConsumedAttrs(
1859         const FunctionProtoType *FromFunctionType,
1860         const FunctionProtoType *ToFunctionType);
1861
1862  void ResetObjCLayout(const ObjCContainerDecl *CD) {
1863    ObjCLayouts[CD] = 0;
1864  }
1865
1866  //===--------------------------------------------------------------------===//
1867  //                    Integer Predicates
1868  //===--------------------------------------------------------------------===//
1869
1870  // The width of an integer, as defined in C99 6.2.6.2. This is the number
1871  // of bits in an integer type excluding any padding bits.
1872  unsigned getIntWidth(QualType T) const;
1873
1874  // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
1875  // unsigned integer type.  This method takes a signed type, and returns the
1876  // corresponding unsigned integer type.
1877  QualType getCorrespondingUnsignedType(QualType T) const;
1878
1879  //===--------------------------------------------------------------------===//
1880  //                    Type Iterators.
1881  //===--------------------------------------------------------------------===//
1882
1883  typedef std::vector<Type*>::iterator       type_iterator;
1884  typedef std::vector<Type*>::const_iterator const_type_iterator;
1885
1886  type_iterator types_begin() { return Types.begin(); }
1887  type_iterator types_end() { return Types.end(); }
1888  const_type_iterator types_begin() const { return Types.begin(); }
1889  const_type_iterator types_end() const { return Types.end(); }
1890
1891  //===--------------------------------------------------------------------===//
1892  //                    Integer Values
1893  //===--------------------------------------------------------------------===//
1894
1895  /// \brief Make an APSInt of the appropriate width and signedness for the
1896  /// given \p Value and integer \p Type.
1897  llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
1898    llvm::APSInt Res(getIntWidth(Type),
1899                     !Type->isSignedIntegerOrEnumerationType());
1900    Res = Value;
1901    return Res;
1902  }
1903
1904  bool isSentinelNullExpr(const Expr *E);
1905
1906  /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
1907  /// none exists.
1908  ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
1909  /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
1910  /// none exists.
1911  ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
1912
1913  /// \brief Return true if there is at least one \@implementation in the TU.
1914  bool AnyObjCImplementation() {
1915    return !ObjCImpls.empty();
1916  }
1917
1918  /// \brief Set the implementation of ObjCInterfaceDecl.
1919  void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1920                             ObjCImplementationDecl *ImplD);
1921  /// \brief Set the implementation of ObjCCategoryDecl.
1922  void setObjCImplementation(ObjCCategoryDecl *CatD,
1923                             ObjCCategoryImplDecl *ImplD);
1924
1925  /// \brief Get the duplicate declaration of a ObjCMethod in the same
1926  /// interface, or null if none exists.
1927  const ObjCMethodDecl *getObjCMethodRedeclaration(
1928                                               const ObjCMethodDecl *MD) const {
1929    return ObjCMethodRedecls.lookup(MD);
1930  }
1931
1932  void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
1933                                  const ObjCMethodDecl *Redecl) {
1934    assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
1935    ObjCMethodRedecls[MD] = Redecl;
1936  }
1937
1938  /// \brief Returns the Objective-C interface that \p ND belongs to if it is
1939  /// an Objective-C method/property/ivar etc. that is part of an interface,
1940  /// otherwise returns null.
1941  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
1942
1943  /// \brief Set the copy inialization expression of a block var decl.
1944  void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
1945  /// \brief Get the copy initialization expression of the VarDecl \p VD, or
1946  /// NULL if none exists.
1947  Expr *getBlockVarCopyInits(const VarDecl* VD);
1948
1949  /// \brief Allocate an uninitialized TypeSourceInfo.
1950  ///
1951  /// The caller should initialize the memory held by TypeSourceInfo using
1952  /// the TypeLoc wrappers.
1953  ///
1954  /// \param T the type that will be the basis for type source info. This type
1955  /// should refer to how the declarator was written in source code, not to
1956  /// what type semantic analysis resolved the declarator to.
1957  ///
1958  /// \param Size the size of the type info to create, or 0 if the size
1959  /// should be calculated based on the type.
1960  TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
1961
1962  /// \brief Allocate a TypeSourceInfo where all locations have been
1963  /// initialized to a given location, which defaults to the empty
1964  /// location.
1965  TypeSourceInfo *
1966  getTrivialTypeSourceInfo(QualType T,
1967                           SourceLocation Loc = SourceLocation()) const;
1968
1969  TypeSourceInfo *getNullTypeSourceInfo() { return &NullTypeSourceInfo; }
1970
1971  /// \brief Add a deallocation callback that will be invoked when the
1972  /// ASTContext is destroyed.
1973  ///
1974  /// \param Callback A callback function that will be invoked on destruction.
1975  ///
1976  /// \param Data Pointer data that will be provided to the callback function
1977  /// when it is called.
1978  void AddDeallocation(void (*Callback)(void*), void *Data);
1979
1980  GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD);
1981  GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
1982
1983  /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
1984  /// lazily, only when used; this is only relevant for function or file scoped
1985  /// var definitions.
1986  ///
1987  /// \returns true if the function/var must be CodeGen'ed/deserialized even if
1988  /// it is not used.
1989  bool DeclMustBeEmitted(const Decl *D);
1990
1991  /// \brief Retrieve the lambda mangling number for a lambda expression.
1992  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
1993
1994  /// \brief Used by ParmVarDecl to store on the side the
1995  /// index of the parameter when it exceeds the size of the normal bitfield.
1996  void setParameterIndex(const ParmVarDecl *D, unsigned index);
1997
1998  /// \brief Used by ParmVarDecl to retrieve on the side the
1999  /// index of the parameter when it exceeds the size of the normal bitfield.
2000  unsigned getParameterIndex(const ParmVarDecl *D) const;
2001
2002  //===--------------------------------------------------------------------===//
2003  //                    Statistics
2004  //===--------------------------------------------------------------------===//
2005
2006  /// \brief The number of implicitly-declared default constructors.
2007  static unsigned NumImplicitDefaultConstructors;
2008
2009  /// \brief The number of implicitly-declared default constructors for
2010  /// which declarations were built.
2011  static unsigned NumImplicitDefaultConstructorsDeclared;
2012
2013  /// \brief The number of implicitly-declared copy constructors.
2014  static unsigned NumImplicitCopyConstructors;
2015
2016  /// \brief The number of implicitly-declared copy constructors for
2017  /// which declarations were built.
2018  static unsigned NumImplicitCopyConstructorsDeclared;
2019
2020  /// \brief The number of implicitly-declared move constructors.
2021  static unsigned NumImplicitMoveConstructors;
2022
2023  /// \brief The number of implicitly-declared move constructors for
2024  /// which declarations were built.
2025  static unsigned NumImplicitMoveConstructorsDeclared;
2026
2027  /// \brief The number of implicitly-declared copy assignment operators.
2028  static unsigned NumImplicitCopyAssignmentOperators;
2029
2030  /// \brief The number of implicitly-declared copy assignment operators for
2031  /// which declarations were built.
2032  static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2033
2034  /// \brief The number of implicitly-declared move assignment operators.
2035  static unsigned NumImplicitMoveAssignmentOperators;
2036
2037  /// \brief The number of implicitly-declared move assignment operators for
2038  /// which declarations were built.
2039  static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2040
2041  /// \brief The number of implicitly-declared destructors.
2042  static unsigned NumImplicitDestructors;
2043
2044  /// \brief The number of implicitly-declared destructors for which
2045  /// declarations were built.
2046  static unsigned NumImplicitDestructorsDeclared;
2047
2048private:
2049  ASTContext(const ASTContext &) LLVM_DELETED_FUNCTION;
2050  void operator=(const ASTContext &) LLVM_DELETED_FUNCTION;
2051
2052public:
2053  /// \brief Initialize built-in types.
2054  ///
2055  /// This routine may only be invoked once for a given ASTContext object.
2056  /// It is normally invoked by the ASTContext constructor. However, the
2057  /// constructor can be asked to delay initialization, which places the burden
2058  /// of calling this function on the user of that object.
2059  ///
2060  /// \param Target The target
2061  void InitBuiltinTypes(const TargetInfo &Target);
2062
2063private:
2064  void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2065
2066  // Return the Objective-C type encoding for a given type.
2067  void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2068                                  bool ExpandPointedToStructures,
2069                                  bool ExpandStructures,
2070                                  const FieldDecl *Field,
2071                                  bool OutermostType = false,
2072                                  bool EncodingProperty = false,
2073                                  bool StructField = false,
2074                                  bool EncodeBlockParameters = false,
2075                                  bool EncodeClassNames = false) const;
2076
2077  // Adds the encoding of the structure's members.
2078  void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2079                                       const FieldDecl *Field,
2080                                       bool includeVBases = true) const;
2081
2082  // Adds the encoding of a method parameter or return type.
2083  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2084                                         QualType T, std::string& S,
2085                                         bool Extended) const;
2086
2087  const ASTRecordLayout &
2088  getObjCLayout(const ObjCInterfaceDecl *D,
2089                const ObjCImplementationDecl *Impl) const;
2090
2091private:
2092  /// \brief A set of deallocations that should be performed when the
2093  /// ASTContext is destroyed.
2094  SmallVector<std::pair<void (*)(void*), void *>, 16> Deallocations;
2095
2096  // FIXME: This currently contains the set of StoredDeclMaps used
2097  // by DeclContext objects.  This probably should not be in ASTContext,
2098  // but we include it here so that ASTContext can quickly deallocate them.
2099  llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2100
2101  /// \brief A counter used to uniquely identify "blocks".
2102  mutable unsigned int UniqueBlockByRefTypeID;
2103
2104  friend class DeclContext;
2105  friend class DeclarationNameTable;
2106  void ReleaseDeclContextMaps();
2107};
2108
2109/// \brief Utility function for constructing a nullary selector.
2110static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2111  IdentifierInfo* II = &Ctx.Idents.get(name);
2112  return Ctx.Selectors.getSelector(0, &II);
2113}
2114
2115/// \brief Utility function for constructing an unary selector.
2116static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2117  IdentifierInfo* II = &Ctx.Idents.get(name);
2118  return Ctx.Selectors.getSelector(1, &II);
2119}
2120
2121}  // end namespace clang
2122
2123// operator new and delete aren't allowed inside namespaces.
2124
2125/// @brief Placement new for using the ASTContext's allocator.
2126///
2127/// This placement form of operator new uses the ASTContext's allocator for
2128/// obtaining memory.
2129///
2130/// IMPORTANT: These are also declared in clang/AST/Attr.h! Any changes here
2131/// need to also be made there.
2132///
2133/// We intentionally avoid using a nothrow specification here so that the calls
2134/// to this operator will not perform a null check on the result -- the
2135/// underlying allocator never returns null pointers.
2136///
2137/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2138/// @code
2139/// // Default alignment (8)
2140/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2141/// // Specific alignment
2142/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2143/// @endcode
2144/// Please note that you cannot use delete on the pointer; it must be
2145/// deallocated using an explicit destructor call followed by
2146/// @c Context.Deallocate(Ptr).
2147///
2148/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2149/// @param C The ASTContext that provides the allocator.
2150/// @param Alignment The alignment of the allocated memory (if the underlying
2151///                  allocator supports it).
2152/// @return The allocated memory. Could be NULL.
2153inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2154                          size_t Alignment) {
2155  return C.Allocate(Bytes, Alignment);
2156}
2157/// @brief Placement delete companion to the new above.
2158///
2159/// This operator is just a companion to the new above. There is no way of
2160/// invoking it directly; see the new operator for more details. This operator
2161/// is called implicitly by the compiler if a placement new expression using
2162/// the ASTContext throws in the object constructor.
2163inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2164  C.Deallocate(Ptr);
2165}
2166
2167/// This placement form of operator new[] uses the ASTContext's allocator for
2168/// obtaining memory.
2169///
2170/// We intentionally avoid using a nothrow specification here so that the calls
2171/// to this operator will not perform a null check on the result -- the
2172/// underlying allocator never returns null pointers.
2173///
2174/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2175/// @code
2176/// // Default alignment (8)
2177/// char *data = new (Context) char[10];
2178/// // Specific alignment
2179/// char *data = new (Context, 4) char[10];
2180/// @endcode
2181/// Please note that you cannot use delete on the pointer; it must be
2182/// deallocated using an explicit destructor call followed by
2183/// @c Context.Deallocate(Ptr).
2184///
2185/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2186/// @param C The ASTContext that provides the allocator.
2187/// @param Alignment The alignment of the allocated memory (if the underlying
2188///                  allocator supports it).
2189/// @return The allocated memory. Could be NULL.
2190inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2191                            size_t Alignment = 8) {
2192  return C.Allocate(Bytes, Alignment);
2193}
2194
2195/// @brief Placement delete[] companion to the new[] above.
2196///
2197/// This operator is just a companion to the new[] above. There is no way of
2198/// invoking it directly; see the new[] operator for more details. This operator
2199/// is called implicitly by the compiler if a placement new[] expression using
2200/// the ASTContext throws in the object constructor.
2201inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2202  C.Deallocate(Ptr);
2203}
2204
2205#endif
2206