Coverage Report

Created: 2022-01-25 06:29

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