Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 9756, column 23
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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