Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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