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);
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 else {
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 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
184 // If location of the tag decl is inside a macro, but the spelling of
185 // the tag name comes from a macro argument, it looks like a special
186 // macro like NS_ENUM is being used to define the tag decl. In that
187 // case, adjust the source location to the expansion loc so that we can
188 // attach the comment to the tag decl.
189 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
190 TD->isCompleteDefinition())
191 return SourceMgr.getExpansionLoc(DeclLoc);
192 }
193 }
194 return DeclLoc;
195 }
196
197 return {};
198}
199
200RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
201 const Decl *D, const SourceLocation RepresentativeLocForDecl,
202 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
203 // If the declaration doesn't map directly to a location in a file, we
204 // can't find the comment.
205 if (RepresentativeLocForDecl.isInvalid() ||
206 !RepresentativeLocForDecl.isFileID())
207 return nullptr;
208
209 // If there are no comments anywhere, we won't find anything.
210 if (CommentsInTheFile.empty())
211 return nullptr;
212
213 // Decompose the location for the declaration and find the beginning of the
214 // file buffer.
215 const std::pair<FileID, unsigned> DeclLocDecomp =
216 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
217
218 // Slow path.
219 auto OffsetCommentBehindDecl =
220 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
221
222 // First check whether we have a trailing comment.
223 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
224 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
225 if ((CommentBehindDecl->isDocumentation() ||
226 LangOpts.CommentOpts.ParseAllComments) &&
227 CommentBehindDecl->isTrailingComment() &&
228 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
229 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
230
231 // Check that Doxygen trailing comment comes after the declaration, starts
232 // on the same line and in the same file as the declaration.
233 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
234 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
235 OffsetCommentBehindDecl->first)) {
236 return CommentBehindDecl;
237 }
238 }
239 }
240
241 // The comment just after the declaration was not a trailing comment.
242 // Let's look at the previous comment.
243 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
244 return nullptr;
245
246 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
247 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
248
249 // Check that we actually have a non-member Doxygen comment.
250 if (!(CommentBeforeDecl->isDocumentation() ||
251 LangOpts.CommentOpts.ParseAllComments) ||
252 CommentBeforeDecl->isTrailingComment())
253 return nullptr;
254
255 // Decompose the end of the comment.
256 const unsigned CommentEndOffset =
257 Comments.getCommentEndOffset(CommentBeforeDecl);
258
259 // Get the corresponding buffer.
260 bool Invalid = false;
261 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
262 &Invalid).data();
263 if (Invalid)
264 return nullptr;
265
266 // Extract text between the comment and declaration.
267 StringRef Text(Buffer + CommentEndOffset,
268 DeclLocDecomp.second - CommentEndOffset);
269
270 // There should be no other declarations or preprocessor directives between
271 // comment and declaration.
272 if (Text.find_first_of(";{}#@") != StringRef::npos)
273 return nullptr;
274
275 return CommentBeforeDecl;
276}
277
278RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
279 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
280
281 // If the declaration doesn't map directly to a location in a file, we
282 // can't find the comment.
283 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
284 return nullptr;
285
286 if (ExternalSource && !CommentsLoaded) {
287 ExternalSource->ReadComments();
288 CommentsLoaded = true;
289 }
290
291 if (Comments.empty())
292 return nullptr;
293
294 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
295 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
296 if (!CommentsInThisFile || CommentsInThisFile->empty())
297 return nullptr;
298
299 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
300}
301
302void ASTContext::addComment(const RawComment &RC) {
303 assert(LangOpts.RetainCommentsFromSystemHeaders ||
304 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
305 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
306}
307
308/// If we have a 'templated' declaration for a template, adjust 'D' to
309/// refer to the actual template.
310/// If we have an implicit instantiation, adjust 'D' to refer to template.
311static const Decl &adjustDeclToTemplate(const Decl &D) {
312 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
313 // Is this function declaration part of a function template?
314 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
315 return *FTD;
316
317 // Nothing to do if function is not an implicit instantiation.
318 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
319 return D;
320
321 // Function is an implicit instantiation of a function template?
322 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
323 return *FTD;
324
325 // Function is instantiated from a member definition of a class template?
326 if (const FunctionDecl *MemberDecl =
327 FD->getInstantiatedFromMemberFunction())
328 return *MemberDecl;
329
330 return D;
331 }
332 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
333 // Static data member is instantiated from a member definition of a class
334 // template?
335 if (VD->isStaticDataMember())
336 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
337 return *MemberDecl;
338
339 return D;
340 }
341 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
342 // Is this class declaration part of a class template?
343 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
344 return *CTD;
345
346 // Class is an implicit instantiation of a class template or partial
347 // specialization?
348 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
349 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
350 return D;
351 llvm::PointerUnion<ClassTemplateDecl *,
352 ClassTemplatePartialSpecializationDecl *>
353 PU = CTSD->getSpecializedTemplateOrPartial();
354 return PU.is<ClassTemplateDecl *>()
355 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
356 : *static_cast<const Decl *>(
357 PU.get<ClassTemplatePartialSpecializationDecl *>());
358 }
359
360 // Class is instantiated from a member definition of a class template?
361 if (const MemberSpecializationInfo *Info =
362 CRD->getMemberSpecializationInfo())
363 return *Info->getInstantiatedFrom();
364
365 return D;
366 }
367 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
368 // Enum is instantiated from a member definition of a class template?
369 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
370 return *MemberDecl;
371
372 return D;
373 }
374 // FIXME: Adjust alias templates?
375 return D;
376}
377
378const RawComment *ASTContext::getRawCommentForAnyRedecl(
379 const Decl *D,
380 const Decl **OriginalDecl) const {
381 if (!D) {
382 if (OriginalDecl)
383 OriginalDecl = nullptr;
384 return nullptr;
385 }
386
387 D = &adjustDeclToTemplate(*D);
388
389 // Any comment directly attached to D?
390 {
391 auto DeclComment = DeclRawComments.find(D);
392 if (DeclComment != DeclRawComments.end()) {
393 if (OriginalDecl)
394 *OriginalDecl = D;
395 return DeclComment->second;
396 }
397 }
398
399 // Any comment attached to any redeclaration of D?
400 const Decl *CanonicalD = D->getCanonicalDecl();
401 if (!CanonicalD)
402 return nullptr;
403
404 {
405 auto RedeclComment = RedeclChainComments.find(CanonicalD);
406 if (RedeclComment != RedeclChainComments.end()) {
407 if (OriginalDecl)
408 *OriginalDecl = RedeclComment->second;
409 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
410 assert(CommentAtRedecl != DeclRawComments.end() &&
411 "This decl is supposed to have comment attached.");
412 return CommentAtRedecl->second;
413 }
414 }
415
416 // Any redeclarations of D that we haven't checked for comments yet?
417 // We can't use DenseMap::iterator directly since it'd get invalid.
418 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
419 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
420 if (LookupRes != CommentlessRedeclChains.end())
421 return LookupRes->second;
422 return nullptr;
423 }();
424
425 for (const auto Redecl : D->redecls()) {
426 assert(Redecl);
427 // Skip all redeclarations that have been checked previously.
428 if (LastCheckedRedecl) {
429 if (LastCheckedRedecl == Redecl) {
430 LastCheckedRedecl = nullptr;
431 }
432 continue;
433 }
434 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
435 if (RedeclComment) {
436 cacheRawCommentForDecl(*Redecl, *RedeclComment);
437 if (OriginalDecl)
438 *OriginalDecl = Redecl;
439 return RedeclComment;
440 }
441 CommentlessRedeclChains[CanonicalD] = Redecl;
442 }
443
444 if (OriginalDecl)
445 *OriginalDecl = nullptr;
446 return nullptr;
447}
448
449void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
450 const RawComment &Comment) const {
451 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
452 DeclRawComments.try_emplace(&OriginalD, &Comment);
453 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
454 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
455 CommentlessRedeclChains.erase(CanonicalDecl);
456}
457
458static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
459 SmallVectorImpl<const NamedDecl *> &Redeclared) {
460 const DeclContext *DC = ObjCMethod->getDeclContext();
461 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
462 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
463 if (!ID)
464 return;
465 // Add redeclared method here.
466 for (const auto *Ext : ID->known_extensions()) {
467 if (ObjCMethodDecl *RedeclaredMethod =
468 Ext->getMethod(ObjCMethod->getSelector(),
469 ObjCMethod->isInstanceMethod()))
470 Redeclared.push_back(RedeclaredMethod);
471 }
472 }
473}
474
475void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
476 const Preprocessor *PP) {
477 if (Comments.empty() || Decls.empty())
478 return;
479
480 FileID File;
481 for (Decl *D : Decls) {
482 SourceLocation Loc = D->getLocation();
483 if (Loc.isValid()) {
484 // See if there are any new comments that are not attached to a decl.
485 // The location doesn't have to be precise - we care only about the file.
486 File = SourceMgr.getDecomposedLoc(Loc).first;
487 break;
488 }
489 }
490
491 if (File.isInvalid())
492 return;
493
494 auto CommentsInThisFile = Comments.getCommentsInFile(File);
495 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
496 CommentsInThisFile->rbegin()->second->isAttached())
497 return;
498
499 // There is at least one comment not attached to a decl.
500 // Maybe it should be attached to one of Decls?
501 //
502 // Note that this way we pick up not only comments that precede the
503 // declaration, but also comments that *follow* the declaration -- thanks to
504 // the lookahead in the lexer: we've consumed the semicolon and looked
505 // ahead through comments.
506
507 for (const Decl *D : Decls) {
508 assert(D);
509 if (D->isInvalidDecl())
510 continue;
511
512 D = &adjustDeclToTemplate(*D);
513
514 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
515
516 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
517 continue;
518
519 if (DeclRawComments.count(D) > 0)
520 continue;
521
522 if (RawComment *const DocComment =
523 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
524 cacheRawCommentForDecl(*D, *DocComment);
525 comments::FullComment *FC = DocComment->parse(*this, PP, D);
526 ParsedComments[D->getCanonicalDecl()] = FC;
527 }
528 }
529}
530
531comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
532 const Decl *D) const {
533 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
534 ThisDeclInfo->CommentDecl = D;
535 ThisDeclInfo->IsFilled = false;
536 ThisDeclInfo->fill();
537 ThisDeclInfo->CommentDecl = FC->getDecl();
538 if (!ThisDeclInfo->TemplateParameters)
539 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
540 comments::FullComment *CFC =
541 new (*this) comments::FullComment(FC->getBlocks(),
542 ThisDeclInfo);
543 return CFC;
544}
545
546comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
547 const RawComment *RC = getRawCommentForDeclNoCache(D);
548 return RC ? RC->parse(*this, nullptr, D) : nullptr;
549}
550
551comments::FullComment *ASTContext::getCommentForDecl(
552 const Decl *D,
553 const Preprocessor *PP) const {
554 if (!D || D->isInvalidDecl())
555 return nullptr;
556 D = &adjustDeclToTemplate(*D);
557
558 const Decl *Canonical = D->getCanonicalDecl();
559 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
560 ParsedComments.find(Canonical);
561
562 if (Pos != ParsedComments.end()) {
563 if (Canonical != D) {
564 comments::FullComment *FC = Pos->second;
565 comments::FullComment *CFC = cloneFullComment(FC, D);
566 return CFC;
567 }
568 return Pos->second;
569 }
570
571 const Decl *OriginalDecl = nullptr;
572
573 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
574 if (!RC) {
575 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
576 SmallVector<const NamedDecl*, 8> Overridden;
577 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
578 if (OMD && OMD->isPropertyAccessor())
579 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
580 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
581 return cloneFullComment(FC, D);
582 if (OMD)
583 addRedeclaredMethods(OMD, Overridden);
584 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
585 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
586 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
587 return cloneFullComment(FC, D);
588 }
589 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
590 // Attach any tag type's documentation to its typedef if latter
591 // does not have one of its own.
592 QualType QT = TD->getUnderlyingType();
593 if (const auto *TT = QT->getAs<TagType>())
594 if (const Decl *TD = TT->getDecl())
595 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
596 return cloneFullComment(FC, D);
597 }
598 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
599 while (IC->getSuperClass()) {
600 IC = IC->getSuperClass();
601 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
602 return cloneFullComment(FC, D);
603 }
604 }
605 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
606 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
607 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
608 return cloneFullComment(FC, D);
609 }
610 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
611 if (!(RD = RD->getDefinition()))
612 return nullptr;
613 // Check non-virtual bases.
614 for (const auto &I : RD->bases()) {
615 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
616 continue;
617 QualType Ty = I.getType();
618 if (Ty.isNull())
619 continue;
620 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
621 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
622 continue;
623
624 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
625 return cloneFullComment(FC, D);
626 }
627 }
628 // Check virtual bases.
629 for (const auto &I : RD->vbases()) {
630 if (I.getAccessSpecifier() != AS_public)
631 continue;
632 QualType Ty = I.getType();
633 if (Ty.isNull())
634 continue;
635 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
636 if (!(VirtualBase= VirtualBase->getDefinition()))
637 continue;
638 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
639 return cloneFullComment(FC, D);
640 }
641 }
642 }
643 return nullptr;
644 }
645
646 // If the RawComment was attached to other redeclaration of this Decl, we
647 // should parse the comment in context of that other Decl. This is important
648 // because comments can contain references to parameter names which can be
649 // different across redeclarations.
650 if (D != OriginalDecl && OriginalDecl)
651 return getCommentForDecl(OriginalDecl, PP);
652
653 comments::FullComment *FC = RC->parse(*this, PP, D);
654 ParsedComments[Canonical] = FC;
655 return FC;
656}
657
658void
659ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
660 const ASTContext &C,
661 TemplateTemplateParmDecl *Parm) {
662 ID.AddInteger(Parm->getDepth());
663 ID.AddInteger(Parm->getPosition());
664 ID.AddBoolean(Parm->isParameterPack());
665
666 TemplateParameterList *Params = Parm->getTemplateParameters();
667 ID.AddInteger(Params->size());
668 for (TemplateParameterList::const_iterator P = Params->begin(),
669 PEnd = Params->end();
670 P != PEnd; ++P) {
671 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
672 ID.AddInteger(0);
673 ID.AddBoolean(TTP->isParameterPack());
674 const TypeConstraint *TC = TTP->getTypeConstraint();
675 ID.AddBoolean(TC != nullptr);
676 if (TC)
677 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
678 /*Canonical=*/true);
679 if (TTP->isExpandedParameterPack()) {
680 ID.AddBoolean(true);
681 ID.AddInteger(TTP->getNumExpansionParameters());
682 } else
683 ID.AddBoolean(false);
684 continue;
685 }
686
687 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
688 ID.AddInteger(1);
689 ID.AddBoolean(NTTP->isParameterPack());
690 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
691 if (NTTP->isExpandedParameterPack()) {
692 ID.AddBoolean(true);
693 ID.AddInteger(NTTP->getNumExpansionTypes());
694 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
695 QualType T = NTTP->getExpansionType(I);
696 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
697 }
698 } else
699 ID.AddBoolean(false);
700 continue;
701 }
702
703 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
704 ID.AddInteger(2);
705 Profile(ID, C, TTP);
706 }
707 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
708 ID.AddBoolean(RequiresClause != nullptr);
709 if (RequiresClause)
710 RequiresClause->Profile(ID, C, /*Canonical=*/true);
711}
712
713static Expr *
714canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
715 QualType ConstrainedType) {
716 // This is a bit ugly - we need to form a new immediately-declared
717 // constraint that references the new parameter; this would ideally
718 // require semantic analysis (e.g. template<C T> struct S {}; - the
719 // converted arguments of C<T> could be an argument pack if C is
720 // declared as template<typename... T> concept C = ...).
721 // We don't have semantic analysis here so we dig deep into the
722 // ready-made constraint expr and change the thing manually.
723 ConceptSpecializationExpr *CSE;
724 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
725 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
726 else
727 CSE = cast<ConceptSpecializationExpr>(IDC);
728 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
729 SmallVector<TemplateArgument, 3> NewConverted;
730 NewConverted.reserve(OldConverted.size());
731 if (OldConverted.front().getKind() == TemplateArgument::Pack) {
732 // The case:
733 // template<typename... T> concept C = true;
734 // template<C<int> T> struct S; -> constraint is C<{T, int}>
735 NewConverted.push_back(ConstrainedType);
736 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
737 NewConverted.push_back(Arg);
738 TemplateArgument NewPack(NewConverted);
739
740 NewConverted.clear();
741 NewConverted.push_back(NewPack);
742 assert(OldConverted.size() == 1 &&
743 "Template parameter pack should be the last parameter");
744 } else {
745 assert(OldConverted.front().getKind() == TemplateArgument::Type &&
746 "Unexpected first argument kind for immediately-declared "
747 "constraint");
748 NewConverted.push_back(ConstrainedType);
749 for (auto &Arg : OldConverted.drop_front(1))
750 NewConverted.push_back(Arg);
751 }
752 Expr *NewIDC = ConceptSpecializationExpr::Create(
753 C, CSE->getNamedConcept(), NewConverted, nullptr,
754 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
755
756 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
757 NewIDC = new (C) CXXFoldExpr(
758 OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
759 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
760 SourceLocation(), /*NumExpansions=*/None);
761 return NewIDC;
762}
763
764TemplateTemplateParmDecl *
765ASTContext::getCanonicalTemplateTemplateParmDecl(
766 TemplateTemplateParmDecl *TTP) const {
767 // Check if we already have a canonical template template parameter.
768 llvm::FoldingSetNodeID ID;
769 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
770 void *InsertPos = nullptr;
771 CanonicalTemplateTemplateParm *Canonical
772 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
773 if (Canonical)
774 return Canonical->getParam();
775
776 // Build a canonical template parameter list.
777 TemplateParameterList *Params = TTP->getTemplateParameters();
778 SmallVector<NamedDecl *, 4> CanonParams;
779 CanonParams.reserve(Params->size());
780 for (TemplateParameterList::const_iterator P = Params->begin(),
781 PEnd = Params->end();
782 P != PEnd; ++P) {
783 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
784 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
785 getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
786 TTP->getDepth(), TTP->getIndex(), nullptr, false,
787 TTP->isParameterPack(), TTP->hasTypeConstraint(),
788 TTP->isExpandedParameterPack() ?
789 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
790 if (const auto *TC = TTP->getTypeConstraint()) {
791 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
792 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
793 *this, TC->getImmediatelyDeclaredConstraint(),
794 ParamAsArgument);
795 TemplateArgumentListInfo CanonArgsAsWritten;
796 if (auto *Args = TC->getTemplateArgsAsWritten())
797 for (const auto &ArgLoc : Args->arguments())
798 CanonArgsAsWritten.addArgument(
799 TemplateArgumentLoc(ArgLoc.getArgument(),
800 TemplateArgumentLocInfo()));
801 NewTTP->setTypeConstraint(
802 NestedNameSpecifierLoc(),
803 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
804 SourceLocation()), /*FoundDecl=*/nullptr,
805 // Actually canonicalizing a TemplateArgumentLoc is difficult so we
806 // simply omit the ArgsAsWritten
807 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
808 }
809 CanonParams.push_back(NewTTP);
810 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
811 QualType T = getCanonicalType(NTTP->getType());
812 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
813 NonTypeTemplateParmDecl *Param;
814 if (NTTP->isExpandedParameterPack()) {
815 SmallVector<QualType, 2> ExpandedTypes;
816 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
817 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
818 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
819 ExpandedTInfos.push_back(
820 getTrivialTypeSourceInfo(ExpandedTypes.back()));
821 }
822
823 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
824 SourceLocation(),
825 SourceLocation(),
826 NTTP->getDepth(),
827 NTTP->getPosition(), nullptr,
828 T,
829 TInfo,
830 ExpandedTypes,
831 ExpandedTInfos);
832 } else {
833 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
834 SourceLocation(),
835 SourceLocation(),
836 NTTP->getDepth(),
837 NTTP->getPosition(), nullptr,
838 T,
839 NTTP->isParameterPack(),
840 TInfo);
841 }
842 if (AutoType *AT = T->getContainedAutoType()) {
843 if (AT->isConstrained()) {
844 Param->setPlaceholderTypeConstraint(
845 canonicalizeImmediatelyDeclaredConstraint(
846 *this, NTTP->getPlaceholderTypeConstraint(), T));
847 }
848 }
849 CanonParams.push_back(Param);
850
851 } else
852 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
853 cast<TemplateTemplateParmDecl>(*P)));
854 }
855
856 Expr *CanonRequiresClause = nullptr;
857 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
858 CanonRequiresClause = RequiresClause;
859
860 TemplateTemplateParmDecl *CanonTTP
861 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
862 SourceLocation(), TTP->getDepth(),
863 TTP->getPosition(),
864 TTP->isParameterPack(),
865 nullptr,
866 TemplateParameterList::Create(*this, SourceLocation(),
867 SourceLocation(),
868 CanonParams,
869 SourceLocation(),
870 CanonRequiresClause));
871
872 // Get the new insert position for the node we care about.
873 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
874 assert(!Canonical && "Shouldn't be in the map!");
875 (void)Canonical;
876
877 // Create the canonical template template parameter entry.
878 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
879 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
880 return CanonTTP;
881}
882
883TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
884 auto Kind = getTargetInfo().getCXXABI().getKind();
885 return getLangOpts().CXXABI.getValueOr(Kind);
886}
887
888CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
889 if (!LangOpts.CPlusPlus) return nullptr;
890
891 switch (getCXXABIKind()) {
892 case TargetCXXABI::AppleARM64:
893 case TargetCXXABI::Fuchsia:
894 case TargetCXXABI::GenericARM: // Same as Itanium at this level
895 case TargetCXXABI::iOS:
896 case TargetCXXABI::WatchOS:
897 case TargetCXXABI::GenericAArch64:
898 case TargetCXXABI::GenericMIPS:
899 case TargetCXXABI::GenericItanium:
900 case TargetCXXABI::WebAssembly:
901 case TargetCXXABI::XL:
902 return CreateItaniumCXXABI(*this);
903 case TargetCXXABI::Microsoft:
904 return CreateMicrosoftCXXABI(*this);
905 }
906 llvm_unreachable("Invalid CXXABI type!");
907}
908
909interp::Context &ASTContext::getInterpContext() {
910 if (!InterpContext) {
911 InterpContext.reset(new interp::Context(*this));
912 }
913 return *InterpContext.get();
914}
915
916ParentMapContext &ASTContext::getParentMapContext() {
917 if (!ParentMapCtx)
918 ParentMapCtx.reset(new ParentMapContext(*this));
919 return *ParentMapCtx.get();
920}
921
922static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
923 const LangOptions &LOpts) {
924 if (LOpts.FakeAddressSpaceMap) {
925 // The fake address space map must have a distinct entry for each
926 // language-specific address space.
927 static const unsigned FakeAddrSpaceMap[] = {
928 0, // Default
929 1, // opencl_global
930 3, // opencl_local
931 2, // opencl_constant
932 0, // opencl_private
933 4, // opencl_generic
934 5, // opencl_global_device
935 6, // opencl_global_host
936 7, // cuda_device
937 8, // cuda_constant
938 9, // cuda_shared
939 1, // sycl_global
940 3, // sycl_local
941 0, // sycl_private
942 10, // ptr32_sptr
943 11, // ptr32_uptr
944 12 // ptr64
945 };
946 return &FakeAddrSpaceMap;
947 } else {
948 return &T.getAddressSpaceMap();
949 }
950}
951
952static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
953 const LangOptions &LangOpts) {
954 switch (LangOpts.getAddressSpaceMapMangling()) {
955 case LangOptions::ASMM_Target:
956 return TI.useAddressSpaceMapMangling();
957 case LangOptions::ASMM_On:
958 return true;
959 case LangOptions::ASMM_Off:
960 return false;
961 }
962 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
963}
964
965ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
966 IdentifierTable &idents, SelectorTable &sels,
967 Builtin::Context &builtins)
968 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
969 TemplateSpecializationTypes(this_()),
970 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
971 SubstTemplateTemplateParmPacks(this_()),
972 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
973 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
974 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
975 LangOpts.XRayNeverInstrumentFiles,
976 LangOpts.XRayAttrListFiles, SM)),
977 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
978 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
979 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
980 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
981 CompCategories(this_()), LastSDM(nullptr, 0) {
982 TUDecl = TranslationUnitDecl::Create(*this);
983 TraversalScope = {TUDecl};
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");
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() &&
1140 "GetExternalDecl for lazy module initializer added more inits");
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 = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1198 BuiltinTemplate->setImplicit();
1199 TUDecl->addDecl(BuiltinTemplate);
1200
1201 return BuiltinTemplate;
1202}
1203
1204BuiltinTemplateDecl *
1205ASTContext::getMakeIntegerSeqDecl() const {
1206 if (!MakeIntegerSeqDecl)
1207 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1208 getMakeIntegerSeqName());
1209 return MakeIntegerSeqDecl;
1210}
1211
1212BuiltinTemplateDecl *
1213ASTContext::getTypePackElementDecl() const {
1214 if (!TypePackElementDecl)
1215 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1216 getTypePackElementName());
1217 return TypePackElementDecl;
1218}
1219
1220RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1221 RecordDecl::TagKind TK) const {
1222 SourceLocation Loc;
1223 RecordDecl *NewDecl;
1224 if (getLangOpts().CPlusPlus)
1225 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1226 Loc, &Idents.get(Name));
1227 else
1228 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1229 &Idents.get(Name));
1230 NewDecl->setImplicit();
1231 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1232 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1233 return NewDecl;
1234}
1235
1236TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1237 StringRef Name) const {
1238 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1239 TypedefDecl *NewDecl = TypedefDecl::Create(
1240 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1241 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1242 NewDecl->setImplicit();
1243 return NewDecl;
1244}
1245
1246TypedefDecl *ASTContext::getInt128Decl() const {
1247 if (!Int128Decl)
1248 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1249 return Int128Decl;
1250}
1251
1252TypedefDecl *ASTContext::getUInt128Decl() const {
1253 if (!UInt128Decl)
1254 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1255 return UInt128Decl;
1256}
1257
1258void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1259 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1260 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1261 Types.push_back(Ty);
1262}
1263
1264void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1265 const TargetInfo *AuxTarget) {
1266 assert((!this->Target || this->Target == &Target) &&
1267 "Incorrect target reinitialization");
1268 assert(VoidTy.isNull() && "Context reinitialized?");
1269
1270 this->Target = &Target;
1271 this->AuxTarget = AuxTarget;
1272
1273 ABI.reset(createCXXABI(Target));
1274 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1275 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1276
1277 // C99 6.2.5p19.
1278 InitBuiltinType(VoidTy, BuiltinType::Void);
1279
1280 // C99 6.2.5p2.
1281 InitBuiltinType(BoolTy, BuiltinType::Bool);
1282 // C99 6.2.5p3.
1283 if (LangOpts.CharIsSigned)
1284 InitBuiltinType(CharTy, BuiltinType::Char_S);
1285 else
1286 InitBuiltinType(CharTy, BuiltinType::Char_U);
1287 // C99 6.2.5p4.
1288 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1289 InitBuiltinType(ShortTy, BuiltinType::Short);
1290 InitBuiltinType(IntTy, BuiltinType::Int);
1291 InitBuiltinType(LongTy, BuiltinType::Long);
1292 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1293
1294 // C99 6.2.5p6.
1295 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1296 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1297 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1298 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1299 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1300
1301 // C99 6.2.5p10.
1302 InitBuiltinType(FloatTy, BuiltinType::Float);
1303 InitBuiltinType(DoubleTy, BuiltinType::Double);
1304 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1305
1306 // GNU extension, __float128 for IEEE quadruple precision
1307 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1308
1309 // C11 extension ISO/IEC TS 18661-3
1310 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1311
1312 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1313 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1314 InitBuiltinType(AccumTy, BuiltinType::Accum);
1315 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1316 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1317 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1318 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1319 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1320 InitBuiltinType(FractTy, BuiltinType::Fract);
1321 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1322 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1323 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1324 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1325 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1326 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1327 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1328 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1329 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1330 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1331 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1332 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1333 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1334 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1335 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1336 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1337
1338 // GNU extension, 128-bit integers.
1339 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1340 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1341
1342 // C++ 3.9.1p5
1343 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1344 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1345 else // -fshort-wchar makes wchar_t be unsigned.
1346 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1347 if (LangOpts.CPlusPlus && LangOpts.WChar)
1348 WideCharTy = WCharTy;
1349 else {
1350 // C99 (or C++ using -fno-wchar).
1351 WideCharTy = getFromTargetType(Target.getWCharType());
1352 }
1353
1354 WIntTy = getFromTargetType(Target.getWIntType());
1355
1356 // C++20 (proposed)
1357 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1358
1359 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1360 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1361 else // C99
1362 Char16Ty = getFromTargetType(Target.getChar16Type());
1363
1364 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1365 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1366 else // C99
1367 Char32Ty = getFromTargetType(Target.getChar32Type());
1368
1369 // Placeholder type for type-dependent expressions whose type is
1370 // completely unknown. No code should ever check a type against
1371 // DependentTy and users should never see it; however, it is here to
1372 // help diagnose failures to properly check for type-dependent
1373 // expressions.
1374 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1375
1376 // Placeholder type for functions.
1377 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1378
1379 // Placeholder type for bound members.
1380 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1381
1382 // Placeholder type for pseudo-objects.
1383 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1384
1385 // "any" type; useful for debugger-like clients.
1386 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1387
1388 // Placeholder type for unbridged ARC casts.
1389 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1390
1391 // Placeholder type for builtin functions.
1392 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1393
1394 // Placeholder type for OMP array sections.
1395 if (LangOpts.OpenMP) {
1396 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1397 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1398 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1399 }
1400 if (LangOpts.MatrixTypes)
1401 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1402
1403 // C99 6.2.5p11.
1404 FloatComplexTy = getComplexType(FloatTy);
1405 DoubleComplexTy = getComplexType(DoubleTy);
1406 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1407 Float128ComplexTy = getComplexType(Float128Ty);
1408
1409 // Builtin types for 'id', 'Class', and 'SEL'.
1410 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1411 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1412 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1413
1414 if (LangOpts.OpenCL) {
1415#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1416 InitBuiltinType(SingletonId, BuiltinType::Id);
1417#include "clang/Basic/OpenCLImageTypes.def"
1418
1419 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1420 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1421 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1422 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1423 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1424
1425#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1426 InitBuiltinType(Id##Ty, BuiltinType::Id);
1427#include "clang/Basic/OpenCLExtensionTypes.def"
1428 }
1429
1430 if (Target.hasAArch64SVETypes()) {
1431#define SVE_TYPE(Name, Id, SingletonId) \
1432 InitBuiltinType(SingletonId, BuiltinType::Id);
1433#include "clang/Basic/AArch64SVEACLETypes.def"
1434 }
1435
1436 if (Target.getTriple().isPPC64() &&
1437 Target.hasFeature("paired-vector-memops")) {
1438 if (Target.hasFeature("mma")) {
1439#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1440 InitBuiltinType(Id##Ty, BuiltinType::Id);
1441#include "clang/Basic/PPCTypes.def"
1442 }
1443#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1444 InitBuiltinType(Id##Ty, BuiltinType::Id);
1445#include "clang/Basic/PPCTypes.def"
1446 }
1447
1448 if (Target.hasRISCVVTypes()) {
1449#define RVV_TYPE(Name, Id, SingletonId) \
1450 InitBuiltinType(SingletonId, BuiltinType::Id);
1451#include "clang/Basic/RISCVVTypes.def"
1452 }
1453
1454 // Builtin type for __objc_yes and __objc_no
1455 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1456 SignedCharTy : BoolTy);
1457
1458 ObjCConstantStringType = QualType();
1459
1460 ObjCSuperType = QualType();
1461
1462 // void * type
1463 if (LangOpts.OpenCLGenericAddressSpace) {
1464 auto Q = VoidTy.getQualifiers();
1465 Q.setAddressSpace(LangAS::opencl_generic);
1466 VoidPtrTy = getPointerType(getCanonicalType(
1467 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1468 } else {
1469 VoidPtrTy = getPointerType(VoidTy);
1470 }
1471
1472 // nullptr type (C++0x 2.14.7)
1473 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1474
1475 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1476 InitBuiltinType(HalfTy, BuiltinType::Half);
1477
1478 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1479
1480 // Builtin type used to help define __builtin_va_list.
1481 VaListTagDecl = nullptr;
1482
1483 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1484 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1485 MSGuidTagDecl = buildImplicitRecord("_GUID");
1486 TUDecl->addDecl(MSGuidTagDecl);
1487 }
1488}
1489
1490DiagnosticsEngine &ASTContext::getDiagnostics() const {
1491 return SourceMgr.getDiagnostics();
1492}
1493
1494AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1495 AttrVec *&Result = DeclAttrs[D];
1496 if (!Result) {
1497 void *Mem = Allocate(sizeof(AttrVec));
1498 Result = new (Mem) AttrVec;
1499 }
1500
1501 return *Result;
1502}
1503
1504/// Erase the attributes corresponding to the given declaration.
1505void ASTContext::eraseDeclAttrs(const Decl *D) {
1506 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1507 if (Pos != DeclAttrs.end()) {
1508 Pos->second->~AttrVec();
1509 DeclAttrs.erase(Pos);
1510 }
1511}
1512
1513// FIXME: Remove ?
1514MemberSpecializationInfo *
1515ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1516 assert(Var->isStaticDataMember() && "Not a static data member");
1517 return getTemplateOrSpecializationInfo(Var)
1518 .dyn_cast<MemberSpecializationInfo *>();
1519}
1520
1521ASTContext::TemplateOrSpecializationInfo
1522ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1523 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1524 TemplateOrInstantiation.find(Var);
1525 if (Pos == TemplateOrInstantiation.end())
1526 return {};
1527
1528 return Pos->second;
1529}
1530
1531void
1532ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1533 TemplateSpecializationKind TSK,
1534 SourceLocation PointOfInstantiation) {
1535 assert(Inst->isStaticDataMember() && "Not a static data member");
1536 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1537 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1538 Tmpl, TSK, PointOfInstantiation));
1539}
1540
1541void
1542ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1543 TemplateOrSpecializationInfo TSI) {
1544 assert(!TemplateOrInstantiation[Inst] &&
1545 "Already noted what the variable was instantiated from");
1546 TemplateOrInstantiation[Inst] = TSI;
1547}
1548
1549NamedDecl *
1550ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1551 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1552 if (Pos == InstantiatedFromUsingDecl.end())
1553 return nullptr;
1554
1555 return Pos->second;
1556}
1557
1558void
1559ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1560 assert((isa<UsingDecl>(Pattern) ||
1561 isa<UnresolvedUsingValueDecl>(Pattern) ||
1562 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1563 "pattern decl is not a using decl");
1564 assert((isa<UsingDecl>(Inst) ||
1565 isa<UnresolvedUsingValueDecl>(Inst) ||
1566 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1567 "instantiation did not produce a using decl");
1568 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1569 InstantiatedFromUsingDecl[Inst] = Pattern;
1570}
1571
1572UsingShadowDecl *
1573ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1574 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1575 = InstantiatedFromUsingShadowDecl.find(Inst);
1576 if (Pos == InstantiatedFromUsingShadowDecl.end())
1577 return nullptr;
1578
1579 return Pos->second;
1580}
1581
1582void
1583ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1584 UsingShadowDecl *Pattern) {
1585 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1586 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1587}
1588
1589FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1590 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1591 = InstantiatedFromUnnamedFieldDecl.find(Field);
1592 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1593 return nullptr;
1594
1595 return Pos->second;
1596}
1597
1598void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1599 FieldDecl *Tmpl) {
1600 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1601 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1602 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1603 "Already noted what unnamed field was instantiated from");
1604
1605 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1606}
1607
1608ASTContext::overridden_cxx_method_iterator
1609ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1610 return overridden_methods(Method).begin();
1611}
1612
1613ASTContext::overridden_cxx_method_iterator
1614ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1615 return overridden_methods(Method).end();
1616}
1617
1618unsigned
1619ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1620 auto Range = overridden_methods(Method);
1621 return Range.end() - Range.begin();
1622}
1623
1624ASTContext::overridden_method_range
1625ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1626 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1627 OverriddenMethods.find(Method->getCanonicalDecl());
1628 if (Pos == OverriddenMethods.end())
1629 return overridden_method_range(nullptr, nullptr);
1630 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1631}
1632
1633void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1634 const CXXMethodDecl *Overridden) {
1635 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1636 OverriddenMethods[Method].push_back(Overridden);
1637}
1638
1639void ASTContext::getOverriddenMethods(
1640 const NamedDecl *D,
1641 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1642 assert(D);
1643
1644 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1645 Overridden.append(overridden_methods_begin(CXXMethod),
1646 overridden_methods_end(CXXMethod));
1647 return;
1648 }
1649
1650 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1651 if (!Method)
1652 return;
1653
1654 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1655 Method->getOverriddenMethods(OverDecls);
1656 Overridden.append(OverDecls.begin(), OverDecls.end());
1657}
1658
1659void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1660 assert(!Import->getNextLocalImport() &&
1661 "Import declaration already in the chain");
1662 assert(!Import->isFromASTFile() && "Non-local import declaration");
1663 if (!FirstLocalImport) {
1664 FirstLocalImport = Import;
1665 LastLocalImport = Import;
1666 return;
1667 }
1668
1669 LastLocalImport->setNextLocalImport(Import);
1670 LastLocalImport = Import;
1671}
1672
1673//===----------------------------------------------------------------------===//
1674// Type Sizing and Analysis
1675//===----------------------------------------------------------------------===//
1676
1677/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1678/// scalar floating point type.
1679const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1680 switch (T->castAs<BuiltinType>()->getKind()) {
1681 default:
1682 llvm_unreachable("Not a floating point type!");
1683 case BuiltinType::BFloat16:
1684 return Target->getBFloat16Format();
1685 case BuiltinType::Float16:
1686 case BuiltinType::Half:
1687 return Target->getHalfFormat();
1688 case BuiltinType::Float: return Target->getFloatFormat();
1689 case BuiltinType::Double: return Target->getDoubleFormat();
1690 case BuiltinType::LongDouble:
1691 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1692 return AuxTarget->getLongDoubleFormat();
1693 return Target->getLongDoubleFormat();
1694 case BuiltinType::Float128:
1695 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1696 return AuxTarget->getFloat128Format();
1697 return Target->getFloat128Format();
1698 }
1699}
1700
1701CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1702 unsigned Align = Target->getCharWidth();
1703
1704 bool UseAlignAttrOnly = false;
1705 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1706 Align = AlignFromAttr;
1707
1708 // __attribute__((aligned)) can increase or decrease alignment
1709 // *except* on a struct or struct member, where it only increases
1710 // alignment unless 'packed' is also specified.
1711 //
1712 // It is an error for alignas to decrease alignment, so we can
1713 // ignore that possibility; Sema should diagnose it.
1714 if (isa<FieldDecl>(D)) {
1715 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1716 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1717 } else {
1718 UseAlignAttrOnly = true;
1719 }
1720 }
1721 else if (isa<FieldDecl>(D))
1722 UseAlignAttrOnly =
1723 D->hasAttr<PackedAttr>() ||
1724 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1725
1726 // If we're using the align attribute only, just ignore everything
1727 // else about the declaration and its type.
1728 if (UseAlignAttrOnly) {
1729 // do nothing
1730 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1731 QualType T = VD->getType();
1732 if (const auto *RT = T->getAs<ReferenceType>()) {
1733 if (ForAlignof)
1734 T = RT->getPointeeType();
1735 else
1736 T = getPointerType(RT->getPointeeType());
1737 }
1738 QualType BaseT = getBaseElementType(T);
1739 if (T->isFunctionType())
1740 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1741 else if (!BaseT->isIncompleteType()) {
1742 // Adjust alignments of declarations with array type by the
1743 // large-array alignment on the target.
1744 if (const ArrayType *arrayType = getAsArrayType(T)) {
1745 unsigned MinWidth = Target->getLargeArrayMinWidth();
1746 if (!ForAlignof && MinWidth) {
1747 if (isa<VariableArrayType>(arrayType))
1748 Align = std::max(Align, Target->getLargeArrayAlign());
1749 else if (isa<ConstantArrayType>(arrayType) &&
1750 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1751 Align = std::max(Align, Target->getLargeArrayAlign());
1752 }
1753 }
1754 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1755 if (BaseT.getQualifiers().hasUnaligned())
1756 Align = Target->getCharWidth();
1757 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1758 if (VD->hasGlobalStorage() && !ForAlignof) {
1759 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1760 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1761 }
1762 }
1763 }
1764
1765 // Fields can be subject to extra alignment constraints, like if
1766 // the field is packed, the struct is packed, or the struct has a
1767 // a max-field-alignment constraint (#pragma pack). So calculate
1768 // the actual alignment of the field within the struct, and then
1769 // (as we're expected to) constrain that by the alignment of the type.
1770 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1771 const RecordDecl *Parent = Field->getParent();
1772 // We can only produce a sensible answer if the record is valid.
1773 if (!Parent->isInvalidDecl()) {
1774 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1775
1776 // Start with the record's overall alignment.
1777 unsigned FieldAlign = toBits(Layout.getAlignment());
1778
1779 // Use the GCD of that and the offset within the record.
1780 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1781 if (Offset > 0) {
1782 // Alignment is always a power of 2, so the GCD will be a power of 2,
1783 // which means we get to do this crazy thing instead of Euclid's.
1784 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1785 if (LowBitOfOffset < FieldAlign)
1786 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1787 }
1788
1789 Align = std::min(Align, FieldAlign);
1790 }
1791 }
1792 }
1793
1794 // Some targets have hard limitation on the maximum requestable alignment in
1795 // aligned attribute for static variables.
1796 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1797 const auto *VD = dyn_cast<VarDecl>(D);
1798 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1799 Align = std::min(Align, MaxAlignedAttr);
1800
1801 return toCharUnitsFromBits(Align);
1802}
1803
1804CharUnits ASTContext::getExnObjectAlignment() const {
1805 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1806}
1807
1808// getTypeInfoDataSizeInChars - Return the size of a type, in
1809// chars. If the type is a record, its data size is returned. This is
1810// the size of the memcpy that's performed when assigning this type
1811// using a trivial copy/move assignment operator.
1812TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1813 TypeInfoChars Info = getTypeInfoInChars(T);
1814
1815 // In C++, objects can sometimes be allocated into the tail padding
1816 // of a base-class subobject. We decide whether that's possible
1817 // during class layout, so here we can just trust the layout results.
1818 if (getLangOpts().CPlusPlus) {
1819 if (const auto *RT = T->getAs<RecordType>()) {
1820 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1821 Info.Width = layout.getDataSize();
1822 }
1823 }
1824
1825 return Info;
1826}
1827
1828/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1829/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1830TypeInfoChars
1831static getConstantArrayInfoInChars(const ASTContext &Context,
1832 const ConstantArrayType *CAT) {
1833 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1834 uint64_t Size = CAT->getSize().getZExtValue();
1835 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1836 (uint64_t)(-1)/Size) &&
1837 "Overflow in array type char size evaluation");
1838 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1839 unsigned Align = EltInfo.Align.getQuantity();
1840 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1841 Context.getTargetInfo().getPointerWidth(0) == 64)
1842 Width = llvm::alignTo(Width, Align);
1843 return TypeInfoChars(CharUnits::fromQuantity(Width),
1844 CharUnits::fromQuantity(Align),
1845 EltInfo.AlignIsRequired);
1846}
1847
1848TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1849 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1850 return getConstantArrayInfoInChars(*this, CAT);
1851 TypeInfo Info = getTypeInfo(T);
1852 return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1853 toCharUnitsFromBits(Info.Align),
1854 Info.AlignIsRequired);
1855}
1856
1857TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1858 return getTypeInfoInChars(T.getTypePtr());
1859}
1860
1861bool ASTContext::isAlignmentRequired(const Type *T) const {
1862 return getTypeInfo(T).AlignIsRequired;
1863}
1864
1865bool ASTContext::isAlignmentRequired(QualType T) const {
1866 return isAlignmentRequired(T.getTypePtr());
1867}
1868
1869unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1870 bool NeedsPreferredAlignment) const {
1871 // An alignment on a typedef overrides anything else.
1872 if (const auto *TT = T->getAs<TypedefType>())
1873 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1874 return Align;
1875
1876 // If we have an (array of) complete type, we're done.
1877 T = getBaseElementType(T);
1878 if (!T->isIncompleteType())
1879 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1880
1881 // If we had an array type, its element type might be a typedef
1882 // type with an alignment attribute.
1883 if (const auto *TT = T->getAs<TypedefType>())
1884 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1885 return Align;
1886
1887 // Otherwise, see if the declaration of the type had an attribute.
1888 if (const auto *TT = T->getAs<TagType>())
1889 return TT->getDecl()->getMaxAlignment();
1890
1891 return 0;
1892}
1893
1894TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1895 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1896 if (I != MemoizedTypeInfo.end())
1897 return I->second;
1898
1899 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1900 TypeInfo TI = getTypeInfoImpl(T);
1901 MemoizedTypeInfo[T] = TI;
1902 return TI;
1903}
1904
1905/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1906/// method does not work on incomplete types.
1907///
1908/// FIXME: Pointers into different addr spaces could have different sizes and
1909/// alignment requirements: getPointerInfo should take an AddrSpace, this
1910/// should take a QualType, &c.
1911TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1912 uint64_t Width = 0;
1913 unsigned Align = 8;
1914 bool AlignIsRequired = false;
1915 unsigned AS = 0;
1916 switch (T->getTypeClass()) {
1917#define TYPE(Class, Base)
1918#define ABSTRACT_TYPE(Class, Base)
1919#define NON_CANONICAL_TYPE(Class, Base)
1920#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1921#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1922 case Type::Class: \
1923 assert(!T->isDependentType() && "should not see dependent types here"); \
1924 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1925#include "clang/AST/TypeNodes.inc"
1926 llvm_unreachable("Should not see dependent types");
1927
1928 case Type::FunctionNoProto:
1929 case Type::FunctionProto:
1930 // GCC extension: alignof(function) = 32 bits
1931 Width = 0;
1932 Align = 32;
1933 break;
1934
1935 case Type::IncompleteArray:
1936 case Type::VariableArray:
1937 case Type::ConstantArray: {
1938 // Model non-constant sized arrays as size zero, but track the alignment.
1939 uint64_t Size = 0;
1940 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1941 Size = CAT->getSize().getZExtValue();
1942
1943 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1944 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1945 "Overflow in array type bit size evaluation");
1946 Width = EltInfo.Width * Size;
1947 Align = EltInfo.Align;
1948 AlignIsRequired = EltInfo.AlignIsRequired;
1949 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1950 getTargetInfo().getPointerWidth(0) == 64)
1951 Width = llvm::alignTo(Width, Align);
1952 break;
1953 }
1954
1955 case Type::ExtVector:
1956 case Type::Vector: {
1957 const auto *VT = cast<VectorType>(T);
1958 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1959 Width = EltInfo.Width * VT->getNumElements();
1960 Align = Width;
1961 // If the alignment is not a power of 2, round up to the next power of 2.
1962 // This happens for non-power-of-2 length vectors.
1963 if (Align & (Align-1)) {
1964 Align = llvm::NextPowerOf2(Align);
1965 Width = llvm::alignTo(Width, Align);
1966 }
1967 // Adjust the alignment based on the target max.
1968 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1969 if (TargetVectorAlign && TargetVectorAlign < Align)
1970 Align = TargetVectorAlign;
1971 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
1972 // Adjust the alignment for fixed-length SVE vectors. This is important
1973 // for non-power-of-2 vector lengths.
1974 Align = 128;
1975 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
1976 // Adjust the alignment for fixed-length SVE predicates.
1977 Align = 16;
1978 break;
1979 }
1980
1981 case Type::ConstantMatrix: {
1982 const auto *MT = cast<ConstantMatrixType>(T);
1983 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1984 // The internal layout of a matrix value is implementation defined.
1985 // Initially be ABI compatible with arrays with respect to alignment and
1986 // size.
1987 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1988 Align = ElementInfo.Align;
1989 break;
1990 }
1991
1992 case Type::Builtin:
1993 switch (cast<BuiltinType>(T)->getKind()) {
1994 default: llvm_unreachable("Unknown builtin type!");
1995 case BuiltinType::Void:
1996 // GCC extension: alignof(void) = 8 bits.
1997 Width = 0;
1998 Align = 8;
1999 break;
2000 case BuiltinType::Bool:
2001 Width = Target->getBoolWidth();
2002 Align = Target->getBoolAlign();
2003 break;
2004 case BuiltinType::Char_S:
2005 case BuiltinType::Char_U:
2006 case BuiltinType::UChar:
2007 case BuiltinType::SChar:
2008 case BuiltinType::Char8:
2009 Width = Target->getCharWidth();
2010 Align = Target->getCharAlign();
2011 break;
2012 case BuiltinType::WChar_S:
2013 case BuiltinType::WChar_U:
2014 Width = Target->getWCharWidth();
2015 Align = Target->getWCharAlign();
2016 break;
2017 case BuiltinType::Char16:
2018 Width = Target->getChar16Width();
2019 Align = Target->getChar16Align();
2020 break;
2021 case BuiltinType::Char32:
2022 Width = Target->getChar32Width();
2023 Align = Target->getChar32Align();
2024 break;
2025 case BuiltinType::UShort:
2026 case BuiltinType::Short:
2027 Width = Target->getShortWidth();
2028 Align = Target->getShortAlign();
2029 break;
2030 case BuiltinType::UInt:
2031 case BuiltinType::Int:
2032 Width = Target->getIntWidth();
2033 Align = Target->getIntAlign();
2034 break;
2035 case BuiltinType::ULong:
2036 case BuiltinType::Long:
2037 Width = Target->getLongWidth();
2038 Align = Target->getLongAlign();
2039 break;
2040 case BuiltinType::ULongLong:
2041 case BuiltinType::LongLong:
2042 Width = Target->getLongLongWidth();
2043 Align = Target->getLongLongAlign();
2044 break;
2045 case BuiltinType::Int128:
2046 case BuiltinType::UInt128:
2047 Width = 128;
2048 Align = 128; // int128_t is 128-bit aligned on all targets.
2049 break;
2050 case BuiltinType::ShortAccum:
2051 case BuiltinType::UShortAccum:
2052 case BuiltinType::SatShortAccum:
2053 case BuiltinType::SatUShortAccum:
2054 Width = Target->getShortAccumWidth();
2055 Align = Target->getShortAccumAlign();
2056 break;
2057 case BuiltinType::Accum:
2058 case BuiltinType::UAccum:
2059 case BuiltinType::SatAccum:
2060 case BuiltinType::SatUAccum:
2061 Width = Target->getAccumWidth();
2062 Align = Target->getAccumAlign();
2063 break;
2064 case BuiltinType::LongAccum:
2065 case BuiltinType::ULongAccum:
2066 case BuiltinType::SatLongAccum:
2067 case BuiltinType::SatULongAccum:
2068 Width = Target->getLongAccumWidth();
2069 Align = Target->getLongAccumAlign();
2070 break;
2071 case BuiltinType::ShortFract:
2072 case BuiltinType::UShortFract:
2073 case BuiltinType::SatShortFract:
2074 case BuiltinType::SatUShortFract:
2075 Width = Target->getShortFractWidth();
2076 Align = Target->getShortFractAlign();
2077 break;
2078 case BuiltinType::Fract:
2079 case BuiltinType::UFract:
2080 case BuiltinType::SatFract:
2081 case BuiltinType::SatUFract:
2082 Width = Target->getFractWidth();
2083 Align = Target->getFractAlign();
2084 break;
2085 case BuiltinType::LongFract:
2086 case BuiltinType::ULongFract:
2087 case BuiltinType::SatLongFract:
2088 case BuiltinType::SatULongFract:
2089 Width = Target->getLongFractWidth();
2090 Align = Target->getLongFractAlign();
2091 break;
2092 case BuiltinType::BFloat16:
2093 Width = Target->getBFloat16Width();
2094 Align = Target->getBFloat16Align();
2095 break;
2096 case BuiltinType::Float16:
2097 case BuiltinType::Half:
2098 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2099 !getLangOpts().OpenMPIsDevice) {
2100 Width = Target->getHalfWidth();
2101 Align = Target->getHalfAlign();
2102 } else {
2103 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2104 "Expected OpenMP device compilation.");
2105 Width = AuxTarget->getHalfWidth();
2106 Align = AuxTarget->getHalfAlign();
2107 }
2108 break;
2109 case BuiltinType::Float:
2110 Width = Target->getFloatWidth();
2111 Align = Target->getFloatAlign();
2112 break;
2113 case BuiltinType::Double:
2114 Width = Target->getDoubleWidth();
2115 Align = Target->getDoubleAlign();
2116 break;
2117 case BuiltinType::LongDouble:
2118 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2119 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2120 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2121 Width = AuxTarget->getLongDoubleWidth();
2122 Align = AuxTarget->getLongDoubleAlign();
2123 } else {
2124 Width = Target->getLongDoubleWidth();
2125 Align = Target->getLongDoubleAlign();
2126 }
2127 break;
2128 case BuiltinType::Float128:
2129 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2130 !getLangOpts().OpenMPIsDevice) {
2131 Width = Target->getFloat128Width();
2132 Align = Target->getFloat128Align();
2133 } else {
2134 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2135 "Expected OpenMP device compilation.");
2136 Width = AuxTarget->getFloat128Width();
2137 Align = AuxTarget->getFloat128Align();
2138 }
2139 break;
2140 case BuiltinType::NullPtr:
2141 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2142 Align = Target->getPointerAlign(0); // == sizeof(void*)
2143 break;
2144 case BuiltinType::ObjCId:
2145 case BuiltinType::ObjCClass:
2146 case BuiltinType::ObjCSel:
2147 Width = Target->getPointerWidth(0);
2148 Align = Target->getPointerAlign(0);
2149 break;
2150 case BuiltinType::OCLSampler:
2151 case BuiltinType::OCLEvent:
2152 case BuiltinType::OCLClkEvent:
2153 case BuiltinType::OCLQueue:
2154 case BuiltinType::OCLReserveID:
2155#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2156 case BuiltinType::Id:
2157#include "clang/Basic/OpenCLImageTypes.def"
2158#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2159 case BuiltinType::Id:
2160#include "clang/Basic/OpenCLExtensionTypes.def"
2161 AS = getTargetAddressSpace(
2162 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2163 Width = Target->getPointerWidth(AS);
2164 Align = Target->getPointerAlign(AS);
2165 break;
2166 // The SVE types are effectively target-specific. The length of an
2167 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2168 // of 128 bits. There is one predicate bit for each vector byte, so the
2169 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2170 //
2171 // Because the length is only known at runtime, we use a dummy value
2172 // of 0 for the static length. The alignment values are those defined
2173 // by the Procedure Call Standard for the Arm Architecture.
2174#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2175 IsSigned, IsFP, IsBF) \
2176 case BuiltinType::Id: \
2177 Width = 0; \
2178 Align = 128; \
2179 break;
2180#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2181 case BuiltinType::Id: \
2182 Width = 0; \
2183 Align = 16; \
2184 break;
2185#include "clang/Basic/AArch64SVEACLETypes.def"
2186#define PPC_VECTOR_TYPE(Name, Id, Size) \
2187 case BuiltinType::Id: \
2188 Width = Size; \
2189 Align = Size; \
2190 break;
2191#include "clang/Basic/PPCTypes.def"
2192#define