Coverage Report

Created: 2021-08-24 07:12

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