Coverage Report

Created: 2020-02-15 09:57

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