]> granicus.if.org Git - clang/blob - include/clang/AST/ASTContext.h
[clang] Add getSignedSizeType method
[clang] / include / clang / AST / ASTContext.h
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
74 namespace llvm {
75
76 struct fltSemantics;
77
78 } // end namespace llvm
79
80 namespace clang {
81
82 class ASTMutationListener;
83 class ASTRecordLayout;
84 class AtomicExpr;
85 class BlockExpr;
86 class CharUnits;
87 class CXXABI;
88 class DiagnosticsEngine;
89 class Expr;
90 class MangleNumberingContext;
91 class MaterializeTemporaryExpr;
92 class TargetInfo;
93 // Decls
94 class MangleContext;
95 class ObjCIvarDecl;
96 class ObjCPropertyDecl;
97 class UnresolvedSetIterator;
98 class UsingDecl;
99 class UsingShadowDecl;
100 class VTableContextBase;
101
102 namespace Builtin {
103
104   class Context;
105
106 } // end namespace Builtin
107
108 enum BuiltinTemplateKind : int;
109
110 namespace comments {
111
112   class FullComment;
113
114 } // end namespace comments
115
116 struct 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.
128 class 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
366 public:
367   /// \brief A type synonym for the TemplateOrInstantiation mapping.
368   typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
369   TemplateOrSpecializationInfo;
370
371 private:
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
512 public:
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
750 public:
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
786 private:
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
826 public:
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
1055 private:
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
1063 public:
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
1286 private:
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
1292 public:
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 signed counterpart of 
1445   /// the integer type corresponding to size_t.
1446   CanQualType getSignedSizeType() const;
1447
1448   /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1449   /// <stdint.h>.
1450   CanQualType getIntMaxType() const;
1451
1452   /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1453   /// <stdint.h>.
1454   CanQualType getUIntMaxType() const;
1455
1456   /// \brief Return the unique wchar_t type available in C++ (and available as
1457   /// __wchar_t as a Microsoft extension).
1458   QualType getWCharType() const { return WCharTy; }
1459
1460   /// \brief Return the type of wide characters. In C++, this returns the
1461   /// unique wchar_t type. In C99, this returns a type compatible with the type
1462   /// defined in <stddef.h> as defined by the target.
1463   QualType getWideCharType() const { return WideCharTy; }
1464
1465   /// \brief Return the type of "signed wchar_t".
1466   ///
1467   /// Used when in C++, as a GCC extension.
1468   QualType getSignedWCharType() const;
1469
1470   /// \brief Return the type of "unsigned wchar_t".
1471   ///
1472   /// Used when in C++, as a GCC extension.
1473   QualType getUnsignedWCharType() const;
1474
1475   /// \brief In C99, this returns a type compatible with the type
1476   /// defined in <stddef.h> as defined by the target.
1477   QualType getWIntType() const { return WIntTy; }
1478
1479   /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1480   /// as defined by the target.
1481   QualType getIntPtrType() const;
1482
1483   /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1484   /// as defined by the target.
1485   QualType getUIntPtrType() const;
1486
1487   /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1488   /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1489   QualType getPointerDiffType() const;
1490
1491   /// \brief Return the unique type for "pid_t" defined in
1492   /// <sys/types.h>. We need this to compute the correct type for vfork().
1493   QualType getProcessIDType() const;
1494
1495   /// \brief Return the C structure type used to represent constant CFStrings.
1496   QualType getCFConstantStringType() const;
1497
1498   /// \brief Returns the C struct type for objc_super
1499   QualType getObjCSuperType() const;
1500   void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1501
1502   /// Get the structure type used to representation CFStrings, or NULL
1503   /// if it hasn't yet been built.
1504   QualType getRawCFConstantStringType() const {
1505     if (CFConstantStringTypeDecl)
1506       return getTypedefType(CFConstantStringTypeDecl);
1507     return QualType();
1508   }
1509   void setCFConstantStringType(QualType T);
1510   TypedefDecl *getCFConstantStringDecl() const;
1511   RecordDecl *getCFConstantStringTagDecl() const;
1512
1513   // This setter/getter represents the ObjC type for an NSConstantString.
1514   void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1515   QualType getObjCConstantStringInterface() const {
1516     return ObjCConstantStringType;
1517   }
1518
1519   QualType getObjCNSStringType() const {
1520     return ObjCNSStringType;
1521   }
1522
1523   void setObjCNSStringType(QualType T) {
1524     ObjCNSStringType = T;
1525   }
1526
1527   /// \brief Retrieve the type that \c id has been defined to, which may be
1528   /// different from the built-in \c id if \c id has been typedef'd.
1529   QualType getObjCIdRedefinitionType() const {
1530     if (ObjCIdRedefinitionType.isNull())
1531       return getObjCIdType();
1532     return ObjCIdRedefinitionType;
1533   }
1534
1535   /// \brief Set the user-written type that redefines \c id.
1536   void setObjCIdRedefinitionType(QualType RedefType) {
1537     ObjCIdRedefinitionType = RedefType;
1538   }
1539
1540   /// \brief Retrieve the type that \c Class has been defined to, which may be
1541   /// different from the built-in \c Class if \c Class has been typedef'd.
1542   QualType getObjCClassRedefinitionType() const {
1543     if (ObjCClassRedefinitionType.isNull())
1544       return getObjCClassType();
1545     return ObjCClassRedefinitionType;
1546   }
1547
1548   /// \brief Set the user-written type that redefines 'SEL'.
1549   void setObjCClassRedefinitionType(QualType RedefType) {
1550     ObjCClassRedefinitionType = RedefType;
1551   }
1552
1553   /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1554   /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1555   QualType getObjCSelRedefinitionType() const {
1556     if (ObjCSelRedefinitionType.isNull())
1557       return getObjCSelType();
1558     return ObjCSelRedefinitionType;
1559   }
1560
1561   /// \brief Set the user-written type that redefines 'SEL'.
1562   void setObjCSelRedefinitionType(QualType RedefType) {
1563     ObjCSelRedefinitionType = RedefType;
1564   }
1565
1566   /// Retrieve the identifier 'NSObject'.
1567   IdentifierInfo *getNSObjectName() {
1568     if (!NSObjectName) {
1569       NSObjectName = &Idents.get("NSObject");
1570     }
1571
1572     return NSObjectName;
1573   }
1574
1575   /// Retrieve the identifier 'NSCopying'.
1576   IdentifierInfo *getNSCopyingName() {
1577     if (!NSCopyingName) {
1578       NSCopyingName = &Idents.get("NSCopying");
1579     }
1580
1581     return NSCopyingName;
1582   }
1583
1584   /// Retrieve the identifier 'bool'.
1585   IdentifierInfo *getBoolName() const {
1586     if (!BoolName)
1587       BoolName = &Idents.get("bool");
1588     return BoolName;
1589   }
1590
1591   IdentifierInfo *getMakeIntegerSeqName() const {
1592     if (!MakeIntegerSeqName)
1593       MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1594     return MakeIntegerSeqName;
1595   }
1596
1597   IdentifierInfo *getTypePackElementName() const {
1598     if (!TypePackElementName)
1599       TypePackElementName = &Idents.get("__type_pack_element");
1600     return TypePackElementName;
1601   }
1602
1603   /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1604   /// otherwise, returns a NULL type;
1605   QualType getObjCInstanceType() {
1606     return getTypeDeclType(getObjCInstanceTypeDecl());
1607   }
1608
1609   /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1610   /// "instancetype" type.
1611   TypedefDecl *getObjCInstanceTypeDecl();
1612
1613   /// \brief Set the type for the C FILE type.
1614   void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1615
1616   /// \brief Retrieve the C FILE type.
1617   QualType getFILEType() const {
1618     if (FILEDecl)
1619       return getTypeDeclType(FILEDecl);
1620     return QualType();
1621   }
1622
1623   /// \brief Set the type for the C jmp_buf type.
1624   void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1625     this->jmp_bufDecl = jmp_bufDecl;
1626   }
1627
1628   /// \brief Retrieve the C jmp_buf type.
1629   QualType getjmp_bufType() const {
1630     if (jmp_bufDecl)
1631       return getTypeDeclType(jmp_bufDecl);
1632     return QualType();
1633   }
1634
1635   /// \brief Set the type for the C sigjmp_buf type.
1636   void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1637     this->sigjmp_bufDecl = sigjmp_bufDecl;
1638   }
1639
1640   /// \brief Retrieve the C sigjmp_buf type.
1641   QualType getsigjmp_bufType() const {
1642     if (sigjmp_bufDecl)
1643       return getTypeDeclType(sigjmp_bufDecl);
1644     return QualType();
1645   }
1646
1647   /// \brief Set the type for the C ucontext_t type.
1648   void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1649     this->ucontext_tDecl = ucontext_tDecl;
1650   }
1651
1652   /// \brief Retrieve the C ucontext_t type.
1653   QualType getucontext_tType() const {
1654     if (ucontext_tDecl)
1655       return getTypeDeclType(ucontext_tDecl);
1656     return QualType();
1657   }
1658
1659   /// \brief The result type of logical operations, '<', '>', '!=', etc.
1660   QualType getLogicalOperationType() const {
1661     return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1662   }
1663
1664   /// \brief Emit the Objective-CC type encoding for the given type \p T into
1665   /// \p S.
1666   ///
1667   /// If \p Field is specified then record field names are also encoded.
1668   void getObjCEncodingForType(QualType T, std::string &S,
1669                               const FieldDecl *Field=nullptr,
1670                               QualType *NotEncodedT=nullptr) const;
1671
1672   /// \brief Emit the Objective-C property type encoding for the given
1673   /// type \p T into \p S.
1674   void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1675
1676   void getLegacyIntegralTypeEncoding(QualType &t) const;
1677
1678   /// \brief Put the string version of the type qualifiers \p QT into \p S.
1679   void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1680                                        std::string &S) const;
1681
1682   /// \brief Emit the encoded type for the function \p Decl into \p S.
1683   ///
1684   /// This is in the same format as Objective-C method encodings.
1685   ///
1686   /// \returns true if an error occurred (e.g., because one of the parameter
1687   /// types is incomplete), false otherwise.
1688   std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1689
1690   /// \brief Emit the encoded type for the method declaration \p Decl into
1691   /// \p S.
1692   std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1693                                            bool Extended = false) const;
1694
1695   /// \brief Return the encoded type for this block declaration.
1696   std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1697
1698   /// getObjCEncodingForPropertyDecl - Return the encoded type for
1699   /// this method declaration. If non-NULL, Container must be either
1700   /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1701   /// only be NULL when getting encodings for protocol properties.
1702   std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1703                                              const Decl *Container) const;
1704
1705   bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1706                                       ObjCProtocolDecl *rProto) const;
1707
1708   ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1709                                                   const ObjCPropertyDecl *PD,
1710                                                   const Decl *Container) const;
1711
1712   /// \brief Return the size of type \p T for Objective-C encoding purpose,
1713   /// in characters.
1714   CharUnits getObjCEncodingTypeSize(QualType T) const;
1715
1716   /// \brief Retrieve the typedef corresponding to the predefined \c id type
1717   /// in Objective-C.
1718   TypedefDecl *getObjCIdDecl() const;
1719
1720   /// \brief Represents the Objective-CC \c id type.
1721   ///
1722   /// This is set up lazily, by Sema.  \c id is always a (typedef for a)
1723   /// pointer type, a pointer to a struct.
1724   QualType getObjCIdType() const {
1725     return getTypeDeclType(getObjCIdDecl());
1726   }
1727
1728   /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1729   /// in Objective-C.
1730   TypedefDecl *getObjCSelDecl() const;
1731
1732   /// \brief Retrieve the type that corresponds to the predefined Objective-C
1733   /// 'SEL' type.
1734   QualType getObjCSelType() const {
1735     return getTypeDeclType(getObjCSelDecl());
1736   }
1737
1738   /// \brief Retrieve the typedef declaration corresponding to the predefined
1739   /// Objective-C 'Class' type.
1740   TypedefDecl *getObjCClassDecl() const;
1741
1742   /// \brief Represents the Objective-C \c Class type.
1743   ///
1744   /// This is set up lazily, by Sema.  \c Class is always a (typedef for a)
1745   /// pointer type, a pointer to a struct.
1746   QualType getObjCClassType() const {
1747     return getTypeDeclType(getObjCClassDecl());
1748   }
1749
1750   /// \brief Retrieve the Objective-C class declaration corresponding to
1751   /// the predefined \c Protocol class.
1752   ObjCInterfaceDecl *getObjCProtocolDecl() const;
1753
1754   /// \brief Retrieve declaration of 'BOOL' typedef
1755   TypedefDecl *getBOOLDecl() const {
1756     return BOOLDecl;
1757   }
1758
1759   /// \brief Save declaration of 'BOOL' typedef
1760   void setBOOLDecl(TypedefDecl *TD) {
1761     BOOLDecl = TD;
1762   }
1763
1764   /// \brief type of 'BOOL' type.
1765   QualType getBOOLType() const {
1766     return getTypeDeclType(getBOOLDecl());
1767   }
1768
1769   /// \brief Retrieve the type of the Objective-C \c Protocol class.
1770   QualType getObjCProtoType() const {
1771     return getObjCInterfaceType(getObjCProtocolDecl());
1772   }
1773
1774   /// \brief Retrieve the C type declaration corresponding to the predefined
1775   /// \c __builtin_va_list type.
1776   TypedefDecl *getBuiltinVaListDecl() const;
1777
1778   /// \brief Retrieve the type of the \c __builtin_va_list type.
1779   QualType getBuiltinVaListType() const {
1780     return getTypeDeclType(getBuiltinVaListDecl());
1781   }
1782
1783   /// \brief Retrieve the C type declaration corresponding to the predefined
1784   /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1785   /// for some targets.
1786   Decl *getVaListTagDecl() const;
1787
1788   /// Retrieve the C type declaration corresponding to the predefined
1789   /// \c __builtin_ms_va_list type.
1790   TypedefDecl *getBuiltinMSVaListDecl() const;
1791
1792   /// Retrieve the type of the \c __builtin_ms_va_list type.
1793   QualType getBuiltinMSVaListType() const {
1794     return getTypeDeclType(getBuiltinMSVaListDecl());
1795   }
1796
1797   /// \brief Return a type with additional \c const, \c volatile, or
1798   /// \c restrict qualifiers.
1799   QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1800     return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1801   }
1802
1803   /// \brief Un-split a SplitQualType.
1804   QualType getQualifiedType(SplitQualType split) const {
1805     return getQualifiedType(split.Ty, split.Quals);
1806   }
1807
1808   /// \brief Return a type with additional qualifiers.
1809   QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1810     if (!Qs.hasNonFastQualifiers())
1811       return T.withFastQualifiers(Qs.getFastQualifiers());
1812     QualifierCollector Qc(Qs);
1813     const Type *Ptr = Qc.strip(T);
1814     return getExtQualType(Ptr, Qc);
1815   }
1816
1817   /// \brief Return a type with additional qualifiers.
1818   QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1819     if (!Qs.hasNonFastQualifiers())
1820       return QualType(T, Qs.getFastQualifiers());
1821     return getExtQualType(T, Qs);
1822   }
1823
1824   /// \brief Return a type with the given lifetime qualifier.
1825   ///
1826   /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1827   QualType getLifetimeQualifiedType(QualType type,
1828                                     Qualifiers::ObjCLifetime lifetime) {
1829     assert(type.getObjCLifetime() == Qualifiers::OCL_None);
1830     assert(lifetime != Qualifiers::OCL_None);
1831
1832     Qualifiers qs;
1833     qs.addObjCLifetime(lifetime);
1834     return getQualifiedType(type, qs);
1835   }
1836
1837   /// getUnqualifiedObjCPointerType - Returns version of
1838   /// Objective-C pointer type with lifetime qualifier removed.
1839   QualType getUnqualifiedObjCPointerType(QualType type) const {
1840     if (!type.getTypePtr()->isObjCObjectPointerType() ||
1841         !type.getQualifiers().hasObjCLifetime())
1842       return type;
1843     Qualifiers Qs = type.getQualifiers();
1844     Qs.removeObjCLifetime();
1845     return getQualifiedType(type.getUnqualifiedType(), Qs);
1846   }
1847
1848   DeclarationNameInfo getNameForTemplate(TemplateName Name,
1849                                          SourceLocation NameLoc) const;
1850
1851   TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1852                                          UnresolvedSetIterator End) const;
1853
1854   TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1855                                         bool TemplateKeyword,
1856                                         TemplateDecl *Template) const;
1857
1858   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1859                                         const IdentifierInfo *Name) const;
1860   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1861                                         OverloadedOperatorKind Operator) const;
1862   TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1863                                             TemplateName replacement) const;
1864   TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1865                                         const TemplateArgument &ArgPack) const;
1866
1867   enum GetBuiltinTypeError {
1868     GE_None,              ///< No error
1869     GE_Missing_stdio,     ///< Missing a type from <stdio.h>
1870     GE_Missing_setjmp,    ///< Missing a type from <setjmp.h>
1871     GE_Missing_ucontext   ///< Missing a type from <ucontext.h>
1872   };
1873
1874   /// \brief Return the type for the specified builtin.
1875   ///
1876   /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1877   /// arguments to the builtin that are required to be integer constant
1878   /// expressions.
1879   QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1880                           unsigned *IntegerConstantArgs = nullptr) const;
1881
1882 private:
1883   CanQualType getFromTargetType(unsigned Type) const;
1884   TypeInfo getTypeInfoImpl(const Type *T) const;
1885
1886   //===--------------------------------------------------------------------===//
1887   //                         Type Predicates.
1888   //===--------------------------------------------------------------------===//
1889
1890 public:
1891   /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1892   /// collection attributes.
1893   Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1894
1895   /// \brief Return true if the given vector types are of the same unqualified
1896   /// type or if they are equivalent to the same GCC vector type.
1897   ///
1898   /// \note This ignores whether they are target-specific (AltiVec or Neon)
1899   /// types.
1900   bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1901
1902   /// \brief Return true if this is an \c NSObject object with its \c NSObject
1903   /// attribute set.
1904   static bool isObjCNSObjectType(QualType Ty) {
1905     return Ty->isObjCNSObjectType();
1906   }
1907
1908   //===--------------------------------------------------------------------===//
1909   //                         Type Sizing and Analysis
1910   //===--------------------------------------------------------------------===//
1911
1912   /// \brief Return the APFloat 'semantics' for the specified scalar floating
1913   /// point type.
1914   const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
1915
1916   /// \brief Get the size and alignment of the specified complete type in bits.
1917   TypeInfo getTypeInfo(const Type *T) const;
1918   TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
1919
1920   /// \brief Get default simd alignment of the specified complete type in bits.
1921   unsigned getOpenMPDefaultSimdAlign(QualType T) const;
1922
1923   /// \brief Return the size of the specified (complete) type \p T, in bits.
1924   uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
1925   uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
1926
1927   /// \brief Return the size of the character type, in bits.
1928   uint64_t getCharWidth() const {
1929     return getTypeSize(CharTy);
1930   }
1931
1932   /// \brief Convert a size in bits to a size in characters.
1933   CharUnits toCharUnitsFromBits(int64_t BitSize) const;
1934
1935   /// \brief Convert a size in characters to a size in bits.
1936   int64_t toBits(CharUnits CharSize) const;
1937
1938   /// \brief Return the size of the specified (complete) type \p T, in
1939   /// characters.
1940   CharUnits getTypeSizeInChars(QualType T) const;
1941   CharUnits getTypeSizeInChars(const Type *T) const;
1942
1943   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1944   /// bits.
1945   unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
1946   unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
1947
1948   /// \brief Return the ABI-specified alignment of a type, in bits, or 0 if
1949   /// the type is incomplete and we cannot determine the alignment (for
1950   /// example, from alignment attributes).
1951   unsigned getTypeAlignIfKnown(QualType T) const;
1952
1953   /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
1954   /// characters.
1955   CharUnits getTypeAlignInChars(QualType T) const;
1956   CharUnits getTypeAlignInChars(const Type *T) const;
1957
1958   // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
1959   // type is a record, its data size is returned.
1960   std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
1961
1962   std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
1963   std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
1964
1965   /// \brief Determine if the alignment the type has was required using an
1966   /// alignment attribute.
1967   bool isAlignmentRequired(const Type *T) const;
1968   bool isAlignmentRequired(QualType T) const;
1969
1970   /// \brief Return the "preferred" alignment of the specified type \p T for
1971   /// the current target, in bits.
1972   ///
1973   /// This can be different than the ABI alignment in cases where it is
1974   /// beneficial for performance to overalign a data type.
1975   unsigned getPreferredTypeAlign(const Type *T) const;
1976
1977   /// \brief Return the default alignment for __attribute__((aligned)) on
1978   /// this target, to be used if no alignment value is specified.
1979   unsigned getTargetDefaultAlignForAttributeAligned() const;
1980
1981   /// \brief Return the alignment in bits that should be given to a
1982   /// global variable with type \p T.
1983   unsigned getAlignOfGlobalVar(QualType T) const;
1984
1985   /// \brief Return the alignment in characters that should be given to a
1986   /// global variable with type \p T.
1987   CharUnits getAlignOfGlobalVarInChars(QualType T) const;
1988
1989   /// \brief Return a conservative estimate of the alignment of the specified
1990   /// decl \p D.
1991   ///
1992   /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
1993   /// alignment.
1994   ///
1995   /// If \p ForAlignof, references are treated like their underlying type
1996   /// and  large arrays don't get any special treatment. If not \p ForAlignof
1997   /// it computes the value expected by CodeGen: references are treated like
1998   /// pointers and large arrays get extra alignment.
1999   CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2000
2001   /// \brief Get or compute information about the layout of the specified
2002   /// record (struct/union/class) \p D, which indicates its size and field
2003   /// position information.
2004   const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2005
2006   /// \brief Get or compute information about the layout of the specified
2007   /// Objective-C interface.
2008   const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2009     const;
2010
2011   void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2012                         bool Simple = false) const;
2013
2014   /// \brief Get or compute information about the layout of the specified
2015   /// Objective-C implementation.
2016   ///
2017   /// This may differ from the interface if synthesized ivars are present.
2018   const ASTRecordLayout &
2019   getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2020
2021   /// \brief Get our current best idea for the key function of the
2022   /// given record decl, or NULL if there isn't one.
2023   ///
2024   /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2025   ///   ...the first non-pure virtual function that is not inline at the
2026   ///   point of class definition.
2027   ///
2028   /// Other ABIs use the same idea.  However, the ARM C++ ABI ignores
2029   /// virtual functions that are defined 'inline', which means that
2030   /// the result of this computation can change.
2031   const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2032
2033   /// \brief Observe that the given method cannot be a key function.
2034   /// Checks the key-function cache for the method's class and clears it
2035   /// if matches the given declaration.
2036   ///
2037   /// This is used in ABIs where out-of-line definitions marked
2038   /// inline are not considered to be key functions.
2039   ///
2040   /// \param method should be the declaration from the class definition
2041   void setNonKeyFunction(const CXXMethodDecl *method);
2042
2043   /// Loading virtual member pointers using the virtual inheritance model
2044   /// always results in an adjustment using the vbtable even if the index is
2045   /// zero.
2046   ///
2047   /// This is usually OK because the first slot in the vbtable points
2048   /// backwards to the top of the MDC.  However, the MDC might be reusing a
2049   /// vbptr from an nv-base.  In this case, the first slot in the vbtable
2050   /// points to the start of the nv-base which introduced the vbptr and *not*
2051   /// the MDC.  Modify the NonVirtualBaseAdjustment to account for this.
2052   CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2053
2054   /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2055   uint64_t getFieldOffset(const ValueDecl *FD) const;
2056
2057   /// Get the offset of an ObjCIvarDecl in bits.
2058   uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2059                                 const ObjCImplementationDecl *ID,
2060                                 const ObjCIvarDecl *Ivar) const;
2061
2062   bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2063
2064   VTableContextBase *getVTableContext();
2065
2066   MangleContext *createMangleContext();
2067
2068   void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2069                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2070
2071   unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2072   void CollectInheritedProtocols(const Decl *CDecl,
2073                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2074
2075   //===--------------------------------------------------------------------===//
2076   //                            Type Operators
2077   //===--------------------------------------------------------------------===//
2078
2079   /// \brief Return the canonical (structural) type corresponding to the
2080   /// specified potentially non-canonical type \p T.
2081   ///
2082   /// The non-canonical version of a type may have many "decorated" versions of
2083   /// types.  Decorators can include typedefs, 'typeof' operators, etc. The
2084   /// returned type is guaranteed to be free of any of these, allowing two
2085   /// canonical types to be compared for exact equality with a simple pointer
2086   /// comparison.
2087   CanQualType getCanonicalType(QualType T) const {
2088     return CanQualType::CreateUnsafe(T.getCanonicalType());
2089   }
2090
2091   const Type *getCanonicalType(const Type *T) const {
2092     return T->getCanonicalTypeInternal().getTypePtr();
2093   }
2094
2095   /// \brief Return the canonical parameter type corresponding to the specific
2096   /// potentially non-canonical one.
2097   ///
2098   /// Qualifiers are stripped off, functions are turned into function
2099   /// pointers, and arrays decay one level into pointers.
2100   CanQualType getCanonicalParamType(QualType T) const;
2101
2102   /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
2103   bool hasSameType(QualType T1, QualType T2) const {
2104     return getCanonicalType(T1) == getCanonicalType(T2);
2105   }
2106
2107   bool hasSameType(const Type *T1, const Type *T2) const {
2108     return getCanonicalType(T1) == getCanonicalType(T2);
2109   }
2110
2111   /// \brief Return this type as a completely-unqualified array type,
2112   /// capturing the qualifiers in \p Quals.
2113   ///
2114   /// This will remove the minimal amount of sugaring from the types, similar
2115   /// to the behavior of QualType::getUnqualifiedType().
2116   ///
2117   /// \param T is the qualified type, which may be an ArrayType
2118   ///
2119   /// \param Quals will receive the full set of qualifiers that were
2120   /// applied to the array.
2121   ///
2122   /// \returns if this is an array type, the completely unqualified array type
2123   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2124   QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2125
2126   /// \brief Determine whether the given types are equivalent after
2127   /// cvr-qualifiers have been removed.
2128   bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2129     return getCanonicalType(T1).getTypePtr() ==
2130            getCanonicalType(T2).getTypePtr();
2131   }
2132
2133   bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2134                                        bool IsParam) const {
2135     auto SubTnullability = SubT->getNullability(*this);
2136     auto SuperTnullability = SuperT->getNullability(*this);
2137     if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2138       // Neither has nullability; return true
2139       if (!SubTnullability)
2140         return true;
2141       // Both have nullability qualifier.
2142       if (*SubTnullability == *SuperTnullability ||
2143           *SubTnullability == NullabilityKind::Unspecified ||
2144           *SuperTnullability == NullabilityKind::Unspecified)
2145         return true;
2146
2147       if (IsParam) {
2148         // Ok for the superclass method parameter to be "nonnull" and the subclass
2149         // method parameter to be "nullable"
2150         return (*SuperTnullability == NullabilityKind::NonNull &&
2151                 *SubTnullability == NullabilityKind::Nullable);
2152       }
2153       else {
2154         // For the return type, it's okay for the superclass method to specify
2155         // "nullable" and the subclass method specify "nonnull"
2156         return (*SuperTnullability == NullabilityKind::Nullable &&
2157                 *SubTnullability == NullabilityKind::NonNull);
2158       }
2159     }
2160     return true;
2161   }
2162
2163   bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2164                            const ObjCMethodDecl *MethodImp);
2165
2166   bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2167
2168   /// \brief Retrieves the "canonical" nested name specifier for a
2169   /// given nested name specifier.
2170   ///
2171   /// The canonical nested name specifier is a nested name specifier
2172   /// that uniquely identifies a type or namespace within the type
2173   /// system. For example, given:
2174   ///
2175   /// \code
2176   /// namespace N {
2177   ///   struct S {
2178   ///     template<typename T> struct X { typename T* type; };
2179   ///   };
2180   /// }
2181   ///
2182   /// template<typename T> struct Y {
2183   ///   typename N::S::X<T>::type member;
2184   /// };
2185   /// \endcode
2186   ///
2187   /// Here, the nested-name-specifier for N::S::X<T>:: will be
2188   /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2189   /// by declarations in the type system and the canonical type for
2190   /// the template type parameter 'T' is template-param-0-0.
2191   NestedNameSpecifier *
2192   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2193
2194   /// \brief Retrieves the default calling convention for the current target.
2195   CallingConv getDefaultCallingConvention(bool isVariadic,
2196                                           bool IsCXXMethod) const;
2197
2198   /// \brief Retrieves the "canonical" template name that refers to a
2199   /// given template.
2200   ///
2201   /// The canonical template name is the simplest expression that can
2202   /// be used to refer to a given template. For most templates, this
2203   /// expression is just the template declaration itself. For example,
2204   /// the template std::vector can be referred to via a variety of
2205   /// names---std::vector, \::std::vector, vector (if vector is in
2206   /// scope), etc.---but all of these names map down to the same
2207   /// TemplateDecl, which is used to form the canonical template name.
2208   ///
2209   /// Dependent template names are more interesting. Here, the
2210   /// template name could be something like T::template apply or
2211   /// std::allocator<T>::template rebind, where the nested name
2212   /// specifier itself is dependent. In this case, the canonical
2213   /// template name uses the shortest form of the dependent
2214   /// nested-name-specifier, which itself contains all canonical
2215   /// types, values, and templates.
2216   TemplateName getCanonicalTemplateName(TemplateName Name) const;
2217
2218   /// \brief Determine whether the given template names refer to the same
2219   /// template.
2220   bool hasSameTemplateName(TemplateName X, TemplateName Y);
2221
2222   /// \brief Retrieve the "canonical" template argument.
2223   ///
2224   /// The canonical template argument is the simplest template argument
2225   /// (which may be a type, value, expression, or declaration) that
2226   /// expresses the value of the argument.
2227   TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2228     const;
2229
2230   /// Type Query functions.  If the type is an instance of the specified class,
2231   /// return the Type pointer for the underlying maximally pretty type.  This
2232   /// is a member of ASTContext because this may need to do some amount of
2233   /// canonicalization, e.g. to move type qualifiers into the element type.
2234   const ArrayType *getAsArrayType(QualType T) const;
2235   const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2236     return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2237   }
2238   const VariableArrayType *getAsVariableArrayType(QualType T) const {
2239     return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2240   }
2241   const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2242     return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2243   }
2244   const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2245     const {
2246     return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2247   }
2248
2249   /// \brief Return the innermost element type of an array type.
2250   ///
2251   /// For example, will return "int" for int[m][n]
2252   QualType getBaseElementType(const ArrayType *VAT) const;
2253
2254   /// \brief Return the innermost element type of a type (which needn't
2255   /// actually be an array type).
2256   QualType getBaseElementType(QualType QT) const;
2257
2258   /// \brief Return number of constant array elements.
2259   uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2260
2261   /// \brief Perform adjustment on the parameter type of a function.
2262   ///
2263   /// This routine adjusts the given parameter type @p T to the actual
2264   /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2265   /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2266   QualType getAdjustedParameterType(QualType T) const;
2267
2268   /// \brief Retrieve the parameter type as adjusted for use in the signature
2269   /// of a function, decaying array and function types and removing top-level
2270   /// cv-qualifiers.
2271   QualType getSignatureParameterType(QualType T) const;
2272
2273   QualType getExceptionObjectType(QualType T) const;
2274
2275   /// \brief Return the properly qualified result of decaying the specified
2276   /// array type to a pointer.
2277   ///
2278   /// This operation is non-trivial when handling typedefs etc.  The canonical
2279   /// type of \p T must be an array type, this returns a pointer to a properly
2280   /// qualified element of the array.
2281   ///
2282   /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2283   QualType getArrayDecayedType(QualType T) const;
2284
2285   /// \brief Return the type that \p PromotableType will promote to: C99
2286   /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2287   QualType getPromotedIntegerType(QualType PromotableType) const;
2288
2289   /// \brief Recurses in pointer/array types until it finds an Objective-C
2290   /// retainable type and returns its ownership.
2291   Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2292
2293   /// \brief Whether this is a promotable bitfield reference according
2294   /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2295   ///
2296   /// \returns the type this bit-field will promote to, or NULL if no
2297   /// promotion occurs.
2298   QualType isPromotableBitField(Expr *E) const;
2299
2300   /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2301   ///
2302   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
2303   /// \p LHS < \p RHS, return -1.
2304   int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2305
2306   /// \brief Compare the rank of the two specified floating point types,
2307   /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2308   ///
2309   /// If \p LHS > \p RHS, returns 1.  If \p LHS == \p RHS, returns 0.  If
2310   /// \p LHS < \p RHS, return -1.
2311   int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2312
2313   /// \brief Return a real floating point or a complex type (based on
2314   /// \p typeDomain/\p typeSize).
2315   ///
2316   /// \param typeDomain a real floating point or complex type.
2317   /// \param typeSize a real floating point or complex type.
2318   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2319                                              QualType typeDomain) const;
2320
2321   unsigned getTargetAddressSpace(QualType T) const {
2322     return getTargetAddressSpace(T.getQualifiers());
2323   }
2324
2325   unsigned getTargetAddressSpace(Qualifiers Q) const {
2326     return getTargetAddressSpace(Q.getAddressSpace());
2327   }
2328
2329   unsigned getTargetAddressSpace(unsigned AS) const;
2330
2331   /// Get target-dependent integer value for null pointer which is used for
2332   /// constant folding.
2333   uint64_t getTargetNullPointerValue(QualType QT) const;
2334
2335   bool addressSpaceMapManglingFor(unsigned AS) const {
2336     return AddrSpaceMapMangling || AS >= LangAS::FirstTargetAddressSpace;
2337   }
2338
2339 private:
2340   // Helper for integer ordering
2341   unsigned getIntegerRank(const Type *T) const;
2342
2343 public:
2344   //===--------------------------------------------------------------------===//
2345   //                    Type Compatibility Predicates
2346   //===--------------------------------------------------------------------===//
2347
2348   /// Compatibility predicates used to check assignment expressions.
2349   bool typesAreCompatible(QualType T1, QualType T2,
2350                           bool CompareUnqualified = false); // C99 6.2.7p1
2351
2352   bool propertyTypesAreCompatible(QualType, QualType);
2353   bool typesAreBlockPointerCompatible(QualType, QualType);
2354
2355   bool isObjCIdType(QualType T) const {
2356     return T == getObjCIdType();
2357   }
2358   bool isObjCClassType(QualType T) const {
2359     return T == getObjCClassType();
2360   }
2361   bool isObjCSelType(QualType T) const {
2362     return T == getObjCSelType();
2363   }
2364   bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2365                                          bool ForCompare);
2366
2367   bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2368
2369   // Check the safety of assignment from LHS to RHS
2370   bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2371                                const ObjCObjectPointerType *RHSOPT);
2372   bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2373                                const ObjCObjectType *RHS);
2374   bool canAssignObjCInterfacesInBlockPointer(
2375                                           const ObjCObjectPointerType *LHSOPT,
2376                                           const ObjCObjectPointerType *RHSOPT,
2377                                           bool BlockReturnType);
2378   bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2379   QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2380                                    const ObjCObjectPointerType *RHSOPT);
2381   bool canBindObjCObjectType(QualType To, QualType From);
2382
2383   // Functions for calculating composite types
2384   QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2385                       bool Unqualified = false, bool BlockReturnType = false);
2386   QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2387                               bool Unqualified = false);
2388   QualType mergeFunctionParameterTypes(QualType, QualType,
2389                                        bool OfBlockPointer = false,
2390                                        bool Unqualified = false);
2391   QualType mergeTransparentUnionType(QualType, QualType,
2392                                      bool OfBlockPointer=false,
2393                                      bool Unqualified = false);
2394
2395   QualType mergeObjCGCQualifiers(QualType, QualType);
2396
2397   bool doFunctionTypesMatchOnExtParameterInfos(
2398          const FunctionProtoType *FromFunctionType,
2399          const FunctionProtoType *ToFunctionType);
2400
2401   void ResetObjCLayout(const ObjCContainerDecl *CD);
2402
2403   //===--------------------------------------------------------------------===//
2404   //                    Integer Predicates
2405   //===--------------------------------------------------------------------===//
2406
2407   // The width of an integer, as defined in C99 6.2.6.2. This is the number
2408   // of bits in an integer type excluding any padding bits.
2409   unsigned getIntWidth(QualType T) const;
2410
2411   // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2412   // unsigned integer type.  This method takes a signed type, and returns the
2413   // corresponding unsigned integer type.
2414   QualType getCorrespondingUnsignedType(QualType T) const;
2415
2416   //===--------------------------------------------------------------------===//
2417   //                    Integer Values
2418   //===--------------------------------------------------------------------===//
2419
2420   /// \brief Make an APSInt of the appropriate width and signedness for the
2421   /// given \p Value and integer \p Type.
2422   llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2423     // If Type is a signed integer type larger than 64 bits, we need to be sure
2424     // to sign extend Res appropriately.
2425     llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2426     Res = Value;
2427     unsigned Width = getIntWidth(Type);
2428     if (Width != Res.getBitWidth())
2429       return Res.extOrTrunc(Width);
2430     return Res;
2431   }
2432
2433   bool isSentinelNullExpr(const Expr *E);
2434
2435   /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
2436   /// none exists.
2437   ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2438   /// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
2439   /// none exists.
2440   ObjCCategoryImplDecl   *getObjCImplementation(ObjCCategoryDecl *D);
2441
2442   /// \brief Return true if there is at least one \@implementation in the TU.
2443   bool AnyObjCImplementation() {
2444     return !ObjCImpls.empty();
2445   }
2446
2447   /// \brief Set the implementation of ObjCInterfaceDecl.
2448   void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2449                              ObjCImplementationDecl *ImplD);
2450   /// \brief Set the implementation of ObjCCategoryDecl.
2451   void setObjCImplementation(ObjCCategoryDecl *CatD,
2452                              ObjCCategoryImplDecl *ImplD);
2453
2454   /// \brief Get the duplicate declaration of a ObjCMethod in the same
2455   /// interface, or null if none exists.
2456   const ObjCMethodDecl *
2457   getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2458
2459   void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2460                                   const ObjCMethodDecl *Redecl);
2461
2462   /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2463   /// an Objective-C method/property/ivar etc. that is part of an interface,
2464   /// otherwise returns null.
2465   const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2466
2467   /// \brief Set the copy inialization expression of a block var decl.
2468   void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2469   /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2470   /// NULL if none exists.
2471   Expr *getBlockVarCopyInits(const VarDecl* VD);
2472
2473   /// \brief Allocate an uninitialized TypeSourceInfo.
2474   ///
2475   /// The caller should initialize the memory held by TypeSourceInfo using
2476   /// the TypeLoc wrappers.
2477   ///
2478   /// \param T the type that will be the basis for type source info. This type
2479   /// should refer to how the declarator was written in source code, not to
2480   /// what type semantic analysis resolved the declarator to.
2481   ///
2482   /// \param Size the size of the type info to create, or 0 if the size
2483   /// should be calculated based on the type.
2484   TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2485
2486   /// \brief Allocate a TypeSourceInfo where all locations have been
2487   /// initialized to a given location, which defaults to the empty
2488   /// location.
2489   TypeSourceInfo *
2490   getTrivialTypeSourceInfo(QualType T,
2491                            SourceLocation Loc = SourceLocation()) const;
2492
2493   /// \brief Add a deallocation callback that will be invoked when the
2494   /// ASTContext is destroyed.
2495   ///
2496   /// \param Callback A callback function that will be invoked on destruction.
2497   ///
2498   /// \param Data Pointer data that will be provided to the callback function
2499   /// when it is called.
2500   void AddDeallocation(void (*Callback)(void*), void *Data);
2501
2502   /// If T isn't trivially destructible, calls AddDeallocation to register it
2503   /// for destruction.
2504   template <typename T>
2505   void addDestruction(T *Ptr) {
2506     if (!std::is_trivially_destructible<T>::value) {
2507       auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2508       AddDeallocation(DestroyPtr, Ptr);
2509     }
2510   }
2511
2512   GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2513   GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2514
2515   /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2516   /// lazily, only when used; this is only relevant for function or file scoped
2517   /// var definitions.
2518   ///
2519   /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2520   /// it is not used.
2521   bool DeclMustBeEmitted(const Decl *D);
2522
2523   const CXXConstructorDecl *
2524   getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2525
2526   void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2527                                             CXXConstructorDecl *CD);
2528
2529   void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2530
2531   TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2532
2533   void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2534
2535   DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2536
2537   void setManglingNumber(const NamedDecl *ND, unsigned Number);
2538   unsigned getManglingNumber(const NamedDecl *ND) const;
2539
2540   void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2541   unsigned getStaticLocalNumber(const VarDecl *VD) const;
2542
2543   /// \brief Retrieve the context for computing mangling numbers in the given
2544   /// DeclContext.
2545   MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2546
2547   std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2548
2549   /// \brief Used by ParmVarDecl to store on the side the
2550   /// index of the parameter when it exceeds the size of the normal bitfield.
2551   void setParameterIndex(const ParmVarDecl *D, unsigned index);
2552
2553   /// \brief Used by ParmVarDecl to retrieve on the side the
2554   /// index of the parameter when it exceeds the size of the normal bitfield.
2555   unsigned getParameterIndex(const ParmVarDecl *D) const;
2556
2557   /// \brief Get the storage for the constant value of a materialized temporary
2558   /// of static storage duration.
2559   APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2560                                          bool MayCreate);
2561
2562   //===--------------------------------------------------------------------===//
2563   //                    Statistics
2564   //===--------------------------------------------------------------------===//
2565
2566   /// \brief The number of implicitly-declared default constructors.
2567   static unsigned NumImplicitDefaultConstructors;
2568
2569   /// \brief The number of implicitly-declared default constructors for
2570   /// which declarations were built.
2571   static unsigned NumImplicitDefaultConstructorsDeclared;
2572
2573   /// \brief The number of implicitly-declared copy constructors.
2574   static unsigned NumImplicitCopyConstructors;
2575
2576   /// \brief The number of implicitly-declared copy constructors for
2577   /// which declarations were built.
2578   static unsigned NumImplicitCopyConstructorsDeclared;
2579
2580   /// \brief The number of implicitly-declared move constructors.
2581   static unsigned NumImplicitMoveConstructors;
2582
2583   /// \brief The number of implicitly-declared move constructors for
2584   /// which declarations were built.
2585   static unsigned NumImplicitMoveConstructorsDeclared;
2586
2587   /// \brief The number of implicitly-declared copy assignment operators.
2588   static unsigned NumImplicitCopyAssignmentOperators;
2589
2590   /// \brief The number of implicitly-declared copy assignment operators for
2591   /// which declarations were built.
2592   static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2593
2594   /// \brief The number of implicitly-declared move assignment operators.
2595   static unsigned NumImplicitMoveAssignmentOperators;
2596
2597   /// \brief The number of implicitly-declared move assignment operators for
2598   /// which declarations were built.
2599   static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2600
2601   /// \brief The number of implicitly-declared destructors.
2602   static unsigned NumImplicitDestructors;
2603
2604   /// \brief The number of implicitly-declared destructors for which
2605   /// declarations were built.
2606   static unsigned NumImplicitDestructorsDeclared;
2607
2608 public:
2609   /// \brief Initialize built-in types.
2610   ///
2611   /// This routine may only be invoked once for a given ASTContext object.
2612   /// It is normally invoked after ASTContext construction.
2613   ///
2614   /// \param Target The target
2615   void InitBuiltinTypes(const TargetInfo &Target,
2616                         const TargetInfo *AuxTarget = nullptr);
2617
2618 private:
2619   void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2620
2621   // Return the Objective-C type encoding for a given type.
2622   void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2623                                   bool ExpandPointedToStructures,
2624                                   bool ExpandStructures,
2625                                   const FieldDecl *Field,
2626                                   bool OutermostType = false,
2627                                   bool EncodingProperty = false,
2628                                   bool StructField = false,
2629                                   bool EncodeBlockParameters = false,
2630                                   bool EncodeClassNames = false,
2631                                   bool EncodePointerToObjCTypedef = false,
2632                                   QualType *NotEncodedT=nullptr) const;
2633
2634   // Adds the encoding of the structure's members.
2635   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2636                                        const FieldDecl *Field,
2637                                        bool includeVBases = true,
2638                                        QualType *NotEncodedT=nullptr) const;
2639 public:
2640   // Adds the encoding of a method parameter or return type.
2641   void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2642                                          QualType T, std::string& S,
2643                                          bool Extended) const;
2644
2645   /// \brief Returns true if this is an inline-initialized static data member
2646   /// which is treated as a definition for MSVC compatibility.
2647   bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2648
2649   enum class InlineVariableDefinitionKind {
2650     None,        ///< Not an inline variable.
2651     Weak,        ///< Weak definition of inline variable.
2652     WeakUnknown, ///< Weak for now, might become strong later in this TU.
2653     Strong       ///< Strong definition.
2654   };
2655   /// \brief Determine whether a definition of this inline variable should
2656   /// be treated as a weak or strong definition. For compatibility with
2657   /// C++14 and before, for a constexpr static data member, if there is an
2658   /// out-of-line declaration of the member, we may promote it from weak to
2659   /// strong.
2660   InlineVariableDefinitionKind
2661   getInlineVariableDefinitionKind(const VarDecl *VD) const;
2662
2663 private:
2664   const ASTRecordLayout &
2665   getObjCLayout(const ObjCInterfaceDecl *D,
2666                 const ObjCImplementationDecl *Impl) const;
2667
2668   /// \brief A set of deallocations that should be performed when the
2669   /// ASTContext is destroyed.
2670   // FIXME: We really should have a better mechanism in the ASTContext to
2671   // manage running destructors for types which do variable sized allocation
2672   // within the AST. In some places we thread the AST bump pointer allocator
2673   // into the datastructures which avoids this mess during deallocation but is
2674   // wasteful of memory, and here we require a lot of error prone book keeping
2675   // in order to track and run destructors while we're tearing things down.
2676   typedef llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>
2677       DeallocationFunctionsAndArguments;
2678   DeallocationFunctionsAndArguments Deallocations;
2679
2680   // FIXME: This currently contains the set of StoredDeclMaps used
2681   // by DeclContext objects.  This probably should not be in ASTContext,
2682   // but we include it here so that ASTContext can quickly deallocate them.
2683   llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
2684
2685   friend class DeclContext;
2686   friend class DeclarationNameTable;
2687
2688   void ReleaseDeclContextMaps();
2689   void ReleaseParentMapEntries();
2690
2691   std::unique_ptr<ParentMapPointers> PointerParents;
2692   std::unique_ptr<ParentMapOtherNodes> OtherParents;
2693
2694   std::unique_ptr<VTableContextBase> VTContext;
2695
2696 public:
2697   enum PragmaSectionFlag : unsigned {
2698     PSF_None = 0,
2699     PSF_Read = 0x1,
2700     PSF_Write = 0x2,
2701     PSF_Execute = 0x4,
2702     PSF_Implicit = 0x8,
2703     PSF_Invalid = 0x80000000U,
2704   };
2705
2706   struct SectionInfo {
2707     DeclaratorDecl *Decl;
2708     SourceLocation PragmaSectionLocation;
2709     int SectionFlags;
2710
2711     SectionInfo() = default;
2712     SectionInfo(DeclaratorDecl *Decl,
2713                 SourceLocation PragmaSectionLocation,
2714                 int SectionFlags)
2715       : Decl(Decl),
2716         PragmaSectionLocation(PragmaSectionLocation),
2717         SectionFlags(SectionFlags) {}
2718   };
2719
2720   llvm::StringMap<SectionInfo> SectionInfos;
2721 };
2722
2723 /// \brief Utility function for constructing a nullary selector.
2724 static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
2725   IdentifierInfo* II = &Ctx.Idents.get(name);
2726   return Ctx.Selectors.getSelector(0, &II);
2727 }
2728
2729 /// \brief Utility function for constructing an unary selector.
2730 static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
2731   IdentifierInfo* II = &Ctx.Idents.get(name);
2732   return Ctx.Selectors.getSelector(1, &II);
2733 }
2734
2735 }  // end namespace clang
2736
2737 // operator new and delete aren't allowed inside namespaces.
2738
2739 /// @brief Placement new for using the ASTContext's allocator.
2740 ///
2741 /// This placement form of operator new uses the ASTContext's allocator for
2742 /// obtaining memory.
2743 ///
2744 /// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2745 /// here need to also be made there.
2746 ///
2747 /// We intentionally avoid using a nothrow specification here so that the calls
2748 /// to this operator will not perform a null check on the result -- the
2749 /// underlying allocator never returns null pointers.
2750 ///
2751 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2752 /// @code
2753 /// // Default alignment (8)
2754 /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2755 /// // Specific alignment
2756 /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2757 /// @endcode
2758 /// Memory allocated through this placement new operator does not need to be
2759 /// explicitly freed, as ASTContext will free all of this memory when it gets
2760 /// destroyed. Please note that you cannot use delete on the pointer.
2761 ///
2762 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2763 /// @param C The ASTContext that provides the allocator.
2764 /// @param Alignment The alignment of the allocated memory (if the underlying
2765 ///                  allocator supports it).
2766 /// @return The allocated memory. Could be NULL.
2767 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2768                           size_t Alignment) {
2769   return C.Allocate(Bytes, Alignment);
2770 }
2771 /// @brief Placement delete companion to the new above.
2772 ///
2773 /// This operator is just a companion to the new above. There is no way of
2774 /// invoking it directly; see the new operator for more details. This operator
2775 /// is called implicitly by the compiler if a placement new expression using
2776 /// the ASTContext throws in the object constructor.
2777 inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2778   C.Deallocate(Ptr);
2779 }
2780
2781 /// This placement form of operator new[] uses the ASTContext's allocator for
2782 /// obtaining memory.
2783 ///
2784 /// We intentionally avoid using a nothrow specification here so that the calls
2785 /// to this operator will not perform a null check on the result -- the
2786 /// underlying allocator never returns null pointers.
2787 ///
2788 /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2789 /// @code
2790 /// // Default alignment (8)
2791 /// char *data = new (Context) char[10];
2792 /// // Specific alignment
2793 /// char *data = new (Context, 4) char[10];
2794 /// @endcode
2795 /// Memory allocated through this placement new[] operator does not need to be
2796 /// explicitly freed, as ASTContext will free all of this memory when it gets
2797 /// destroyed. Please note that you cannot use delete on the pointer.
2798 ///
2799 /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2800 /// @param C The ASTContext that provides the allocator.
2801 /// @param Alignment The alignment of the allocated memory (if the underlying
2802 ///                  allocator supports it).
2803 /// @return The allocated memory. Could be NULL.
2804 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2805                             size_t Alignment = 8) {
2806   return C.Allocate(Bytes, Alignment);
2807 }
2808
2809 /// @brief Placement delete[] companion to the new[] above.
2810 ///
2811 /// This operator is just a companion to the new[] above. There is no way of
2812 /// invoking it directly; see the new[] operator for more details. This operator
2813 /// is called implicitly by the compiler if a placement new[] expression using
2814 /// the ASTContext throws in the object constructor.
2815 inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2816   C.Deallocate(Ptr);
2817 }
2818
2819 /// \brief Create the representation of a LazyGenerationalUpdatePtr.
2820 template <typename Owner, typename T,
2821           void (clang::ExternalASTSource::*Update)(Owner)>
2822 typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2823     clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2824         const clang::ASTContext &Ctx, T Value) {
2825   // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2826   // include ASTContext.h. We explicitly instantiate it for all relevant types
2827   // in ASTContext.cpp.
2828   if (auto *Source = Ctx.getExternalSource())
2829     return new (Ctx) LazyData(Source, Value);
2830   return Value;
2831 }
2832
2833 #endif // LLVM_CLANG_AST_ASTCONTEXT_H