Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 3053, column 12
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

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