Coverage Report

Created: 2019-07-24 05:18

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