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