Bug Summary

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