Bug Summary

File:build/source/clang/lib/AST/ASTContext.cpp
Warning:line 4149, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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