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