Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/ASTContext.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the ASTContext interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "CXXABI.h"
15
#include "Interp/Context.h"
16
#include "clang/AST/APValue.h"
17
#include "clang/AST/ASTConcept.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/ASTTypeTraits.h"
20
#include "clang/AST/Attr.h"
21
#include "clang/AST/AttrIterator.h"
22
#include "clang/AST/CharUnits.h"
23
#include "clang/AST/Comment.h"
24
#include "clang/AST/Decl.h"
25
#include "clang/AST/DeclBase.h"
26
#include "clang/AST/DeclCXX.h"
27
#include "clang/AST/DeclContextInternals.h"
28
#include "clang/AST/DeclObjC.h"
29
#include "clang/AST/DeclOpenMP.h"
30
#include "clang/AST/DeclTemplate.h"
31
#include "clang/AST/DeclarationName.h"
32
#include "clang/AST/DependenceFlags.h"
33
#include "clang/AST/Expr.h"
34
#include "clang/AST/ExprCXX.h"
35
#include "clang/AST/ExprConcepts.h"
36
#include "clang/AST/ExternalASTSource.h"
37
#include "clang/AST/Mangle.h"
38
#include "clang/AST/MangleNumberingContext.h"
39
#include "clang/AST/NestedNameSpecifier.h"
40
#include "clang/AST/ParentMapContext.h"
41
#include "clang/AST/RawCommentList.h"
42
#include "clang/AST/RecordLayout.h"
43
#include "clang/AST/Stmt.h"
44
#include "clang/AST/TemplateBase.h"
45
#include "clang/AST/TemplateName.h"
46
#include "clang/AST/Type.h"
47
#include "clang/AST/TypeLoc.h"
48
#include "clang/AST/UnresolvedSet.h"
49
#include "clang/AST/VTableBuilder.h"
50
#include "clang/Basic/AddressSpaces.h"
51
#include "clang/Basic/Builtins.h"
52
#include "clang/Basic/CommentOptions.h"
53
#include "clang/Basic/ExceptionSpecificationType.h"
54
#include "clang/Basic/IdentifierTable.h"
55
#include "clang/Basic/LLVM.h"
56
#include "clang/Basic/LangOptions.h"
57
#include "clang/Basic/Linkage.h"
58
#include "clang/Basic/Module.h"
59
#include "clang/Basic/NoSanitizeList.h"
60
#include "clang/Basic/ObjCRuntime.h"
61
#include "clang/Basic/SourceLocation.h"
62
#include "clang/Basic/SourceManager.h"
63
#include "clang/Basic/Specifiers.h"
64
#include "clang/Basic/TargetCXXABI.h"
65
#include "clang/Basic/TargetInfo.h"
66
#include "clang/Basic/XRayLists.h"
67
#include "llvm/ADT/APFixedPoint.h"
68
#include "llvm/ADT/APInt.h"
69
#include "llvm/ADT/APSInt.h"
70
#include "llvm/ADT/ArrayRef.h"
71
#include "llvm/ADT/DenseMap.h"
72
#include "llvm/ADT/DenseSet.h"
73
#include "llvm/ADT/FoldingSet.h"
74
#include "llvm/ADT/None.h"
75
#include "llvm/ADT/Optional.h"
76
#include "llvm/ADT/PointerUnion.h"
77
#include "llvm/ADT/STLExtras.h"
78
#include "llvm/ADT/SmallPtrSet.h"
79
#include "llvm/ADT/SmallVector.h"
80
#include "llvm/ADT/StringExtras.h"
81
#include "llvm/ADT/StringRef.h"
82
#include "llvm/ADT/Triple.h"
83
#include "llvm/Support/Capacity.h"
84
#include "llvm/Support/Casting.h"
85
#include "llvm/Support/Compiler.h"
86
#include "llvm/Support/ErrorHandling.h"
87
#include "llvm/Support/MD5.h"
88
#include "llvm/Support/MathExtras.h"
89
#include "llvm/Support/raw_ostream.h"
90
#include <algorithm>
91
#include <cassert>
92
#include <cstddef>
93
#include <cstdint>
94
#include <cstdlib>
95
#include <map>
96
#include <memory>
97
#include <string>
98
#include <tuple>
99
#include <utility>
100
101
using namespace clang;
102
103
enum FloatingRank {
104
  BFloat16Rank,
105
  Float16Rank,
106
  HalfRank,
107
  FloatRank,
108
  DoubleRank,
109
  LongDoubleRank,
110
  Float128Rank,
111
  Ibm128Rank
112
};
113
114
/// \returns location that is relevant when searching for Doc comments related
115
/// to \p D.
116
static SourceLocation getDeclLocForCommentSearch(const Decl *D,
117
48.5k
                                                 SourceManager &SourceMgr) {
118
48.5k
  assert(D);
119
120
  // User can not attach documentation to implicit declarations.
121
48.5k
  if (D->isImplicit())
122
10.8k
    return {};
123
124
  // User can not attach documentation to implicit instantiations.
125
37.7k
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
126
18.3k
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
127
220
      return {};
128
18.3k
  }
129
130
37.5k
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
131
8.10k
    if (VD->isStaticDataMember() &&
132
8.10k
        
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation60
)
133
8
      return {};
134
8.10k
  }
135
136
37.5k
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
137
2.23k
    if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
138
126
      return {};
139
2.23k
  }
140
141
37.3k
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
142
167
    TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
143
167
    if (TSK == TSK_ImplicitInstantiation ||
144
167
        TSK == TSK_Undeclared)
145
19
      return {};
146
167
  }
147
148
37.3k
  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
149
171
    if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
150
4
      return {};
151
171
  }
152
37.3k
  if (const auto *TD = dyn_cast<TagDecl>(D)) {
153
    // When tag declaration (but not definition!) is part of the
154
    // decl-specifier-seq of some other declaration, it doesn't get comment
155
2.52k
    if (TD->isEmbeddedInDeclarator() && 
!TD->isCompleteDefinition()232
)
156
33
      return {};
157
2.52k
  }
158
  // TODO: handle comments for function parameters properly.
159
37.3k
  if (isa<ParmVarDecl>(D))
160
3.77k
    return {};
161
162
  // TODO: we could look up template parameter documentation in the template
163
  // documentation.
164
33.5k
  if (isa<TemplateTypeParmDecl>(D) ||
165
33.5k
      
isa<NonTypeTemplateParmDecl>(D)32.7k
||
166
33.5k
      
isa<TemplateTemplateParmDecl>(D)32.4k
)
167
1.11k
    return {};
168
169
  // Find declaration location.
170
  // For Objective-C declarations we generally don't expect to have multiple
171
  // declarators, thus use declaration starting location as the "declaration
172
  // location".
173
  // For all other declarations multiple declarators are used quite frequently,
174
  // so we use the location of the identifier as the "declaration location".
175
32.4k
  if (isa<ObjCMethodDecl>(D) || 
isa<ObjCContainerDecl>(D)32.1k
||
176
32.4k
      
isa<ObjCPropertyDecl>(D)31.6k
||
177
32.4k
      
isa<RedeclarableTemplateDecl>(D)31.4k
||
178
32.4k
      
isa<ClassTemplateSpecializationDecl>(D)30.4k
||
179
      // Allow association with Y across {} in `typedef struct X {} Y`.
180
32.4k
      
isa<TypedefDecl>(D)30.3k
)
181
2.85k
    return D->getBeginLoc();
182
183
29.5k
  const SourceLocation DeclLoc = D->getLocation();
184
29.5k
  if (DeclLoc.isMacroID()) {
185
67
    if (isa<TypedefDecl>(D)) {
186
      // If location of the typedef name is in a macro, it is because being
187
      // declared via a macro. Try using declaration's starting location as
188
      // the "declaration location".
189
0
      return D->getBeginLoc();
190
0
    }
191
192
67
    if (const auto *TD = dyn_cast<TagDecl>(D)) {
193
      // If location of the tag decl is inside a macro, but the spelling of
194
      // the tag name comes from a macro argument, it looks like a special
195
      // macro like NS_ENUM is being used to define the tag decl.  In that
196
      // case, adjust the source location to the expansion loc so that we can
197
      // attach the comment to the tag decl.
198
3
      if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
199
3
        return SourceMgr.getExpansionLoc(DeclLoc);
200
3
    }
201
67
  }
202
203
29.5k
  return DeclLoc;
204
29.5k
}
205
206
RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
207
    const Decl *D, const SourceLocation RepresentativeLocForDecl,
208
6.21k
    const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
209
  // If the declaration doesn't map directly to a location in a file, we
210
  // can't find the comment.
211
6.21k
  if (RepresentativeLocForDecl.isInvalid() ||
212
6.21k
      !RepresentativeLocForDecl.isFileID())
213
0
    return nullptr;
214
215
  // If there are no comments anywhere, we won't find anything.
216
6.21k
  if (CommentsInTheFile.empty())
217
0
    return nullptr;
218
219
  // Decompose the location for the declaration and find the beginning of the
220
  // file buffer.
221
6.21k
  const std::pair<FileID, unsigned> DeclLocDecomp =
222
6.21k
      SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
223
224
  // Slow path.
225
6.21k
  auto OffsetCommentBehindDecl =
226
6.21k
      CommentsInTheFile.lower_bound(DeclLocDecomp.second);
227
228
  // First check whether we have a trailing comment.
229
6.21k
  if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
230
1.92k
    RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
231
1.92k
    if ((CommentBehindDecl->isDocumentation() ||
232
1.92k
         
LangOpts.CommentOpts.ParseAllComments22
) &&
233
1.92k
        CommentBehindDecl->isTrailingComment() &&
234
1.92k
        
(191
isa<FieldDecl>(D)191
||
isa<EnumConstantDecl>(D)161
||
isa<VarDecl>(D)142
||
235
191
         
isa<ObjCMethodDecl>(D)78
||
isa<ObjCPropertyDecl>(D)66
)) {
236
237
      // Check that Doxygen trailing comment comes after the declaration, starts
238
      // on the same line and in the same file as the declaration.
239
137
      if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
240
137
          Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
241
137
                                       OffsetCommentBehindDecl->first)) {
242
117
        return CommentBehindDecl;
243
117
      }
244
137
    }
245
1.92k
  }
246
247
  // The comment just after the declaration was not a trailing comment.
248
  // Let's look at the previous comment.
249
6.09k
  if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
250
221
    return nullptr;
251
252
5.87k
  auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
253
5.87k
  RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
254
255
  // Check that we actually have a non-member Doxygen comment.
256
5.87k
  if (!(CommentBeforeDecl->isDocumentation() ||
257
5.87k
        
LangOpts.CommentOpts.ParseAllComments27
) ||
258
5.87k
      CommentBeforeDecl->isTrailingComment())
259
61
    return nullptr;
260
261
  // Decompose the end of the comment.
262
5.81k
  const unsigned CommentEndOffset =
263
5.81k
      Comments.getCommentEndOffset(CommentBeforeDecl);
264
265
  // Get the corresponding buffer.
266
5.81k
  bool Invalid = false;
267
5.81k
  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
268
5.81k
                                               &Invalid).data();
269
5.81k
  if (Invalid)
270
0
    return nullptr;
271
272
  // Extract text between the comment and declaration.
273
5.81k
  StringRef Text(Buffer + CommentEndOffset,
274
5.81k
                 DeclLocDecomp.second - CommentEndOffset);
275
276
  // There should be no other declarations or preprocessor directives between
277
  // comment and declaration.
278
5.81k
  if (Text.find_first_of(";{}#@") != StringRef::npos)
279
2.60k
    return nullptr;
280
281
3.21k
  return CommentBeforeDecl;
282
5.81k
}
283
284
43.8k
RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
285
43.8k
  const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
286
287
  // If the declaration doesn't map directly to a location in a file, we
288
  // can't find the comment.
289
43.8k
  if (DeclLoc.isInvalid() || 
!DeclLoc.isFileID()25.4k
)
290
18.4k
    return nullptr;
291
292
25.3k
  if (ExternalSource && 
!CommentsLoaded13.5k
) {
293
258
    ExternalSource->ReadComments();
294
258
    CommentsLoaded = true;
295
258
  }
296
297
25.3k
  if (Comments.empty())
298
23.8k
    return nullptr;
299
300
1.58k
  const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
301
1.58k
  const auto CommentsInThisFile = Comments.getCommentsInFile(File);
302
1.58k
  if (!CommentsInThisFile || 
CommentsInThisFile->empty()1.58k
)
303
6
    return nullptr;
304
305
1.58k
  return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
306
1.58k
}
307
308
53.6M
void ASTContext::addComment(const RawComment &RC) {
309
53.6M
  assert(LangOpts.RetainCommentsFromSystemHeaders ||
310
53.6M
         !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
311
0
  Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
312
53.6M
}
313
314
/// If we have a 'templated' declaration for a template, adjust 'D' to
315
/// refer to the actual template.
316
/// If we have an implicit instantiation, adjust 'D' to refer to template.
317
28.3k
static const Decl &adjustDeclToTemplate(const Decl &D) {
318
28.3k
  if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
319
    // Is this function declaration part of a function template?
320
9.05k
    if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
321
3
      return *FTD;
322
323
    // Nothing to do if function is not an implicit instantiation.
324
9.05k
    if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
325
9.02k
      return D;
326
327
    // Function is an implicit instantiation of a function template?
328
28
    if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
329
4
      return *FTD;
330
331
    // Function is instantiated from a member definition of a class template?
332
24
    if (const FunctionDecl *MemberDecl =
333
24
            FD->getInstantiatedFromMemberFunction())
334
24
      return *MemberDecl;
335
336
0
    return D;
337
24
  }
338
19.2k
  if (const auto *VD = dyn_cast<VarDecl>(&D)) {
339
    // Static data member is instantiated from a member definition of a class
340
    // template?
341
4.50k
    if (VD->isStaticDataMember())
342
83
      if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
343
6
        return *MemberDecl;
344
345
4.50k
    return D;
346
4.50k
  }
347
14.7k
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
348
    // Is this class declaration part of a class template?
349
2.52k
    if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
350
48
      return *CTD;
351
352
    // Class is an implicit instantiation of a class template or partial
353
    // specialization?
354
2.48k
    if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
355
217
      if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
356
184
        return D;
357
33
      llvm::PointerUnion<ClassTemplateDecl *,
358
33
                         ClassTemplatePartialSpecializationDecl *>
359
33
          PU = CTSD->getSpecializedTemplateOrPartial();
360
33
      return PU.is<ClassTemplateDecl *>()
361
33
                 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
362
33
                 : *static_cast<const Decl *>(
363
0
                       PU.get<ClassTemplatePartialSpecializationDecl *>());
364
217
    }
365
366
    // Class is instantiated from a member definition of a class template?
367
2.26k
    if (const MemberSpecializationInfo *Info =
368
2.26k
            CRD->getMemberSpecializationInfo())
369
4
      return *Info->getInstantiatedFrom();
370
371
2.26k
    return D;
372
2.26k
  }
373
12.2k
  if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
374
    // Enum is instantiated from a member definition of a class template?
375
534
    if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
376
4
      return *MemberDecl;
377
378
530
    return D;
379
534
  }
380
  // FIXME: Adjust alias templates?
381
11.7k
  return D;
382
12.2k
}
383
384
const RawComment *ASTContext::getRawCommentForAnyRedecl(
385
                                                const Decl *D,
386
16.2k
                                                const Decl **OriginalDecl) const {
387
16.2k
  if (!D) {
388
0
    if (OriginalDecl)
389
0
      OriginalDecl = nullptr;
390
0
    return nullptr;
391
0
  }
392
393
16.2k
  D = &adjustDeclToTemplate(*D);
394
395
  // Any comment directly attached to D?
396
16.2k
  {
397
16.2k
    auto DeclComment = DeclRawComments.find(D);
398
16.2k
    if (DeclComment != DeclRawComments.end()) {
399
2.64k
      if (OriginalDecl)
400
853
        *OriginalDecl = D;
401
2.64k
      return DeclComment->second;
402
2.64k
    }
403
16.2k
  }
404
405
  // Any comment attached to any redeclaration of D?
406
13.5k
  const Decl *CanonicalD = D->getCanonicalDecl();
407
13.5k
  if (!CanonicalD)
408
0
    return nullptr;
409
410
13.5k
  {
411
13.5k
    auto RedeclComment = RedeclChainComments.find(CanonicalD);
412
13.5k
    if (RedeclComment != RedeclChainComments.end()) {
413
108
      if (OriginalDecl)
414
18
        *OriginalDecl = RedeclComment->second;
415
108
      auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
416
108
      assert(CommentAtRedecl != DeclRawComments.end() &&
417
108
             "This decl is supposed to have comment attached.");
418
0
      return CommentAtRedecl->second;
419
108
    }
420
13.5k
  }
421
422
  // Any redeclarations of D that we haven't checked for comments yet?
423
  // We can't use DenseMap::iterator directly since it'd get invalid.
424
13.4k
  auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
425
13.4k
    auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
426
13.4k
    if (LookupRes != CommentlessRedeclChains.end())
427
8.32k
      return LookupRes->second;
428
5.16k
    return nullptr;
429
13.4k
  }();
430
431
34.6k
  for (const auto Redecl : D->redecls()) {
432
34.6k
    assert(Redecl);
433
    // Skip all redeclarations that have been checked previously.
434
34.6k
    if (LastCheckedRedecl) {
435
19.1k
      if (LastCheckedRedecl == Redecl) {
436
8.32k
        LastCheckedRedecl = nullptr;
437
8.32k
      }
438
19.1k
      continue;
439
19.1k
    }
440
15.4k
    const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
441
15.4k
    if (RedeclComment) {
442
948
      cacheRawCommentForDecl(*Redecl, *RedeclComment);
443
948
      if (OriginalDecl)
444
2
        *OriginalDecl = Redecl;
445
948
      return RedeclComment;
446
948
    }
447
14.5k
    CommentlessRedeclChains[CanonicalD] = Redecl;
448
14.5k
  }
449
450
12.5k
  if (OriginalDecl)
451
6.38k
    *OriginalDecl = nullptr;
452
12.5k
  return nullptr;
453
13.4k
}
454
455
void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
456
3.24k
                                        const RawComment &Comment) const {
457
3.24k
  assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
458
0
  DeclRawComments.try_emplace(&OriginalD, &Comment);
459
3.24k
  const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
460
3.24k
  RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
461
3.24k
  CommentlessRedeclChains.erase(CanonicalDecl);
462
3.24k
}
463
464
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
465
365
                   SmallVectorImpl<const NamedDecl *> &Redeclared) {
466
365
  const DeclContext *DC = ObjCMethod->getDeclContext();
467
365
  if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
468
82
    const ObjCInterfaceDecl *ID = IMD->getClassInterface();
469
82
    if (!ID)
470
0
      return;
471
    // Add redeclared method here.
472
82
    for (const auto *Ext : ID->known_extensions()) {
473
10
      if (ObjCMethodDecl *RedeclaredMethod =
474
10
            Ext->getMethod(ObjCMethod->getSelector(),
475
10
                                  ObjCMethod->isInstanceMethod()))
476
3
        Redeclared.push_back(RedeclaredMethod);
477
10
    }
478
82
  }
479
365
}
480
481
void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
482
10.7k
                                                 const Preprocessor *PP) {
483
10.7k
  if (Comments.empty() || 
Decls.empty()10.3k
)
484
328
    return;
485
486
10.3k
  FileID File;
487
10.3k
  for (Decl *D : Decls) {
488
10.3k
    SourceLocation Loc = D->getLocation();
489
10.3k
    if (Loc.isValid()) {
490
      // See if there are any new comments that are not attached to a decl.
491
      // The location doesn't have to be precise - we care only about the file.
492
10.3k
      File = SourceMgr.getDecomposedLoc(Loc).first;
493
10.3k
      break;
494
10.3k
    }
495
10.3k
  }
496
497
10.3k
  if (File.isInvalid())
498
0
    return;
499
500
10.3k
  auto CommentsInThisFile = Comments.getCommentsInFile(File);
501
10.3k
  if (!CommentsInThisFile || 
CommentsInThisFile->empty()4.69k
||
502
10.3k
      
CommentsInThisFile->rbegin()->second->isAttached()4.69k
)
503
5.69k
    return;
504
505
  // There is at least one comment not attached to a decl.
506
  // Maybe it should be attached to one of Decls?
507
  //
508
  // Note that this way we pick up not only comments that precede the
509
  // declaration, but also comments that *follow* the declaration -- thanks to
510
  // the lookahead in the lexer: we've consumed the semicolon and looked
511
  // ahead through comments.
512
513
4.72k
  
for (const Decl *D : Decls)4.69k
{
514
4.72k
    assert(D);
515
4.72k
    if (D->isInvalidDecl())
516
7
      continue;
517
518
4.71k
    D = &adjustDeclToTemplate(*D);
519
520
4.71k
    const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
521
522
4.71k
    if (DeclLoc.isInvalid() || 
!DeclLoc.isFileID()4.71k
)
523
1
      continue;
524
525
4.71k
    if (DeclRawComments.count(D) > 0)
526
83
      continue;
527
528
4.63k
    if (RawComment *const DocComment =
529
4.63k
            getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
530
2.30k
      cacheRawCommentForDecl(*D, *DocComment);
531
2.30k
      comments::FullComment *FC = DocComment->parse(*this, PP, D);
532
2.30k
      ParsedComments[D->getCanonicalDecl()] = FC;
533
2.30k
    }
534
4.63k
  }
535
4.69k
}
536
537
comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
538
106
                                                    const Decl *D) const {
539
106
  auto *ThisDeclInfo = new (*this) comments::DeclInfo;
540
106
  ThisDeclInfo->CommentDecl = D;
541
106
  ThisDeclInfo->IsFilled = false;
542
106
  ThisDeclInfo->fill();
543
106
  ThisDeclInfo->CommentDecl = FC->getDecl();
544
106
  if (!ThisDeclInfo->TemplateParameters)
545
97
    ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
546
106
  comments::FullComment *CFC =
547
106
    new (*this) comments::FullComment(FC->getBlocks(),
548
106
                                      ThisDeclInfo);
549
106
  return CFC;
550
106
}
551
552
28.2k
comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
553
28.2k
  const RawComment *RC = getRawCommentForDeclNoCache(D);
554
28.2k
  return RC ? 
RC->parse(*this, nullptr, D)58
:
nullptr28.2k
;
555
28.2k
}
556
557
comments::FullComment *ASTContext::getCommentForDecl(
558
                                              const Decl *D,
559
7.46k
                                              const Preprocessor *PP) const {
560
7.46k
  if (!D || D->isInvalidDecl())
561
90
    return nullptr;
562
7.37k
  D = &adjustDeclToTemplate(*D);
563
564
7.37k
  const Decl *Canonical = D->getCanonicalDecl();
565
7.37k
  llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
566
7.37k
      ParsedComments.find(Canonical);
567
568
7.37k
  if (Pos != ParsedComments.end()) {
569
116
    if (Canonical != D) {
570
32
      comments::FullComment *FC = Pos->second;
571
32
      comments::FullComment *CFC = cloneFullComment(FC, D);
572
32
      return CFC;
573
32
    }
574
84
    return Pos->second;
575
116
  }
576
577
7.25k
  const Decl *OriginalDecl = nullptr;
578
579
7.25k
  const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
580
7.25k
  if (!RC) {
581
6.38k
    if (isa<ObjCMethodDecl>(D) || 
isa<FunctionDecl>(D)5.97k
) {
582
1.52k
      SmallVector<const NamedDecl*, 8> Overridden;
583
1.52k
      const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
584
1.52k
      if (OMD && 
OMD->isPropertyAccessor()407
)
585
116
        if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
586
116
          if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
587
42
            return cloneFullComment(FC, D);
588
1.48k
      if (OMD)
589
365
        addRedeclaredMethods(OMD, Overridden);
590
1.48k
      getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
591
1.54k
      for (unsigned i = 0, e = Overridden.size(); i < e; 
i++62
)
592
66
        if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
593
4
          return cloneFullComment(FC, D);
594
1.48k
    }
595
4.85k
    else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
596
      // Attach any tag type's documentation to its typedef if latter
597
      // does not have one of its own.
598
429
      QualType QT = TD->getUnderlyingType();
599
429
      if (const auto *TT = QT->getAs<TagType>())
600
57
        if (const Decl *TD = TT->getDecl())
601
57
          if (comments::FullComment *FC = getCommentForDecl(TD, PP))
602
4
            return cloneFullComment(FC, D);
603
429
    }
604
4.42k
    else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
605
480
      while (IC->getSuperClass()) {
606
98
        IC = IC->getSuperClass();
607
98
        if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608
5
          return cloneFullComment(FC, D);
609
98
      }
610
387
    }
611
4.04k
    else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
612
56
      if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
613
56
        if (comments::FullComment *FC = getCommentForDecl(IC, PP))
614
1
          return cloneFullComment(FC, D);
615
56
    }
616
3.98k
    else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
617
682
      if (!(RD = RD->getDefinition()))
618
19
        return nullptr;
619
      // Check non-virtual bases.
620
663
      for (const auto &I : RD->bases()) {
621
217
        if (I.isVirtual() || 
(I.getAccessSpecifier() != AS_public)147
)
622
76
          continue;
623
141
        QualType Ty = I.getType();
624
141
        if (Ty.isNull())
625
0
          continue;
626
141
        if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
627
141
          if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
628
0
            continue;
629
630
141
          if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
631
8
            return cloneFullComment(FC, D);
632
141
        }
633
141
      }
634
      // Check virtual bases.
635
655
      for (const auto &I : RD->vbases()) {
636
116
        if (I.getAccessSpecifier() != AS_public)
637
21
          continue;
638
95
        QualType Ty = I.getType();
639
95
        if (Ty.isNull())
640
0
          continue;
641
95
        if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
642
95
          if (!(VirtualBase= VirtualBase->getDefinition()))
643
0
            continue;
644
95
          if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
645
10
            return cloneFullComment(FC, D);
646
95
        }
647
95
      }
648
655
    }
649
6.29k
    return nullptr;
650
6.38k
  }
651
652
  // If the RawComment was attached to other redeclaration of this Decl, we
653
  // should parse the comment in context of that other Decl.  This is important
654
  // because comments can contain references to parameter names which can be
655
  // different across redeclarations.
656
873
  if (D != OriginalDecl && 
OriginalDecl18
)
657
18
    return getCommentForDecl(OriginalDecl, PP);
658
659
855
  comments::FullComment *FC = RC->parse(*this, PP, D);
660
855
  ParsedComments[Canonical] = FC;
661
855
  return FC;
662
873
}
663
664
void
665
ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
666
                                                   const ASTContext &C,
667
91.0k
                                               TemplateTemplateParmDecl *Parm) {
668
91.0k
  ID.AddInteger(Parm->getDepth());
669
91.0k
  ID.AddInteger(Parm->getPosition());
670
91.0k
  ID.AddBoolean(Parm->isParameterPack());
671
672
91.0k
  TemplateParameterList *Params = Parm->getTemplateParameters();
673
91.0k
  ID.AddInteger(Params->size());
674
91.0k
  for (TemplateParameterList::const_iterator P = Params->begin(),
675
91.0k
                                          PEnd = Params->end();
676
194k
       P != PEnd; 
++P103k
) {
677
103k
    if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
678
100k
      ID.AddInteger(0);
679
100k
      ID.AddBoolean(TTP->isParameterPack());
680
100k
      const TypeConstraint *TC = TTP->getTypeConstraint();
681
100k
      ID.AddBoolean(TC != nullptr);
682
100k
      if (TC)
683
1
        TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
684
1
                                                        /*Canonical=*/true);
685
100k
      if (TTP->isExpandedParameterPack()) {
686
0
        ID.AddBoolean(true);
687
0
        ID.AddInteger(TTP->getNumExpansionParameters());
688
0
      } else
689
100k
        ID.AddBoolean(false);
690
100k
      continue;
691
100k
    }
692
693
2.55k
    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
694
2.53k
      ID.AddInteger(1);
695
2.53k
      ID.AddBoolean(NTTP->isParameterPack());
696
2.53k
      ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
697
2.53k
      if (NTTP->isExpandedParameterPack()) {
698
1
        ID.AddBoolean(true);
699
1
        ID.AddInteger(NTTP->getNumExpansionTypes());
700
4
        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; 
++I3
) {
701
3
          QualType T = NTTP->getExpansionType(I);
702
3
          ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
703
3
        }
704
1
      } else
705
2.53k
        ID.AddBoolean(false);
706
2.53k
      continue;
707
2.53k
    }
708
709
22
    auto *TTP = cast<TemplateTemplateParmDecl>(*P);
710
22
    ID.AddInteger(2);
711
22
    Profile(ID, C, TTP);
712
22
  }
713
91.0k
  Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
714
91.0k
  ID.AddBoolean(RequiresClause != nullptr);
715
91.0k
  if (RequiresClause)
716
0
    RequiresClause->Profile(ID, C, /*Canonical=*/true);
717
91.0k
}
718
719
static Expr *
720
canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
721
1
                                          QualType ConstrainedType) {
722
  // This is a bit ugly - we need to form a new immediately-declared
723
  // constraint that references the new parameter; this would ideally
724
  // require semantic analysis (e.g. template<C T> struct S {}; - the
725
  // converted arguments of C<T> could be an argument pack if C is
726
  // declared as template<typename... T> concept C = ...).
727
  // We don't have semantic analysis here so we dig deep into the
728
  // ready-made constraint expr and change the thing manually.
729
1
  ConceptSpecializationExpr *CSE;
730
1
  if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
731
0
    CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
732
1
  else
733
1
    CSE = cast<ConceptSpecializationExpr>(IDC);
734
1
  ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
735
1
  SmallVector<TemplateArgument, 3> NewConverted;
736
1
  NewConverted.reserve(OldConverted.size());
737
1
  if (OldConverted.front().getKind() == TemplateArgument::Pack) {
738
    // The case:
739
    // template<typename... T> concept C = true;
740
    // template<C<int> T> struct S; -> constraint is C<{T, int}>
741
0
    NewConverted.push_back(ConstrainedType);
742
0
    llvm::append_range(NewConverted,
743
0
                       OldConverted.front().pack_elements().drop_front(1));
744
0
    TemplateArgument NewPack(NewConverted);
745
746
0
    NewConverted.clear();
747
0
    NewConverted.push_back(NewPack);
748
0
    assert(OldConverted.size() == 1 &&
749
0
           "Template parameter pack should be the last parameter");
750
1
  } else {
751
1
    assert(OldConverted.front().getKind() == TemplateArgument::Type &&
752
1
           "Unexpected first argument kind for immediately-declared "
753
1
           "constraint");
754
0
    NewConverted.push_back(ConstrainedType);
755
1
    llvm::append_range(NewConverted, OldConverted.drop_front(1));
756
1
  }
757
0
  Expr *NewIDC = ConceptSpecializationExpr::Create(
758
1
      C, CSE->getNamedConcept(), NewConverted, nullptr,
759
1
      CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
760
761
1
  if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
762
0
    NewIDC = new (C) CXXFoldExpr(
763
0
        OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
764
0
        BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
765
0
        SourceLocation(), /*NumExpansions=*/None);
766
1
  return NewIDC;
767
1
}
768
769
TemplateTemplateParmDecl *
770
ASTContext::getCanonicalTemplateTemplateParmDecl(
771
48.4k
                                          TemplateTemplateParmDecl *TTP) const {
772
  // Check if we already have a canonical template template parameter.
773
48.4k
  llvm::FoldingSetNodeID ID;
774
48.4k
  CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
775
48.4k
  void *InsertPos = nullptr;
776
48.4k
  CanonicalTemplateTemplateParm *Canonical
777
48.4k
    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
778
48.4k
  if (Canonical)
779
41.6k
    return Canonical->getParam();
780
781
  // Build a canonical template parameter list.
782
6.80k
  TemplateParameterList *Params = TTP->getTemplateParameters();
783
6.80k
  SmallVector<NamedDecl *, 4> CanonParams;
784
6.80k
  CanonParams.reserve(Params->size());
785
6.80k
  for (TemplateParameterList::const_iterator P = Params->begin(),
786
6.80k
                                          PEnd = Params->end();
787
15.5k
       P != PEnd; 
++P8.76k
) {
788
8.76k
    if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
789
7.52k
      TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
790
7.52k
          getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
791
7.52k
          TTP->getDepth(), TTP->getIndex(), nullptr, false,
792
7.52k
          TTP->isParameterPack(), TTP->hasTypeConstraint(),
793
7.52k
          TTP->isExpandedParameterPack() ?
794
7.52k
          
llvm::Optional<unsigned>(TTP->getNumExpansionParameters())0
: None);
795
7.52k
      if (const auto *TC = TTP->getTypeConstraint()) {
796
1
        QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
797
1
        Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
798
1
                *this, TC->getImmediatelyDeclaredConstraint(),
799
1
                ParamAsArgument);
800
1
        TemplateArgumentListInfo CanonArgsAsWritten;
801
1
        if (auto *Args = TC->getTemplateArgsAsWritten())
802
0
          for (const auto &ArgLoc : Args->arguments())
803
0
            CanonArgsAsWritten.addArgument(
804
0
                TemplateArgumentLoc(ArgLoc.getArgument(),
805
0
                                    TemplateArgumentLocInfo()));
806
1
        NewTTP->setTypeConstraint(
807
1
            NestedNameSpecifierLoc(),
808
1
            DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
809
1
                                SourceLocation()), /*FoundDecl=*/nullptr,
810
            // Actually canonicalizing a TemplateArgumentLoc is difficult so we
811
            // simply omit the ArgsAsWritten
812
1
            TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
813
1
      }
814
7.52k
      CanonParams.push_back(NewTTP);
815
7.52k
    } else 
if (const auto *1.24k
NTTP1.24k
= dyn_cast<NonTypeTemplateParmDecl>(*P)) {
816
1.24k
      QualType T = getCanonicalType(NTTP->getType());
817
1.24k
      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
818
1.24k
      NonTypeTemplateParmDecl *Param;
819
1.24k
      if (NTTP->isExpandedParameterPack()) {
820
1
        SmallVector<QualType, 2> ExpandedTypes;
821
1
        SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
822
4
        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; 
++I3
) {
823
3
          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
824
3
          ExpandedTInfos.push_back(
825
3
                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
826
3
        }
827
828
1
        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
829
1
                                                SourceLocation(),
830
1
                                                SourceLocation(),
831
1
                                                NTTP->getDepth(),
832
1
                                                NTTP->getPosition(), nullptr,
833
1
                                                T,
834
1
                                                TInfo,
835
1
                                                ExpandedTypes,
836
1
                                                ExpandedTInfos);
837
1.23k
      } else {
838
1.23k
        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
839
1.23k
                                                SourceLocation(),
840
1.23k
                                                SourceLocation(),
841
1.23k
                                                NTTP->getDepth(),
842
1.23k
                                                NTTP->getPosition(), nullptr,
843
1.23k
                                                T,
844
1.23k
                                                NTTP->isParameterPack(),
845
1.23k
                                                TInfo);
846
1.23k
      }
847
1.24k
      if (AutoType *AT = T->getContainedAutoType()) {
848
3
        if (AT->isConstrained()) {
849
0
          Param->setPlaceholderTypeConstraint(
850
0
              canonicalizeImmediatelyDeclaredConstraint(
851
0
                  *this, NTTP->getPlaceholderTypeConstraint(), T));
852
0
        }
853
3
      }
854
1.24k
      CanonParams.push_back(Param);
855
856
1.24k
    } else
857
4
      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
858
4
                                           cast<TemplateTemplateParmDecl>(*P)));
859
8.76k
  }
860
861
6.80k
  Expr *CanonRequiresClause = nullptr;
862
6.80k
  if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
863
0
    CanonRequiresClause = RequiresClause;
864
865
6.80k
  TemplateTemplateParmDecl *CanonTTP
866
6.80k
    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
867
6.80k
                                       SourceLocation(), TTP->getDepth(),
868
6.80k
                                       TTP->getPosition(),
869
6.80k
                                       TTP->isParameterPack(),
870
6.80k
                                       nullptr,
871
6.80k
                         TemplateParameterList::Create(*this, SourceLocation(),
872
6.80k
                                                       SourceLocation(),
873
6.80k
                                                       CanonParams,
874
6.80k
                                                       SourceLocation(),
875
6.80k
                                                       CanonRequiresClause));
876
877
  // Get the new insert position for the node we care about.
878
6.80k
  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
879
6.80k
  assert(!Canonical && "Shouldn't be in the map!");
880
0
  (void)Canonical;
881
882
  // Create the canonical template template parameter entry.
883
6.80k
  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
884
6.80k
  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
885
6.80k
  return CanonTTP;
886
48.4k
}
887
888
146k
TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
889
146k
  auto Kind = getTargetInfo().getCXXABI().getKind();
890
146k
  return getLangOpts().CXXABI.getValueOr(Kind);
891
146k
}
892
893
95.0k
CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
894
95.0k
  if (!LangOpts.CPlusPlus) 
return nullptr18.8k
;
895
896
76.2k
  switch (getCXXABIKind()) {
897
36
  case TargetCXXABI::AppleARM64:
898
63
  case TargetCXXABI::Fuchsia:
899
138
  case TargetCXXABI::GenericARM: // Same as Itanium at this level
900
169
  case TargetCXXABI::iOS:
901
177
  case TargetCXXABI::WatchOS:
902
1.26k
  case TargetCXXABI::GenericAArch64:
903
1.31k
  case TargetCXXABI::GenericMIPS:
904
68.6k
  case TargetCXXABI::GenericItanium:
905
68.6k
  case TargetCXXABI::WebAssembly:
906
68.7k
  case TargetCXXABI::XL:
907
68.7k
    return CreateItaniumCXXABI(*this);
908
7.42k
  case TargetCXXABI::Microsoft:
909
7.42k
    return CreateMicrosoftCXXABI(*this);
910
76.2k
  }
911
0
  llvm_unreachable("Invalid CXXABI type!");
912
0
}
913
914
15
interp::Context &ASTContext::getInterpContext() {
915
15
  if (!InterpContext) {
916
2
    InterpContext.reset(new interp::Context(*this));
917
2
  }
918
15
  return *InterpContext.get();
919
15
}
920
921
4.60M
ParentMapContext &ASTContext::getParentMapContext() {
922
4.60M
  if (!ParentMapCtx)
923
21.6k
    ParentMapCtx.reset(new ParentMapContext(*this));
924
4.60M
  return *ParentMapCtx.get();
925
4.60M
}
926
927
static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
928
95.0k
                                           const LangOptions &LOpts) {
929
95.0k
  if (LOpts.FakeAddressSpaceMap) {
930
    // The fake address space map must have a distinct entry for each
931
    // language-specific address space.
932
45
    static const unsigned FakeAddrSpaceMap[] = {
933
45
        0,  // Default
934
45
        1,  // opencl_global
935
45
        3,  // opencl_local
936
45
        2,  // opencl_constant
937
45
        0,  // opencl_private
938
45
        4,  // opencl_generic
939
45
        5,  // opencl_global_device
940
45
        6,  // opencl_global_host
941
45
        7,  // cuda_device
942
45
        8,  // cuda_constant
943
45
        9,  // cuda_shared
944
45
        1,  // sycl_global
945
45
        5,  // sycl_global_device
946
45
        6,  // sycl_global_host
947
45
        3,  // sycl_local
948
45
        0,  // sycl_private
949
45
        10, // ptr32_sptr
950
45
        11, // ptr32_uptr
951
45
        12  // ptr64
952
45
    };
953
45
    return &FakeAddrSpaceMap;
954
94.9k
  } else {
955
94.9k
    return &T.getAddressSpaceMap();
956
94.9k
  }
957
95.0k
}
958
959
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
960
95.0k
                                          const LangOptions &LangOpts) {
961
95.0k
  switch (LangOpts.getAddressSpaceMapMangling()) {
962
95.0k
  case LangOptions::ASMM_Target:
963
95.0k
    return TI.useAddressSpaceMapMangling();
964
3
  case LangOptions::ASMM_On:
965
3
    return true;
966
4
  case LangOptions::ASMM_Off:
967
4
    return false;
968
95.0k
  }
969
0
  llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
970
0
}
971
972
ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
973
                       IdentifierTable &idents, SelectorTable &sels,
974
                       Builtin::Context &builtins, TranslationUnitKind TUKind)
975
    : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
976
      FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
977
      TemplateSpecializationTypes(this_()),
978
      DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
979
      SubstTemplateTemplateParmPacks(this_()),
980
      CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
981
      NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
982
      XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
983
                                        LangOpts.XRayNeverInstrumentFiles,
984
                                        LangOpts.XRayAttrListFiles, SM)),
985
      ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
986
      PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
987
      BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
988
      Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
989
95.0k
      CompCategories(this_()), LastSDM(nullptr, 0) {
990
95.0k
  addTranslationUnitDecl();
991
95.0k
}
992
993
94.3k
void ASTContext::cleanup() {
994
  // Release the DenseMaps associated with DeclContext objects.
995
  // FIXME: Is this the ideal solution?
996
94.3k
  ReleaseDeclContextMaps();
997
998
  // Call all of the deallocation functions on all of their targets.
999
94.3k
  for (auto &Pair : Deallocations)
1000
1.46M
    (Pair.first)(Pair.second);
1001
94.3k
  Deallocations.clear();
1002
1003
  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
1004
  // because they can contain DenseMaps.
1005
94.3k
  for (llvm::DenseMap<const ObjCContainerDecl*,
1006
94.3k
       const ASTRecordLayout*>::iterator
1007
100k
       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
1008
    // Increment in loop to prevent using deallocated memory.
1009
6.25k
    if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1010
5.09k
      R->Destroy(*this);
1011
94.3k
  ObjCLayouts.clear();
1012
1013
94.3k
  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1014
487k
       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1015
    // Increment in loop to prevent using deallocated memory.
1016
393k
    if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1017
393k
      R->Destroy(*this);
1018
393k
  }
1019
94.3k
  ASTRecordLayouts.clear();
1020
1021
94.3k
  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1022
94.3k
                                                    AEnd = DeclAttrs.end();
1023
31.3M
       A != AEnd; 
++A31.2M
)
1024
31.2M
    A->second->~AttrVec();
1025
94.3k
  DeclAttrs.clear();
1026
1027
94.3k
  for (const auto &Value : ModuleInitializers)
1028
676
    Value.second->~PerModuleInitializers();
1029
94.3k
  ModuleInitializers.clear();
1030
94.3k
}
1031
1032
90.1k
ASTContext::~ASTContext() { cleanup(); }
1033
1034
3
void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1035
3
  TraversalScope = TopLevelDecls;
1036
3
  getParentMapContext().clear();
1037
3
}
1038
1039
1.47M
void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1040
1.47M
  Deallocations.push_back({Callback, Data});
1041
1.47M
}
1042
1043
void
1044
38.7k
ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1045
38.7k
  ExternalSource = std::move(Source);
1046
38.7k
}
1047
1048
4
void ASTContext::PrintStats() const {
1049
4
  llvm::errs() << "\n*** AST Context Stats:\n";
1050
4
  llvm::errs() << "  " << Types.size() << " types total.\n";
1051
1052
4
  unsigned counts[] = {
1053
216
#define TYPE(Name, Parent) 0,
1054
4
#define ABSTRACT_TYPE(Name, Parent)
1055
4
#include "clang/AST/TypeNodes.inc"
1056
4
    0 // Extra
1057
4
  };
1058
1059
295
  for (unsigned i = 0, e = Types.size(); i != e; 
++i291
) {
1060
291
    Type *T = Types[i];
1061
291
    counts[(unsigned)T->getTypeClass()]++;
1062
291
  }
1063
1064
4
  unsigned Idx = 0;
1065
4
  unsigned TotalBytes = 0;
1066
4
#define TYPE(Name, Parent)                                              \
1067
216
  if (counts[Idx])                                                      \
1068
216
    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1069
27
                 << " types, " << sizeof(Name##Type) << " each "        \
1070
27
                 << "(" << counts[Idx] * sizeof(Name##Type)             \
1071
27
                 << " bytes)\n";                                        \
1072
216
  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1073
216
  ++Idx;
1074
4
#define ABSTRACT_TYPE(Name, Parent)
1075
4
#include "clang/AST/TypeNodes.inc"
1076
1077
4
  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1078
1079
  // Implicit special member functions.
1080
4
  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1081
4
               << NumImplicitDefaultConstructors
1082
4
               << " implicit default constructors created\n";
1083
4
  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1084
4
               << NumImplicitCopyConstructors
1085
4
               << " implicit copy constructors created\n";
1086
4
  if (getLangOpts().CPlusPlus)
1087
1
    llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1088
1
                 << NumImplicitMoveConstructors
1089
1
                 << " implicit move constructors created\n";
1090
4
  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1091
4
               << NumImplicitCopyAssignmentOperators
1092
4
               << " implicit copy assignment operators created\n";
1093
4
  if (getLangOpts().CPlusPlus)
1094
1
    llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1095
1
                 << NumImplicitMoveAssignmentOperators
1096
1
                 << " implicit move assignment operators created\n";
1097
4
  llvm::errs() << NumImplicitDestructorsDeclared << "/"
1098
4
               << NumImplicitDestructors
1099
4
               << " implicit destructors created\n";
1100
1101
4
  if (ExternalSource) {
1102
3
    llvm::errs() << "\n";
1103
3
    ExternalSource->PrintStats();
1104
3
  }
1105
1106
4
  BumpAlloc.PrintStats();
1107
4
}
1108
1109
void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1110
3.26k
                                           bool NotifyListeners) {
1111
3.26k
  if (NotifyListeners)
1112
2.99k
    if (auto *Listener = getASTMutationListener())
1113
2.56k
      Listener->RedefinedHiddenDefinition(ND, M);
1114
1115
3.26k
  MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1116
3.26k
}
1117
1118
557
void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1119
557
  auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1120
557
  if (It == MergedDefModules.end())
1121
0
    return;
1122
1123
557
  auto &Merged = It->second;
1124
557
  llvm::DenseSet<Module*> Found;
1125
557
  for (Module *&M : Merged)
1126
3.97k
    if (!Found.insert(M).second)
1127
0
      M = nullptr;
1128
557
  llvm::erase_value(Merged, nullptr);
1129
557
}
1130
1131
ArrayRef<Module *>
1132
40.2k
ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1133
40.2k
  auto MergedIt =
1134
40.2k
      MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1135
40.2k
  if (MergedIt == MergedDefModules.end())
1136
39.1k
    return None;
1137
1.10k
  return MergedIt->second;
1138
40.2k
}
1139
1140
299
void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1141
299
  if (LazyInitializers.empty())
1142
236
    return;
1143
1144
63
  auto *Source = Ctx.getExternalSource();
1145
63
  assert(Source && "lazy initializers but no external source");
1146
1147
0
  auto LazyInits = std::move(LazyInitializers);
1148
63
  LazyInitializers.clear();
1149
1150
63
  for (auto ID : LazyInits)
1151
77
    Initializers.push_back(Source->GetExternalDecl(ID));
1152
1153
63
  assert(LazyInitializers.empty() &&
1154
63
         "GetExternalDecl for lazy module initializer added more inits");
1155
63
}
1156
1157
99.3k
void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1158
  // One special case: if we add a module initializer that imports another
1159
  // module, and that module's only initializer is an ImportDecl, simplify.
1160
99.3k
  if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1161
98.9k
    auto It = ModuleInitializers.find(ID->getImportedModule());
1162
1163
    // Maybe the ImportDecl does nothing at all. (Common case.)
1164
98.9k
    if (It == ModuleInitializers.end())
1165
98.8k
      return;
1166
1167
    // Maybe the ImportDecl only imports another ImportDecl.
1168
106
    auto &Imported = *It->second;
1169
106
    if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1170
55
      Imported.resolve(*this);
1171
55
      auto *OnlyDecl = Imported.Initializers.front();
1172
55
      if (isa<ImportDecl>(OnlyDecl))
1173
0
        D = OnlyDecl;
1174
55
    }
1175
106
  }
1176
1177
526
  auto *&Inits = ModuleInitializers[M];
1178
526
  if (!Inits)
1179
296
    Inits = new (*this) PerModuleInitializers;
1180
526
  Inits->Initializers.push_back(D);
1181
526
}
1182
1183
382
void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1184
382
  auto *&Inits = ModuleInitializers[M];
1185
382
  if (!Inits)
1186
382
    Inits = new (*this) PerModuleInitializers;
1187
382
  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1188
382
                                 IDs.begin(), IDs.end());
1189
382
}
1190
1191
501k
ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1192
501k
  auto It = ModuleInitializers.find(M);
1193
501k
  if (It == ModuleInitializers.end())
1194
500k
    return None;
1195
1196
244
  auto *Inits = It->second;
1197
244
  Inits->resolve(*this);
1198
244
  return Inits->Initializers;
1199
501k
}
1200
1201
24.7M
ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1202
24.7M
  if (!ExternCContext)
1203
67.0k
    ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1204
1205
24.7M
  return ExternCContext;
1206
24.7M
}
1207
1208
BuiltinTemplateDecl *
1209
ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1210
1.10k
                                     const IdentifierInfo *II) const {
1211
1.10k
  auto *BuiltinTemplate =
1212
1.10k
      BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1213
1.10k
  BuiltinTemplate->setImplicit();
1214
1.10k
  getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1215
1216
1.10k
  return BuiltinTemplate;
1217
1.10k
}
1218
1219
BuiltinTemplateDecl *
1220
916
ASTContext::getMakeIntegerSeqDecl() const {
1221
916
  if (!MakeIntegerSeqDecl)
1222
617
    MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1223
617
                                                  getMakeIntegerSeqName());
1224
916
  return MakeIntegerSeqDecl;
1225
916
}
1226
1227
BuiltinTemplateDecl *
1228
1.02k
ASTContext::getTypePackElementDecl() const {
1229
1.02k
  if (!TypePackElementDecl)
1230
483
    TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1231
483
                                                   getTypePackElementName());
1232
1.02k
  return TypePackElementDecl;
1233
1.02k
}
1234
1235
RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1236
168k
                                            RecordDecl::TagKind TK) const {
1237
168k
  SourceLocation Loc;
1238
168k
  RecordDecl *NewDecl;
1239
168k
  if (getLangOpts().CPlusPlus)
1240
134k
    NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1241
134k
                                    Loc, &Idents.get(Name));
1242
34.0k
  else
1243
34.0k
    NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1244
34.0k
                                 &Idents.get(Name));
1245
168k
  NewDecl->setImplicit();
1246
168k
  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1247
168k
      const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1248
168k
  return NewDecl;
1249
168k
}
1250
1251
TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1252
640k
                                              StringRef Name) const {
1253
640k
  TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1254
640k
  TypedefDecl *NewDecl = TypedefDecl::Create(
1255
640k
      const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1256
640k
      SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1257
640k
  NewDecl->setImplicit();
1258
640k
  return NewDecl;
1259
640k
}
1260
1261
72.4k
TypedefDecl *ASTContext::getInt128Decl() const {
1262
72.4k
  if (!Int128Decl)
1263
70.5k
    Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1264
72.4k
  return Int128Decl;
1265
72.4k
}
1266
1267
72.4k
TypedefDecl *ASTContext::getUInt128Decl() const {
1268
72.4k
  if (!UInt128Decl)
1269
70.5k
    UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1270
72.4k
  return UInt128Decl;
1271
72.4k
}
1272
1273
6.07M
void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1274
6.07M
  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1275
6.07M
  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1276
6.07M
  Types.push_back(Ty);
1277
6.07M
}
1278
1279
void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1280
95.0k
                                  const TargetInfo *AuxTarget) {
1281
95.0k
  assert((!this->Target || this->Target == &Target) &&
1282
95.0k
         "Incorrect target reinitialization");
1283
0
  assert(VoidTy.isNull() && "Context reinitialized?");
1284
1285
0
  this->Target = &Target;
1286
95.0k
  this->AuxTarget = AuxTarget;
1287
1288
95.0k
  ABI.reset(createCXXABI(Target));
1289
95.0k
  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1290
95.0k
  AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1291
1292
  // C99 6.2.5p19.
1293
95.0k
  InitBuiltinType(VoidTy,              BuiltinType::Void);
1294
1295
  // C99 6.2.5p2.
1296
95.0k
  InitBuiltinType(BoolTy,              BuiltinType::Bool);
1297
  // C99 6.2.5p3.
1298
95.0k
  if (LangOpts.CharIsSigned)
1299
94.6k
    InitBuiltinType(CharTy,            BuiltinType::Char_S);
1300
406
  else
1301
406
    InitBuiltinType(CharTy,            BuiltinType::Char_U);
1302
  // C99 6.2.5p4.
1303
95.0k
  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1304
95.0k
  InitBuiltinType(ShortTy,             BuiltinType::Short);
1305
95.0k
  InitBuiltinType(IntTy,               BuiltinType::Int);
1306
95.0k
  InitBuiltinType(LongTy,              BuiltinType::Long);
1307
95.0k
  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1308
1309
  // C99 6.2.5p6.
1310
95.0k
  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1311
95.0k
  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1312
95.0k
  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1313
95.0k
  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1314
95.0k
  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1315
1316
  // C99 6.2.5p10.
1317
95.0k
  InitBuiltinType(FloatTy,             BuiltinType::Float);
1318
95.0k
  InitBuiltinType(DoubleTy,            BuiltinType::Double);
1319
95.0k
  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1320
1321
  // GNU extension, __float128 for IEEE quadruple precision
1322
95.0k
  InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1323
1324
  // __ibm128 for IBM extended precision
1325
95.0k
  InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1326
1327
  // C11 extension ISO/IEC TS 18661-3
1328
95.0k
  InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1329
1330
  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1331
95.0k
  InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1332
95.0k
  InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1333
95.0k
  InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1334
95.0k
  InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1335
95.0k
  InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1336
95.0k
  InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1337
95.0k
  InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1338
95.0k
  InitBuiltinType(FractTy,                 BuiltinType::Fract);
1339
95.0k
  InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1340
95.0k
  InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1341
95.0k
  InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1342
95.0k
  InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1343
95.0k
  InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1344
95.0k
  InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1345
95.0k
  InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1346
95.0k
  InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1347
95.0k
  InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1348
95.0k
  InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1349
95.0k
  InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1350
95.0k
  InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1351
95.0k
  InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1352
95.0k
  InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1353
95.0k
  InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1354
95.0k
  InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1355
1356
  // GNU extension, 128-bit integers.
1357
95.0k
  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1358
95.0k
  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1359
1360
  // C++ 3.9.1p5
1361
95.0k
  if (TargetInfo::isTypeSigned(Target.getWCharType()))
1362
82.7k
    InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1363
12.3k
  else  // -fshort-wchar makes wchar_t be unsigned.
1364
12.3k
    InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1365
95.0k
  if (LangOpts.CPlusPlus && 
LangOpts.WChar76.2k
)
1366
76.1k
    WideCharTy = WCharTy;
1367
18.8k
  else {
1368
    // C99 (or C++ using -fno-wchar).
1369
18.8k
    WideCharTy = getFromTargetType(Target.getWCharType());
1370
18.8k
  }
1371
1372
95.0k
  WIntTy = getFromTargetType(Target.getWIntType());
1373
1374
  // C++20 (proposed)
1375
95.0k
  InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1376
1377
95.0k
  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378
76.2k
    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1379
18.8k
  else // C99
1380
18.8k
    Char16Ty = getFromTargetType(Target.getChar16Type());
1381
1382
95.0k
  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1383
76.2k
    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1384
18.8k
  else // C99
1385
18.8k
    Char32Ty = getFromTargetType(Target.getChar32Type());
1386
1387
  // Placeholder type for type-dependent expressions whose type is
1388
  // completely unknown. No code should ever check a type against
1389
  // DependentTy and users should never see it; however, it is here to
1390
  // help diagnose failures to properly check for type-dependent
1391
  // expressions.
1392
95.0k
  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1393
1394
  // Placeholder type for functions.
1395
95.0k
  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1396
1397
  // Placeholder type for bound members.
1398
95.0k
  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1399
1400
  // Placeholder type for pseudo-objects.
1401
95.0k
  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1402
1403
  // "any" type; useful for debugger-like clients.
1404
95.0k
  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1405
1406
  // Placeholder type for unbridged ARC casts.
1407
95.0k
  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1408
1409
  // Placeholder type for builtin functions.
1410
95.0k
  InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1411
1412
  // Placeholder type for OMP array sections.
1413
95.0k
  if (LangOpts.OpenMP) {
1414
11.9k
    InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1415
11.9k
    InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416
11.9k
    InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417
11.9k
  }
1418
95.0k
  if (LangOpts.MatrixTypes)
1419
50
    InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1420
1421
  // Builtin types for 'id', 'Class', and 'SEL'.
1422
95.0k
  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1423
95.0k
  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1424
95.0k
  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1425
1426
95.0k
  if (LangOpts.OpenCL) {
1427
645
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1428
23.2k
    InitBuiltinType(SingletonId, BuiltinType::Id);
1429
645
#include "clang/Basic/OpenCLImageTypes.def"
1430
1431
645
    InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1432
645
    InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1433
645
    InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1434
645
    InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1435
645
    InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1436
1437
645
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1438
7.74k
    InitBuiltinType(Id##Ty, BuiltinType::Id);
1439
645
#include "clang/Basic/OpenCLExtensionTypes.def"
1440
645
  }
1441
1442
95.0k
  if (Target.hasAArch64SVETypes()) {
1443
2.77k
#define SVE_TYPE(Name, Id, SingletonId) \
1444
135k
    InitBuiltinType(SingletonId, BuiltinType::Id);
1445
2.77k
#include "clang/Basic/AArch64SVEACLETypes.def"
1446
2.77k
  }
1447
1448
95.0k
  if (Target.getTriple().isPPC64()) {
1449
3.75k
#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1450
3.75k
      InitBuiltinType(Id##Ty, BuiltinType::Id);
1451
3.75k
#include "clang/Basic/PPCTypes.def"
1452
3.75k
#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1453
3.75k
    InitBuiltinType(Id##Ty, BuiltinType::Id);
1454
3.75k
#include "clang/Basic/PPCTypes.def"
1455
3.75k
  }
1456
1457
95.0k
  if (Target.hasRISCVVTypes()) {
1458
142
#define RVV_TYPE(Name, Id, SingletonId)                                        \
1459
9.37k
  InitBuiltinType(SingletonId, BuiltinType::Id);
1460
142
#include "clang/Basic/RISCVVTypes.def"
1461
142
  }
1462
1463
  // Builtin type for __objc_yes and __objc_no
1464
95.0k
  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1465
94.5k
                       SignedCharTy : 
BoolTy448
);
1466
1467
95.0k
  ObjCConstantStringType = QualType();
1468
1469
95.0k
  ObjCSuperType = QualType();
1470
1471
  // void * type
1472
95.0k
  if (LangOpts.OpenCLGenericAddressSpace) {
1473
343
    auto Q = VoidTy.getQualifiers();
1474
343
    Q.setAddressSpace(LangAS::opencl_generic);
1475
343
    VoidPtrTy = getPointerType(getCanonicalType(
1476
343
        getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1477
94.6k
  } else {
1478
94.6k
    VoidPtrTy = getPointerType(VoidTy);
1479
94.6k
  }
1480
1481
  // nullptr type (C++0x 2.14.7)
1482
95.0k
  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1483
1484
  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1485
95.0k
  InitBuiltinType(HalfTy, BuiltinType::Half);
1486
1487
95.0k
  InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1488
1489
  // Builtin type used to help define __builtin_va_list.
1490
95.0k
  VaListTagDecl = nullptr;
1491
1492
  // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1493
95.0k
  if (LangOpts.MicrosoftExt || 
LangOpts.Borland83.8k
) {
1494
11.2k
    MSGuidTagDecl = buildImplicitRecord("_GUID");
1495
11.2k
    getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1496
11.2k
  }
1497
95.0k
}
1498
1499
10.3M
DiagnosticsEngine &ASTContext::getDiagnostics() const {
1500
10.3M
  return SourceMgr.getDiagnostics();
1501
10.3M
}
1502
1503
1.87G
AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1504
1.87G
  AttrVec *&Result = DeclAttrs[D];
1505
1.87G
  if (!Result) {
1506
31.2M
    void *Mem = Allocate(sizeof(AttrVec));
1507
31.2M
    Result = new (Mem) AttrVec;
1508
31.2M
  }
1509
1510
1.87G
  return *Result;
1511
1.87G
}
1512
1513
/// Erase the attributes corresponding to the given declaration.
1514
4.57k
void ASTContext::eraseDeclAttrs(const Decl *D) {
1515
4.57k
  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1516
4.57k
  if (Pos != DeclAttrs.end()) {
1517
4.57k
    Pos->second->~AttrVec();
1518
4.57k
    DeclAttrs.erase(Pos);
1519
4.57k
  }
1520
4.57k
}
1521
1522
// FIXME: Remove ?
1523
MemberSpecializationInfo *
1524
0
ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1525
0
  assert(Var->isStaticDataMember() && "Not a static data member");
1526
0
  return getTemplateOrSpecializationInfo(Var)
1527
0
      .dyn_cast<MemberSpecializationInfo *>();
1528
0
}
1529
1530
ASTContext::TemplateOrSpecializationInfo
1531
74.5M
ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1532
74.5M
  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1533
74.5M
      TemplateOrInstantiation.find(Var);
1534
74.5M
  if (Pos == TemplateOrInstantiation.end())
1535
37.3M
    return {};
1536
1537
37.1M
  return Pos->second;
1538
74.5M
}
1539
1540
void
1541
ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1542
                                                TemplateSpecializationKind TSK,
1543
209k
                                          SourceLocation PointOfInstantiation) {
1544
209k
  assert(Inst->isStaticDataMember() && "Not a static data member");
1545
0
  assert(Tmpl->isStaticDataMember() && "Not a static data member");
1546
0
  setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1547
209k
                                            Tmpl, TSK, PointOfInstantiation));
1548
209k
}
1549
1550
void
1551
ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1552
214k
                                            TemplateOrSpecializationInfo TSI) {
1553
214k
  assert(!TemplateOrInstantiation[Inst] &&
1554
214k
         "Already noted what the variable was instantiated from");
1555
0
  TemplateOrInstantiation[Inst] = TSI;
1556
214k
}
1557
1558
NamedDecl *
1559
12.0k
ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1560
12.0k
  auto Pos = InstantiatedFromUsingDecl.find(UUD);
1561
12.0k
  if (Pos == InstantiatedFromUsingDecl.end())
1562
11.4k
    return nullptr;
1563
1564
611
  return Pos->second;
1565
12.0k
}
1566
1567
void
1568
1.89k
ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1569
1.89k
  assert((isa<UsingDecl>(Pattern) ||
1570
1.89k
          isa<UnresolvedUsingValueDecl>(Pattern) ||
1571
1.89k
          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1572
1.89k
         "pattern decl is not a using decl");
1573
0
  assert((isa<UsingDecl>(Inst) ||
1574
1.89k
          isa<UnresolvedUsingValueDecl>(Inst) ||
1575
1.89k
          isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1576
1.89k
         "instantiation did not produce a using decl");
1577
0
  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1578
0
  InstantiatedFromUsingDecl[Inst] = Pattern;
1579
1.89k
}
1580
1581
UsingEnumDecl *
1582
9
ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1583
9
  auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
1584
9
  if (Pos == InstantiatedFromUsingEnumDecl.end())
1585
9
    return nullptr;
1586
1587
0
  return Pos->second;
1588
9
}
1589
1590
void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1591
7
                                                  UsingEnumDecl *Pattern) {
1592
7
  assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1593
0
  InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1594
7
}
1595
1596
UsingShadowDecl *
1597
56.3k
ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1598
56.3k
  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1599
56.3k
    = InstantiatedFromUsingShadowDecl.find(Inst);
1600
56.3k
  if (Pos == InstantiatedFromUsingShadowDecl.end())
1601
56.2k
    return nullptr;
1602
1603
123
  return Pos->second;
1604
56.3k
}
1605
1606
void
1607
ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1608
482
                                               UsingShadowDecl *Pattern) {
1609
482
  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1610
0
  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1611
482
}
1612
1613
48.9k
FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1614
48.9k
  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1615
48.9k
    = InstantiatedFromUnnamedFieldDecl.find(Field);
1616
48.9k
  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1617
41.1k
    return nullptr;
1618
1619
7.80k
  return Pos->second;
1620
48.9k
}
1621
1622
void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1623
3.59k
                                                     FieldDecl *Tmpl) {
1624
3.59k
  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1625
0
  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1626
0
  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1627
3.59k
         "Already noted what unnamed field was instantiated from");
1628
1629
0
  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1630
3.59k
}
1631
1632
ASTContext::overridden_cxx_method_iterator
1633
2.94k
ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1634
2.94k
  return overridden_methods(Method).begin();
1635
2.94k
}
1636
1637
ASTContext::overridden_cxx_method_iterator
1638
1.09k
ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1639
1.09k
  return overridden_methods(Method).end();
1640
1.09k
}
1641
1642
unsigned
1643
9.93M
ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1644
9.93M
  auto Range = overridden_methods(Method);
1645
9.93M
  return Range.end() - Range.begin();
1646
9.93M
}
1647
1648
ASTContext::overridden_method_range
1649
12.7M
ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1650
12.7M
  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1651
12.7M
      OverriddenMethods.find(Method->getCanonicalDecl());
1652
12.7M
  if (Pos == OverriddenMethods.end())
1653
12.5M
    return overridden_method_range(nullptr, nullptr);
1654
220k
  return overridden_method_range(Pos->second.begin(), Pos->second.end());
1655
12.7M
}
1656
1657
void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1658
36.8k
                                     const CXXMethodDecl *Overridden) {
1659
36.8k
  assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1660
0
  OverriddenMethods[Method].push_back(Overridden);
1661
36.8k
}
1662
1663
void ASTContext::getOverriddenMethods(
1664
                      const NamedDecl *D,
1665
8.25k
                      SmallVectorImpl<const NamedDecl *> &Overridden) const {
1666
8.25k
  assert(D);
1667
1668
8.25k
  if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1669
1.09k
    Overridden.append(overridden_methods_begin(CXXMethod),
1670
1.09k
                      overridden_methods_end(CXXMethod));
1671
1.09k
    return;
1672
1.09k
  }
1673
1674
7.16k
  const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1675
7.16k
  if (!Method)
1676
6.34k
    return;
1677
1678
822
  SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1679
822
  Method->getOverriddenMethods(OverDecls);
1680
822
  Overridden.append(OverDecls.begin(), OverDecls.end());
1681
822
}
1682
1683
120k
void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1684
120k
  assert(!Import->getNextLocalImport() &&
1685
120k
         "Import declaration already in the chain");
1686
0
  assert(!Import->isFromASTFile() && "Non-local import declaration");
1687
120k
  if (!FirstLocalImport) {
1688
4.29k
    FirstLocalImport = Import;
1689
4.29k
    LastLocalImport = Import;
1690
4.29k
    return;
1691
4.29k
  }
1692
1693
116k
  LastLocalImport->setNextLocalImport(Import);
1694
116k
  LastLocalImport = Import;
1695
116k
}
1696
1697
//===----------------------------------------------------------------------===//
1698
//                         Type Sizing and Analysis
1699
//===----------------------------------------------------------------------===//
1700
1701
/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1702
/// scalar floating point type.
1703
338k
const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1704
338k
  switch (T->castAs<BuiltinType>()->getKind()) {
1705
0
  default:
1706
0
    llvm_unreachable("Not a floating point type!");
1707
344
  case BuiltinType::BFloat16:
1708
344
    return Target->getBFloat16Format();
1709
940
  case BuiltinType::Float16:
1710
9.29k
  case BuiltinType::Half:
1711
9.29k
    return Target->getHalfFormat();
1712
132k
  case BuiltinType::Float:      return Target->getFloatFormat();
1713
158k
  case BuiltinType::Double:     return Target->getDoubleFormat();
1714
94
  case BuiltinType::Ibm128:
1715
94
    return Target->getIbm128Format();
1716
36.2k
  case BuiltinType::LongDouble:
1717
36.2k
    if (getLangOpts().OpenMP && 
getLangOpts().OpenMPIsDevice1.96k
)
1718
458
      return AuxTarget->getLongDoubleFormat();
1719
35.7k
    return Target->getLongDoubleFormat();
1720
1.26k
  case BuiltinType::Float128:
1721
1.26k
    if (getLangOpts().OpenMP && 
getLangOpts().OpenMPIsDevice55
)
1722
36
      return AuxTarget->getFloat128Format();
1723
1.23k
    return Target->getFloat128Format();
1724
338k
  }
1725
338k
}
1726
1727
1.99M
CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1728
1.99M
  unsigned Align = Target->getCharWidth();
1729
1730
1.99M
  bool UseAlignAttrOnly = false;
1731
1.99M
  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1732
2.03k
    Align = AlignFromAttr;
1733
1734
    // __attribute__((aligned)) can increase or decrease alignment
1735
    // *except* on a struct or struct member, where it only increases
1736
    // alignment unless 'packed' is also specified.
1737
    //
1738
    // It is an error for alignas to decrease alignment, so we can
1739
    // ignore that possibility;  Sema should diagnose it.
1740
2.03k
    if (isa<FieldDecl>(D)) {
1741
6
      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1742
6
        
cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>()4
;
1743
2.02k
    } else {
1744
2.02k
      UseAlignAttrOnly = true;
1745
2.02k
    }
1746
2.03k
  }
1747
1.99M
  else if (isa<FieldDecl>(D))
1748
74
      UseAlignAttrOnly =
1749
74
        D->hasAttr<PackedAttr>() ||
1750
74
        
cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>()58
;
1751
1752
  // If we're using the align attribute only, just ignore everything
1753
  // else about the declaration and its type.
1754
1.99M
  if (UseAlignAttrOnly) {
1755
    // do nothing
1756
1.99M
  } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1757
1.99M
    QualType T = VD->getType();
1758
1.99M
    if (const auto *RT = T->getAs<ReferenceType>()) {
1759
96.5k
      if (ForAlignof)
1760
2
        T = RT->getPointeeType();
1761
96.4k
      else
1762
96.4k
        T = getPointerType(RT->getPointeeType());
1763
96.5k
    }
1764
1.99M
    QualType BaseT = getBaseElementType(T);
1765
1.99M
    if (T->isFunctionType())
1766
3.32k
      Align = getTypeInfoImpl(T.getTypePtr()).Align;
1767
1.98M
    else if (!BaseT->isIncompleteType()) {
1768
      // Adjust alignments of declarations with array type by the
1769
      // large-array alignment on the target.
1770
1.98M
      if (const ArrayType *arrayType = getAsArrayType(T)) {
1771
27.2k
        unsigned MinWidth = Target->getLargeArrayMinWidth();
1772
27.2k
        if (!ForAlignof && 
MinWidth27.2k
) {
1773
7.80k
          if (isa<VariableArrayType>(arrayType))
1774
384
            Align = std::max(Align, Target->getLargeArrayAlign());
1775
7.41k
          else if (isa<ConstantArrayType>(arrayType) &&
1776
7.41k
                   
MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))7.36k
)
1777
4.40k
            Align = std::max(Align, Target->getLargeArrayAlign());
1778
7.80k
        }
1779
27.2k
      }
1780
1.98M
      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1781
1.98M
      if (BaseT.getQualifiers().hasUnaligned())
1782
50
        Align = Target->getCharWidth();
1783
1.98M
      if (const auto *VD = dyn_cast<VarDecl>(D)) {
1784
1.98M
        if (VD->hasGlobalStorage() && 
!ForAlignof191k
) {
1785
191k
          uint64_t TypeSize = getTypeSize(T.getTypePtr());
1786
191k
          Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1787
191k
        }
1788
1.98M
      }
1789
1.98M
    }
1790
1791
    // Fields can be subject to extra alignment constraints, like if
1792
    // the field is packed, the struct is packed, or the struct has a
1793
    // a max-field-alignment constraint (#pragma pack).  So calculate
1794
    // the actual alignment of the field within the struct, and then
1795
    // (as we're expected to) constrain that by the alignment of the type.
1796
1.99M
    if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1797
39
      const RecordDecl *Parent = Field->getParent();
1798
      // We can only produce a sensible answer if the record is valid.
1799
39
      if (!Parent->isInvalidDecl()) {
1800
37
        const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1801
1802
        // Start with the record's overall alignment.
1803
37
        unsigned FieldAlign = toBits(Layout.getAlignment());
1804
1805
        // Use the GCD of that and the offset within the record.
1806
37
        uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1807
37
        if (Offset > 0) {
1808
          // Alignment is always a power of 2, so the GCD will be a power of 2,
1809
          // which means we get to do this crazy thing instead of Euclid's.
1810
18
          uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1811
18
          if (LowBitOfOffset < FieldAlign)
1812
0
            FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1813
18
        }
1814
1815
37
        Align = std::min(Align, FieldAlign);
1816
37
      }
1817
39
    }
1818
1.99M
  }
1819
1820
  // Some targets have hard limitation on the maximum requestable alignment in
1821
  // aligned attribute for static variables.
1822
1.99M
  const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1823
1.99M
  const auto *VD = dyn_cast<VarDecl>(D);
1824
1.99M
  if (MaxAlignedAttr && 
VD96
&&
VD->getStorageClass() == SC_Static96
)
1825
12
    Align = std::min(Align, MaxAlignedAttr);
1826
1827
1.99M
  return toCharUnitsFromBits(Align);
1828
1.99M
}
1829
1830
5.94k
CharUnits ASTContext::getExnObjectAlignment() const {
1831
5.94k
  return toCharUnitsFromBits(Target->getExnObjectAlignment());
1832
5.94k
}
1833
1834
// getTypeInfoDataSizeInChars - Return the size of a type, in
1835
// chars. If the type is a record, its data size is returned.  This is
1836
// the size of the memcpy that's performed when assigning this type
1837
// using a trivial copy/move assignment operator.
1838
12.2k
TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1839
12.2k
  TypeInfoChars Info = getTypeInfoInChars(T);
1840
1841
  // In C++, objects can sometimes be allocated into the tail padding
1842
  // of a base-class subobject.  We decide whether that's possible
1843
  // during class layout, so here we can just trust the layout results.
1844
12.2k
  if (getLangOpts().CPlusPlus) {
1845
10.7k
    if (const auto *RT = T->getAs<RecordType>()) {
1846
9.05k
      const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1847
9.05k
      Info.Width = layout.getDataSize();
1848
9.05k
    }
1849
10.7k
  }
1850
1851
12.2k
  return Info;
1852
12.2k
}
1853
1854
/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1855
/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1856
TypeInfoChars
1857
static getConstantArrayInfoInChars(const ASTContext &Context,
1858
134k
                                   const ConstantArrayType *CAT) {
1859
134k
  TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1860
134k
  uint64_t Size = CAT->getSize().getZExtValue();
1861
134k
  assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1862
134k
              (uint64_t)(-1)/Size) &&
1863
134k
         "Overflow in array type char size evaluation");
1864
0
  uint64_t Width = EltInfo.Width.getQuantity() * Size;
1865
134k
  unsigned Align = EltInfo.Align.getQuantity();
1866
134k
  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1867
134k
      
Context.getTargetInfo().getPointerWidth(0) == 64340
)
1868
134k
    Width = llvm::alignTo(Width, Align);
1869
134k
  return TypeInfoChars(CharUnits::fromQuantity(Width),
1870
134k
                       CharUnits::fromQuantity(Align),
1871
134k
                       EltInfo.AlignRequirement);
1872
134k
}
1873
1874
4.06M
TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1875
4.06M
  if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1876
134k
    return getConstantArrayInfoInChars(*this, CAT);
1877
3.92M
  TypeInfo Info = getTypeInfo(T);
1878
3.92M
  return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1879
3.92M
                       toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1880
4.06M
}
1881
1882
4.03M
TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1883
4.03M
  return getTypeInfoInChars(T.getTypePtr());
1884
4.03M
}
1885
1886
3.30k
bool ASTContext::isAlignmentRequired(const Type *T) const {
1887
3.30k
  return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1888
3.30k
}
1889
1890
3.30k
bool ASTContext::isAlignmentRequired(QualType T) const {
1891
3.30k
  return isAlignmentRequired(T.getTypePtr());
1892
3.30k
}
1893
1894
unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1895
2.10k
                                         bool NeedsPreferredAlignment) const {
1896
  // An alignment on a typedef overrides anything else.
1897
2.10k
  if (const auto *TT = T->getAs<TypedefType>())
1898
392
    if (unsigned Align = TT->getDecl()->getMaxAlignment())
1899
0
      return Align;
1900
1901
  // If we have an (array of) complete type, we're done.
1902
2.10k
  T = getBaseElementType(T);
1903
2.10k
  if (!T->isIncompleteType())
1904
2.10k
    return NeedsPreferredAlignment ? 
getPreferredTypeAlign(T)38
:
getTypeAlign(T)2.06k
;
1905
1906
  // If we had an array type, its element type might be a typedef
1907
  // type with an alignment attribute.
1908
3
  if (const auto *TT = T->getAs<TypedefType>())
1909
0
    if (unsigned Align = TT->getDecl()->getMaxAlignment())
1910
0
      return Align;
1911
1912
  // Otherwise, see if the declaration of the type had an attribute.
1913
3
  if (const auto *TT = T->getAs<TagType>())
1914
0
    return TT->getDecl()->getMaxAlignment();
1915
1916
3
  return 0;
1917
3
}
1918
1919
106M
TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1920
106M
  TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1921
106M
  if (I != MemoizedTypeInfo.end())
1922
104M
    return I->second;
1923
1924
  // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1925
2.21M
  TypeInfo TI = getTypeInfoImpl(T);
1926
2.21M
  MemoizedTypeInfo[T] = TI;
1927
2.21M
  return TI;
1928
106M
}
1929
1930
/// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1931
/// method does not work on incomplete types.
1932
///
1933
/// FIXME: Pointers into different addr spaces could have different sizes and
1934
/// alignment requirements: getPointerInfo should take an AddrSpace, this
1935
/// should take a QualType, &c.
1936
2.22M
TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1937
2.22M
  uint64_t Width = 0;
1938
2.22M
  unsigned Align = 8;
1939
2.22M
  AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1940
2.22M
  unsigned AS = 0;
1941
2.22M
  switch (T->getTypeClass()) {
1942
0
#define TYPE(Class, Base)
1943
0
#define ABSTRACT_TYPE(Class, Base)
1944
0
#define NON_CANONICAL_TYPE(Class, Base)
1945
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1946
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1947
116k
  case Type::Class:                                                            \
1948
116k
  assert(!T->isDependentType() && "should not see dependent types here");      \
1949
116k
  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1950
0
#include "clang/AST/TypeNodes.inc"
1951
0
    llvm_unreachable("Should not see dependent types");
1952
1953
21
  case Type::FunctionNoProto:
1954
7.35k
  case Type::FunctionProto:
1955
    // GCC extension: alignof(function) = 32 bits
1956
7.35k
    Width = 0;
1957
7.35k
    Align = 32;
1958
7.35k
    break;
1959
1960
228
  case Type::IncompleteArray:
1961
4.00k
  case Type::VariableArray:
1962
70.0k
  case Type::ConstantArray: {
1963
    // Model non-constant sized arrays as size zero, but track the alignment.
1964
70.0k
    uint64_t Size = 0;
1965
70.0k
    if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1966
66.0k
      Size = CAT->getSize().getZExtValue();
1967
1968
70.0k
    TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1969
70.0k
    assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1970
70.0k
           "Overflow in array type bit size evaluation");
1971
0
    Width = EltInfo.Width * Size;
1972
70.0k
    Align = EltInfo.Align;
1973
70.0k
    AlignRequirement = EltInfo.AlignRequirement;
1974
70.0k
    if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1975
70.0k
        
getTargetInfo().getPointerWidth(0) == 64332
)
1976
69.9k
      Width = llvm::alignTo(Width, Align);
1977
70.0k
    break;
1978
4.00k
  }
1979
1980
722
  case Type::ExtVector:
1981
29.6k
  case Type::Vector: {
1982
29.6k
    const auto *VT = cast<VectorType>(T);
1983
29.6k
    TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1984
29.6k
    Width = VT->isExtVectorBoolType() ? 
VT->getNumElements()26
1985
29.6k
                                      : 
EltInfo.Width * VT->getNumElements()29.6k
;
1986
    // Enforce at least byte alignment.
1987
29.6k
    Align = std::max<unsigned>(8, Width);
1988
1989
    // If the alignment is not a power of 2, round up to the next power of 2.
1990
    // This happens for non-power-of-2 length vectors.
1991
29.6k
    if (Align & (Align-1)) {
1992
1.49k
      Align = llvm::NextPowerOf2(Align);
1993
1.49k
      Width = llvm::alignTo(Width, Align);
1994
1.49k
    }
1995
    // Adjust the alignment based on the target max.
1996
29.6k
    uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1997
29.6k
    if (TargetVectorAlign && 
TargetVectorAlign < Align24.0k
)
1998
6.92k
      Align = TargetVectorAlign;
1999
29.6k
    if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
2000
      // Adjust the alignment for fixed-length SVE vectors. This is important
2001
      // for non-power-of-2 vector lengths.
2002
305
      Align = 128;
2003
29.3k
    else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
2004
      // Adjust the alignment for fixed-length SVE predicates.
2005
30
      Align = 16;
2006
29.6k
    break;
2007
722
  }
2008
2009
176
  case Type::ConstantMatrix: {
2010
176
    const auto *MT = cast<ConstantMatrixType>(T);
2011
176
    TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2012
    // The internal layout of a matrix value is implementation defined.
2013
    // Initially be ABI compatible with arrays with respect to alignment and
2014
    // size.
2015
176
    Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2016
176
    Align = ElementInfo.Align;
2017
176
    break;
2018
722
  }
2019
2020
355k
  case Type::Builtin:
2021
355k
    switch (cast<BuiltinType>(T)->getKind()) {
2022
0
    default: llvm_unreachable("Unknown builtin type!");
2023
91
    case BuiltinType::Void:
2024
      // GCC extension: alignof(void) = 8 bits.
2025
91
      Width = 0;
2026
91
      Align = 8;
2027
91
      break;
2028
7.81k
    case BuiltinType::Bool:
2029
7.81k
      Width = Target->getBoolWidth();
2030
7.81k
      Align = Target->getBoolAlign();
2031
7.81k
      break;
2032
55.9k
    case BuiltinType::Char_S:
2033
56.2k
    case BuiltinType::Char_U:
2034
67.9k
    case BuiltinType::UChar:
2035
72.7k
    case BuiltinType::SChar:
2036
72.7k
    case BuiltinType::Char8:
2037
72.7k
      Width = Target->getCharWidth();
2038
72.7k
      Align = Target->getCharAlign();
2039
72.7k
      break;
2040
25.6k
    case BuiltinType::WChar_S:
2041
27.3k
    case BuiltinType::WChar_U:
2042
27.3k
      Width = Target->getWCharWidth();
2043
27.3k
      Align = Target->getWCharAlign();
2044
27.3k
      break;
2045
520
    case BuiltinType::Char16:
2046
520
      Width = Target->getChar16Width();
2047
520
      Align = Target->getChar16Align();
2048
520
      break;
2049
518
    case BuiltinType::Char32:
2050
518
      Width = Target->getChar32Width();
2051
518
      Align = Target->getChar32Align();
2052
518
      break;
2053
7.65k
    case BuiltinType::UShort:
2054
30.3k
    case BuiltinType::Short:
2055
30.3k
      Width = Target->getShortWidth();
2056
30.3k
      Align = Target->getShortAlign();
2057
30.3k
      break;
2058
20.9k
    case BuiltinType::UInt:
2059
73.4k
    case BuiltinType::Int:
2060
73.4k
      Width = Target->getIntWidth();
2061
73.4k
      Align = Target->getIntAlign();
2062
73.4k
      break;
2063
63.0k
    case BuiltinType::ULong:
2064
89.6k
    case BuiltinType::Long:
2065
89.6k
      Width = Target->getLongWidth();
2066
89.6k
      Align = Target->getLongAlign();
2067
89.6k
      break;
2068
5.13k
    case BuiltinType::ULongLong:
2069
13.5k
    case BuiltinType::LongLong:
2070
13.5k
      Width = Target->getLongLongWidth();
2071
13.5k
      Align = Target->getLongLongAlign();
2072
13.5k
      break;
2073
1.44k
    case BuiltinType::Int128:
2074
2.37k
    case BuiltinType::UInt128:
2075
2.37k
      Width = 128;
2076
2.37k
      Align = 128; // int128_t is 128-bit aligned on all targets.
2077
2.37k
      break;
2078
37
    case BuiltinType::ShortAccum:
2079
78
    case BuiltinType::UShortAccum:
2080
113
    case BuiltinType::SatShortAccum:
2081
148
    case BuiltinType::SatUShortAccum:
2082
148
      Width = Target->getShortAccumWidth();
2083
148
      Align = Target->getShortAccumAlign();
2084
148
      break;
2085
48
    case BuiltinType::Accum:
2086
85
    case BuiltinType::UAccum:
2087
109
    case BuiltinType::SatAccum:
2088
131
    case BuiltinType::SatUAccum:
2089
131
      Width = Target->getAccumWidth();
2090
131
      Align = Target->getAccumAlign();
2091
131
      break;
2092
36
    case BuiltinType::LongAccum:
2093
65
    case BuiltinType::ULongAccum:
2094
87
    case BuiltinType::SatLongAccum:
2095
107
    case BuiltinType::SatULongAccum:
2096
107
      Width = Target->getLongAccumWidth();
2097
107
      Align = Target->getLongAccumAlign();
2098
107
      break;
2099
38
    case BuiltinType::ShortFract:
2100
63
    case BuiltinType::UShortFract:
2101
80
    case BuiltinType::SatShortFract:
2102
88
    case BuiltinType::SatUShortFract:
2103
88
      Width = Target->getShortFractWidth();
2104
88
      Align = Target->getShortFractAlign();
2105
88
      break;
2106
51
    case BuiltinType::Fract:
2107
86
    case BuiltinType::UFract:
2108
100
    case BuiltinType::SatFract:
2109
124
    case BuiltinType::SatUFract:
2110
124
      Width = Target->getFractWidth();
2111
124
      Align = Target->getFractAlign();
2112
124
      break;
2113
33
    case BuiltinType::LongFract:
2114
58
    case BuiltinType::ULongFract:
2115
70
    case BuiltinType::SatLongFract:
2116
76
    case BuiltinType::SatULongFract:
2117
76
      Width = Target->getLongFractWidth();
2118
76
      Align = Target->getLongFractAlign();
2119
76
      break;
2120
334
    case BuiltinType::BFloat16:
2121
334
      if (Target->hasBFloat16Type()) {
2122
333
        Width = Target->getBFloat16Width();
2123
333
        Align = Target->getBFloat16Align();
2124
333
      }
2125
334
      break;
2126
27
    case BuiltinType::Float16:
2127
2.42k
    case BuiltinType::Half:
2128
2.42k
      if (Target->hasFloat16Type() || 
!getLangOpts().OpenMP43
||
2129
2.42k
          
!getLangOpts().OpenMPIsDevice0
) {
2130
2.42k
        Width = Target->getHalfWidth();
2131
2.42k
        Align = Target->getHalfAlign();
2132
2.42k
      } else {
2133
0
        assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2134
0
               "Expected OpenMP device compilation.");
2135
0
        Width = AuxTarget->getHalfWidth();
2136
0
        Align = AuxTarget->getHalfAlign();
2137
0
      }
2138
0
      break;
2139
9.70k
    case BuiltinType::Float:
2140
9.70k
      Width = Target->getFloatWidth();
2141
9.70k
      Align = Target->getFloatAlign();
2142
9.70k
      break;
2143
9.21k
    case BuiltinType::Double:
2144
9.21k
      Width = Target->getDoubleWidth();
2145
9.21k
      Align = Target->getDoubleAlign();
2146
9.21k
      break;
2147
7
    case BuiltinType::Ibm128:
2148
7
      Width = Target->getIbm128Width();
2149
7
      Align = Target->getIbm128Align();
2150
7
      break;
2151
1.59k
    case BuiltinType::LongDouble:
2152
1.59k
      if (getLangOpts().OpenMP && 
getLangOpts().OpenMPIsDevice61
&&
2153
1.59k
          
(12
Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth()12
||
2154
12
           
Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign()5
)) {
2155
7
        Width = AuxTarget->getLongDoubleWidth();
2156
7
        Align = AuxTarget->getLongDoubleAlign();
2157
1.58k
      } else {
2158
1.58k
        Width = Target->getLongDoubleWidth();
2159
1.58k
        Align = Target->getLongDoubleAlign();
2160
1.58k
      }
2161
1.59k
      break;
2162
41
    case BuiltinType::Float128:
2163
41
      if (Target->hasFloat128Type() || 
!getLangOpts().OpenMP7
||
2164
41
          
!getLangOpts().OpenMPIsDevice2
) {
2165
39
        Width = Target->getFloat128Width();
2166
39
        Align = Target->getFloat128Align();
2167
39
      } else {
2168
2
        assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2169
2
               "Expected OpenMP device compilation.");
2170
0
        Width = AuxTarget->getFloat128Width();
2171
2
        Align = AuxTarget->getFloat128Align();
2172
2
      }
2173
0
      break;
2174
331
    case BuiltinType::NullPtr:
2175
331
      Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2176
331
      Align = Target->getPointerAlign(0); //   == sizeof(void*)
2177
331
      break;
2178
30
    case BuiltinType::ObjCId:
2179
48
    case BuiltinType::ObjCClass:
2180
58
    case BuiltinType::ObjCSel:
2181
58
      Width = Target->getPointerWidth(0);
2182
58
      Align = Target->getPointerAlign(0);
2183
58
      break;
2184
11
    case BuiltinType::OCLSampler:
2185
17
    case BuiltinType::OCLEvent:
2186
29
    case BuiltinType::OCLClkEvent:
2187
44
    case BuiltinType::OCLQueue:
2188
52
    case BuiltinType::OCLReserveID:
2189
52
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2190
2.99k
    case BuiltinType::Id:
2191
2.99k
#include 
"clang/Basic/OpenCLImageTypes.def"52
2192
2.99k
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2193
2.99k
  
case BuiltinType::Id:1.19k
2194
2.99k
#include 
"clang/Basic/OpenCLExtensionTypes.def"93
2195
105
      AS = getTargetAddressSpace(
2196
105
          Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2197
105
      Width = Target->getPointerWidth(AS);
2198
105
      Align = Target->getPointerAlign(AS);
2199
105
      break;
2200
    // The SVE types are effectively target-specific.  The length of an
2201
    // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2202
    // of 128 bits.  There is one predicate bit for each vector byte, so the
2203
    // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2204
    //
2205
    // Because the length is only known at runtime, we use a dummy value
2206
    // of 0 for the static length.  The alignment values are those defined
2207
    // by the Procedure Call Standard for the Arm Architecture.
2208
0
#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2209
0
                        IsSigned, IsFP, IsBF)                                  \
2210
11.0k
  case BuiltinType::Id:                                                        \
2211
11.0k
    Width = 0;                                                                 \
2212
11.0k
    Align = 128;                                                               \
2213
11.0k
    break;
2214
0
#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2215
1.05k
  case BuiltinType::Id:                                                        \
2216
1.05k
    Width = 0;                                                                 \
2217
1.05k
    Align = 16;                                                                \
2218
1.05k
    break;
2219
105
#include "clang/Basic/AArch64SVEACLETypes.def"
2220
0
#define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2221
26
  case BuiltinType::Id:                                                        \
2222
26
    Width = Size;                                                              \
2223
26
    Align = Size;                                                              \
2224
26
    break;
2225
1.05k
#include "clang/Basic/PPCTypes.def"
2226
0
#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2227
0
                        IsFP)                                                  \
2228
3
  case BuiltinType::Id:                                                        \
2229
3
    Width = 0;                                                                 \
2230
3
    Align = ElBits;                                                            \
2231
3
    break;
2232
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2233
0
  case BuiltinType::Id:                                                        \
2234
0
    Width = 0;                                                                 \
2235
0
    Align = 8;                                                                 \
2236
0
    break;
2237
355k
#include 
"clang/Basic/RISCVVTypes.def"13
2238
355k
    }
2239
355k
    break;
2240
355k
  case Type::ObjCObjectPointer:
2241
41.5k
    Width = Target->getPointerWidth(0);
2242
41.5k
    Align = Target->getPointerAlign(0);
2243
41.5k
    break;
2244
1.50k
  case Type::BlockPointer:
2245
1.50k
    AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2246
1.50k
    Width = Target->getPointerWidth(AS);
2247
1.50k
    Align = Target->getPointerAlign(AS);
2248
1.50k
    break;
2249
104k
  case Type::LValueReference:
2250
122k
  case Type::RValueReference:
2251
    // alignof and sizeof should never enter this code path here, so we go
2252
    // the pointer route.
2253
122k
    AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2254
122k
    Width = Target->getPointerWidth(AS);
2255
122k
    Align = Target->getPointerAlign(AS);
2256
122k
    break;
2257
358k
  case Type::Pointer:
2258
358k
    AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2259
358k
    Width = Target->getPointerWidth(AS);
2260
358k
    Align = Target->getPointerAlign(AS);
2261
358k
    break;
2262
1.63k
  case Type::MemberPointer: {
2263
1.63k
    const auto *MPT = cast<MemberPointerType>(T);
2264
1.63k
    CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2265
1.63k
    Width = MPI.Width;
2266
1.63k
    Align = MPI.Align;
2267
1.63k
    break;
2268
104k
  }
2269
792
  case Type::Complex: {
2270
    // Complex types have the same alignment as their elements, but twice the
2271
    // size.
2272
792
    TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2273
792
    Width = EltInfo.Width * 2;
2274
792
    Align = EltInfo.Align;
2275
792
    break;
2276
104k
  }
2277
13
  case Type::ObjCObject:
2278
13
    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2279
0
  case Type::Adjusted:
2280
1.81k
  case Type::Decayed:
2281
1.81k
    return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2282
3.74k
  case Type::ObjCInterface: {
2283
3.74k
    const auto *ObjCI = cast<ObjCInterfaceType>(T);
2284
3.74k
    if (ObjCI->getDecl()->isInvalidDecl()) {
2285
1
      Width = 8;
2286
1
      Align = 8;
2287
1
      break;
2288
1
    }
2289
3.73k
    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2290
3.73k
    Width = toBits(Layout.getSize());
2291
3.73k
    Align = toBits(Layout.getAlignment());
2292
3.73k
    break;
2293
3.74k
  }
2294
425
  case Type::BitInt: {
2295
425
    const auto *EIT = cast<BitIntType>(T);
2296
425
    Align =
2297
425
        std::min(static_cast<unsigned>(std::max(
2298
425
                     getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2299
425
                 Target->getLongLongAlign());
2300
425
    Width = llvm::alignTo(EIT->getNumBits(), Align);
2301
425
    break;
2302
3.74k
  }
2303
325k
  case Type::Record:
2304
344k
  case Type::Enum: {
2305
344k
    const auto *TT = cast<TagType>(T);
2306
2307
344k
    if (TT->getDecl()->isInvalidDecl()) {
2308
157
      Width = 8;
2309
157
      Align = 8;
2310
157
      break;
2311
157
    }
2312
2313
344k
    if (const auto *ET = dyn_cast<EnumType>(TT)) {
2314
19.6k
      const EnumDecl *ED = ET->getDecl();
2315
19.6k
      TypeInfo Info =
2316
19.6k
          getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2317
19.6k
      if (unsigned AttrAlign = ED->getMaxAlignment()) {
2318
4
        Info.Align = AttrAlign;
2319
4
        Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2320
4
      }
2321
19.6k
      return Info;
2322
19.6k
    }
2323
2324
325k
    const auto *RT = cast<RecordType>(TT);
2325
325k
    const RecordDecl *RD = RT->getDecl();
2326
325k
    const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2327
325k
    Width = toBits(Layout.getSize());
2328
325k
    Align = toBits(Layout.getAlignment());
2329
325k
    AlignRequirement = RD->hasAttr<AlignedAttr>()
2330
325k
                           ? 
AlignRequirementKind::RequiredByRecord3.08k
2331
325k
                           : 
AlignRequirementKind::None322k
;
2332
325k
    break;
2333
344k
  }
2334
2335
136k
  case Type::SubstTemplateTypeParm:
2336
136k
    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2337
136k
                       getReplacementType().getTypePtr());
2338
2339
6.64k
  case Type::Auto:
2340
6.86k
  case Type::DeducedTemplateSpecialization: {
2341
6.86k
    const auto *A = cast<DeducedType>(T);
2342
6.86k
    assert(!A->getDeducedType().isNull() &&
2343
6.86k
           "cannot request the size of an undeduced or dependent auto type");
2344
0
    return getTypeInfo(A->getDeducedType().getTypePtr());
2345
6.64k
  }
2346
2347
3.80k
  case Type::Paren:
2348
3.80k
    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2349
2350
326
  case Type::MacroQualified:
2351
326
    return getTypeInfo(
2352
326
        cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2353
2354
31
  case Type::ObjCTypeParam:
2355
31
    return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2356
2357
5.72k
  case Type::Using:
2358
5.72k
    return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2359
2360
412k
  case Type::Typedef: {
2361
412k
    const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2362
412k
    TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2363
    // If the typedef has an aligned attribute on it, it overrides any computed
2364
    // alignment we have.  This violates the GCC documentation (which says that
2365
    // attribute(aligned) can only round up) but matches its implementation.
2366
412k
    if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2367
6.97k
      Align = AttrAlign;
2368
6.97k
      AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2369
405k
    } else {
2370
405k
      Align = Info.Align;
2371
405k
      AlignRequirement = Info.AlignRequirement;
2372
405k
    }
2373
412k
    Width = Info.Width;
2374
412k
    break;
2375
6.64k
  }
2376
2377
185k
  case Type::Elaborated:
2378
185k
    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2379
2380
12.4k
  case Type::Attributed:
2381
12.4k
    return getTypeInfo(
2382
12.4k
                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2383
2384
2
  case Type::BTFTagAttributed:
2385
2
    return getTypeInfo(
2386
2
        cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2387
2388
1.18k
  case Type::Atomic: {
2389
    // Start with the base type information.
2390
1.18k
    TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2391
1.18k
    Width = Info.Width;
2392
1.18k
    Align = Info.Align;
2393
2394
1.18k
    if (!Width) {
2395
      // An otherwise zero-sized type should still generate an
2396
      // atomic operation.
2397
4
      Width = Target->getCharWidth();
2398
4
      assert(Align);
2399
1.18k
    } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2400
      // If the size of the type doesn't exceed the platform's max
2401
      // atomic promotion width, make the size and alignment more
2402
      // favorable to atomic operations:
2403
2404
      // Round the size up to a power of 2.
2405
1.10k
      if (!llvm::isPowerOf2_64(Width))
2406
16
        Width = llvm::NextPowerOf2(Width);
2407
2408
      // Set the alignment equal to the size.
2409
1.10k
      Align = static_cast<unsigned>(Width);
2410
1.10k
    }
2411
1.18k
  }
2412
0
  break;
2413
2414
132
  case Type::Pipe:
2415
132
    Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2416
132
    Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2417
132
    break;
2418
2.22M
  }
2419
2420
1.73M
  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2421
0
  return TypeInfo(Width, Align, AlignRequirement);
2422
2.22M
}
2423
2424
1.04k
unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2425
1.04k
  UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2426
1.04k
  if (I != MemoizedUnadjustedAlign.end())
2427
316
    return I->second;
2428
2429
724
  unsigned UnadjustedAlign;
2430
724
  if (const auto *RT = T->getAs<RecordType>()) {
2431
628
    const RecordDecl *RD = RT->getDecl();
2432
628
    const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2433
628
    UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2434
628
  } else 
if (const auto *96
ObjCI96
= T->getAs<ObjCInterfaceType>()) {
2435
0
    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2436
0
    UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2437
96
  } else {
2438
96
    UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2439
96
  }
2440
2441
724
  MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2442
724
  return UnadjustedAlign;
2443
1.04k
}
2444
2445
337
unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2446
337
  unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2447
337
  return SimdAlign;
2448
337
}
2449
2450
/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2451
18.1M
CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2452
18.1M
  return CharUnits::fromQuantity(BitSize / getCharWidth());
2453
18.1M
}
2454
2455
/// toBits - Convert a size in characters to a size in characters.
2456
7.39M
int64_t ASTContext::toBits(CharUnits CharSize) const {
2457
7.39M
  return CharSize.getQuantity() * getCharWidth();
2458
7.39M
}
2459
2460
/// getTypeSizeInChars - Return the size of the specified type, in characters.
2461
/// This method does not work on incomplete types.
2462
3.05M
CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2463
3.05M
  return getTypeInfoInChars(T).Width;
2464
3.05M
}
2465
22.6k
CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2466
22.6k
  return getTypeInfoInChars(T).Width;
2467
22.6k
}
2468
2469
/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2470
/// characters. This method does not work on incomplete types.
2471
4.30M
CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2472
4.30M
  return toCharUnitsFromBits(getTypeAlign(T));
2473
4.30M
}
2474
2.99k
CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2475
2.99k
  return toCharUnitsFromBits(getTypeAlign(T));
2476
2.99k
}
2477
2478
/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2479
/// type, in characters, before alignment adustments. This method does
2480
/// not work on incomplete types.
2481
958
CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2482
958
  return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2483
958
}
2484
0
CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2485
0
  return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2486
0
}
2487
2488
/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2489
/// type for the current target in bits.  This can be different than the ABI
2490
/// alignment in cases where it is beneficial for performance or backwards
2491
/// compatibility preserving to overalign a data type. (Note: despite the name,
2492
/// the preferred alignment is ABI-impacting, and not an optimization.)
2493
2.08M
unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2494
2.08M
  TypeInfo TI = getTypeInfo(T);
2495
2.08M
  unsigned ABIAlign = TI.Align;
2496
2497
2.08M
  T = T->getBaseElementTypeUnsafe();
2498
2499
  // The preferred alignment of member pointers is that of a pointer.
2500
2.08M
  if (T->isMemberPointerType())
2501
1.24k
    return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2502
2503
2.08M
  if (!Target->allowsLargerPreferedTypeAlignment())
2504
150
    return ABIAlign;
2505
2506
2.08M
  if (const auto *RT = T->getAs<RecordType>()) {
2507
81.8k
    const RecordDecl *RD = RT->getDecl();
2508
2509
    // When used as part of a typedef, or together with a 'packed' attribute,
2510
    // the 'aligned' attribute can be used to decrease alignment. Note that the
2511
    // 'packed' case is already taken into consideration when computing the
2512
    // alignment, we only need to handle the typedef case here.
2513
81.8k
    if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2514
81.8k
        
RD->isInvalidDecl()81.8k
)
2515
53
      return ABIAlign;
2516
2517
81.8k
    unsigned PreferredAlign = static_cast<unsigned>(
2518
81.8k
        toBits(getASTRecordLayout(RD).PreferredAlignment));
2519
81.8k
    assert(PreferredAlign >= ABIAlign &&
2520
81.8k
           "PreferredAlign should be at least as large as ABIAlign.");
2521
0
    return PreferredAlign;
2522
81.8k
  }
2523
2524
  // Double (and, for targets supporting AIX `power` alignment, long double) and
2525
  // long long should be naturally aligned (despite requiring less alignment) if
2526
  // possible.
2527
2.00M
  if (const auto *CT = T->getAs<ComplexType>())
2528
1.73k
    T = CT->getElementType().getTypePtr();
2529
2.00M
  if (const auto *ET = T->getAs<EnumType>())
2530
1.78k
    T = ET->getDecl()->getIntegerType().getTypePtr();
2531
2.00M
  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2532
2.00M
      
T->isSpecificBuiltinType(BuiltinType::LongLong)1.98M
||
2533
2.00M
      
T->isSpecificBuiltinType(BuiltinType::ULongLong)1.97M
||
2534
2.00M
      
(1.97M
T->isSpecificBuiltinType(BuiltinType::LongDouble)1.97M
&&
2535
1.97M
       
Target->defaultsToAIXPowerAlignment()1.72k
))
2536
    // Don't increase the alignment if an alignment attribute was specified on a
2537
    // typedef declaration.
2538
28.5k
    if (!TI.isAlignRequired())
2539
28.5k
      return std::max(ABIAlign, (unsigned)getTypeSize(T));
2540
2541
1.97M
  return ABIAlign;
2542
2.00M
}
2543
2544
/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2545
/// for __attribute__((aligned)) on this target, to be used if no alignment
2546
/// value is specified.
2547
61
unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2548
61
  return getTargetInfo().getDefaultAlignForAttributeAligned();
2549
61
}
2550
2551
/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2552
/// to a global variable of the specified type.
2553
88.1k
unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2554
88.1k
  uint64_t TypeSize = getTypeSize(T.getTypePtr());
2555
88.1k
  return std::max(getPreferredTypeAlign(T),
2556
88.1k
                  getTargetInfo().getMinGlobalAlign(TypeSize));
2557
88.1k
}
2558
2559
/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2560
/// should be given to a global variable of the specified type.
2561
88.1k
CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2562
88.1k
  return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2563
88.1k
}
2564
2565
24
CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2566
24
  CharUnits Offset = CharUnits::Zero();
2567
24
  const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2568
30
  while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2569
6
    Offset += Layout->getBaseClassOffset(Base);
2570
6
    Layout = &getASTRecordLayout(Base);
2571
6
  }
2572
24
  return Offset;
2573
24
}
2574
2575
206
CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2576
206
  const ValueDecl *MPD = MP.getMemberPointerDecl();
2577
206
  CharUnits ThisAdjustment = CharUnits::Zero();
2578
206
  ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2579
206
  bool DerivedMember = MP.isMemberPointerToDerivedMember();
2580
206
  const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2581
301
  for (unsigned I = 0, N = Path.size(); I != N; 
++I95
) {
2582
95
    const CXXRecordDecl *Base = RD;
2583
95
    const CXXRecordDecl *Derived = Path[I];
2584
95
    if (DerivedMember)
2585
21
      std::swap(Base, Derived);
2586
95
    ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2587
95
    RD = Path[I];
2588
95
  }
2589
206
  if (DerivedMember)
2590
18
    ThisAdjustment = -ThisAdjustment;
2591
206
  return ThisAdjustment;
2592
206
}
2593
2594
/// DeepCollectObjCIvars -
2595
/// This routine first collects all declared, but not synthesized, ivars in
2596
/// super class and then collects all ivars, including those synthesized for
2597
/// current class. This routine is used for implementation of current class
2598
/// when all ivars, declared and synthesized are known.
2599
void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2600
                                      bool leafClass,
2601
196
                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2602
196
  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2603
38
    DeepCollectObjCIvars(SuperClass, false, Ivars);
2604
196
  if (!leafClass) {
2605
38
    llvm::append_range(Ivars, OI->ivars());
2606
158
  } else {
2607
158
    auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2608
483
    for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2609
325
         Iv= Iv->getNextIvar())
2610
325
      Ivars.push_back(Iv);
2611
158
  }
2612
196
}
2613
2614
/// CollectInheritedProtocols - Collect all protocols in current class and
2615
/// those inherited by it.
2616
void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2617
1.35k
                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2618
1.35k
  if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2619
    // We can use protocol_iterator here instead of
2620
    // all_referenced_protocol_iterator since we are walking all categories.
2621
720
    for (auto *Proto : OI->all_referenced_protocols()) {
2622
547
      CollectInheritedProtocols(Proto, Protocols);
2623
547
    }
2624
2625
    // Categories of this Interface.
2626
720
    for (const auto *Cat : OI->visible_categories())
2627
15
      CollectInheritedProtocols(Cat, Protocols);
2628
2629
720
    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2630
671
      
while (290
SD) {
2631
381
        CollectInheritedProtocols(SD, Protocols);
2632
381
        SD = SD->getSuperClass();
2633
381
      }
2634
720
  } else 
if (const auto *638
OC638
= dyn_cast<ObjCCategoryDecl>(CDecl)) {
2635
15
    for (auto *Proto : OC->protocols()) {
2636
15
      CollectInheritedProtocols(Proto, Protocols);
2637
15
    }
2638
623
  } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2639
    // Insert the protocol.
2640
623
    if (!Protocols.insert(
2641
623
          const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2642
107
      return;
2643
2644
516
    for (auto *Proto : OP->protocols())
2645
17
      CollectInheritedProtocols(Proto, Protocols);
2646
516
  }
2647
1.35k
}
2648
2649
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2650
12
                                                const RecordDecl *RD) {
2651
12
  assert(RD->isUnion() && "Must be union type");
2652
0
  CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2653
2654
12
  for (const auto *Field : RD->fields()) {
2655
12
    if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2656
0
      return false;
2657
12
    CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2658
12
    if (FieldSize != UnionSize)
2659
6
      return false;
2660
12
  }
2661
6
  return !RD->field_empty();
2662
12
}
2663
2664
static int64_t getSubobjectOffset(const FieldDecl *Field,
2665
                                  const ASTContext &Context,
2666
114
                                  const clang::ASTRecordLayout & /*Layout*/) {
2667
114
  return Context.getFieldOffset(Field);
2668
114
}
2669
2670
static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2671
                                  const ASTContext &Context,
2672
12
                                  const clang::ASTRecordLayout &Layout) {
2673
12
  return Context.toBits(Layout.getBaseClassOffset(RD));
2674
12
}
2675
2676
static llvm::Optional<int64_t>
2677
structHasUniqueObjectRepresentations(const ASTContext &Context,
2678
                                     const RecordDecl *RD);
2679
2680
static llvm::Optional<int64_t>
2681
127
getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
2682
127
  if (Field->getType()->isRecordType()) {
2683
5
    const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2684
5
    if (!RD->isUnion())
2685
5
      return structHasUniqueObjectRepresentations(Context, RD);
2686
5
  }
2687
122
  if (!Field->getType()->isReferenceType() &&
2688
122
      
!Context.hasUniqueObjectRepresentations(Field->getType())113
)
2689
3
    return llvm::None;
2690
2691
119
  int64_t FieldSizeInBits =
2692
119
      Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2693
119
  if (Field->isBitField()) {
2694
27
    int64_t BitfieldSize = Field->getBitWidthValue(Context);
2695
27
    if (BitfieldSize > FieldSizeInBits)
2696
6
      return llvm::None;
2697
21
    FieldSizeInBits = BitfieldSize;
2698
21
  }
2699
113
  return FieldSizeInBits;
2700
119
}
2701
2702
static llvm::Optional<int64_t>
2703
21
getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
2704
21
  return structHasUniqueObjectRepresentations(Context, RD);
2705
21
}
2706
2707
template <typename RangeT>
2708
static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2709
    const RangeT &Subobjects, int64_t CurOffsetInBits,
2710
211
    const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2711
211
  for (const auto *Subobject : Subobjects) {
2712
148
    llvm::Optional<int64_t> SizeInBits =
2713
148
        getSubobjectSizeInBits(Subobject, Context);
2714
148
    if (!SizeInBits)
2715
12
      return llvm::None;
2716
136
    if (*SizeInBits != 0) {
2717
126
      int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718
126
      if (Offset != CurOffsetInBits)
2719
9
        return llvm::None;
2720
117
      CurOffsetInBits += *SizeInBits;
2721
117
    }
2722
136
  }
2723
190
  return CurOffsetInBits;
2724
211
}
ASTContext.cpp:llvm::Optional<long long> structSubobjectsHaveUniqueObjectRepresentations<llvm::SmallVector<clang::CXXRecordDecl*, 4u> >(llvm::SmallVector<clang::CXXRecordDecl*, 4u> const&, long long, clang::ASTContext const&, clang::ASTRecordLayout const&)
Line
Count
Source
2710
107
    const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2711
107
  for (const auto *Subobject : Subobjects) {
2712
21
    llvm::Optional<int64_t> SizeInBits =
2713
21
        getSubobjectSizeInBits(Subobject, Context);
2714
21
    if (!SizeInBits)
2715
3
      return llvm::None;
2716
18
    if (*SizeInBits != 0) {
2717
12
      int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718
12
      if (Offset != CurOffsetInBits)
2719
0
        return llvm::None;
2720
12
      CurOffsetInBits += *SizeInBits;
2721
12
    }
2722
18
  }
2723
104
  return CurOffsetInBits;
2724
107
}
ASTContext.cpp:llvm::Optional<long long> structSubobjectsHaveUniqueObjectRepresentations<llvm::iterator_range<clang::DeclContext::specific_decl_iterator<clang::FieldDecl> > >(llvm::iterator_range<clang::DeclContext::specific_decl_iterator<clang::FieldDecl> > const&, long long, clang::ASTContext const&, clang::ASTRecordLayout const&)
Line
Count
Source
2710
104
    const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2711
127
  for (const auto *Subobject : Subobjects) {
2712
127
    llvm::Optional<int64_t> SizeInBits =
2713
127
        getSubobjectSizeInBits(Subobject, Context);
2714
127
    if (!SizeInBits)
2715
9
      return llvm::None;
2716
118
    if (*SizeInBits != 0) {
2717
114
      int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718
114
      if (Offset != CurOffsetInBits)
2719
9
        return llvm::None;
2720
105
      CurOffsetInBits += *SizeInBits;
2721
105
    }
2722
118
  }
2723
86
  return CurOffsetInBits;
2724
104
}
2725
2726
static llvm::Optional<int64_t>
2727
structHasUniqueObjectRepresentations(const ASTContext &Context,
2728
107
                                     const RecordDecl *RD) {
2729
107
  assert(!RD->isUnion() && "Must be struct/class type");
2730
0
  const auto &Layout = Context.getASTRecordLayout(RD);
2731
2732
107
  int64_t CurOffsetInBits = 0;
2733
107
  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2734
107
    if (ClassDecl->isDynamicClass())
2735
0
      return llvm::None;
2736
2737
107
    SmallVector<CXXRecordDecl *, 4> Bases;
2738
107
    for (const auto &Base : ClassDecl->bases()) {
2739
      // Empty types can be inherited from, and non-empty types can potentially
2740
      // have tail padding, so just make sure there isn't an error.
2741
21
      Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2742
21
    }
2743
2744
107
    llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2745
0
      return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2746
0
    });
2747
2748
107
    llvm::Optional<int64_t> OffsetAfterBases =
2749
107
        structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
2750
107
                                                        Context, Layout);
2751
107
    if (!OffsetAfterBases)
2752
3
      return llvm::None;
2753
104
    CurOffsetInBits = *OffsetAfterBases;
2754
104
  }
2755
2756
104
  llvm::Optional<int64_t> OffsetAfterFields =
2757
104
      structSubobjectsHaveUniqueObjectRepresentations(
2758
104
          RD->fields(), CurOffsetInBits, Context, Layout);
2759
104
  if (!OffsetAfterFields)
2760
18
    return llvm::None;
2761
86
  CurOffsetInBits = *OffsetAfterFields;
2762
2763
86
  return CurOffsetInBits;
2764
104
}
2765
2766
514
bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2767
  // C++17 [meta.unary.prop]:
2768
  //   The predicate condition for a template specialization
2769
  //   has_unique_object_representations<T> shall be
2770
  //   satisfied if and only if:
2771
  //     (9.1) - T is trivially copyable, and
2772
  //     (9.2) - any two objects of type T with the same value have the same
2773
  //     object representation, where two objects
2774
  //   of array or non-union class type are considered to have the same value
2775
  //   if their respective sequences of
2776
  //   direct subobjects have the same values, and two objects of union type
2777
  //   are considered to have the same
2778
  //   value if they have the same active member and the corresponding members
2779
  //   have the same value.
2780
  //   The set of scalar types for which this condition holds is
2781
  //   implementation-defined. [ Note: If a type has padding
2782
  //   bits, the condition does not hold; otherwise, the condition holds true
2783
  //   for unsigned integral types. -- end note ]
2784
514
  assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2785
2786
  // Arrays are unique only if their element type is unique.
2787
514
  if (Ty->isArrayType())
2788
25
    return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2789
2790
  // (9.1) - T is trivially copyable...
2791
489
  if (!Ty.isTriviallyCopyableType(*this))
2792
108
    return false;
2793
2794
  // All integrals and enums are unique.
2795
381
  if (Ty->isIntegralOrEnumerationType())
2796
189
    return true;
2797
2798
  // All other pointers are unique.
2799
192
  if (Ty->isPointerType())
2800
36
    return true;
2801
2802
156
  if (Ty->isMemberPointerType()) {
2803
36
    const auto *MPT = Ty->getAs<MemberPointerType>();
2804
36
    return !ABI->getMemberPointerInfo(MPT).HasPadding;
2805
36
  }
2806
2807
120
  if (Ty->isRecordType()) {
2808
96
    const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2809
2810
96
    if (Record->isInvalidDecl())
2811
3
      return false;
2812
2813
93
    if (Record->isUnion())
2814
12
      return unionHasUniqueObjectRepresentations(*this, Record);
2815
2816
81
    Optional<int64_t> StructSize =
2817
81
        structHasUniqueObjectRepresentations(*this, Record);
2818
2819
81
    return StructSize &&
2820
81
           
StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty))63
;
2821
93
  }
2822
2823
  // FIXME: More cases to handle here (list by rsmith):
2824
  // vectors (careful about, eg, vector of 3 foo)
2825
  // _Complex int and friends
2826
  // _Atomic T
2827
  // Obj-C block pointers
2828
  // Obj-C object pointers
2829
  // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2830
  // clk_event_t, queue_t, reserve_id_t)
2831
  // There're also Obj-C class types and the Obj-C selector type, but I think it
2832
  // makes sense for those to return false here.
2833
2834
24
  return false;
2835
120
}
2836
2837
2.56k
unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2838
2.56k
  unsigned count = 0;
2839
  // Count ivars declared in class extension.
2840
2.56k
  for (const auto *Ext : OI->known_extensions())
2841
48
    count += Ext->ivar_size();
2842
2843
  // Count ivar defined in this class's implementation.  This
2844
  // includes synthesized ivars.
2845
2.56k
  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2846
2.56k
    count += ImplDecl->ivar_size();
2847
2848
2.56k
  return count;
2849
2.56k
}
2850
2851
300
bool ASTContext::isSentinelNullExpr(const Expr *E) {
2852
300
  if (!E)
2853
0
    return false;
2854
2855
  // nullptr_t is always treated as null.
2856
300
  if (E->getType()->isNullPtrType()) 
return true19
;
2857
2858
281
  if (E->getType()->isAnyPointerType() &&
2859
281
      E->IgnoreParenCasts()->isNullPointerConstant(*this,
2860
254
                                                Expr::NPC_ValueDependentIsNull))
2861
253
    return true;
2862
2863
  // Unfortunately, __null has type 'int'.
2864
28
  if (isa<GNUNullExpr>(E)) 
return true3
;
2865
2866
25
  return false;
2867
28
}
2868
2869
/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2870
/// exists.
2871
820k
ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2872
820k
  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2873
820k
    I = ObjCImpls.find(D);
2874
820k
  if (I != ObjCImpls.end())
2875
33.4k
    return cast<ObjCImplementationDecl>(I->second);
2876
786k
  return nullptr;
2877
820k
}
2878
2879
/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2880
/// exists.
2881
883k
ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2882
883k
  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2883
883k
    I = ObjCImpls.find(D);
2884
883k
  if (I != ObjCImpls.end())
2885
3.46k
    return cast<ObjCCategoryImplDecl>(I->second);
2886
880k
  return nullptr;
2887
883k
}
2888
2889
/// Set the implementation of ObjCInterfaceDecl.
2890
void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2891
4.90k
                           ObjCImplementationDecl *ImplD) {
2892
4.90k
  assert(IFaceD && ImplD && "Passed null params");
2893
0
  ObjCImpls[IFaceD] = ImplD;
2894
4.90k
}
2895
2896
/// Set the implementation of ObjCCategoryDecl.
2897
void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2898
522
                           ObjCCategoryImplDecl *ImplD) {
2899
522
  assert(CatD && ImplD && "Passed null params");
2900
0
  ObjCImpls[CatD] = ImplD;
2901
522
}
2902
2903
const ObjCMethodDecl *
2904
54
ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2905
54
  return ObjCMethodRedecls.lookup(MD);
2906
54
}
2907
2908
void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2909
16
                                            const ObjCMethodDecl *Redecl) {
2910
16
  assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2911
0
  ObjCMethodRedecls[MD] = Redecl;
2912
16
}
2913
2914
const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2915
751
                                              const NamedDecl *ND) const {
2916
751
  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2917
209
    return ID;
2918
542
  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2919
29
    return CD->getClassInterface();
2920
513
  if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2921
53
    return IMD->getClassInterface();
2922
2923
460
  return nullptr;
2924
513
}
2925
2926
/// Get the copy initialization expression of VarDecl, or nullptr if
2927
/// none exists.
2928
635
BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2929
635
  assert(VD && "Passed null params");
2930
0
  assert(VD->hasAttr<BlocksAttr>() &&
2931
635
         "getBlockVarCopyInits - not __block var");
2932
0
  auto I = BlockVarCopyInits.find(VD);
2933
635
  if (I != BlockVarCopyInits.end())
2934
127
    return I->second;
2935
508
  return {nullptr, false};
2936
635
}
2937
2938
/// Set the copy initialization expression of a block var decl.
2939
void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2940
63
                                     bool CanThrow) {
2941
63
  assert(VD && CopyExpr && "Passed null params");
2942
0
  assert(VD->hasAttr<BlocksAttr>() &&
2943
63
         "setBlockVarCopyInits - not __block var");
2944
0
  BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2945
63
}
2946
2947
TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2948
147M
                                                 unsigned DataSize) const {
2949
147M
  if (!DataSize)
2950
131M
    DataSize = TypeLoc::getFullDataSizeForType(T);
2951
15.4M
  else
2952
15.4M
    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2953
147M
           "incorrect data size provided to CreateTypeSourceInfo!");
2954
2955
0
  auto *TInfo =
2956
147M
    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2957
147M
  new (TInfo) TypeSourceInfo(T);
2958
147M
  return TInfo;
2959
147M
}
2960
2961
TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2962
13.6M
                                                     SourceLocation L) const {
2963
13.6M
  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2964
13.6M
  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2965
13.6M
  return DI;
2966
13.6M
}
2967
2968
const ASTRecordLayout &
2969
12.9k
ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2970
12.9k
  return getObjCLayout(D, nullptr);
2971
12.9k
}
2972
2973
const ASTRecordLayout &
2974
ASTContext::getASTObjCImplementationLayout(
2975
3.58k
                                        const ObjCImplementationDecl *D) const {
2976
3.58k
  return getObjCLayout(D->getClassInterface(), D);
2977
3.58k
}
2978
2979
//===----------------------------------------------------------------------===//
2980
//                   Type creation/memoization methods
2981
//===----------------------------------------------------------------------===//
2982
2983
QualType
2984
626k
ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2985
626k
  unsigned fastQuals = quals.getFastQualifiers();
2986
626k
  quals.removeFastQualifiers();
2987
2988
  // Check if we've already instantiated this type.
2989
626k
  llvm::FoldingSetNodeID ID;
2990
626k
  ExtQuals::Profile(ID, baseType, quals);
2991
626k
  void *insertPos = nullptr;
2992
626k
  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2993
580k
    assert(eq->getQualifiers() == quals);
2994
0
    return QualType(eq, fastQuals);
2995
580k
  }
2996
2997
  // If the base type is not canonical, make the appropriate canonical type.
2998
46.3k
  QualType canon;
2999
46.3k
  if (!baseType->isCanonicalUnqualified()) {
3000
18.9k
    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3001
18.9k
    canonSplit.Quals.addConsistentQualifiers(quals);
3002
18.9k
    canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3003
3004
    // Re-find the insert position.
3005
18.9k
    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3006
18.9k
  }
3007
3008
46.3k
  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
3009
46.3k
  ExtQualNodes.InsertNode(eq, insertPos);
3010
46.3k
  return QualType(eq, fastQuals);
3011
626k
}
3012
3013
QualType ASTContext::getAddrSpaceQualType(QualType T,
3014
4.46M
                                          LangAS AddressSpace) const {
3015
4.46M
  QualType CanT = getCanonicalType(T);
3016
4.46M
  if (CanT.getAddressSpace() == AddressSpace)
3017
3.92M
    return T;
3018
3019
  // If we are composing extended qualifiers together, merge together
3020
  // into one ExtQuals node.
3021
531k
  QualifierCollector Quals;
3022
531k
  const Type *TypeNode = Quals.strip(T);
3023
3024
  // If this type already has an address space specified, it cannot get
3025
  // another one.
3026
531k
  assert(!Quals.hasAddressSpace() &&
3027
531k
         "Type cannot be in multiple addr spaces!");
3028
0
  Quals.addAddressSpace(AddressSpace);
3029
3030
531k
  return getExtQualType(TypeNode, Quals);
3031
4.46M
}
3032
3033
218
QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3034
  // If the type is not qualified with an address space, just return it
3035
  // immediately.
3036
218
  if (!T.hasAddressSpace())
3037
56
    return T;
3038
3039
  // If we are composing extended qualifiers together, merge together
3040
  // into one ExtQuals node.
3041
162
  QualifierCollector Quals;
3042
162
  const Type *TypeNode;
3043
3044
163
  while (T.hasAddressSpace()) {
3045
163
    TypeNode = Quals.strip(T);
3046
3047
    // If the type no longer has an address space after stripping qualifiers,
3048
    // jump out.
3049
163
    if (!QualType(TypeNode, 0).hasAddressSpace())
3050
162
      break;
3051
3052
    // There might be sugar in the way. Strip it and try again.
3053
1
    T = T.getSingleStepDesugaredType(*this);
3054
1
  }
3055
3056
162
  Quals.removeAddressSpace();
3057
3058
  // Removal of the address space can mean there are no longer any
3059
  // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3060
  // or required.
3061
162
  if (Quals.hasNonFastQualifiers())
3062
0
    return getExtQualType(TypeNode, Quals);
3063
162
  else
3064
162
    return QualType(TypeNode, Quals.getFastQualifiers());
3065
162
}
3066
3067
QualType ASTContext::getObjCGCQualType(QualType T,
3068
230
                                       Qualifiers::GC GCAttr) const {
3069
230
  QualType CanT = getCanonicalType(T);
3070
230
  if (CanT.getObjCGCAttr() == GCAttr)
3071
1
    return T;
3072
3073
229
  if (const auto *ptr = T->getAs<PointerType>()) {
3074
87
    QualType Pointee = ptr->getPointeeType();
3075
87
    if (Pointee->isAnyPointerType()) {
3076
12
      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3077
12
      return getPointerType(ResultType);
3078
12
    }
3079
87
  }
3080
3081
  // If we are composing extended qualifiers together, merge together
3082
  // into one ExtQuals node.
3083
217
  QualifierCollector Quals;
3084
217
  const Type *TypeNode = Quals.strip(T);
3085
3086
  // If this type already has an ObjCGC specified, it cannot get
3087
  // another one.
3088
217
  assert(!Quals.hasObjCGCAttr() &&
3089
217
         "Type cannot have multiple ObjCGCs!");
3090
0
  Quals.addObjCGCAttr(GCAttr);
3091
3092
217
  return getExtQualType(TypeNode, Quals);
3093
229
}
3094
3095
190M
QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3096
190M
  if (const PointerType *Ptr = T->getAs<PointerType>()) {
3097
10.9M
    QualType Pointee = Ptr->getPointeeType();
3098
10.9M
    if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3099
3
      return getPointerType(removeAddrSpaceQualType(Pointee));
3100
3
    }
3101
10.9M
  }
3102
190M
  return T;
3103
190M
}
3104
3105
const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3106
8.65k
                                                   FunctionType::ExtInfo Info) {
3107
8.65k
  if (T->getExtInfo() == Info)
3108
20
    return T;
3109
3110
8.63k
  QualType Result;
3111
8.63k
  if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3112
26
    Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3113
8.60k
  } else {
3114
8.60k
    const auto *FPT = cast<FunctionProtoType>(T);
3115
8.60k
    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3116
8.60k
    EPI.ExtInfo = Info;
3117
8.60k
    Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3118
8.60k
  }
3119
3120
8.63k
  return cast<FunctionType>(Result.getTypePtr());
3121
8.65k
}
3122
3123
void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3124
6.77k
                                                 QualType ResultType) {
3125
6.77k
  FD = FD->getMostRecentDecl();
3126
6.93k
  while (true) {
3127
6.93k
    const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3128
6.93k
    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3129
6.93k
    FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3130
6.93k
    if (FunctionDecl *Next = FD->getPreviousDecl())
3131
155
      FD = Next;
3132
6.77k
    else
3133
6.77k
      break;
3134
6.93k
  }
3135
6.77k
  if (ASTMutationListener *L = getASTMutationListener())
3136
65
    L->DeducedReturnType(FD, ResultType);
3137
6.77k
}
3138
3139
/// Get a function type and produce the equivalent function type with the
3140
/// specified exception specification. Type sugar that can be present on a
3141
/// declaration of a function with an exception specification is permitted
3142
/// and preserved. Other type sugar (for instance, typedefs) is not.
3143
QualType ASTContext::getFunctionTypeWithExceptionSpec(
3144
682k
    QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
3145
  // Might have some parens.
3146
682k
  if (const auto *PT = dyn_cast<ParenType>(Orig))
3147
19
    return getParenType(
3148
19
        getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3149
3150
  // Might be wrapped in a macro qualified type.
3151
682k
  if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3152
2
    return getMacroQualifiedType(
3153
2
        getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3154
2
        MQT->getMacroIdentifier());
3155
3156
  // Might have a calling-convention attribute.
3157
682k
  if (const auto *AT = dyn_cast<AttributedType>(Orig))
3158
2
    return getAttributedType(
3159
2
        AT->getAttrKind(),
3160
2
        getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3161
2
        getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3162
3163
  // Anything else must be a function type. Rebuild it with the new exception
3164
  // specification.
3165
682k
  const auto *Proto = Orig->castAs<FunctionProtoType>();
3166
682k
  return getFunctionType(
3167
682k
      Proto->getReturnType(), Proto->getParamTypes(),
3168
682k
      Proto->getExtProtoInfo().withExceptionSpec(ESI));
3169
682k
}
3170
3171
bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3172
576k
                                                          QualType U) {
3173
576k
  return hasSameType(T, U) ||
3174
576k
         
(17.1k
getLangOpts().CPlusPlus1717.1k
&&
3175
17.1k
          hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3176
261
                      getFunctionTypeWithExceptionSpec(U, EST_None)));
3177
576k
}
3178
3179
366
QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3180
366
  if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3181
340
    QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3182
340
    SmallVector<QualType, 16> Args(Proto->param_types());
3183
737
    for (unsigned i = 0, n = Args.size(); i != n; 
++i397
)
3184
397
      Args[i] = removePtrSizeAddrSpace(Args[i]);
3185
340
    return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3186
340
  }
3187
3188
26
  if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3189
26
    QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3190
26
    return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3191
26
  }
3192
3193
0
  return T;
3194
26
}
3195
3196
183
bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3197
183
  return hasSameType(T, U) ||
3198
183
         hasSameType(getFunctionTypeWithoutPtrSizes(T),
3199
183
                     getFunctionTypeWithoutPtrSizes(U));
3200
183
}
3201
3202
void ASTContext::adjustExceptionSpec(
3203
    FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3204
621k
    bool AsWritten) {
3205
  // Update the type.
3206
621k
  QualType Updated =
3207
621k
      getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3208
621k
  FD->setType(Updated);
3209
3210
621k
  if (!AsWritten)
3211
587k
    return;
3212
3213
  // Update the type in the type source information too.
3214
33.7k
  if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3215
    // If the type and the type-as-written differ, we may need to update
3216
    // the type-as-written too.
3217
33.7k
    if (TSInfo->getType() != FD->getType())
3218
33.7k
      Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3219
3220
    // FIXME: When we get proper type location information for exceptions,
3221
    // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3222
    // up the TypeSourceInfo;
3223
33.7k
    assert(TypeLoc::getFullDataSizeForType(Updated) ==
3224
33.7k
               TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3225
33.7k
           "TypeLoc size mismatch from updating exception specification");
3226
0
    TSInfo->overrideType(Updated);
3227
33.7k
  }
3228
33.7k
}
3229
3230
/// getComplexType - Return the uniqued reference to the type for a complex
3231
/// number with the specified element type.
3232
13.0k
QualType ASTContext::getComplexType(QualType T) const {
3233
  // Unique pointers, to guarantee there is only one pointer of a particular
3234
  // structure.
3235
13.0k
  llvm::FoldingSetNodeID ID;
3236
13.0k
  ComplexType::Profile(ID, T);
3237
3238
13.0k
  void *InsertPos = nullptr;
3239
13.0k
  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3240
11.7k
    return QualType(CT, 0);
3241
3242
  // If the pointee type isn't canonical, this won't be a canonical type either,
3243
  // so fill in the canonical type field.
3244
1.23k
  QualType Canonical;
3245
1.23k
  if (!T.isCanonical()) {
3246
4
    Canonical = getComplexType(getCanonicalType(T));
3247
3248
    // Get the new insert position for the node we care about.
3249
4
    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3250
4
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3251
4
  }
3252
0
  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3253
1.23k
  Types.push_back(New);
3254
1.23k
  ComplexTypes.InsertNode(New, InsertPos);
3255
1.23k
  return QualType(New, 0);
3256
13.0k
}
3257
3258
/// getPointerType - Return the uniqued reference to the type for a pointer to
3259
/// the specified type.
3260
26.9M
QualType ASTContext::getPointerType(QualType T) const {
3261
  // Unique pointers, to guarantee there is only one pointer of a particular
3262
  // structure.
3263
26.9M
  llvm::FoldingSetNodeID ID;
3264
26.9M
  PointerType::Profile(ID, T);
3265
3266
26.9M
  void *InsertPos = nullptr;
3267
26.9M
  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3268
21.8M
    return QualType(PT, 0);
3269
3270
  // If the pointee type isn't canonical, this won't be a canonical type either,
3271
  // so fill in the canonical type field.
3272
5.17M
  QualType Canonical;
3273
5.17M
  if (!T.isCanonical()) {
3274
1.93M
    Canonical = getPointerType(getCanonicalType(T));
3275
3276
    // Get the new insert position for the node we care about.
3277
1.93M
    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3278
1.93M
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3279
1.93M
  }
3280
0
  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3281
5.17M
  Types.push_back(New);
3282
5.17M
  PointerTypes.InsertNode(New, InsertPos);
3283
5.17M
  return QualType(New, 0);
3284
26.9M
}
3285
3286
34
QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3287
34
  llvm::FoldingSetNodeID ID;
3288
34
  AdjustedType::Profile(ID, Orig, New);
3289
34
  void *InsertPos = nullptr;
3290
34
  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3291
34
  if (AT)
3292
7
    return QualType(AT, 0);
3293
3294
27
  QualType Canonical = getCanonicalType(New);
3295
3296
  // Get the new insert position for the node we care about.
3297
27
  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3298
27
  assert(!AT && "Shouldn't be in the map!");
3299
3300
0
  AT = new (*this, TypeAlignment)
3301
27
      AdjustedType(Type::Adjusted, Orig, New, Canonical);
3302
27
  Types.push_back(AT);
3303
27
  AdjustedTypes.InsertNode(AT, InsertPos);
3304
27
  return QualType(AT, 0);
3305
34
}
3306
3307
88.5k
QualType ASTContext::getDecayedType(QualType T) const {
3308
88.5k
  assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3309
3310
0
  QualType Decayed;
3311
3312
  // C99 6.7.5.3p7:
3313
  //   A declaration of a parameter as "array of type" shall be
3314
  //   adjusted to "qualified pointer to type", where the type
3315
  //   qualifiers (if any) are those specified within the [ and ] of
3316
  //   the array type derivation.
3317
88.5k
  if (T->isArrayType())
3318
85.6k
    Decayed = getArrayDecayedType(T);
3319
3320
  // C99 6.7.5.3p8:
3321
  //   A declaration of a parameter as "function returning type"
3322
  //   shall be adjusted to "pointer to function returning type", as
3323
  //   in 6.3.2.1.
3324
88.5k
  if (T->isFunctionType())
3325
2.95k
    Decayed = getPointerType(T);
3326
3327
88.5k
  llvm::FoldingSetNodeID ID;
3328
88.5k
  AdjustedType::Profile(ID, T, Decayed);
3329
88.5k
  void *InsertPos = nullptr;
3330
88.5k
  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3331
88.5k
  if (AT)
3332
57.5k
    return QualType(AT, 0);
3333
3334
30.9k
  QualType Canonical = getCanonicalType(Decayed);
3335
3336
  // Get the new insert position for the node we care about.
3337
30.9k
  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3338
30.9k
  assert(!AT && "Shouldn't be in the map!");
3339
3340
0
  AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3341
30.9k
  Types.push_back(AT);
3342
30.9k
  AdjustedTypes.InsertNode(AT, InsertPos);
3343
30.9k
  return QualType(AT, 0);
3344
88.5k
}
3345
3346
/// getBlockPointerType - Return the uniqued reference to the type for
3347
/// a pointer to the specified block.
3348
97.5k
QualType ASTContext::getBlockPointerType(QualType T) const {
3349
97.5k
  assert(T->isFunctionType() && "block of function types only");
3350
  // Unique pointers, to guarantee there is only one block of a particular
3351
  // structure.
3352
0
  llvm::FoldingSetNodeID ID;
3353
97.5k
  BlockPointerType::Profile(ID, T);
3354
3355
97.5k
  void *InsertPos = nullptr;
3356
97.5k
  if (BlockPointerType *PT =
3357
97.5k
        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3358
33.7k
    return QualType(PT, 0);
3359
3360
  // If the block pointee type isn't canonical, this won't be a canonical
3361
  // type either so fill in the canonical type field.
3362
63.8k
  QualType Canonical;
3363
63.8k
  if (!T.isCanonical()) {
3364
32.9k
    Canonical = getBlockPointerType(getCanonicalType(T));
3365
3366
    // Get the new insert position for the node we care about.
3367
32.9k
    BlockPointerType *NewIP =
3368
32.9k
      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3369
32.9k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3370
32.9k
  }
3371
0
  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3372
63.8k
  Types.push_back(New);
3373
63.8k
  BlockPointerTypes.InsertNode(New, InsertPos);
3374
63.8k
  return QualType(New, 0);
3375
97.5k
}
3376
3377
/// getLValueReferenceType - Return the uniqued reference to the type for an
3378
/// lvalue reference to the specified type.
3379
QualType
3380
9.96M
ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3381
9.96M
  assert((!T->isPlaceholderType() ||
3382
9.96M
          T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3383
9.96M
         "Unresolved placeholder type");
3384
3385
  // Unique pointers, to guarantee there is only one pointer of a particular
3386
  // structure.
3387
0
  llvm::FoldingSetNodeID ID;
3388
9.96M
  ReferenceType::Profile(ID, T, SpelledAsLValue);
3389
3390
9.96M
  void *InsertPos = nullptr;
3391
9.96M
  if (LValueReferenceType *RT =
3392
9.96M
        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3393
7.50M
    return QualType(RT, 0);
3394
3395
2.46M
  const auto *InnerRef = T->getAs<ReferenceType>();
3396
3397
  // If the referencee type isn't canonical, this won't be a canonical type
3398
  // either, so fill in the canonical type field.
3399
2.46M
  QualType Canonical;
3400
2.46M
  if (!SpelledAsLValue || 
InnerRef2.42M
||
!T.isCanonical()2.42M
) {
3401
1.64M
    QualType PointeeType = (InnerRef ? 
InnerRef->getPointeeType()43.5k
:
T1.59M
);
3402
1.64M
    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3403
3404
    // Get the new insert position for the node we care about.
3405
1.64M
    LValueReferenceType *NewIP =
3406
1.64M
      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3407
1.64M
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3408
1.64M
  }
3409
3410
0
  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3411
2.46M
                                                             SpelledAsLValue);
3412
2.46M
  Types.push_back(New);
3413
2.46M
  LValueReferenceTypes.InsertNode(New, InsertPos);
3414
3415
2.46M
  return QualType(New, 0);
3416
9.96M
}
3417
3418
/// getRValueReferenceType - Return the uniqued reference to the type for an
3419
/// rvalue reference to the specified type.
3420
1.26M
QualType ASTContext::getRValueReferenceType(QualType T) const {
3421
1.26M
  assert((!T->isPlaceholderType() ||
3422
1.26M
          T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3423
1.26M
         "Unresolved placeholder type");
3424
3425
  // Unique pointers, to guarantee there is only one pointer of a particular
3426
  // structure.
3427
0
  llvm::FoldingSetNodeID ID;
3428
1.26M
  ReferenceType::Profile(ID, T, false);
3429
3430
1.26M
  void *InsertPos = nullptr;
3431
1.26M
  if (RValueReferenceType *RT =
3432
1.26M
        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3433
614k
    return QualType(RT, 0);
3434
3435
648k
  const auto *InnerRef = T->getAs<ReferenceType>();
3436
3437
  // If the referencee type isn't canonical, this won't be a canonical type
3438
  // either, so fill in the canonical type field.
3439
648k
  QualType Canonical;
3440
648k
  if (InnerRef || 
!T.isCanonical()647k
) {
3441
408k
    QualType PointeeType = (InnerRef ? 
InnerRef->getPointeeType()594
:
T408k
);
3442
408k
    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3443
3444
    // Get the new insert position for the node we care about.
3445
408k
    RValueReferenceType *NewIP =
3446
408k
      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3447
408k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3448
408k
  }
3449
3450
0
  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3451
648k
  Types.push_back(New);
3452
648k
  RValueReferenceTypes.InsertNode(New, InsertPos);
3453
648k
  return QualType(New, 0);
3454
1.26M
}
3455
3456
/// getMemberPointerType - Return the uniqued reference to the type for a
3457
/// member pointer to the specified type, in the specified class.
3458
49.8k
QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3459
  // Unique pointers, to guarantee there is only one pointer of a particular
3460
  // structure.
3461
49.8k
  llvm::FoldingSetNodeID ID;
3462
49.8k
  MemberPointerType::Profile(ID, T, Cls);
3463
3464
49.8k
  void *InsertPos = nullptr;
3465
49.8k
  if (MemberPointerType *PT =
3466
49.8k
      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3467
7.16k
    return QualType(PT, 0);
3468
3469
  // If the pointee or class type isn't canonical, this won't be a canonical
3470
  // type either, so fill in the canonical type field.
3471
42.6k
  QualType Canonical;
3472
42.6k
  if (!T.isCanonical() || 
!Cls->isCanonicalUnqualified()21.5k
) {
3473
21.4k
    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3474
3475
    // Get the new insert position for the node we care about.
3476
21.4k
    MemberPointerType *NewIP =
3477
21.4k
      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3478
21.4k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3479
21.4k
  }
3480
0
  auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3481
42.6k
  Types.push_back(New);
3482
42.6k
  MemberPointerTypes.InsertNode(New, InsertPos);
3483
42.6k
  return QualType(New, 0);
3484
49.8k
}
3485
3486
/// getConstantArrayType - Return the unique reference to the type for an
3487
/// array of the specified element type.
3488
QualType ASTContext::getConstantArrayType(QualType EltTy,
3489
                                          const llvm::APInt &ArySizeIn,
3490
                                          const Expr *SizeExpr,
3491
                                          ArrayType::ArraySizeModifier ASM,
3492
4.60M
                                          unsigned IndexTypeQuals) const {
3493
4.60M
  assert((EltTy->isDependentType() ||
3494
4.60M
          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3495
4.60M
         "Constant array of VLAs is illegal!");
3496
3497
  // We only need the size as part of the type if it's instantiation-dependent.
3498
4.60M
  if (SizeExpr && 
!SizeExpr->isInstantiationDependent()257k
)
3499
257k
    SizeExpr = nullptr;
3500
3501
  // Convert the array size into a canonical width matching the pointer size for
3502
  // the target.
3503
4.60M
  llvm::APInt ArySize(ArySizeIn);
3504
4.60M
  ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3505
3506
4.60M
  llvm::FoldingSetNodeID ID;
3507
4.60M
  ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3508
4.60M
                             IndexTypeQuals);
3509
3510
4.60M
  void *InsertPos = nullptr;
3511
4.60M
  if (ConstantArrayType *ATP =
3512
4.60M
      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3513
4.07M
    return QualType(ATP, 0);
3514
3515
  // If the element type isn't canonical or has qualifiers, or the array bound
3516
  // is instantiation-dependent, this won't be a canonical type either, so fill
3517
  // in the canonical type field.
3518
534k
  QualType Canon;
3519
534k
  if (!EltTy.isCanonical() || 
EltTy.hasLocalQualifiers()441k
||
SizeExpr335k
) {
3520
199k
    SplitQualType canonSplit = getCanonicalType(EltTy).split();
3521
199k
    Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3522
199k
                                 ASM, IndexTypeQuals);
3523
199k
    Canon = getQualifiedType(Canon, canonSplit.Quals);
3524
3525
    // Get the new insert position for the node we care about.
3526
199k
    ConstantArrayType *NewIP =
3527
199k
      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3528
199k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3529
199k
  }
3530
3531
0
  void *Mem = Allocate(
3532
534k
      ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 
1165
:
0534k
),
3533
534k
      TypeAlignment);
3534
534k
  auto *New = new (Mem)
3535
534k
    ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3536
534k
  ConstantArrayTypes.InsertNode(New, InsertPos);
3537
534k
  Types.push_back(New);
3538
534k
  return QualType(New, 0);
3539
4.60M
}
3540
3541
/// getVariableArrayDecayedType - Turns the given type, which may be
3542
/// variably-modified, into the corresponding type with all the known
3543
/// sizes replaced with [*].
3544
24.9M
QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3545
  // Vastly most common case.
3546
24.9M
  if (!type->isVariablyModifiedType()) 
return type24.9M
;
3547
3548
233
  QualType result;
3549
3550
233
  SplitQualType split = type.getSplitDesugaredType();
3551
233
  const Type *ty = split.Ty;
3552
233
  switch (ty->getTypeClass()) {
3553
0
#define TYPE(Class, Base)
3554
0
#define ABSTRACT_TYPE(Class, Base)
3555
0
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3556
0
#include "clang/AST/TypeNodes.inc"
3557
0
    llvm_unreachable("didn't desugar past all non-canonical types?");
3558
3559
  // These types should never be variably-modified.
3560
0
  case Type::Builtin:
3561
0
  case Type::Complex:
3562
0
  case Type::Vector:
3563
0
  case Type::DependentVector:
3564
0
  case Type::ExtVector:
3565
0
  case Type::DependentSizedExtVector:
3566
0
  case Type::ConstantMatrix:
3567
0
  case Type::DependentSizedMatrix:
3568
0
  case Type::DependentAddressSpace:
3569
0
  case Type::ObjCObject:
3570
0
  case Type::ObjCInterface:
3571
0
  case Type::ObjCObjectPointer:
3572
0
  case Type::Record:
3573
0
  case Type::Enum:
3574
0
  case Type::UnresolvedUsing:
3575
0
  case Type::TypeOfExpr:
3576
0
  case Type::TypeOf:
3577
0
  case Type::Decltype:
3578
0
  case Type::UnaryTransform:
3579
0
  case Type::DependentName:
3580
0
  case Type::InjectedClassName:
3581
0
  case Type::TemplateSpecialization:
3582
0
  case Type::DependentTemplateSpecialization:
3583
0
  case Type::TemplateTypeParm:
3584
0
  case Type::SubstTemplateTypeParmPack:
3585
0
  case Type::Auto:
3586
0
  case Type::DeducedTemplateSpecialization:
3587
0
  case Type::PackExpansion:
3588
0
  case Type::BitInt:
3589
0
  case Type::DependentBitInt:
3590
0
    llvm_unreachable("type should never be variably-modified");
3591
3592
  // These types can be variably-modified but should never need to
3593
  // further decay.
3594
0
  case Type::FunctionNoProto:
3595
3
  case Type::FunctionProto:
3596
3
  case Type::BlockPointer:
3597
3
  case Type::MemberPointer:
3598
3
  case Type::Pipe:
3599
3
    return type;
3600
3601
  // These types can be variably-modified.  All these modifications
3602
  // preserve structure except as noted by comments.
3603
  // TODO: if we ever care about optimizing VLAs, there are no-op
3604
  // optimizations available here.
3605
170
  case Type::Pointer:
3606
170
    result = getPointerType(getVariableArrayDecayedType(
3607
170
                              cast<PointerType>(ty)->getPointeeType()));
3608
170
    break;
3609
3610
1
  case Type::LValueReference: {
3611
1
    const auto *lv = cast<LValueReferenceType>(ty);
3612
1
    result = getLValueReferenceType(
3613
1
                 getVariableArrayDecayedType(lv->getPointeeType()),
3614
1
                                    lv->isSpelledAsLValue());
3615
1
    break;
3616
3
  }
3617
3618
0
  case Type::RValueReference: {
3619
0
    const auto *lv = cast<RValueReferenceType>(ty);
3620
0
    result = getRValueReferenceType(
3621
0
                 getVariableArrayDecayedType(lv->getPointeeType()));
3622
0
    break;
3623
3
  }
3624
3625
0
  case Type::Atomic: {
3626
0
    const auto *at = cast<AtomicType>(ty);
3627
0
    result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3628
0
    break;
3629
3
  }
3630
3631
0
  case Type::ConstantArray: {
3632
0
    const auto *cat = cast<ConstantArrayType>(ty);
3633
0
    result = getConstantArrayType(
3634
0
                 getVariableArrayDecayedType(cat->getElementType()),
3635
0
                                  cat->getSize(),
3636
0
                                  cat->getSizeExpr(),
3637
0
                                  cat->getSizeModifier(),
3638
0
                                  cat->getIndexTypeCVRQualifiers());
3639
0
    break;
3640
3
  }
3641
3642
0
  case Type::DependentSizedArray: {
3643
0
    const auto *dat = cast<DependentSizedArrayType>(ty);
3644
0
    result = getDependentSizedArrayType(
3645
0
                 getVariableArrayDecayedType(dat->getElementType()),
3646
0
                                        dat->getSizeExpr(),
3647
0
                                        dat->getSizeModifier(),
3648
0
                                        dat->getIndexTypeCVRQualifiers(),
3649
0
                                        dat->getBracketsRange());
3650
0
    break;
3651
3
  }
3652
3653
  // Turn incomplete types into [*] types.
3654
0
  case Type::IncompleteArray: {
3655
0
    const auto *iat = cast<IncompleteArrayType>(ty);
3656
0
    result = getVariableArrayType(
3657
0
                 getVariableArrayDecayedType(iat->getElementType()),
3658
0
                                  /*size*/ nullptr,
3659
0
                                  ArrayType::Normal,
3660
0
                                  iat->getIndexTypeCVRQualifiers(),
3661
0
                                  SourceRange());
3662
0
    break;
3663
3
  }
3664
3665
  // Turn VLA types into [*] types.
3666
59
  case Type::VariableArray: {
3667
59
    const auto *vat = cast<VariableArrayType>(ty);
3668
59
    result = getVariableArrayType(
3669
59
                 getVariableArrayDecayedType(vat->getElementType()),
3670
59
                                  /*size*/ nullptr,
3671
59
                                  ArrayType::Star,
3672
59
                                  vat->getIndexTypeCVRQualifiers(),
3673
59
                                  vat->getBracketsRange());
3674
59
    break;
3675
3
  }
3676
233
  }
3677
3678
  // Apply the top-level qualifiers from the original.
3679
230
  return getQualifiedType(result, split.Quals);
3680
233
}
3681
3682
/// getVariableArrayType - Returns a non-unique reference to the type for a
3683
/// variable array of the specified element type.
3684
QualType ASTContext::getVariableArrayType(QualType EltTy,
3685
                                          Expr *NumElts,
3686
                                          ArrayType::ArraySizeModifier ASM,
3687
                                          unsigned IndexTypeQuals,
3688
7.62k
                                          SourceRange Brackets) const {
3689
  // Since we don't unique expressions, it isn't possible to unique VLA's
3690
  // that have an expression provided for their size.
3691
7.62k
  QualType Canon;
3692
3693
  // Be sure to pull qualifiers off the element type.
3694
7.62k
  if (!EltTy.isCanonical() || 
EltTy.hasLocalQualifiers()7.23k
) {
3695
413
    SplitQualType canonSplit = getCanonicalType(EltTy).split();
3696
413
    Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3697
413
                                 IndexTypeQuals, Brackets);
3698
413
    Canon = getQualifiedType(Canon, canonSplit.Quals);
3699
413
  }
3700
3701
7.62k
  auto *New = new (*this, TypeAlignment)
3702
7.62k
    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3703
3704
7.62k
  VariableArrayTypes.push_back(New);
3705
7.62k
  Types.push_back(New);
3706
7.62k
  return QualType(New, 0);
3707
7.62k
}
3708
3709
/// getDependentSizedArrayType - Returns a non-unique reference to
3710
/// the type for a dependently-sized array of the specified element
3711
/// type.
3712
QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3713
                                                Expr *numElements,
3714
                                                ArrayType::ArraySizeModifier ASM,
3715
                                                unsigned elementTypeQuals,
3716
24.5k
                                                SourceRange brackets) const {
3717
24.5k
  assert((!numElements || numElements->isTypeDependent() ||
3718
24.5k
          numElements->isValueDependent()) &&
3719
24.5k
         "Size must be type- or value-dependent!");
3720
3721
  // Dependently-sized array types that do not have a specified number
3722
  // of elements will have their sizes deduced from a dependent
3723
  // initializer.  We do no canonicalization here at all, which is okay
3724
  // because they can't be used in most locations.
3725
24.5k
  if (!numElements) {
3726
50
    auto *newType
3727
50
      = new (*this, TypeAlignment)
3728
50
          DependentSizedArrayType(*this, elementType, QualType(),
3729
50
                                  numElements, ASM, elementTypeQuals,
3730
50
                                  brackets);
3731
50
    Types.push_back(newType);
3732
50
    return QualType(newType, 0);
3733
50
  }
3734
3735
  // Otherwise, we actually build a new type every time, but we
3736
  // also build a canonical type.
3737
3738
24.5k
  SplitQualType canonElementType = getCanonicalType(elementType).split();
3739
3740
24.5k
  void *insertPos = nullptr;
3741
24.5k
  llvm::FoldingSetNodeID ID;
3742
24.5k
  DependentSizedArrayType::Profile(ID, *this,
3743
24.5k
                                   QualType(canonElementType.Ty, 0),
3744
24.5k
                                   ASM, elementTypeQuals, numElements);
3745
3746
  // Look for an existing type with these properties.
3747
24.5k
  DependentSizedArrayType *canonTy =
3748
24.5k
    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3749
3750
  // If we don't have one, build one.
3751
24.5k
  if (!canonTy) {
3752
15.3k
    canonTy = new (*this, TypeAlignment)
3753
15.3k
      DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3754
15.3k
                              QualType(), numElements, ASM, elementTypeQuals,
3755
15.3k
                              brackets);
3756
15.3k
    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3757
15.3k
    Types.push_back(canonTy);
3758
15.3k
  }
3759
3760
  // Apply qualifiers from the element type to the array.
3761
24.5k
  QualType canon = getQualifiedType(QualType(canonTy,0),
3762
24.5k
                                    canonElementType.Quals);
3763
3764
  // If we didn't need extra canonicalization for the element type or the size
3765
  // expression, then just use that as our result.
3766
24.5k
  if (QualType(canonElementType.Ty, 0) == elementType &&
3767
24.5k
      
canonTy->getSizeExpr() == numElements10.2k
)
3768
9.65k
    return canon;
3769
3770
  // Otherwise, we need to build a type which follows the spelling
3771
  // of the element type.
3772
14.8k
  auto *sugaredType
3773
14.8k
    = new (*this, TypeAlignment)
3774
14.8k
        DependentSizedArrayType(*this, elementType, canon, numElements,
3775
14.8k
                                ASM, elementTypeQuals, brackets);
3776
14.8k
  Types.push_back(sugaredType);
3777
14.8k
  return QualType(sugaredType, 0);
3778
24.5k
}
3779
3780
QualType ASTContext::getIncompleteArrayType(QualType elementType,
3781
                                            ArrayType::ArraySizeModifier ASM,
3782
93.6k
                                            unsigned elementTypeQuals) const {
3783
93.6k
  llvm::FoldingSetNodeID ID;
3784
93.6k
  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3785
3786
93.6k
  void *insertPos = nullptr;
3787
93.6k
  if (IncompleteArrayType *iat =
3788
93.6k
       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3789
41.2k
    return QualType(iat, 0);
3790
3791
  // If the element type isn't canonical, this won't be a canonical type
3792
  // either, so fill in the canonical type field.  We also have to pull
3793
  // qualifiers off the element type.
3794
52.3k
  QualType canon;
3795
3796
52.3k
  if (!elementType.isCanonical() || 
elementType.hasLocalQualifiers()24.4k
) {
3797
31.0k
    SplitQualType canonSplit = getCanonicalType(elementType).split();
3798
31.0k
    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3799
31.0k
                                   ASM, elementTypeQuals);
3800
31.0k
    canon = getQualifiedType(canon, canonSplit.Quals);
3801
3802
    // Get the new insert position for the node we care about.
3803
31.0k
    IncompleteArrayType *existing =
3804
31.0k
      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3805
31.0k
    assert(!existing && "Shouldn't be in the map!"); (void) existing;
3806
31.0k
  }
3807
3808
0
  auto *newType = new (*this, TypeAlignment)
3809
52.3k
    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3810
3811
52.3k
  IncompleteArrayTypes.InsertNode(newType, insertPos);
3812
52.3k
  Types.push_back(newType);
3813
52.3k
  return QualType(newType, 0);
3814
93.6k
}
3815
3816
ASTContext::BuiltinVectorTypeInfo
3817
464k
ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3818
464k
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3819
464k
  {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3820
272k
   NUMVECTORS};
3821
3822
464k
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3823
464k
  
{ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}191k
;
3824
3825
464k
  switch (Ty->getKind()) {
3826
0
  default:
3827
0
    llvm_unreachable("Unsupported builtin vector type");
3828
26.1k
  case BuiltinType::SveInt8:
3829
26.1k
    return SVE_INT_ELTTY(8, 16, true, 1);
3830
24.3k
  case BuiltinType::SveUint8:
3831
24.3k
    return SVE_INT_ELTTY(8, 16, false, 1);
3832
221
  case BuiltinType::SveInt8x2:
3833
221
    return SVE_INT_ELTTY(8, 16, true, 2);
3834
221
  case BuiltinType::SveUint8x2:
3835
221
    return SVE_INT_ELTTY(8, 16, false, 2);
3836
197
  case BuiltinType::SveInt8x3:
3837
197
    return SVE_INT_ELTTY(8, 16, true, 3);
3838
197
  case BuiltinType::SveUint8x3:
3839
197
    return SVE_INT_ELTTY(8, 16, false, 3);
3840
197
  case BuiltinType::SveInt8x4:
3841
197
    return SVE_INT_ELTTY(8, 16, true, 4);
3842
197
  case BuiltinType::SveUint8x4:
3843
197
    return SVE_INT_ELTTY(8, 16, false, 4);
3844
32.3k
  case BuiltinType::SveInt16:
3845
32.3k
    return SVE_INT_ELTTY(16, 8, true, 1);
3846
28.2k
  case BuiltinType::SveUint16:
3847
28.2k
    return SVE_INT_ELTTY(16, 8, false, 1);
3848
221
  case BuiltinType::SveInt16x2:
3849
221
    return SVE_INT_ELTTY(16, 8, true, 2);
3850
221
  case BuiltinType::SveUint16x2:
3851
221
    return SVE_INT_ELTTY(16, 8, false, 2);
3852
197
  case BuiltinType::SveInt16x3:
3853
197
    return SVE_INT_ELTTY(16, 8, true, 3);
3854
197
  case BuiltinType::SveUint16x3:
3855
197
    return SVE_INT_ELTTY(16, 8, false, 3);
3856
197
  case BuiltinType::SveInt16x4:
3857
197
    return SVE_INT_ELTTY(16, 8, true, 4);
3858
197
  case BuiltinType::SveUint16x4:
3859
197
    return SVE_INT_ELTTY(16, 8, false, 4);
3860
39.2k
  case BuiltinType::SveInt32:
3861
39.2k
    return SVE_INT_ELTTY(32, 4, true, 1);
3862
39.4k
  case BuiltinType::SveUint32:
3863
39.4k
    return SVE_INT_ELTTY(32, 4, false, 1);
3864
221
  case BuiltinType::SveInt32x2:
3865
221
    return SVE_INT_ELTTY(32, 4, true, 2);
3866
221
  case BuiltinType::SveUint32x2:
3867
221
    return SVE_INT_ELTTY(32, 4, false, 2);
3868
197
  case BuiltinType::SveInt32x3:
3869
197
    return SVE_INT_ELTTY(32, 4, true, 3);
3870
197
  case BuiltinType::SveUint32x3:
3871
197
    return SVE_INT_ELTTY(32, 4, false, 3);
3872
197
  case BuiltinType::SveInt32x4:
3873
197
    return SVE_INT_ELTTY(32, 4, true, 4);
3874
197
  case BuiltinType::SveUint32x4:
3875
197
    return SVE_INT_ELTTY(32, 4, false, 4);
3876
37.3k
  case BuiltinType::SveInt64:
3877
37.3k
    return SVE_INT_ELTTY(64, 2, true, 1);
3878
40.6k
  case BuiltinType::SveUint64:
3879
40.6k
    return SVE_INT_ELTTY(64, 2, false, 1);
3880
221
  case BuiltinType::SveInt64x2:
3881
221
    return SVE_INT_ELTTY(64, 2, true, 2);
3882
221
  case BuiltinType::SveUint64x2:
3883
221
    return SVE_INT_ELTTY(64, 2, false, 2);
3884
197
  case BuiltinType::SveInt64x3:
3885
197
    return SVE_INT_ELTTY(64, 2, true, 3);
3886
197
  case BuiltinType::SveUint64x3:
3887
197
    return SVE_INT_ELTTY(64, 2, false, 3);
3888
197
  case BuiltinType::SveInt64x4:
3889
197
    return SVE_INT_ELTTY(64, 2, true, 4);
3890
197
  case BuiltinType::SveUint64x4:
3891
197
    return SVE_INT_ELTTY(64, 2, false, 4);
3892
121k
  case BuiltinType::SveBool:
3893
121k
    return SVE_ELTTY(BoolTy, 16, 1);
3894
20.5k
  case BuiltinType::SveFloat16:
3895
20.5k
    return SVE_ELTTY(HalfTy, 8, 1);
3896
221
  case BuiltinType::SveFloat16x2:
3897
221
    return SVE_ELTTY(HalfTy, 8, 2);
3898
197
  case BuiltinType::SveFloat16x3:
3899
197
    return SVE_ELTTY(HalfTy, 8, 3);
3900
197
  case BuiltinType::SveFloat16x4:
3901
197
    return SVE_ELTTY(HalfTy, 8, 4);
3902
21.8k
  case BuiltinType::SveFloat32:
3903
21.8k
    return SVE_ELTTY(FloatTy, 4, 1);
3904
221
  case BuiltinType::SveFloat32x2:
3905
221
    return SVE_ELTTY(FloatTy, 4, 2);
3906
197
  case BuiltinType::SveFloat32x3:
3907
197
    return SVE_ELTTY(FloatTy, 4, 3);
3908
197
  case BuiltinType::SveFloat32x4:
3909
197
    return SVE_ELTTY(FloatTy, 4, 4);
3910
20.6k
  case BuiltinType::SveFloat64:
3911
20.6k
    return SVE_ELTTY(DoubleTy, 2, 1);
3912
221
  case BuiltinType::SveFloat64x2:
3913
221
    return SVE_ELTTY(DoubleTy, 2, 2);
3914
197
  case BuiltinType::SveFloat64x3:
3915
197
    return SVE_ELTTY(DoubleTy, 2, 3);
3916
197
  case BuiltinType::SveFloat64x4:
3917
197
    return SVE_ELTTY(DoubleTy, 2, 4);
3918
4.50k
  case BuiltinType::SveBFloat16:
3919
4.50k
    return SVE_ELTTY(BFloat16Ty, 8, 1);
3920
255
  case BuiltinType::SveBFloat16x2:
3921
255
    return SVE_ELTTY(BFloat16Ty, 8, 2);
3922
285
  case BuiltinType::SveBFloat16x3:
3923
285
    return SVE_ELTTY(BFloat16Ty, 8, 3);
3924
339
  case BuiltinType::SveBFloat16x4:
3925
339
    return SVE_ELTTY(BFloat16Ty, 8, 4);
3926
0
#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3927
0
                            IsSigned)                                          \
3928
51
  case BuiltinType::Id:                                                        \
3929
51
    return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3930
51
            llvm::ElementCount::getScalable(NumEls), NF};
3931
0
#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3932
0
  case BuiltinType::Id:                                                        \
3933
0
    return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy),    \
3934
0
            llvm::ElementCount::getScalable(NumEls), NF};
3935
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3936
0
  case BuiltinType::Id:                                                        \
3937
0
    return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3938
464k
#include 
"clang/Basic/RISCVVTypes.def"0
3939
464k
  }
3940
464k
}
3941
3942
/// getScalableVectorType - Return the unique reference to a scalable vector
3943
/// type of the specified element type and size. VectorType must be a built-in
3944
/// type.
3945
QualType ASTContext::getScalableVectorType(QualType EltTy,
3946
1.15M
                                           unsigned NumElts) const {
3947
1.15M
  if (Target->hasAArch64SVETypes()) {
3948
1.15M
    uint64_t EltTySize = getTypeSize(EltTy);
3949
1.15M
#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3950
1.15M
                        IsSigned, IsFP, IsBF)                                  \
3951
8.95M
  if (!EltTy->isBooleanType() &&                                               \
3952
8.95M
      
(6.80M
(6.80M
EltTy->hasIntegerRepresentation()6.80M
&& \
3953
6.80M
        
EltTy->hasSignedIntegerRepresentation() == IsSigned3.71M
) || \
3954
6.80M
       
(4.73M
EltTy->hasFloatingRepresentation()4.73M
&&
!EltTy->isBFloat16Type()3.08M
&& \
3955
4.73M
        
IsFP2.31M
&&
!IsBF0
) || \
3956
6.80M
       
(4.15M
EltTy->hasFloatingRepresentation()4.15M
&&
EltTy->isBFloat16Type()2.51M
&& \
3957
4.15M
        
IsBF182k
&&
!IsFP0
)) && \
3958
8.95M
      
EltTySize == ElBits2.67M
&&
NumElts == NumEls1.12M
) { \
3959
1.11M
    return SingletonId;                                                        \
3960
1.11M
  }
3961
1.15M
#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3962
1.15M
  
if (44.7k
EltTy->isBooleanType()44.7k
&&
NumElts == NumEls44.7k
) \
3963
44.7k
    return SingletonId;
3964
7.84M
#include 
"clang/Basic/AArch64SVEACLETypes.def"1.15M
3965
7.84M
  } else 
if (0
Target->hasRISCVVTypes()0
) {
3966
0
    uint64_t EltTySize = getTypeSize(EltTy);
3967
0
#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3968
0
                        IsFP)                                                  \
3969
0
    if (!EltTy->isBooleanType() &&                                             \
3970
0
        ((EltTy->hasIntegerRepresentation() &&                                 \
3971
0
          EltTy->hasSignedIntegerRepresentation() == IsSigned) ||              \
3972
0
         (EltTy->hasFloatingRepresentation() && IsFP)) &&                      \
3973
0
        EltTySize == ElBits && NumElts == NumEls)                              \
3974
0
      return SingletonId;
3975
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3976
0
    if (EltTy->isBooleanType() && NumElts == NumEls)                           \
3977
0
      return SingletonId;
3978
0
#include "clang/Basic/RISCVVTypes.def"
3979
0
  }
3980
0
  return QualType();
3981
1.15M
}
3982
3983
/// getVectorType - Return the unique reference to a vector type of
3984
/// the specified element type and size. VectorType must be a built-in type.
3985
QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3986
4.60M
                                   VectorType::VectorKind VecKind) const {
3987
4.60M
  assert(vecType->isBuiltinType());
3988
3989
  // Check if we've already instantiated a vector of this type.
3990
0
  llvm::FoldingSetNodeID ID;
3991
4.60M
  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3992
3993
4.60M
  void *InsertPos = nullptr;
3994
4.60M
  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3995
4.55M
    return QualType(VTP, 0);
3996
3997
  // If the element type isn't canonical, this won't be a canonical type either,
3998
  // so fill in the canonical type field.
3999
48.6k
  QualType Canonical;
4000
48.6k
  if (!vecType.isCanonical()) {
4001
12.3k
    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4002
4003
    // Get the new insert position for the node we care about.
4004
12.3k
    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4005
12.3k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4006
12.3k
  }
4007
0
  auto *New = new (*this, TypeAlignment)
4008
48.6k
    VectorType(vecType, NumElts, Canonical, VecKind);
4009
48.6k
  VectorTypes.InsertNode(New, InsertPos);
4010
48.6k
  Types.push_back(New);
4011
48.6k
  return QualType(New, 0);
4012
4.60M
}
4013
4014
QualType
4015
ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4016
                                   SourceLocation AttrLoc,
4017
85
                                   VectorType::VectorKind VecKind) const {
4018
85
  llvm::FoldingSetNodeID ID;
4019
85
  DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4020
85
                               VecKind);
4021
85
  void *InsertPos = nullptr;
4022
85
  DependentVectorType *Canon =
4023
85
      DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4024
85
  DependentVectorType *New;
4025
4026
85
  if (Canon) {
4027
5
    New = new (*this, TypeAlignment) DependentVectorType(
4028
5
        *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4029
80
  } else {
4030
80
    QualType CanonVecTy = getCanonicalType(VecType);
4031
80
    if (CanonVecTy == VecType) {
4032
40
      New = new (*this, TypeAlignment) DependentVectorType(
4033
40
          *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4034
4035
40
      DependentVectorType *CanonCheck =
4036
40
          DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4037
40
      assert(!CanonCheck &&
4038
40
             "Dependent-sized vector_size canonical type broken");
4039
0
      (void)CanonCheck;
4040
40
      DependentVectorTypes.InsertNode(New, InsertPos);
4041
40
    } else {
4042
40
      QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4043
40
                                                SourceLocation(), VecKind);
4044
40
      New = new (*this, TypeAlignment) DependentVectorType(
4045
40
          *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4046
40
    }
4047
80
  }
4048
4049
0
  Types.push_back(New);
4050
85
  return QualType(New, 0);
4051
85
}
4052
4053
/// getExtVectorType - Return the unique reference to an extended vector type of
4054
/// the specified element type and size. VectorType must be a built-in type.
4055
QualType
4056
809k
ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
4057
809k
  assert(vecType->isBuiltinType() || vecType->isDependentType());
4058
4059
  // Check if we've already instantiated a vector of this type.
4060
0
  llvm::FoldingSetNodeID ID;
4061
809k
  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4062
809k
                      VectorType::GenericVector);
4063
809k
  void *InsertPos = nullptr;
4064
809k
  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4065
803k
    return QualType(VTP, 0);
4066
4067
  // If the element type isn't canonical, this won't be a canonical type either,
4068
  // so fill in the canonical type field.
4069
6.08k
  QualType Canonical;
4070
6.08k
  if (!vecType.isCanonical()) {
4071
1.33k
    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4072
4073
    // Get the new insert position for the node we care about.
4074
1.33k
    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4075
1.33k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4076
1.33k
  }
4077
0
  auto *New = new (*this, TypeAlignment)
4078
6.08k
    ExtVectorType(vecType, NumElts, Canonical);
4079
6.08k
  VectorTypes.InsertNode(New, InsertPos);
4080
6.08k
  Types.push_back(New);
4081
6.08k
  return QualType(New, 0);
4082
809k
}
4083
4084
QualType
4085
ASTContext::getDependentSizedExtVectorType(QualType vecType,
4086
                                           Expr *SizeExpr,
4087
42
                                           SourceLocation AttrLoc) const {
4088
42
  llvm::FoldingSetNodeID ID;
4089
42
  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4090
42
                                       SizeExpr);
4091
4092
42
  void *InsertPos = nullptr;
4093
42
  DependentSizedExtVectorType *Canon
4094
42
    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4095
42
  DependentSizedExtVectorType *New;
4096
42
  if (Canon) {
4097
    // We already have a canonical version of this array type; use it as
4098
    // the canonical type for a newly-built type.
4099
8
    New = new (*this, TypeAlignment)
4100
8
      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4101
8
                                  SizeExpr, AttrLoc);
4102
34
  } else {
4103
34
    QualType CanonVecTy = getCanonicalType(vecType);
4104
34
    if (CanonVecTy == vecType) {
4105
25
      New = new (*this, TypeAlignment)
4106
25
        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4107
25
                                    AttrLoc);
4108
4109
25
      DependentSizedExtVectorType *CanonCheck
4110
25
        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4111
25
      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4112
0
      (void)CanonCheck;
4113
25
      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4114
25
    } else {
4115
9
      QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4116
9
                                                           SourceLocation());
4117
9
      New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4118
9
          *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4119
9
    }
4120
34
  }
4121
4122
0
  Types.push_back(New);
4123
42
  return QualType(New, 0);
4124
42
}
4125
4126
QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4127
681
                                           unsigned NumColumns) const {
4128
681
  llvm::FoldingSetNodeID ID;
4129
681
  ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4130
681
                              Type::ConstantMatrix);
4131
4132
681
  assert(MatrixType::isValidElementType(ElementTy) &&
4133
681
         "need a valid element type");
4134
0
  assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4135
681
         ConstantMatrixType::isDimensionValid(NumColumns) &&
4136
681
         "need valid matrix dimensions");
4137
0
  void *InsertPos = nullptr;
4138
681
  if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4139
318
    return QualType(MTP, 0);
4140
4141
363
  QualType Canonical;
4142
363
  if (!ElementTy.isCanonical()) {
4143
116
    Canonical =
4144
116
        getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4145
4146
116
    ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4147
116
    assert(!NewIP && "Matrix type shouldn't already exist in the map");
4148
0
    (void)NewIP;
4149
116
  }
4150
4151
0
  auto *New = new (*this, TypeAlignment)
4152
363
      ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4153
363
  MatrixTypes.InsertNode(New, InsertPos);
4154
363
  Types.push_back(New);
4155
363
  return QualType(New, 0);
4156
681
}
4157
4158
QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4159
                                                 Expr *RowExpr,
4160
                                                 Expr *ColumnExpr,
4161
77
                                                 SourceLocation AttrLoc) const {
4162
77
  QualType CanonElementTy = getCanonicalType(ElementTy);
4163
77
  llvm::FoldingSetNodeID ID;
4164
77
  DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4165
77
                                    ColumnExpr);
4166
4167
77
  void *InsertPos = nullptr;
4168
77
  DependentSizedMatrixType *Canon =
4169
77
      DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4170
4171
77
  if (!Canon) {
4172
52
    Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4173
52
        *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4174
52
#ifndef NDEBUG
4175
52
    DependentSizedMatrixType *CanonCheck =
4176
52
        DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4177
52
    assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4178
0
#endif
4179
0
    DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4180
52
    Types.push_back(Canon);
4181
52
  }
4182
4183
  // Already have a canonical version of the matrix type
4184
  //
4185
  // If it exactly matches the requested type, use it directly.
4186
77
  if (Canon->getElementType() == ElementTy && 
Canon->getRowExpr() == RowExpr28
&&
4187
77
      
Canon->getRowExpr() == ColumnExpr28
)
4188
0
    return QualType(Canon, 0);
4189
4190
  // Use Canon as the canonical type for newly-built type.
4191
77
  DependentSizedMatrixType *New = new (*this, TypeAlignment)
4192
77
      DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4193
77
                               ColumnExpr, AttrLoc);
4194
77
  Types.push_back(New);
4195
77
  return QualType(New, 0);
4196
77
}
4197
4198
QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4199
                                                  Expr *AddrSpaceExpr,
4200
52
                                                  SourceLocation AttrLoc) const {
4201
52
  assert(AddrSpaceExpr->isInstantiationDependent());
4202
4203
0
  QualType canonPointeeType = getCanonicalType(PointeeType);
4204
4205
52
  void *insertPos = nullptr;
4206
52
  llvm::FoldingSetNodeID ID;
4207
52
  DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4208
52
                                     AddrSpaceExpr);
4209
4210
52
  DependentAddressSpaceType *canonTy =
4211
52
    DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4212
4213
52
  if (!canonTy) {
4214
36
    canonTy = new (*this, TypeAlignment)
4215
36
      DependentAddressSpaceType(*this, canonPointeeType,
4216
36
                                QualType(), AddrSpaceExpr, AttrLoc);
4217
36
    DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4218
36
    Types.push_back(canonTy);
4219
36
  }
4220
4221
52
  if (canonPointeeType == PointeeType &&
4222
52
      
canonTy->getAddrSpaceExpr() == AddrSpaceExpr0
)
4223
0
    return QualType(canonTy, 0);
4224
4225
52
  auto *sugaredType
4226
52
    = new (*this, TypeAlignment)
4227
52
        DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4228
52
                                  AddrSpaceExpr, AttrLoc);
4229
52
  Types.push_back(sugaredType);
4230
52
  return QualType(sugaredType, 0);
4231
52
}
4232
4233
/// Determine whether \p T is canonical as the result type of a function.
4234
13.3M
static bool isCanonicalResultType(QualType T) {
4235
13.3M
  return T.isCanonical() &&
4236
13.3M
         
(8.96M
T.getObjCLifetime() == Qualifiers::OCL_None8.96M
||
4237
8.96M
          
T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone0
);
4238
13.3M
}
4239
4240
/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4241
QualType
4242
ASTContext::getFunctionNoProtoType(QualType ResultTy,
4243
191k
                                   const FunctionType::ExtInfo &Info) const {
4244
  // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4245
  // functionality creates a function without a prototype regardless of
4246
  // language mode (so it makes them even in C++). Once the rewriter has been
4247
  // fixed, this assertion can be enabled again.
4248
  //assert(!LangOpts.requiresStrictPrototypes() &&
4249
  //       "strict prototypes are disabled");
4250
4251
  // Unique functions, to guarantee there is only one function of a particular
4252
  // structure.
4253
191k
  llvm::FoldingSetNodeID ID;
4254
191k
  FunctionNoProtoType::Profile(ID, ResultTy, Info);
4255
4256
191k
  void *InsertPos = nullptr;
4257
191k
  if (FunctionNoProtoType *FT =
4258
191k
        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4259
183k
    return QualType(FT, 0);
4260
4261
8.28k
  QualType Canonical;
4262
8.28k
  if (!isCanonicalResultType(ResultTy)) {
4263
1.83k
    Canonical =
4264
1.83k
      getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4265
4266
    // Get the new insert position for the node we care about.
4267
1.83k
    FunctionNoProtoType *NewIP =
4268
1.83k
      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4269
1.83k
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4270
1.83k
  }
4271
4272
0
  auto *New = new (*this, TypeAlignment)
4273
8.28k
    FunctionNoProtoType(ResultTy, Canonical, Info);
4274
8.28k
  Types.push_back(New);
4275
8.28k
  FunctionNoProtoTypes.InsertNode(New, InsertPos);
4276
8.28k
  return QualType(New, 0);
4277
191k
}
4278
4279
CanQualType
4280
8.45M
ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4281
8.45M
  CanQualType CanResultType = getCanonicalType(ResultType);
4282
4283
  // Canonical result types do not have ARC lifetime qualifiers.
4284
8.45M
  if (CanResultType.getQualifiers().hasObjCLifetime()) {
4285
49
    Qualifiers Qs = CanResultType.getQualifiers();
4286
49
    Qs.removeObjCLifetime();
4287
49
    return CanQualType::CreateUnsafe(
4288
49
             getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4289
49
  }
4290
4291
8.45M
  return CanResultType;
4292
8.45M
}
4293
4294
static bool isCanonicalExceptionSpecification(
4295
15.4M
    const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4296
15.4M
  if (ESI.Type == EST_None)
4297
13.2M
    return true;
4298
2.21M
  if (!NoexceptInType)
4299
2.11M
    return false;
4300
4301
  // C++17 onwards: exception specification is part of the type, as a simple
4302
  // boolean "can this function type throw".
4303
101k
  if (ESI.Type == EST_BasicNoexcept)
4304
45.4k
    return true;
4305
4306
  // A noexcept(expr) specification is (possibly) canonical if expr is
4307
  // value-dependent.
4308
55.9k
  if (ESI.Type == EST_DependentNoexcept)
4309
4.75k
    return true;
4310
4311
  // A dynamic exception specification is canonical if it only contains pack
4312
  // expansions (so we can't tell whether it's non-throwing) and all its
4313
  // contained types are canonical.
4314
51.1k
  if (ESI.Type == EST_Dynamic) {
4315
42
    bool AnyPackExpansions = false;
4316
54
    for (QualType ET : ESI.Exceptions) {
4317
54
      if (!ET.isCanonical())
4318
19
        return false;
4319
35
      if (ET->getAs<PackExpansionType>())
4320
3
        AnyPackExpansions = true;
4321
35
    }
4322
23
    return AnyPackExpansions;
4323
42
  }
4324
4325
51.1k
  return false;
4326
51.1k
}
4327
4328
QualType ASTContext::getFunctionTypeInternal(
4329
    QualType ResultTy, ArrayRef<QualType> ArgArray,
4330
42.2M
    const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4331
42.2M
  size_t NumArgs = ArgArray.size();
4332
4333
  // Unique functions, to guarantee there is only one function of a particular
4334
  // structure.
4335
42.2M
  llvm::FoldingSetNodeID ID;
4336
42.2M
  FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4337
42.2M
                             *this, true);
4338
4339
42.2M
  QualType Canonical;
4340
42.2M
  bool Unique = false;
4341
4342
42.2M
  void *InsertPos = nullptr;
4343
42.2M
  if (FunctionProtoType *FPT =
4344
42.2M
        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4345
26.8M
    QualType Existing = QualType(FPT, 0);
4346
4347
    // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4348
    // it so long as our exception specification doesn't contain a dependent
4349
    // noexcept expression, or we're just looking for a canonical type.
4350
    // Otherwise, we're going to need to create a type
4351
    // sugar node to hold the concrete expression.
4352
26.8M
    if (OnlyWantCanonical || 
!isComputedNoexcept(EPI.ExceptionSpec.Type)24.6M
||
4353
26.8M
        
EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr()2.04k
)
4354
26.8M
      return Existing;
4355
4356
    // We need a new type sugar node for this one, to hold the new noexcept
4357
    // expression. We do no canonicalization here, but that's OK since we don't
4358
    // expect to see the same noexcept expression much more than once.
4359
1.33k
    Canonical = getCanonicalType(Existing);
4360
1.33k
    Unique = true;
4361
1.33k
  }
4362
4363
15.4M
  bool NoexceptInType = getLangOpts().CPlusPlus17;
4364
15.4M
  bool IsCanonicalExceptionSpec =
4365
15.4M
      isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4366
4367
  // Determine whether the type being created is already canonical or not.
4368
15.4M
  bool isCanonical = !Unique && 
IsCanonicalExceptionSpec15.4M
&&
4369
15.4M
                     
isCanonicalResultType(ResultTy)13.3M
&&
!EPI.HasTrailingReturn8.95M
;
4370
32.3M
  for (unsigned i = 0; i != NumArgs && 
isCanonical23.9M
;
++i16.9M
)
4371
16.9M
    if (!ArgArray[i].isCanonicalAsParam())
4372
1.93M
      isCanonical = false;
4373
4374
15.4M
  if (OnlyWantCanonical)
4375
6.26M
    assert(isCanonical &&
4376
15.4M
           "given non-canonical parameters constructing canonical type");
4377
4378
  // If this type isn't canonical, get the canonical version of it if we don't
4379
  // already have it. The exception spec is only partially part of the
4380
  // canonical type, and only in C++17 onwards.
4381
15.4M
  if (!isCanonical && 
Canonical.isNull()8.45M
) {
4382
8.44M
    SmallVector<QualType, 16> CanonicalArgs;
4383
8.44M
    CanonicalArgs.reserve(NumArgs);
4384
24.9M
    for (unsigned i = 0; i != NumArgs; 
++i16.5M
)
4385
16.5M
      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4386
4387
8.44M
    llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4388
8.44M
    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4389
8.44M
    CanonicalEPI.HasTrailingReturn = false;
4390
4391
8.44M
    if (IsCanonicalExceptionSpec) {
4392
      // Exception spec is already OK.
4393
6.28M
    } else 
if (2.16M
NoexceptInType2.16M
) {
4394
50.7k
      switch (EPI.ExceptionSpec.Type) {
4395
49.8k
      
case EST_Unparsed: 1.08k
case EST_Unevaluated: 48.6k
case EST_Uninstantiated:
4396
        // We don't know yet. It shouldn't matter what we pick here; no-one
4397
        // should ever look at this.
4398
49.8k
        LLVM_FALLTHROUGH;
4399
50.1k
      
case EST_None: 49.8k
case EST_MSAny: 49.8k
case EST_NoexceptFalse:
4400
50.1k
        CanonicalEPI.ExceptionSpec.Type = EST_None;
4401
50.1k
        break;
4402
4403
        // A dynamic exception specification is almost always "not noexcept",
4404
        // with the exception that a pack expansion might expand to no types.
4405
39
      case EST_Dynamic: {
4406
39
        bool AnyPacks = false;
4407
52
        for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4408
52
          if (ET->getAs<PackExpansionType>())
4409
4
            AnyPacks = true;
4410
52
          ExceptionTypeStorage.push_back(getCanonicalType(ET));
4411
52
        }
4412
39
        if (!AnyPacks)
4413
35
          CanonicalEPI.ExceptionSpec.Type = EST_None;
4414
4
        else {
4415
4
          CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4416
4
          CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4417
4
        }
4418
39
        break;
4419
49.8k
      }
4420
4421
252
      case EST_DynamicNone:
4422
252
      case EST_BasicNoexcept:
4423
540
      case EST_NoexceptTrue:
4424
549
      case EST_NoThrow:
4425
549
        CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4426
549
        break;
4427
4428
0
      case EST_DependentNoexcept:
4429
0
        llvm_unreachable("dependent noexcept is already canonical");
4430
50.7k
      }
4431
2.10M
    } else {
4432
2.10M
      CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4433
2.10M
    }
4434
4435
    // Adjust the canonical function result type.
4436
8.44M
    CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4437
8.44M
    Canonical =
4438
8.44M
        getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4439
4440
    // Get the new insert position for the node we care about.
4441
8.44M
    FunctionProtoType *NewIP =
4442
8.44M
      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4443
8.44M
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4444
8.44M
  }
4445
4446
  // Compute the needed size to hold this FunctionProtoType and the
4447
  // various trailing objects.
4448
15.4M
  auto ESH = FunctionProtoType::getExceptionSpecSize(
4449
15.4M
      EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4450
15.4M
  size_t Size = FunctionProtoType::totalSizeToAlloc<
4451
15.4M
      QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4452
15.4M
      FunctionType::ExceptionType, Expr *, FunctionDecl *,
4453
15.4M
      FunctionProtoType::ExtParameterInfo, Qualifiers>(
4454
15.4M
      NumArgs, EPI.Variadic,
4455
15.4M
      FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4456
15.4M
      ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4457
15.4M
      EPI.ExtParameterInfos ? 
NumArgs13.3k
:
015.4M
,
4458
15.4M
      EPI.TypeQuals.hasNonFastQualifiers() ? 
1623
:
015.4M
);
4459
4460
15.4M
  auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4461
15.4M
  FunctionProtoType::ExtProtoInfo newEPI = EPI;
4462
15.4M
  new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4463
15.4M
  Types.push_back(FTP);
4464
15.4M
  if (!Unique)
4465
15.4M
    FunctionProtoTypes.InsertNode(FTP, InsertPos);
4466
15.4M
  return QualType(FTP, 0);
4467
15.4M
}
4468
4469
361
QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4470
361
  llvm::FoldingSetNodeID ID;
4471
361
  PipeType::Profile(ID, T, ReadOnly);
4472
4473
361
  void *InsertPos = nullptr;
4474
361
  if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4475
110
    return QualType(PT, 0);
4476
4477
  // If the pipe element type isn't canonical, this won't be a canonical type
4478
  // either, so fill in the canonical type field.
4479
251
  QualType Canonical;
4480
251
  if (!T.isCanonical()) {
4481
56
    Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4482
4483
    // Get the new insert position for the node we care about.
4484
56
    PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4485
56
    assert(!NewIP && "Shouldn't be in the map!");
4486
0
    (void)NewIP;
4487
56
  }
4488
0
  auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4489
251
  Types.push_back(New);
4490
251
  PipeTypes.InsertNode(New, InsertPos);
4491
251
  return QualType(New, 0);
4492
361
}
4493
4494
3.97M
QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4495
  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4496
3.97M
  return LangOpts.OpenCL ? 
getAddrSpaceQualType(Ty, LangAS::opencl_constant)265
4497
3.97M
                         : 
Ty3.97M
;
4498
3.97M
}
4499
4500
249
QualType ASTContext::getReadPipeType(QualType T) const {
4501
249
  return getPipeType(T, true);
4502
249
}
4503
4504
48
QualType ASTContext::getWritePipeType(QualType T) const {
4505
48
  return getPipeType(T, false);
4506
48
}
4507
4508
1.11k
QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4509
1.11k
  llvm::FoldingSetNodeID ID;
4510
1.11k
  BitIntType::Profile(ID, IsUnsigned, NumBits);
4511
4512
1.11k
  void *InsertPos = nullptr;
4513
1.11k
  if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4514
622
    return QualType(EIT, 0);
4515
4516
496
  auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
4517
496
  BitIntTypes.InsertNode(New, InsertPos);
4518
496
  Types.push_back(New);
4519
496
  return QualType(New, 0);
4520
1.11k
}
4521
4522
QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4523
14
                                            Expr *NumBitsExpr) const {
4524
14
  assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4525
0
  llvm::FoldingSetNodeID ID;
4526
14
  DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4527
4528
14
  void *InsertPos = nullptr;
4529
14
  if (DependentBitIntType *Existing =
4530
14
          DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4531
2
    return QualType(Existing, 0);
4532
4533
12
  auto *New = new (*this, TypeAlignment)
4534
12
      DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
4535
12
  DependentBitIntTypes.InsertNode(New, InsertPos);
4536
4537
12
  Types.push_back(New);
4538
12
  return QualType(New, 0);
4539
14
}
4540
4541
#ifndef NDEBUG
4542
3.43M
static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4543
3.43M
  if (!isa<CXXRecordDecl>(D)) 
return false540k
;
4544
2.89M
  const auto *RD = cast<CXXRecordDecl>(D);
4545
2.89M
  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4546
157k
    return true;
4547
2.74M
  if (RD->getDescribedClassTemplate() &&
4548
2.74M
      
!isa<ClassTemplateSpecializationDecl>(RD)608k
)
4549
608k
    return true;
4550
2.13M
  return false;
4551
2.74M
}
4552
#endif
4553
4554
/// getInjectedClassNameType - Return the unique reference to the
4555
/// injected class name type for the specified templated declaration.
4556
QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4557
765k
                                              QualType TST) const {
4558
765k
  assert(NeedsInjectedClassNameType(Decl));
4559
765k
  if (Decl->TypeForDecl) {
4560
0
    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4561
765k
  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4562
143k
    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4563
0
    Decl->TypeForDecl = PrevDecl->TypeForDecl;
4564
143k
    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4565
622k
  } else {
4566
622k
    Type *newType =
4567
622k
      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4568
622k
    Decl->TypeForDecl = newType;
4569
622k
    Types.push_back(newType);
4570
622k
  }
4571
0
  return QualType(Decl->TypeForDecl, 0);
4572
765k
}
4573
4574
/// getTypeDeclType - Return the unique reference to the type for the
4575
/// specified type declaration.
4576
4.66M
QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4577
4.66M
  assert(Decl && "Passed null for Decl param");
4578
0
  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4579
4580
4.66M
  if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4581
1.51M
    return getTypedefType(Typedef);
4582
4583
3.15M
  assert(!isa<TemplateTypeParmDecl>(Decl) &&
4584
3.15M
         "Template type parameter types are always available.");
4585
4586
3.15M
  if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4587
2.67M
    assert(Record->isFirstDecl() && "struct/union has previous declaration");
4588
0
    assert(!NeedsInjectedClassNameType(Record));
4589
0
    return getRecordType(Record);
4590
2.67M
  } else 
if (const auto *481k
Enum481k
= dyn_cast<EnumDecl>(Decl)) {
4591
481k
    assert(Enum->isFirstDecl() && "enum has previous declaration");
4592
0
    return getEnumType(Enum);
4593
481k
  } else 
if (const auto *437
Using437
= dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4594
445
    return getUnresolvedUsingType(Using);
4595
445
  } else
4596
18.4E
    llvm_unreachable("TypeDecl without a type?");
4597
4598
18.4E
  return QualType(Decl->TypeForDecl, 0);
4599
3.15M
}
4600
4601
/// getTypedefType - Return the unique reference to the type for the
4602
/// specified typedef name decl.
4603
QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4604
3.20M
                                    QualType Underlying) const {
4605
3.20M
  if (Decl->TypeForDecl) 
return QualType(Decl->TypeForDecl, 0)233k
;
4606
4607
2.96M
  if (Underlying.isNull())
4608
2.68M
    Underlying = Decl->getUnderlyingType();
4609
2.96M
  QualType Canonical = getCanonicalType(Underlying);
4610
2.96M
  auto *newType = new (*this, TypeAlignment)
4611
2.96M
      TypedefType(Type::Typedef, Decl, Underlying, Canonical);
4612
2.96M
  Decl->TypeForDecl = newType;
4613
2.96M
  Types.push_back(newType);
4614
2.96M
  return QualType(newType, 0);
4615
3.20M
}
4616
4617
QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4618
348k
                                  QualType Underlying) const {
4619
348k
  llvm::FoldingSetNodeID ID;
4620
348k
  UsingType::Profile(ID, Found);
4621
4622
348k
  void *InsertPos = nullptr;
4623
348k
  UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos);
4624
348k
  if (T)
4625
321k
    return QualType(T, 0);
4626
4627
26.0k
  assert(!Underlying.hasLocalQualifiers());
4628
0
  assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl())));
4629
0
  QualType Canon = Underlying.getCanonicalType();
4630
4631
26.0k
  UsingType *NewType =
4632
26.0k
      new (*this, TypeAlignment) UsingType(Found, Underlying, Canon);
4633
26.0k
  Types.push_back(NewType);
4634
26.0k
  UsingTypes.InsertNode(NewType, InsertPos);
4635
26.0k
  return QualType(NewType, 0);
4636
348k
}
4637
4638
10.6M
QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4639
10.6M
  if (Decl->TypeForDecl) 
return QualType(Decl->TypeForDecl, 0)6.84M
;
4640
4641
3.83M
  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4642
780
    if (PrevDecl->TypeForDecl)
4643
780
      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4644
4645
3.83M
  auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4646
3.83M
  Decl->TypeForDecl = newType;
4647
3.83M
  Types.push_back(newType);
4648
3.83M
  return QualType(newType, 0);
4649
3.83M
}
4650
4651
1.37M
QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4652
1.37M
  if (Decl->TypeForDecl) 
return QualType(Decl->TypeForDecl, 0)886k
;
4653
4654
486k
  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4655
51
    if (PrevDecl->TypeForDecl)
4656
51
      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4657
4658
486k
  auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4659
486k
  Decl->TypeForDecl = newType;
4660
486k
  Types.push_back(newType);
4661
486k
  return QualType(newType, 0);
4662
486k
}
4663
4664
QualType ASTContext::getUnresolvedUsingType(
4665
1.09k
    const UnresolvedUsingTypenameDecl *Decl) const {
4666
1.09k
  if (Decl->TypeForDecl)
4667
0
    return QualType(Decl->TypeForDecl, 0);
4668
4669
1.09k
  if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4670
1.09k
          Decl->getCanonicalDecl())
4671
1.09k
    if (CanonicalDecl->TypeForDecl)
4672
0
      return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4673
4674
1.09k
  Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
4675
1.09k
  Decl->TypeForDecl = newType;
4676
1.09k
  Types.push_back(newType);
4677
1.09k
  return QualType(newType, 0);
4678
1.09k
}
4679
4680
QualType ASTContext::getAttributedType(attr::Kind attrKind,
4681
                                       QualType modifiedType,
4682
3.33M
                                       QualType equivalentType) {
4683
3.33M
  llvm::FoldingSetNodeID id;
4684
3.33M
  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4685
4686
3.33M
  void *insertPos = nullptr;
4687
3.33M
  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4688
3.33M
  if (type) 
return QualType(type, 0)2.92M
;
4689
4690
404k
  QualType canon = getCanonicalType(equivalentType);
4691
404k
  type = new (*this, TypeAlignment)
4692
404k
      AttributedType(canon, attrKind, modifiedType, equivalentType);
4693
4694
404k
  Types.push_back(type);
4695
404k
  AttributedTypes.InsertNode(type, insertPos);
4696
4697
404k
  return QualType(type, 0);
4698
3.33M
}
4699
4700
QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4701
54
                                             QualType Wrapped) {
4702
54
  llvm::FoldingSetNodeID ID;
4703
54
  BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4704
4705
54
  void *InsertPos = nullptr;
4706
54
  BTFTagAttributedType *Ty =
4707
54
      BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4708
54
  if (Ty)
4709
0
    return QualType(Ty, 0);
4710
4711
54
  QualType Canon = getCanonicalType(Wrapped);
4712
54
  Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4713
4714
54
  Types.push_back(Ty);
4715
54
  BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4716
4717
54
  return QualType(Ty, 0);
4718
54
}
4719
4720
/// Retrieve a substitution-result type.
4721
QualType
4722
ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4723
5.07M
                                         QualType Replacement) const {
4724
5.07M
  assert(Replacement.isCanonical()
4725
5.07M
         && "replacement types must always be canonical");
4726
4727
0
  llvm::FoldingSetNodeID ID;
4728
5.07M
  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4729
5.07M
  void *InsertPos = nullptr;
4730
5.07M
  SubstTemplateTypeParmType *SubstParm
4731
5.07M
    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4732
4733
5.07M
  if (!SubstParm) {
4734
1.87M
    SubstParm = new (*this, TypeAlignment)
4735
1.87M
      SubstTemplateTypeParmType(Parm, Replacement);
4736
1.87M
    Types.push_back(SubstParm);
4737
1.87M
    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4738
1.87M
  }
4739
4740
5.07M
  return QualType(SubstParm, 0);
4741
5.07M
}
4742
4743
/// Retrieve a
4744
QualType ASTContext::getSubstTemplateTypeParmPackType(
4745
                                          const TemplateTypeParmType *Parm,
4746
50.3k
                                              const TemplateArgument &ArgPack) {
4747
50.3k
#ifndef NDEBUG
4748
143k
  for (const auto &P : ArgPack.pack_elements()) {
4749
143k
    assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4750
0
    assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4751
143k
  }
4752
50.3k
#endif
4753
4754
50.3k
  llvm::FoldingSetNodeID ID;
4755
50.3k
  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4756
50.3k
  void *InsertPos = nullptr;
4757
50.3k
  if (SubstTemplateTypeParmPackType *SubstParm
4758
50.3k
        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4759
36.0k
    return QualType(SubstParm, 0);
4760
4761
14.2k
  QualType Canon;
4762
14.2k
  if (!Parm->isCanonicalUnqualified()) {
4763
8.64k
    Canon = getCanonicalType(QualType(Parm, 0));
4764
8.64k
    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4765
8.64k
                                             ArgPack);
4766
8.64k
    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4767
8.64k
  }
4768
4769
14.2k
  auto *SubstParm
4770
14.2k
    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4771
14.2k
                                                               ArgPack);
4772
14.2k
  Types.push_back(SubstParm);
4773
14.2k
  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4774
14.2k
  return QualType(SubstParm, 0);
4775
50.3k
}
4776
4777
/// Retrieve the template type parameter type for a template
4778
/// parameter or parameter pack with the given depth, index, and (optionally)
4779
/// name.
4780
QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4781
                                             bool ParameterPack,
4782
10.6M
                                             TemplateTypeParmDecl *TTPDecl) const {
4783
10.6M
  llvm::FoldingSetNodeID ID;
4784
10.6M
  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4785
10.6M
  void *InsertPos = nullptr;
4786
10.6M
  TemplateTypeParmType *TypeParm
4787
10.6M
    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4788
4789
10.6M
  if (TypeParm)
4790
6.23M
    return QualType(TypeParm, 0);
4791
4792
4.41M
  if (TTPDecl) {
4793
4.34M
    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4794
4.34M
    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4795
4796
4.34M
    TemplateTypeParmType *TypeCheck
4797
4.34M
      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4798
4.34M
    assert(!TypeCheck && "Template type parameter canonical type broken");
4799
0
    (void)TypeCheck;
4800
4.34M
  } else
4801
64.6k
    TypeParm = new (*this, TypeAlignment)
4802
64.6k
      TemplateTypeParmType(Depth, Index, ParameterPack);
4803
4804
0
  Types.push_back(TypeParm);
4805
4.41M
  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4806
4807
4.41M
  return QualType(TypeParm, 0);
4808
10.6M
}
4809
4810
TypeSourceInfo *
4811
ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4812
                                              SourceLocation NameLoc,
4813
                                        const TemplateArgumentListInfo &Args,
4814
225k
                                              QualType Underlying) const {
4815
225k
  assert(!Name.getAsDependentTemplateName() &&
4816
225k
         "No dependent template names here!");
4817
0
  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4818
4819
225k
  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4820
225k
  TemplateSpecializationTypeLoc TL =
4821
225k
      DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4822
225k
  TL.setTemplateKeywordLoc(SourceLocation());
4823
225k
  TL.setTemplateNameLoc(NameLoc);
4824
225k
  TL.setLAngleLoc(Args.getLAngleLoc());
4825
225k
  TL.setRAngleLoc(Args.getRAngleLoc());
4826
658k
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; 
++i432k
)
4827
432k
    TL.setArgLocInfo(i, Args[i].getLocInfo());
4828
225k
  return DI;
4829
225k
}
4830
4831
QualType
4832
ASTContext::getTemplateSpecializationType(TemplateName Template,
4833
                                          const TemplateArgumentListInfo &Args,
4834
6.57M
                                          QualType Underlying) const {
4835
6.57M
  assert(!Template.getAsDependentTemplateName() &&
4836
6.57M
         "No dependent template names here!");
4837
4838
0
  SmallVector<TemplateArgument, 4> ArgVec;
4839
6.57M
  ArgVec.reserve(Args.size());
4840
6.57M
  for (const TemplateArgumentLoc &Arg : Args.arguments())
4841
10.5M
    ArgVec.push_back(Arg.getArgument());
4842
4843
6.57M
  return getTemplateSpecializationType(Template, ArgVec, Underlying);
4844
6.57M
}
4845
4846
#ifndef NDEBUG
4847
0
static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4848
0
  for (const TemplateArgument &Arg : Args)
4849
0
    if (Arg.isPackExpansion())
4850
0
      return true;
4851
4852
0
  return true;
4853
0
}
4854
#endif
4855
4856
QualType
4857
ASTContext::getTemplateSpecializationType(TemplateName Template,
4858
                                          ArrayRef<TemplateArgument> Args,
4859
9.98M
                                          QualType Underlying) const {
4860
9.98M
  assert(!Template.getAsDependentTemplateName() &&
4861
9.98M
         "No dependent template names here!");
4862
  // Look through qualified template names.
4863
9.98M
  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4864
188k
    Template = QTN->getUnderlyingTemplate();
4865
4866
9.98M
  bool IsTypeAlias =
4867
9.98M
      isa_and_nonnull<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4868
9.98M
  QualType CanonType;
4869
9.98M
  if (!Underlying.isNull())
4870
9.21M
    CanonType = getCanonicalType(Underlying);
4871
773k
  else {
4872
    // We can get here with an alias template when the specialization contains
4873
    // a pack expansion that does not match up with a parameter pack.
4874
773k
    assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4875
773k
           "Caller must compute aliased type");
4876
0
    IsTypeAlias = false;
4877
773k
    CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4878
773k
  }
4879
4880
  // Allocate the (non-canonical) template specialization type, but don't
4881
  // try to unique it: these types typically have location information that
4882
  // we don't unique and don't want to lose.
4883
0
  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4884
9.98M
                       sizeof(TemplateArgument) * Args.size() +
4885
9.98M
                       (IsTypeAlias? 
sizeof(QualType)1.04M
:
08.94M
),
4886
9.98M
                       TypeAlignment);
4887
9.98M
  auto *Spec
4888
9.98M
    = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4889
9.98M
                                         IsTypeAlias ? 
Underlying1.04M
:
QualType()8.94M
);
4890
4891
9.98M
  Types.push_back(Spec);
4892
9.98M
  return QualType(Spec, 0);
4893
9.98M
}
4894
4895
static bool
4896
getCanonicalTemplateArguments(const ASTContext &C,
4897
                              ArrayRef<TemplateArgument> OrigArgs,
4898
4.47M
                              SmallVectorImpl<TemplateArgument> &CanonArgs) {
4899
4.47M
  bool AnyNonCanonArgs = false;
4900
4.47M
  unsigned NumArgs = OrigArgs.size();
4901
4.47M
  CanonArgs.resize(NumArgs);
4902
12.4M
  for (unsigned I = 0; I != NumArgs; 
++I7.95M
) {
4903
7.95M
    const TemplateArgument &OrigArg = OrigArgs[I];
4904
7.95M
    TemplateArgument &CanonArg = CanonArgs[I];
4905
7.95M
    CanonArg = C.getCanonicalTemplateArgument(OrigArg);
4906
7.95M
    if (!CanonArg.structurallyEquals(OrigArg))
4907
779k
      AnyNonCanonArgs = true;
4908
7.95M
  }
4909
4.47M
  return AnyNonCanonArgs;
4910
4.47M
}
4911
4912
QualType ASTContext::getCanonicalTemplateSpecializationType(
4913
4.40M
    TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4914
4.40M
  assert(!Template.getAsDependentTemplateName() &&
4915
4.40M
         "No dependent template names here!");
4916
4917
  // Look through qualified template names.
4918
4.40M
  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4919
134k
    Template = TemplateName(QTN->getUnderlyingTemplate());
4920
4921
  // Build the canonical template specialization type.
4922
4.40M
  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4923
4.40M
  SmallVector<TemplateArgument, 4> CanonArgs;
4924
4.40M
  ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
4925
4926
  // Determine whether this canonical template specialization type already
4927
  // exists.
4928
4.40M
  llvm::FoldingSetNodeID ID;
4929
4.40M
  TemplateSpecializationType::Profile(ID, CanonTemplate,
4930
4.40M
                                      CanonArgs, *this);
4931
4932
4.40M
  void *InsertPos = nullptr;
4933
4.40M
  TemplateSpecializationType *Spec
4934
4.40M
    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4935
4936
4.40M
  if (!Spec) {
4937
    // Allocate a new canonical template specialization type.
4938
1.88M
    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4939
1.88M
                          sizeof(TemplateArgument) * CanonArgs.size()),
4940
1.88M
                         TypeAlignment);
4941
1.88M
    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4942
1.88M
                                                CanonArgs,
4943
1.88M
                                                QualType(), QualType());
4944
1.88M
    Types.push_back(Spec);
4945
1.88M
    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4946
1.88M
  }
4947
4948
4.40M
  assert(Spec->isDependentType() &&
4949
4.40M
         "Non-dependent template-id type must have a canonical type");
4950
0
  return QualType(Spec, 0);
4951
4.40M
}
4952
4953
QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4954
                                       NestedNameSpecifier *NNS,
4955
                                       QualType NamedType,
4956
2.57M
                                       TagDecl *OwnedTagDecl) const {
4957
2.57M
  llvm::FoldingSetNodeID ID;
4958
2.57M
  ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4959
4960
2.57M
  void *InsertPos = nullptr;
4961
2.57M
  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4962
2.57M
  if (T)
4963
756k
    return QualType(T, 0);
4964
4965
1.82M
  QualType Canon = NamedType;
4966
1.82M
  if (!Canon.isCanonical()) {
4967
1.10M
    Canon = getCanonicalType(NamedType);
4968
1.10M
    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4969
1.10M
    assert(!CheckT && "Elaborated canonical type broken");
4970
0
    (void)CheckT;
4971
1.10M
  }
4972
4973
0
  void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4974
1.82M
                       TypeAlignment);
4975
1.82M
  T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4976
4977
1.82M
  Types.push_back(T);
4978
1.82M
  ElaboratedTypes.InsertNode(T, InsertPos);
4979
1.82M
  return QualType(T, 0);
4980
2.57M
}
4981
4982
QualType
4983
317k
ASTContext::getParenType(QualType InnerType) const {
4984
317k
  llvm::FoldingSetNodeID ID;
4985
317k
  ParenType::Profile(ID, InnerType);
4986
4987
317k
  void *InsertPos = nullptr;
4988
317k
  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4989
317k
  if (T)
4990
112k
    return QualType(T, 0);
4991
4992
205k
  QualType Canon = InnerType;
4993
205k
  if (!Canon.isCanonical()) {
4994
180k
    Canon = getCanonicalType(InnerType);
4995
180k
    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4996
180k
    assert(!CheckT && "Paren canonical type broken");
4997
0
    (void)CheckT;
4998
180k
  }
4999
5000
0
  T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
5001
205k
  Types.push_back(T);
5002
205k
  ParenTypes.InsertNode(T, InsertPos);
5003
205k
  return QualType(T, 0);
5004
317k
}
5005
5006
QualType
5007
ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5008
244k
                                  const IdentifierInfo *MacroII) const {
5009
244k
  QualType Canon = UnderlyingTy;
5010
244k
  if (!Canon.isCanonical())
5011
244k
    Canon = getCanonicalType(UnderlyingTy);
5012
5013
244k
  auto *newType = new (*this, TypeAlignment)
5014
244k
      MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5015
244k
  Types.push_back(newType);
5016
244k
  return QualType(newType, 0);
5017
244k
}
5018
5019
QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5020
                                          NestedNameSpecifier *NNS,
5021
                                          const IdentifierInfo *Name,
5022
2.75M
                                          QualType Canon) const {
5023
2.75M
  if (Canon.isNull()) {
5024
2.32M
    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5025
2.32M
    if (CanonNNS != NNS)
5026
1.08M
      Canon = getDependentNameType(Keyword, CanonNNS, Name);
5027
2.32M
  }
5028
5029
2.75M
  llvm::FoldingSetNodeID ID;
5030
2.75M
  DependentNameType::Profile(ID, Keyword, NNS, Name);
5031
5032
2.75M
  void *InsertPos = nullptr;
5033
2.75M
  DependentNameType *T
5034
2.75M
    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5035
2.75M
  if (T)
5036
716k
    return QualType(T, 0);
5037
5038
2.04M
  T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
5039
2.04M
  Types.push_back(T);
5040
2.04M
  DependentNameTypes.InsertNode(T, InsertPos);
5041
2.04M
  return QualType(T, 0);
5042
2.75M
}
5043
5044
QualType
5045
ASTContext::getDependentTemplateSpecializationType(
5046
                                 ElaboratedTypeKeyword Keyword,
5047
                                 NestedNameSpecifier *NNS,
5048
                                 const IdentifierInfo *Name,
5049
35.1k
                                 const TemplateArgumentListInfo &Args) const {
5050
  // TODO: avoid this copy
5051
35.1k
  SmallVector<TemplateArgument, 16> ArgCopy;
5052
87.5k
  for (unsigned I = 0, E = Args.size(); I != E; 
++I52.3k
)
5053
52.3k
    ArgCopy.push_back(Args[I].getArgument());
5054
35.1k
  return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5055
35.1k
}
5056
5057
QualType
5058
ASTContext::getDependentTemplateSpecializationType(
5059
                                 ElaboratedTypeKeyword Keyword,
5060
                                 NestedNameSpecifier *NNS,
5061
                                 const IdentifierInfo *Name,
5062
88.8k
                                 ArrayRef<TemplateArgument> Args) const {
5063
88.8k
  assert((!NNS || NNS->isDependent()) &&
5064
88.8k
         "nested-name-specifier must be dependent");
5065
5066
0
  llvm::FoldingSetNodeID ID;
5067
88.8k
  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5068
88.8k
                                               Name, Args);
5069
5070
88.8k
  void *InsertPos = nullptr;
5071
88.8k
  DependentTemplateSpecializationType *T
5072
88.8k
    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5073
88.8k
  if (T)
5074
23.2k
    return QualType(T, 0);
5075
5076
65.6k
  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5077
5078
65.6k
  ElaboratedTypeKeyword CanonKeyword = Keyword;
5079
65.6k
  if (Keyword == ETK_None) 
CanonKeyword = ETK_Typename2.75k
;
5080
5081
65.6k
  SmallVector<TemplateArgument, 16> CanonArgs;
5082
65.6k
  bool AnyNonCanonArgs =
5083
65.6k
      ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
5084
5085
65.6k
  QualType Canon;
5086
65.6k
  if (AnyNonCanonArgs || 
CanonNNS != NNS25.9k
||
CanonKeyword != Keyword22.1k
) {
5087
43.5k
    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5088
43.5k
                                                   Name,
5089
43.5k
                                                   CanonArgs);
5090
5091
    // Find the insert position again.
5092
43.5k
    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5093
43.5k
  }
5094
5095
65.6k
  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5096
65.6k
                        sizeof(TemplateArgument) * Args.size()),
5097
65.6k
                       TypeAlignment);
5098
65.6k
  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5099
65.6k
                                                    Name, Args, Canon);
5100
65.6k
  Types.push_back(T);
5101
65.6k
  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5102
65.6k
  return QualType(T, 0);
5103
88.8k
}
5104
5105
793k
TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5106
793k
  TemplateArgument Arg;
5107
793k
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {