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