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