Coverage Report

Created: 2021-09-21 08:58

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