Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 3270, column 3
Value stored to 'AT' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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