Coverage Report

Created: 2020-09-22 08:39

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