Coverage Report

Created: 2018-07-22 10:17

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