clang 19.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"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/Triple.h"
91#include <algorithm>
92#include <cassert>
93#include <cstddef>
94#include <cstdint>
95#include <cstdlib>
96#include <map>
97#include <memory>
98#include <optional>
99#include <string>
100#include <tuple>
101#include <utility>
102
103using namespace clang;
104
115
116/// \returns The locations that are relevant when searching for Doc comments
117/// related to \p D.
120 assert(D);
121
122 // User can not attach documentation to implicit declarations.
123 if (D->isImplicit())
124 return {};
125
126 // User can not attach documentation to implicit instantiations.
127 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
128 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
129 return {};
130 }
131
132 if (const auto *VD = dyn_cast<VarDecl>(D)) {
133 if (VD->isStaticDataMember() &&
134 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
135 return {};
136 }
137
138 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
139 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
140 return {};
141 }
142
143 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
144 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
145 if (TSK == TSK_ImplicitInstantiation ||
146 TSK == TSK_Undeclared)
147 return {};
148 }
149
150 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
151 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152 return {};
153 }
154 if (const auto *TD = dyn_cast<TagDecl>(D)) {
155 // When tag declaration (but not definition!) is part of the
156 // decl-specifier-seq of some other declaration, it doesn't get comment
157 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
158 return {};
159 }
160 // TODO: handle comments for function parameters properly.
161 if (isa<ParmVarDecl>(D))
162 return {};
163
164 // TODO: we could look up template parameter documentation in the template
165 // documentation.
166 if (isa<TemplateTypeParmDecl>(D) ||
167 isa<NonTypeTemplateParmDecl>(D) ||
168 isa<TemplateTemplateParmDecl>(D))
169 return {};
170
172 // Find declaration location.
173 // For Objective-C declarations we generally don't expect to have multiple
174 // declarators, thus use declaration starting location as the "declaration
175 // location".
176 // For all other declarations multiple declarators are used quite frequently,
177 // so we use the location of the identifier as the "declaration location".
178 SourceLocation BaseLocation;
179 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
180 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
181 isa<ClassTemplateSpecializationDecl>(D) ||
182 // Allow association with Y across {} in `typedef struct X {} Y`.
183 isa<TypedefDecl>(D))
184 BaseLocation = D->getBeginLoc();
185 else
186 BaseLocation = D->getLocation();
187
188 if (!D->getLocation().isMacroID()) {
189 Locations.emplace_back(BaseLocation);
190 } else {
191 const auto *DeclCtx = D->getDeclContext();
192
193 // When encountering definitions generated from a macro (that are not
194 // contained by another declaration in the macro) we need to try and find
195 // the comment at the location of the expansion but if there is no comment
196 // there we should retry to see if there is a comment inside the macro as
197 // well. To this end we return first BaseLocation to first look at the
198 // expansion site, the second value is the spelling location of the
199 // beginning of the declaration defined inside the macro.
200 if (!(DeclCtx &&
201 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
202 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
203 }
204
205 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
206 // we don't refer to the macro argument location at the expansion site (this
207 // can happen if the name's spelling is provided via macro argument), and
208 // always to the declaration itself.
209 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
210 }
211
212 return Locations;
213}
214
216 const Decl *D, const SourceLocation RepresentativeLocForDecl,
217 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
218 // If the declaration doesn't map directly to a location in a file, we
219 // can't find the comment.
220 if (RepresentativeLocForDecl.isInvalid() ||
221 !RepresentativeLocForDecl.isFileID())
222 return nullptr;
223
224 // If there are no comments anywhere, we won't find anything.
225 if (CommentsInTheFile.empty())
226 return nullptr;
227
228 // Decompose the location for the declaration and find the beginning of the
229 // file buffer.
230 const std::pair<FileID, unsigned> DeclLocDecomp =
231 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
232
233 // Slow path.
234 auto OffsetCommentBehindDecl =
235 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
236
237 // First check whether we have a trailing comment.
238 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
239 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
240 if ((CommentBehindDecl->isDocumentation() ||
241 LangOpts.CommentOpts.ParseAllComments) &&
242 CommentBehindDecl->isTrailingComment() &&
243 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
244 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
245
246 // Check that Doxygen trailing comment comes after the declaration, starts
247 // on the same line and in the same file as the declaration.
248 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
249 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
250 OffsetCommentBehindDecl->first)) {
251 return CommentBehindDecl;
252 }
253 }
254 }
255
256 // The comment just after the declaration was not a trailing comment.
257 // Let's look at the previous comment.
258 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
259 return nullptr;
260
261 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
262 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
263
264 // Check that we actually have a non-member Doxygen comment.
265 if (!(CommentBeforeDecl->isDocumentation() ||
266 LangOpts.CommentOpts.ParseAllComments) ||
267 CommentBeforeDecl->isTrailingComment())
268 return nullptr;
269
270 // Decompose the end of the comment.
271 const unsigned CommentEndOffset =
272 Comments.getCommentEndOffset(CommentBeforeDecl);
273
274 // Get the corresponding buffer.
275 bool Invalid = false;
276 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
277 &Invalid).data();
278 if (Invalid)
279 return nullptr;
280
281 // Extract text between the comment and declaration.
282 StringRef Text(Buffer + CommentEndOffset,
283 DeclLocDecomp.second - CommentEndOffset);
284
285 // There should be no other declarations or preprocessor directives between
286 // comment and declaration.
287 if (Text.find_last_of(";{}#@") != StringRef::npos)
288 return nullptr;
289
290 return CommentBeforeDecl;
291}
292
294 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
295
296 for (const auto DeclLoc : DeclLocs) {
297 // If the declaration doesn't map directly to a location in a file, we
298 // can't find the comment.
299 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
300 continue;
301
304 CommentsLoaded = true;
305 }
306
307 if (Comments.empty())
308 continue;
309
310 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
311 if (!File.isValid())
312 continue;
313
314 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
315 if (!CommentsInThisFile || CommentsInThisFile->empty())
316 continue;
317
318 if (RawComment *Comment =
319 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
320 return Comment;
321 }
322
323 return nullptr;
324}
325
327 assert(LangOpts.RetainCommentsFromSystemHeaders ||
328 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
329 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
330}
331
332/// If we have a 'templated' declaration for a template, adjust 'D' to
333/// refer to the actual template.
334/// If we have an implicit instantiation, adjust 'D' to refer to template.
335static const Decl &adjustDeclToTemplate(const Decl &D) {
336 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
337 // Is this function declaration part of a function template?
338 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
339 return *FTD;
340
341 // Nothing to do if function is not an implicit instantiation.
342 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
343 return D;
344
345 // Function is an implicit instantiation of a function template?
346 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
347 return *FTD;
348
349 // Function is instantiated from a member definition of a class template?
350 if (const FunctionDecl *MemberDecl =
352 return *MemberDecl;
353
354 return D;
355 }
356 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
357 // Static data member is instantiated from a member definition of a class
358 // template?
359 if (VD->isStaticDataMember())
360 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
361 return *MemberDecl;
362
363 return D;
364 }
365 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
366 // Is this class declaration part of a class template?
367 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
368 return *CTD;
369
370 // Class is an implicit instantiation of a class template or partial
371 // specialization?
372 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
373 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
374 return D;
375 llvm::PointerUnion<ClassTemplateDecl *,
378 return PU.is<ClassTemplateDecl *>()
379 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
380 : *static_cast<const Decl *>(
382 }
383
384 // Class is instantiated from a member definition of a class template?
385 if (const MemberSpecializationInfo *Info =
386 CRD->getMemberSpecializationInfo())
387 return *Info->getInstantiatedFrom();
388
389 return D;
390 }
391 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
392 // Enum is instantiated from a member definition of a class template?
393 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
394 return *MemberDecl;
395
396 return D;
397 }
398 // FIXME: Adjust alias templates?
399 return D;
400}
401
403 const Decl *D,
404 const Decl **OriginalDecl) const {
405 if (!D) {
406 if (OriginalDecl)
407 OriginalDecl = nullptr;
408 return nullptr;
409 }
410
411 D = &adjustDeclToTemplate(*D);
412
413 // Any comment directly attached to D?
414 {
415 auto DeclComment = DeclRawComments.find(D);
416 if (DeclComment != DeclRawComments.end()) {
417 if (OriginalDecl)
418 *OriginalDecl = D;
419 return DeclComment->second;
420 }
421 }
422
423 // Any comment attached to any redeclaration of D?
424 const Decl *CanonicalD = D->getCanonicalDecl();
425 if (!CanonicalD)
426 return nullptr;
427
428 {
429 auto RedeclComment = RedeclChainComments.find(CanonicalD);
430 if (RedeclComment != RedeclChainComments.end()) {
431 if (OriginalDecl)
432 *OriginalDecl = RedeclComment->second;
433 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
434 assert(CommentAtRedecl != DeclRawComments.end() &&
435 "This decl is supposed to have comment attached.");
436 return CommentAtRedecl->second;
437 }
438 }
439
440 // Any redeclarations of D that we haven't checked for comments yet?
441 // We can't use DenseMap::iterator directly since it'd get invalid.
442 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
443 return CommentlessRedeclChains.lookup(CanonicalD);
444 }();
445
446 for (const auto Redecl : D->redecls()) {
447 assert(Redecl);
448 // Skip all redeclarations that have been checked previously.
449 if (LastCheckedRedecl) {
450 if (LastCheckedRedecl == Redecl) {
451 LastCheckedRedecl = nullptr;
452 }
453 continue;
454 }
455 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
456 if (RedeclComment) {
457 cacheRawCommentForDecl(*Redecl, *RedeclComment);
458 if (OriginalDecl)
459 *OriginalDecl = Redecl;
460 return RedeclComment;
461 }
462 CommentlessRedeclChains[CanonicalD] = Redecl;
463 }
464
465 if (OriginalDecl)
466 *OriginalDecl = nullptr;
467 return nullptr;
468}
469
471 const RawComment &Comment) const {
472 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
473 DeclRawComments.try_emplace(&OriginalD, &Comment);
474 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
475 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
476 CommentlessRedeclChains.erase(CanonicalDecl);
477}
478
479static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
481 const DeclContext *DC = ObjCMethod->getDeclContext();
482 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
483 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
484 if (!ID)
485 return;
486 // Add redeclared method here.
487 for (const auto *Ext : ID->known_extensions()) {
488 if (ObjCMethodDecl *RedeclaredMethod =
489 Ext->getMethod(ObjCMethod->getSelector(),
490 ObjCMethod->isInstanceMethod()))
491 Redeclared.push_back(RedeclaredMethod);
492 }
493 }
494}
495
497 const Preprocessor *PP) {
498 if (Comments.empty() || Decls.empty())
499 return;
500
501 FileID File;
502 for (const Decl *D : Decls) {
503 if (D->isInvalidDecl())
504 continue;
505
506 D = &adjustDeclToTemplate(*D);
507 SourceLocation Loc = D->getLocation();
508 if (Loc.isValid()) {
509 // See if there are any new comments that are not attached to a decl.
510 // The location doesn't have to be precise - we care only about the file.
511 File = SourceMgr.getDecomposedLoc(Loc).first;
512 break;
513 }
514 }
515
516 if (File.isInvalid())
517 return;
518
519 auto CommentsInThisFile = Comments.getCommentsInFile(File);
520 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
521 CommentsInThisFile->rbegin()->second->isAttached())
522 return;
523
524 // There is at least one comment not attached to a decl.
525 // Maybe it should be attached to one of Decls?
526 //
527 // Note that this way we pick up not only comments that precede the
528 // declaration, but also comments that *follow* the declaration -- thanks to
529 // the lookahead in the lexer: we've consumed the semicolon and looked
530 // ahead through comments.
531 for (const Decl *D : Decls) {
532 assert(D);
533 if (D->isInvalidDecl())
534 continue;
535
536 D = &adjustDeclToTemplate(*D);
537
538 if (DeclRawComments.count(D) > 0)
539 continue;
540
541 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
542
543 for (const auto DeclLoc : DeclLocs) {
544 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
545 continue;
546
547 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
548 D, DeclLoc, *CommentsInThisFile)) {
549 cacheRawCommentForDecl(*D, *DocComment);
550 comments::FullComment *FC = DocComment->parse(*this, PP, D);
551 ParsedComments[D->getCanonicalDecl()] = FC;
552 break;
553 }
554 }
555 }
556}
557
559 const Decl *D) const {
560 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
561 ThisDeclInfo->CommentDecl = D;
562 ThisDeclInfo->IsFilled = false;
563 ThisDeclInfo->fill();
564 ThisDeclInfo->CommentDecl = FC->getDecl();
565 if (!ThisDeclInfo->TemplateParameters)
566 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
568 new (*this) comments::FullComment(FC->getBlocks(),
569 ThisDeclInfo);
570 return CFC;
571}
572
575 return RC ? RC->parse(*this, nullptr, D) : nullptr;
576}
577
579 const Decl *D,
580 const Preprocessor *PP) const {
581 if (!D || D->isInvalidDecl())
582 return nullptr;
583 D = &adjustDeclToTemplate(*D);
584
585 const Decl *Canonical = D->getCanonicalDecl();
586 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
587 ParsedComments.find(Canonical);
588
589 if (Pos != ParsedComments.end()) {
590 if (Canonical != D) {
591 comments::FullComment *FC = Pos->second;
593 return CFC;
594 }
595 return Pos->second;
596 }
597
598 const Decl *OriginalDecl = nullptr;
599
600 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
601 if (!RC) {
602 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
604 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
605 if (OMD && OMD->isPropertyAccessor())
606 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
607 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
608 return cloneFullComment(FC, D);
609 if (OMD)
610 addRedeclaredMethods(OMD, Overridden);
611 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
612 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
613 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
614 return cloneFullComment(FC, D);
615 }
616 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
617 // Attach any tag type's documentation to its typedef if latter
618 // does not have one of its own.
619 QualType QT = TD->getUnderlyingType();
620 if (const auto *TT = QT->getAs<TagType>())
621 if (const Decl *TD = TT->getDecl())
623 return cloneFullComment(FC, D);
624 }
625 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
626 while (IC->getSuperClass()) {
627 IC = IC->getSuperClass();
629 return cloneFullComment(FC, D);
630 }
631 }
632 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
633 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
635 return cloneFullComment(FC, D);
636 }
637 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
638 if (!(RD = RD->getDefinition()))
639 return nullptr;
640 // Check non-virtual bases.
641 for (const auto &I : RD->bases()) {
642 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
643 continue;
644 QualType Ty = I.getType();
645 if (Ty.isNull())
646 continue;
648 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
649 continue;
650
652 return cloneFullComment(FC, D);
653 }
654 }
655 // Check virtual bases.
656 for (const auto &I : RD->vbases()) {
657 if (I.getAccessSpecifier() != AS_public)
658 continue;
659 QualType Ty = I.getType();
660 if (Ty.isNull())
661 continue;
662 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
663 if (!(VirtualBase= VirtualBase->getDefinition()))
664 continue;
666 return cloneFullComment(FC, D);
667 }
668 }
669 }
670 return nullptr;
671 }
672
673 // If the RawComment was attached to other redeclaration of this Decl, we
674 // should parse the comment in context of that other Decl. This is important
675 // because comments can contain references to parameter names which can be
676 // different across redeclarations.
677 if (D != OriginalDecl && OriginalDecl)
678 return getCommentForDecl(OriginalDecl, PP);
679
680 comments::FullComment *FC = RC->parse(*this, PP, D);
681 ParsedComments[Canonical] = FC;
682 return FC;
683}
684
685void
686ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
687 const ASTContext &C,
689 ID.AddInteger(Parm->getDepth());
690 ID.AddInteger(Parm->getPosition());
691 ID.AddBoolean(Parm->isParameterPack());
692
694 ID.AddInteger(Params->size());
696 PEnd = Params->end();
697 P != PEnd; ++P) {
698 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
699 ID.AddInteger(0);
700 ID.AddBoolean(TTP->isParameterPack());
701 if (TTP->isExpandedParameterPack()) {
702 ID.AddBoolean(true);
703 ID.AddInteger(TTP->getNumExpansionParameters());
704 } else
705 ID.AddBoolean(false);
706 continue;
707 }
708
709 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
710 ID.AddInteger(1);
711 ID.AddBoolean(NTTP->isParameterPack());
712 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
713 .getAsOpaquePtr());
714 if (NTTP->isExpandedParameterPack()) {
715 ID.AddBoolean(true);
716 ID.AddInteger(NTTP->getNumExpansionTypes());
717 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
718 QualType T = NTTP->getExpansionType(I);
719 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
720 }
721 } else
722 ID.AddBoolean(false);
723 continue;
724 }
725
726 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
727 ID.AddInteger(2);
728 Profile(ID, C, TTP);
729 }
730}
731
733ASTContext::getCanonicalTemplateTemplateParmDecl(
734 TemplateTemplateParmDecl *TTP) const {
735 // Check if we already have a canonical template template parameter.
736 llvm::FoldingSetNodeID ID;
737 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
738 void *InsertPos = nullptr;
739 CanonicalTemplateTemplateParm *Canonical
740 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
741 if (Canonical)
742 return Canonical->getParam();
743
744 // Build a canonical template parameter list.
746 SmallVector<NamedDecl *, 4> CanonParams;
747 CanonParams.reserve(Params->size());
749 PEnd = Params->end();
750 P != PEnd; ++P) {
751 // Note that, per C++20 [temp.over.link]/6, when determining whether
752 // template-parameters are equivalent, constraints are ignored.
753 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
756 TTP->getDepth(), TTP->getIndex(), nullptr, false,
757 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
759 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
760 : std::nullopt);
761 CanonParams.push_back(NewTTP);
762 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
766 if (NTTP->isExpandedParameterPack()) {
767 SmallVector<QualType, 2> ExpandedTypes;
769 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
770 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
771 ExpandedTInfos.push_back(
772 getTrivialTypeSourceInfo(ExpandedTypes.back()));
773 }
774
778 NTTP->getDepth(),
779 NTTP->getPosition(), nullptr,
780 T,
781 TInfo,
782 ExpandedTypes,
783 ExpandedTInfos);
784 } else {
788 NTTP->getDepth(),
789 NTTP->getPosition(), nullptr,
790 T,
791 NTTP->isParameterPack(),
792 TInfo);
793 }
794 CanonParams.push_back(Param);
795 } else
796 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
797 cast<TemplateTemplateParmDecl>(*P)));
798 }
799
802 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
804 CanonParams, SourceLocation(),
805 /*RequiresClause=*/nullptr));
806
807 // Get the new insert position for the node we care about.
808 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
809 assert(!Canonical && "Shouldn't be in the map!");
810 (void)Canonical;
811
812 // Create the canonical template template parameter entry.
813 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
814 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
815 return CanonTTP;
816}
817
819 auto Kind = getTargetInfo().getCXXABI().getKind();
820 return getLangOpts().CXXABI.value_or(Kind);
821}
822
823CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
824 if (!LangOpts.CPlusPlus) return nullptr;
825
826 switch (getCXXABIKind()) {
827 case TargetCXXABI::AppleARM64:
828 case TargetCXXABI::Fuchsia:
829 case TargetCXXABI::GenericARM: // Same as Itanium at this level
830 case TargetCXXABI::iOS:
831 case TargetCXXABI::WatchOS:
832 case TargetCXXABI::GenericAArch64:
833 case TargetCXXABI::GenericMIPS:
834 case TargetCXXABI::GenericItanium:
835 case TargetCXXABI::WebAssembly:
836 case TargetCXXABI::XL:
837 return CreateItaniumCXXABI(*this);
838 case TargetCXXABI::Microsoft:
839 return CreateMicrosoftCXXABI(*this);
840 }
841 llvm_unreachable("Invalid CXXABI type!");
842}
843
845 if (!InterpContext) {
846 InterpContext.reset(new interp::Context(*this));
847 }
848 return *InterpContext.get();
849}
850
852 if (!ParentMapCtx)
853 ParentMapCtx.reset(new ParentMapContext(*this));
854 return *ParentMapCtx.get();
855}
856
858 const LangOptions &LangOpts) {
859 switch (LangOpts.getAddressSpaceMapMangling()) {
861 return TI.useAddressSpaceMapMangling();
863 return true;
865 return false;
866 }
867 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
868}
869
871 IdentifierTable &idents, SelectorTable &sels,
872 Builtin::Context &builtins, TranslationUnitKind TUKind)
873 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
874 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
875 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
876 DependentSizedMatrixTypes(this_()),
877 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
878 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
879 TemplateSpecializationTypes(this_()),
880 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
881 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
882 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
883 SourceMgr(SM), LangOpts(LOpts),
884 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
885 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
886 LangOpts.XRayNeverInstrumentFiles,
887 LangOpts.XRayAttrListFiles, SM)),
888 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
889 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
890 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
891 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
892 CompCategories(this_()), LastSDM(nullptr, 0) {
894}
895
897 // Release the DenseMaps associated with DeclContext objects.
898 // FIXME: Is this the ideal solution?
899 ReleaseDeclContextMaps();
900
901 // Call all of the deallocation functions on all of their targets.
902 for (auto &Pair : Deallocations)
903 (Pair.first)(Pair.second);
904 Deallocations.clear();
905
906 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
907 // because they can contain DenseMaps.
908 for (llvm::DenseMap<const ObjCContainerDecl*,
909 const ASTRecordLayout*>::iterator
910 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
911 // Increment in loop to prevent using deallocated memory.
912 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
913 R->Destroy(*this);
914 ObjCLayouts.clear();
915
916 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
917 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
918 // Increment in loop to prevent using deallocated memory.
919 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
920 R->Destroy(*this);
921 }
922 ASTRecordLayouts.clear();
923
924 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
925 AEnd = DeclAttrs.end();
926 A != AEnd; ++A)
927 A->second->~AttrVec();
928 DeclAttrs.clear();
929
930 for (const auto &Value : ModuleInitializers)
931 Value.second->~PerModuleInitializers();
932 ModuleInitializers.clear();
933}
934
936
937void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
938 TraversalScope = TopLevelDecls;
940}
941
942void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
943 Deallocations.push_back({Callback, Data});
944}
945
946void
948 ExternalSource = std::move(Source);
949}
950
952 llvm::errs() << "\n*** AST Context Stats:\n";
953 llvm::errs() << " " << Types.size() << " types total.\n";
954
955 unsigned counts[] = {
956#define TYPE(Name, Parent) 0,
957#define ABSTRACT_TYPE(Name, Parent)
958#include "clang/AST/TypeNodes.inc"
959 0 // Extra
960 };
961
962 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
963 Type *T = Types[i];
964 counts[(unsigned)T->getTypeClass()]++;
965 }
966
967 unsigned Idx = 0;
968 unsigned TotalBytes = 0;
969#define TYPE(Name, Parent) \
970 if (counts[Idx]) \
971 llvm::errs() << " " << counts[Idx] << " " << #Name \
972 << " types, " << sizeof(Name##Type) << " each " \
973 << "(" << counts[Idx] * sizeof(Name##Type) \
974 << " bytes)\n"; \
975 TotalBytes += counts[Idx] * sizeof(Name##Type); \
976 ++Idx;
977#define ABSTRACT_TYPE(Name, Parent)
978#include "clang/AST/TypeNodes.inc"
979
980 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
981
982 // Implicit special member functions.
983 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
985 << " implicit default constructors created\n";
986 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
988 << " implicit copy constructors created\n";
990 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
992 << " implicit move constructors created\n";
993 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
995 << " implicit copy assignment operators created\n";
997 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
999 << " implicit move assignment operators created\n";
1000 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1002 << " implicit destructors created\n";
1003
1004 if (ExternalSource) {
1005 llvm::errs() << "\n";
1007 }
1008
1009 BumpAlloc.PrintStats();
1010}
1011
1013 bool NotifyListeners) {
1014 if (NotifyListeners)
1015 if (auto *Listener = getASTMutationListener())
1017
1018 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1019}
1020
1022 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1023 if (It == MergedDefModules.end())
1024 return;
1025
1026 auto &Merged = It->second;
1028 for (Module *&M : Merged)
1029 if (!Found.insert(M).second)
1030 M = nullptr;
1031 llvm::erase(Merged, nullptr);
1032}
1033
1036 auto MergedIt =
1037 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1038 if (MergedIt == MergedDefModules.end())
1039 return std::nullopt;
1040 return MergedIt->second;
1041}
1042
1043void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1044 if (LazyInitializers.empty())
1045 return;
1046
1047 auto *Source = Ctx.getExternalSource();
1048 assert(Source && "lazy initializers but no external source");
1049
1050 auto LazyInits = std::move(LazyInitializers);
1051 LazyInitializers.clear();
1052
1053 for (auto ID : LazyInits)
1054 Initializers.push_back(Source->GetExternalDecl(ID));
1055
1056 assert(LazyInitializers.empty() &&
1057 "GetExternalDecl for lazy module initializer added more inits");
1058}
1059
1061 // One special case: if we add a module initializer that imports another
1062 // module, and that module's only initializer is an ImportDecl, simplify.
1063 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1064 auto It = ModuleInitializers.find(ID->getImportedModule());
1065
1066 // Maybe the ImportDecl does nothing at all. (Common case.)
1067 if (It == ModuleInitializers.end())
1068 return;
1069
1070 // Maybe the ImportDecl only imports another ImportDecl.
1071 auto &Imported = *It->second;
1072 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1073 Imported.resolve(*this);
1074 auto *OnlyDecl = Imported.Initializers.front();
1075 if (isa<ImportDecl>(OnlyDecl))
1076 D = OnlyDecl;
1077 }
1078 }
1079
1080 auto *&Inits = ModuleInitializers[M];
1081 if (!Inits)
1082 Inits = new (*this) PerModuleInitializers;
1083 Inits->Initializers.push_back(D);
1084}
1085
1088 auto *&Inits = ModuleInitializers[M];
1089 if (!Inits)
1090 Inits = new (*this) PerModuleInitializers;
1091 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1092 IDs.begin(), IDs.end());
1093}
1094
1096 auto It = ModuleInitializers.find(M);
1097 if (It == ModuleInitializers.end())
1098 return std::nullopt;
1099
1100 auto *Inits = It->second;
1101 Inits->resolve(*this);
1102 return Inits->Initializers;
1103}
1104
1106 assert(M->isNamedModule());
1107 assert(!CurrentCXXNamedModule &&
1108 "We should set named module for ASTContext for only once");
1109 CurrentCXXNamedModule = M;
1110}
1111
1113 if (!ExternCContext)
1114 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1115
1116 return ExternCContext;
1117}
1118
1121 const IdentifierInfo *II) const {
1122 auto *BuiltinTemplate =
1124 BuiltinTemplate->setImplicit();
1125 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1126
1127 return BuiltinTemplate;
1128}
1129
1132 if (!MakeIntegerSeqDecl)
1135 return MakeIntegerSeqDecl;
1136}
1137
1140 if (!TypePackElementDecl)
1143 return TypePackElementDecl;
1144}
1145
1147 RecordDecl::TagKind TK) const {
1148 SourceLocation Loc;
1149 RecordDecl *NewDecl;
1150 if (getLangOpts().CPlusPlus)
1151 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1152 Loc, &Idents.get(Name));
1153 else
1154 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1155 &Idents.get(Name));
1156 NewDecl->setImplicit();
1157 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1158 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1159 return NewDecl;
1160}
1161
1163 StringRef Name) const {
1166 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1167 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1168 NewDecl->setImplicit();
1169 return NewDecl;
1170}
1171
1173 if (!Int128Decl)
1174 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1175 return Int128Decl;
1176}
1177
1179 if (!UInt128Decl)
1180 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1181 return UInt128Decl;
1182}
1183
1184void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1185 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1187 Types.push_back(Ty);
1188}
1189
1191 const TargetInfo *AuxTarget) {
1192 assert((!this->Target || this->Target == &Target) &&
1193 "Incorrect target reinitialization");
1194 assert(VoidTy.isNull() && "Context reinitialized?");
1195
1196 this->Target = &Target;
1197 this->AuxTarget = AuxTarget;
1198
1199 ABI.reset(createCXXABI(Target));
1200 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1201
1202 // C99 6.2.5p19.
1203 InitBuiltinType(VoidTy, BuiltinType::Void);
1204
1205 // C99 6.2.5p2.
1206 InitBuiltinType(BoolTy, BuiltinType::Bool);
1207 // C99 6.2.5p3.
1208 if (LangOpts.CharIsSigned)
1209 InitBuiltinType(CharTy, BuiltinType::Char_S);
1210 else
1211 InitBuiltinType(CharTy, BuiltinType::Char_U);
1212 // C99 6.2.5p4.
1213 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1214 InitBuiltinType(ShortTy, BuiltinType::Short);
1215 InitBuiltinType(IntTy, BuiltinType::Int);
1216 InitBuiltinType(LongTy, BuiltinType::Long);
1217 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1218
1219 // C99 6.2.5p6.
1220 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1221 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1222 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1223 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1224 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1225
1226 // C99 6.2.5p10.
1227 InitBuiltinType(FloatTy, BuiltinType::Float);
1228 InitBuiltinType(DoubleTy, BuiltinType::Double);
1229 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1230
1231 // GNU extension, __float128 for IEEE quadruple precision
1232 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1233
1234 // __ibm128 for IBM extended precision
1235 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1236
1237 // C11 extension ISO/IEC TS 18661-3
1238 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1239
1240 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1241 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1242 InitBuiltinType(AccumTy, BuiltinType::Accum);
1243 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1244 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1245 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1246 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1247 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1248 InitBuiltinType(FractTy, BuiltinType::Fract);
1249 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1250 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1251 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1252 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1253 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1254 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1255 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1256 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1257 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1258 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1259 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1260 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1261 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1262 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1263 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1264 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1265
1266 // GNU extension, 128-bit integers.
1267 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1268 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1269
1270 // C++ 3.9.1p5
1271 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1272 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1273 else // -fshort-wchar makes wchar_t be unsigned.
1274 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1275 if (LangOpts.CPlusPlus && LangOpts.WChar)
1277 else {
1278 // C99 (or C++ using -fno-wchar).
1279 WideCharTy = getFromTargetType(Target.getWCharType());
1280 }
1281
1282 WIntTy = getFromTargetType(Target.getWIntType());
1283
1284 // C++20 (proposed)
1285 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1286
1287 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1288 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1289 else // C99
1290 Char16Ty = getFromTargetType(Target.getChar16Type());
1291
1292 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1293 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1294 else // C99
1295 Char32Ty = getFromTargetType(Target.getChar32Type());
1296
1297 // Placeholder type for type-dependent expressions whose type is
1298 // completely unknown. No code should ever check a type against
1299 // DependentTy and users should never see it; however, it is here to
1300 // help diagnose failures to properly check for type-dependent
1301 // expressions.
1302 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1303
1304 // Placeholder type for functions.
1305 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1306
1307 // Placeholder type for bound members.
1308 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1309
1310 // Placeholder type for pseudo-objects.
1311 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1312
1313 // "any" type; useful for debugger-like clients.
1314 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1315
1316 // Placeholder type for unbridged ARC casts.
1317 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1318
1319 // Placeholder type for builtin functions.
1320 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1321
1322 // Placeholder type for OMP array sections.
1323 if (LangOpts.OpenMP) {
1324 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1325 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1326 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1327 }
1328 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1329 // don't bother, as we're just using the same type as OMP.
1330 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1331 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1332 }
1333 if (LangOpts.MatrixTypes)
1334 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1335
1336 // Builtin types for 'id', 'Class', and 'SEL'.
1337 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1338 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1339 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1340
1341 if (LangOpts.OpenCL) {
1342#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1343 InitBuiltinType(SingletonId, BuiltinType::Id);
1344#include "clang/Basic/OpenCLImageTypes.def"
1345
1346 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1347 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1348 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1349 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1350 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1351
1352#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1353 InitBuiltinType(Id##Ty, BuiltinType::Id);
1354#include "clang/Basic/OpenCLExtensionTypes.def"
1355 }
1356
1357 if (Target.hasAArch64SVETypes()) {
1358#define SVE_TYPE(Name, Id, SingletonId) \
1359 InitBuiltinType(SingletonId, BuiltinType::Id);
1360#include "clang/Basic/AArch64SVEACLETypes.def"
1361 }
1362
1363 if (Target.getTriple().isPPC64()) {
1364#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1365 InitBuiltinType(Id##Ty, BuiltinType::Id);
1366#include "clang/Basic/PPCTypes.def"
1367#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1368 InitBuiltinType(Id##Ty, BuiltinType::Id);
1369#include "clang/Basic/PPCTypes.def"
1370 }
1371
1372 if (Target.hasRISCVVTypes()) {
1373#define RVV_TYPE(Name, Id, SingletonId) \
1374 InitBuiltinType(SingletonId, BuiltinType::Id);
1375#include "clang/Basic/RISCVVTypes.def"
1376 }
1377
1378 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1379#define WASM_TYPE(Name, Id, SingletonId) \
1380 InitBuiltinType(SingletonId, BuiltinType::Id);
1381#include "clang/Basic/WebAssemblyReferenceTypes.def"
1382 }
1383
1384 // Builtin type for __objc_yes and __objc_no
1385 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1387
1388 ObjCConstantStringType = QualType();
1389
1390 ObjCSuperType = QualType();
1391
1392 // void * type
1393 if (LangOpts.OpenCLGenericAddressSpace) {
1394 auto Q = VoidTy.getQualifiers();
1398 } else {
1400 }
1401
1402 // nullptr type (C++0x 2.14.7)
1403 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1404
1405 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1406 InitBuiltinType(HalfTy, BuiltinType::Half);
1407
1408 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1409
1410 // Builtin type used to help define __builtin_va_list.
1411 VaListTagDecl = nullptr;
1412
1413 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1414 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1417 }
1418}
1419
1421 return SourceMgr.getDiagnostics();
1422}
1423
1425 AttrVec *&Result = DeclAttrs[D];
1426 if (!Result) {
1427 void *Mem = Allocate(sizeof(AttrVec));
1428 Result = new (Mem) AttrVec;
1429 }
1430
1431 return *Result;
1432}
1433
1434/// Erase the attributes corresponding to the given declaration.
1436 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1437 if (Pos != DeclAttrs.end()) {
1438 Pos->second->~AttrVec();
1439 DeclAttrs.erase(Pos);
1440 }
1441}
1442
1443// FIXME: Remove ?
1446 assert(Var->isStaticDataMember() && "Not a static data member");
1448 .dyn_cast<MemberSpecializationInfo *>();
1449}
1450
1453 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1454 TemplateOrInstantiation.find(Var);
1455 if (Pos == TemplateOrInstantiation.end())
1456 return {};
1457
1458 return Pos->second;
1459}
1460
1461void
1464 SourceLocation PointOfInstantiation) {
1465 assert(Inst->isStaticDataMember() && "Not a static data member");
1466 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1468 Tmpl, TSK, PointOfInstantiation));
1469}
1470
1471void
1474 assert(!TemplateOrInstantiation[Inst] &&
1475 "Already noted what the variable was instantiated from");
1476 TemplateOrInstantiation[Inst] = TSI;
1477}
1478
1479NamedDecl *
1481 return InstantiatedFromUsingDecl.lookup(UUD);
1482}
1483
1484void
1486 assert((isa<UsingDecl>(Pattern) ||
1487 isa<UnresolvedUsingValueDecl>(Pattern) ||
1488 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1489 "pattern decl is not a using decl");
1490 assert((isa<UsingDecl>(Inst) ||
1491 isa<UnresolvedUsingValueDecl>(Inst) ||
1492 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1493 "instantiation did not produce a using decl");
1494 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1495 InstantiatedFromUsingDecl[Inst] = Pattern;
1496}
1497
1500 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1501}
1502
1504 UsingEnumDecl *Pattern) {
1505 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1506 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1507}
1508
1511 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1512}
1513
1514void
1516 UsingShadowDecl *Pattern) {
1517 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1518 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1519}
1520
1522 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1523}
1524
1526 FieldDecl *Tmpl) {
1527 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1528 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1529 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1530 "Already noted what unnamed field was instantiated from");
1531
1532 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1533}
1534
1537 return overridden_methods(Method).begin();
1538}
1539
1542 return overridden_methods(Method).end();
1543}
1544
1545unsigned
1547 auto Range = overridden_methods(Method);
1548 return Range.end() - Range.begin();
1549}
1550
1553 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1554 OverriddenMethods.find(Method->getCanonicalDecl());
1555 if (Pos == OverriddenMethods.end())
1556 return overridden_method_range(nullptr, nullptr);
1557 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1558}
1559
1561 const CXXMethodDecl *Overridden) {
1562 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1563 OverriddenMethods[Method].push_back(Overridden);
1564}
1565
1567 const NamedDecl *D,
1568 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1569 assert(D);
1570
1571 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1572 Overridden.append(overridden_methods_begin(CXXMethod),
1573 overridden_methods_end(CXXMethod));
1574 return;
1575 }
1576
1577 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1578 if (!Method)
1579 return;
1580
1582 Method->getOverriddenMethods(OverDecls);
1583 Overridden.append(OverDecls.begin(), OverDecls.end());
1584}
1585
1587 assert(!Import->getNextLocalImport() &&
1588 "Import declaration already in the chain");
1589 assert(!Import->isFromASTFile() && "Non-local import declaration");
1590 if (!FirstLocalImport) {
1591 FirstLocalImport = Import;
1592 LastLocalImport = Import;
1593 return;
1594 }
1595
1596 LastLocalImport->setNextLocalImport(Import);
1597 LastLocalImport = Import;
1598}
1599
1600//===----------------------------------------------------------------------===//
1601// Type Sizing and Analysis
1602//===----------------------------------------------------------------------===//
1603
1604/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1605/// scalar floating point type.
1606const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1607 switch (T->castAs<BuiltinType>()->getKind()) {
1608 default:
1609 llvm_unreachable("Not a floating point type!");
1610 case BuiltinType::BFloat16:
1611 return Target->getBFloat16Format();
1612 case BuiltinType::Float16:
1613 return Target->getHalfFormat();
1614 case BuiltinType::Half:
1615 // For HLSL, when the native half type is disabled, half will be treat as
1616 // float.
1617 if (getLangOpts().HLSL)
1618 if (getLangOpts().NativeHalfType)
1619 return Target->getHalfFormat();
1620 else
1621 return Target->getFloatFormat();
1622 else
1623 return Target->getHalfFormat();
1624 case BuiltinType::Float: return Target->getFloatFormat();
1625 case BuiltinType::Double: return Target->getDoubleFormat();
1626 case BuiltinType::Ibm128:
1627 return Target->getIbm128Format();
1628 case BuiltinType::LongDouble:
1629 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1630 return AuxTarget->getLongDoubleFormat();
1631 return Target->getLongDoubleFormat();
1632 case BuiltinType::Float128:
1633 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1634 return AuxTarget->getFloat128Format();
1635 return Target->getFloat128Format();
1636 }
1637}
1638
1639CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1640 unsigned Align = Target->getCharWidth();
1641
1642 const unsigned AlignFromAttr = D->getMaxAlignment();
1643 if (AlignFromAttr)
1644 Align = AlignFromAttr;
1645
1646 // __attribute__((aligned)) can increase or decrease alignment
1647 // *except* on a struct or struct member, where it only increases
1648 // alignment unless 'packed' is also specified.
1649 //
1650 // It is an error for alignas to decrease alignment, so we can
1651 // ignore that possibility; Sema should diagnose it.
1652 bool UseAlignAttrOnly;
1653 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1654 UseAlignAttrOnly =
1655 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1656 else
1657 UseAlignAttrOnly = AlignFromAttr != 0;
1658 // If we're using the align attribute only, just ignore everything
1659 // else about the declaration and its type.
1660 if (UseAlignAttrOnly) {
1661 // do nothing
1662 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1663 QualType T = VD->getType();
1664 if (const auto *RT = T->getAs<ReferenceType>()) {
1665 if (ForAlignof)
1666 T = RT->getPointeeType();
1667 else
1668 T = getPointerType(RT->getPointeeType());
1669 }
1670 QualType BaseT = getBaseElementType(T);
1671 if (T->isFunctionType())
1672 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1673 else if (!BaseT->isIncompleteType()) {
1674 // Adjust alignments of declarations with array type by the
1675 // large-array alignment on the target.
1676 if (const ArrayType *arrayType = getAsArrayType(T)) {
1677 unsigned MinWidth = Target->getLargeArrayMinWidth();
1678 if (!ForAlignof && MinWidth) {
1679 if (isa<VariableArrayType>(arrayType))
1680 Align = std::max(Align, Target->getLargeArrayAlign());
1681 else if (isa<ConstantArrayType>(arrayType) &&
1682 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1683 Align = std::max(Align, Target->getLargeArrayAlign());
1684 }
1685 }
1686 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1687 if (BaseT.getQualifiers().hasUnaligned())
1688 Align = Target->getCharWidth();
1689 }
1690
1691 // Ensure miminum alignment for global variables.
1692 if (const auto *VD = dyn_cast<VarDecl>(D))
1693 if (VD->hasGlobalStorage() && !ForAlignof) {
1694 uint64_t TypeSize =
1695 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1696 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1697 }
1698
1699 // Fields can be subject to extra alignment constraints, like if
1700 // the field is packed, the struct is packed, or the struct has a
1701 // a max-field-alignment constraint (#pragma pack). So calculate
1702 // the actual alignment of the field within the struct, and then
1703 // (as we're expected to) constrain that by the alignment of the type.
1704 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1705 const RecordDecl *Parent = Field->getParent();
1706 // We can only produce a sensible answer if the record is valid.
1707 if (!Parent->isInvalidDecl()) {
1708 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1709
1710 // Start with the record's overall alignment.
1711 unsigned FieldAlign = toBits(Layout.getAlignment());
1712
1713 // Use the GCD of that and the offset within the record.
1714 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1715 if (Offset > 0) {
1716 // Alignment is always a power of 2, so the GCD will be a power of 2,
1717 // which means we get to do this crazy thing instead of Euclid's.
1718 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1719 if (LowBitOfOffset < FieldAlign)
1720 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1721 }
1722
1723 Align = std::min(Align, FieldAlign);
1724 }
1725 }
1726 }
1727
1728 // Some targets have hard limitation on the maximum requestable alignment in
1729 // aligned attribute for static variables.
1730 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1731 const auto *VD = dyn_cast<VarDecl>(D);
1732 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1733 Align = std::min(Align, MaxAlignedAttr);
1734
1735 return toCharUnitsFromBits(Align);
1736}
1737
1739 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1740}
1741
1742// getTypeInfoDataSizeInChars - Return the size of a type, in
1743// chars. If the type is a record, its data size is returned. This is
1744// the size of the memcpy that's performed when assigning this type
1745// using a trivial copy/move assignment operator.
1748
1749 // In C++, objects can sometimes be allocated into the tail padding
1750 // of a base-class subobject. We decide whether that's possible
1751 // during class layout, so here we can just trust the layout results.
1752 if (getLangOpts().CPlusPlus) {
1753 if (const auto *RT = T->getAs<RecordType>();
1754 RT && !RT->getDecl()->isInvalidDecl()) {
1755 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1756 Info.Width = layout.getDataSize();
1757 }
1758 }
1759
1760 return Info;
1761}
1762
1763/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1764/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1767 const ConstantArrayType *CAT) {
1768 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1769 uint64_t Size = CAT->getZExtSize();
1770 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1771 (uint64_t)(-1)/Size) &&
1772 "Overflow in array type char size evaluation");
1773 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1774 unsigned Align = EltInfo.Align.getQuantity();
1775 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1777 Width = llvm::alignTo(Width, Align);
1780 EltInfo.AlignRequirement);
1781}
1782
1784 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1785 return getConstantArrayInfoInChars(*this, CAT);
1786 TypeInfo Info = getTypeInfo(T);
1789}
1790
1792 return getTypeInfoInChars(T.getTypePtr());
1793}
1794
1796 // HLSL doesn't promote all small integer types to int, it
1797 // just uses the rank-based promotion rules for all types.
1798 if (getLangOpts().HLSL)
1799 return false;
1800
1801 if (const auto *BT = T->getAs<BuiltinType>())
1802 switch (BT->getKind()) {
1803 case BuiltinType::Bool:
1804 case BuiltinType::Char_S:
1805 case BuiltinType::Char_U:
1806 case BuiltinType::SChar:
1807 case BuiltinType::UChar:
1808 case BuiltinType::Short:
1809 case BuiltinType::UShort:
1810 case BuiltinType::WChar_S:
1811 case BuiltinType::WChar_U:
1812 case BuiltinType::Char8:
1813 case BuiltinType::Char16:
1814 case BuiltinType::Char32:
1815 return true;
1816 default:
1817 return false;
1818 }
1819
1820 // Enumerated types are promotable to their compatible integer types
1821 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1822 if (const auto *ET = T->getAs<EnumType>()) {
1823 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1824 ET->getDecl()->isScoped())
1825 return false;
1826
1827 return true;
1828 }
1829
1830 return false;
1831}
1832
1835}
1836
1838 return isAlignmentRequired(T.getTypePtr());
1839}
1840
1842 bool NeedsPreferredAlignment) const {
1843 // An alignment on a typedef overrides anything else.
1844 if (const auto *TT = T->getAs<TypedefType>())
1845 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1846 return Align;
1847
1848 // If we have an (array of) complete type, we're done.
1850 if (!T->isIncompleteType())
1851 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1852
1853 // If we had an array type, its element type might be a typedef
1854 // type with an alignment attribute.
1855 if (const auto *TT = T->getAs<TypedefType>())
1856 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1857 return Align;
1858
1859 // Otherwise, see if the declaration of the type had an attribute.
1860 if (const auto *TT = T->getAs<TagType>())
1861 return TT->getDecl()->getMaxAlignment();
1862
1863 return 0;
1864}
1865
1867 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1868 if (I != MemoizedTypeInfo.end())
1869 return I->second;
1870
1871 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1872 TypeInfo TI = getTypeInfoImpl(T);
1873 MemoizedTypeInfo[T] = TI;
1874 return TI;
1875}
1876
1877/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1878/// method does not work on incomplete types.
1879///
1880/// FIXME: Pointers into different addr spaces could have different sizes and
1881/// alignment requirements: getPointerInfo should take an AddrSpace, this
1882/// should take a QualType, &c.
1883TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1884 uint64_t Width = 0;
1885 unsigned Align = 8;
1888 switch (T->getTypeClass()) {
1889#define TYPE(Class, Base)
1890#define ABSTRACT_TYPE(Class, Base)
1891#define NON_CANONICAL_TYPE(Class, Base)
1892#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1893#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1894 case Type::Class: \
1895 assert(!T->isDependentType() && "should not see dependent types here"); \
1896 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1897#include "clang/AST/TypeNodes.inc"
1898 llvm_unreachable("Should not see dependent types");
1899
1900 case Type::FunctionNoProto:
1901 case Type::FunctionProto:
1902 // GCC extension: alignof(function) = 32 bits
1903 Width = 0;
1904 Align = 32;
1905 break;
1906
1907 case Type::IncompleteArray:
1908 case Type::VariableArray:
1909 case Type::ConstantArray:
1910 case Type::ArrayParameter: {
1911 // Model non-constant sized arrays as size zero, but track the alignment.
1912 uint64_t Size = 0;
1913 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1914 Size = CAT->getZExtSize();
1915
1916 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1917 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1918 "Overflow in array type bit size evaluation");
1919 Width = EltInfo.Width * Size;
1920 Align = EltInfo.Align;
1921 AlignRequirement = EltInfo.AlignRequirement;
1922 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1923 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1924 Width = llvm::alignTo(Width, Align);
1925 break;
1926 }
1927
1928 case Type::ExtVector:
1929 case Type::Vector: {
1930 const auto *VT = cast<VectorType>(T);
1931 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1932 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1933 : EltInfo.Width * VT->getNumElements();
1934 // Enforce at least byte size and alignment.
1935 Width = std::max<unsigned>(8, Width);
1936 Align = std::max<unsigned>(8, Width);
1937
1938 // If the alignment is not a power of 2, round up to the next power of 2.
1939 // This happens for non-power-of-2 length vectors.
1940 if (Align & (Align-1)) {
1941 Align = llvm::bit_ceil(Align);
1942 Width = llvm::alignTo(Width, Align);
1943 }
1944 // Adjust the alignment based on the target max.
1945 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1946 if (TargetVectorAlign && TargetVectorAlign < Align)
1947 Align = TargetVectorAlign;
1948 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1949 // Adjust the alignment for fixed-length SVE vectors. This is important
1950 // for non-power-of-2 vector lengths.
1951 Align = 128;
1952 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1953 // Adjust the alignment for fixed-length SVE predicates.
1954 Align = 16;
1955 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1956 VT->getVectorKind() == VectorKind::RVVFixedLengthMask)
1957 // Adjust the alignment for fixed-length RVV vectors.
1958 Align = std::min<unsigned>(64, Width);
1959 break;
1960 }
1961
1962 case Type::ConstantMatrix: {
1963 const auto *MT = cast<ConstantMatrixType>(T);
1964 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1965 // The internal layout of a matrix value is implementation defined.
1966 // Initially be ABI compatible with arrays with respect to alignment and
1967 // size.
1968 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1969 Align = ElementInfo.Align;
1970 break;
1971 }
1972
1973 case Type::Builtin:
1974 switch (cast<BuiltinType>(T)->getKind()) {
1975 default: llvm_unreachable("Unknown builtin type!");
1976 case BuiltinType::Void:
1977 // GCC extension: alignof(void) = 8 bits.
1978 Width = 0;
1979 Align = 8;
1980 break;
1981 case BuiltinType::Bool:
1982 Width = Target->getBoolWidth();
1983 Align = Target->getBoolAlign();
1984 break;
1985 case BuiltinType::Char_S:
1986 case BuiltinType::Char_U:
1987 case BuiltinType::UChar:
1988 case BuiltinType::SChar:
1989 case BuiltinType::Char8:
1990 Width = Target->getCharWidth();
1991 Align = Target->getCharAlign();
1992 break;
1993 case BuiltinType::WChar_S:
1994 case BuiltinType::WChar_U:
1995 Width = Target->getWCharWidth();
1996 Align = Target->getWCharAlign();
1997 break;
1998 case BuiltinType::Char16:
1999 Width = Target->getChar16Width();
2000 Align = Target->getChar16Align();
2001 break;
2002 case BuiltinType::Char32:
2003 Width = Target->getChar32Width();
2004 Align = Target->getChar32Align();
2005 break;
2006 case BuiltinType::UShort:
2007 case BuiltinType::Short:
2008 Width = Target->getShortWidth();
2009 Align = Target->getShortAlign();
2010 break;
2011 case BuiltinType::UInt:
2012 case BuiltinType::Int:
2013 Width = Target->getIntWidth();
2014 Align = Target->getIntAlign();
2015 break;
2016 case BuiltinType::ULong:
2017 case BuiltinType::Long:
2018 Width = Target->getLongWidth();
2019 Align = Target->getLongAlign();
2020 break;
2021 case BuiltinType::ULongLong:
2022 case BuiltinType::LongLong:
2023 Width = Target->getLongLongWidth();
2024 Align = Target->getLongLongAlign();
2025 break;
2026 case BuiltinType::Int128:
2027 case BuiltinType::UInt128:
2028 Width = 128;
2029 Align = Target->getInt128Align();
2030 break;
2031 case BuiltinType::ShortAccum:
2032 case BuiltinType::UShortAccum:
2033 case BuiltinType::SatShortAccum:
2034 case BuiltinType::SatUShortAccum:
2035 Width = Target->getShortAccumWidth();
2036 Align = Target->getShortAccumAlign();
2037 break;
2038 case BuiltinType::Accum:
2039 case BuiltinType::UAccum:
2040 case BuiltinType::SatAccum:
2041 case BuiltinType::SatUAccum:
2042 Width = Target->getAccumWidth();
2043 Align = Target->getAccumAlign();
2044 break;
2045 case BuiltinType::LongAccum:
2046 case BuiltinType::ULongAccum:
2047 case BuiltinType::SatLongAccum:
2048 case BuiltinType::SatULongAccum:
2049 Width = Target->getLongAccumWidth();
2050 Align = Target->getLongAccumAlign();
2051 break;
2052 case BuiltinType::ShortFract:
2053 case BuiltinType::UShortFract:
2054 case BuiltinType::SatShortFract:
2055 case BuiltinType::SatUShortFract:
2056 Width = Target->getShortFractWidth();
2057 Align = Target->getShortFractAlign();
2058 break;
2059 case BuiltinType::Fract:
2060 case BuiltinType::UFract:
2061 case BuiltinType::SatFract:
2062 case BuiltinType::SatUFract:
2063 Width = Target->getFractWidth();
2064 Align = Target->getFractAlign();
2065 break;
2066 case BuiltinType::LongFract:
2067 case BuiltinType::ULongFract:
2068 case BuiltinType::SatLongFract:
2069 case BuiltinType::SatULongFract:
2070 Width = Target->getLongFractWidth();
2071 Align = Target->getLongFractAlign();
2072 break;
2073 case BuiltinType::BFloat16:
2074 if (Target->hasBFloat16Type()) {
2075 Width = Target->getBFloat16Width();
2076 Align = Target->getBFloat16Align();
2077 } else if ((getLangOpts().SYCLIsDevice ||
2078 (getLangOpts().OpenMP &&
2079 getLangOpts().OpenMPIsTargetDevice)) &&
2080 AuxTarget->hasBFloat16Type()) {
2081 Width = AuxTarget->getBFloat16Width();
2082 Align = AuxTarget->getBFloat16Align();
2083 }
2084 break;
2085 case BuiltinType::Float16:
2086 case BuiltinType::Half:
2087 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2088 !getLangOpts().OpenMPIsTargetDevice) {
2089 Width = Target->getHalfWidth();
2090 Align = Target->getHalfAlign();
2091 } else {
2092 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2093 "Expected OpenMP device compilation.");
2094 Width = AuxTarget->getHalfWidth();
2095 Align = AuxTarget->getHalfAlign();
2096 }
2097 break;
2098 case BuiltinType::Float:
2099 Width = Target->getFloatWidth();
2100 Align = Target->getFloatAlign();
2101 break;
2102 case BuiltinType::Double:
2103 Width = Target->getDoubleWidth();
2104 Align = Target->getDoubleAlign();
2105 break;
2106 case BuiltinType::Ibm128:
2107 Width = Target->getIbm128Width();
2108 Align = Target->getIbm128Align();
2109 break;
2110 case BuiltinType::LongDouble:
2111 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2112 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2113 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2114 Width = AuxTarget->getLongDoubleWidth();
2115 Align = AuxTarget->getLongDoubleAlign();
2116 } else {
2117 Width = Target->getLongDoubleWidth();
2118 Align = Target->getLongDoubleAlign();
2119 }
2120 break;
2121 case BuiltinType::Float128:
2122 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2123 !getLangOpts().OpenMPIsTargetDevice) {
2124 Width = Target->getFloat128Width();
2125 Align = Target->getFloat128Align();
2126 } else {
2127 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2128 "Expected OpenMP device compilation.");
2129 Width = AuxTarget->getFloat128Width();
2130 Align = AuxTarget->getFloat128Align();
2131 }
2132 break;
2133 case BuiltinType::NullPtr:
2134 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2135 Width = Target->getPointerWidth(LangAS::Default);
2136 Align = Target->getPointerAlign(LangAS::Default);
2137 break;
2138 case BuiltinType::ObjCId:
2139 case BuiltinType::ObjCClass:
2140 case BuiltinType::ObjCSel:
2141 Width = Target->getPointerWidth(LangAS::Default);
2142 Align = Target->getPointerAlign(LangAS::Default);
2143 break;
2144 case BuiltinType::OCLSampler:
2145 case BuiltinType::OCLEvent:
2146 case BuiltinType::OCLClkEvent:
2147 case BuiltinType::OCLQueue:
2148 case BuiltinType::OCLReserveID:
2149#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2150 case BuiltinType::Id:
2151#include "clang/Basic/OpenCLImageTypes.def"
2152#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2153 case BuiltinType::Id:
2154#include "clang/Basic/OpenCLExtensionTypes.def"
2155 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2156 Width = Target->getPointerWidth(AS);
2157 Align = Target->getPointerAlign(AS);
2158 break;
2159 // The SVE types are effectively target-specific. The length of an
2160 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2161 // of 128 bits. There is one predicate bit for each vector byte, so the
2162 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2163 //
2164 // Because the length is only known at runtime, we use a dummy value
2165 // of 0 for the static length. The alignment values are those defined
2166 // by the Procedure Call Standard for the Arm Architecture.
2167#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2168 IsSigned, IsFP, IsBF) \
2169 case BuiltinType::Id: \
2170 Width = 0; \
2171 Align = 128; \
2172 break;
2173#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2174 case BuiltinType::Id: \
2175 Width = 0; \
2176 Align = 16; \
2177 break;
2178#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2179 case BuiltinType::Id: \
2180 Width = 0; \
2181 Align = 16; \
2182 break;
2183#include "clang/Basic/AArch64SVEACLETypes.def"
2184#define PPC_VECTOR_TYPE(Name, Id, Size) \
2185 case BuiltinType::Id: \
2186 Width = Size; \
2187 Align = Size; \
2188 break;
2189#include "clang/Basic/PPCTypes.def"
2190#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2191 IsFP, IsBF) \
2192 case BuiltinType::Id: \
2193 Width = 0; \
2194 Align = ElBits; \
2195 break;
2196#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2197 case BuiltinType::Id: \
2198 Width = 0; \
2199 Align = 8; \
2200 break;
2201#include "clang/Basic/RISCVVTypes.def"
2202#define WASM_TYPE(Name, Id, SingletonId) \
2203 case BuiltinType::Id: \
2204 Width = 0; \
2205 Align = 8; \
2206 break;
2207#include "clang/Basic/WebAssemblyReferenceTypes.def"
2208 }
2209 break;
2210 case Type::ObjCObjectPointer:
2211 Width = Target->getPointerWidth(LangAS::Default);
2212 Align = Target->getPointerAlign(LangAS::Default);
2213 break;
2214 case Type::BlockPointer:
2215 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2216 Width = Target->getPointerWidth(AS);
2217 Align = Target->getPointerAlign(AS);
2218 break;
2219 case Type::LValueReference:
2220 case Type::RValueReference:
2221 // alignof and sizeof should never enter this code path here, so we go
2222 // the pointer route.
2223 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2224 Width = Target->getPointerWidth(AS);
2225 Align = Target->getPointerAlign(AS);
2226 break;
2227 case Type::Pointer:
2228 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2229 Width = Target->getPointerWidth(AS);
2230 Align = Target->getPointerAlign(AS);
2231 break;
2232 case Type::MemberPointer: {
2233 const auto *MPT = cast<MemberPointerType>(T);
2234 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2235 Width = MPI.Width;
2236 Align = MPI.Align;
2237 break;
2238 }
2239 case Type::Complex: {
2240 // Complex types have the same alignment as their elements, but twice the
2241 // size.
2242 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2243 Width = EltInfo.Width * 2;
2244 Align = EltInfo.Align;
2245 break;
2246 }
2247 case Type::ObjCObject:
2248 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2249 case Type::Adjusted:
2250 case Type::Decayed:
2251 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2252 case Type::ObjCInterface: {
2253 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2254 if (ObjCI->getDecl()->isInvalidDecl()) {
2255 Width = 8;
2256 Align = 8;
2257 break;
2258 }
2259 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2260 Width = toBits(Layout.getSize());
2261 Align = toBits(Layout.getAlignment());
2262 break;
2263 }
2264 case Type::BitInt: {
2265 const auto *EIT = cast<BitIntType>(T);
2266 Align = std::clamp<unsigned>(llvm::PowerOf2Ceil(EIT->getNumBits()),
2267 getCharWidth(), Target->getLongLongAlign());
2268 Width = llvm::alignTo(EIT->getNumBits(), Align);
2269 break;
2270 }
2271 case Type::Record:
2272 case Type::Enum: {
2273 const auto *TT = cast<TagType>(T);
2274
2275 if (TT->getDecl()->isInvalidDecl()) {
2276 Width = 8;
2277 Align = 8;
2278 break;
2279 }
2280
2281 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2282 const EnumDecl *ED = ET->getDecl();
2283 TypeInfo Info =
2285 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2286 Info.Align = AttrAlign;
2288 }
2289 return Info;
2290 }
2291
2292 const auto *RT = cast<RecordType>(TT);
2293 const RecordDecl *RD = RT->getDecl();
2294 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2295 Width = toBits(Layout.getSize());
2296 Align = toBits(Layout.getAlignment());
2297 AlignRequirement = RD->hasAttr<AlignedAttr>()
2300 break;
2301 }
2302
2303 case Type::SubstTemplateTypeParm:
2304 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2305 getReplacementType().getTypePtr());
2306
2307 case Type::Auto:
2308 case Type::DeducedTemplateSpecialization: {
2309 const auto *A = cast<DeducedType>(T);
2310 assert(!A->getDeducedType().isNull() &&
2311 "cannot request the size of an undeduced or dependent auto type");
2312 return getTypeInfo(A->getDeducedType().getTypePtr());
2313 }
2314
2315 case Type::Paren:
2316 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2317
2318 case Type::MacroQualified:
2319 return getTypeInfo(
2320 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2321
2322 case Type::ObjCTypeParam:
2323 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2324
2325 case Type::Using:
2326 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2327
2328 case Type::Typedef: {
2329 const auto *TT = cast<TypedefType>(T);
2330 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2331 // If the typedef has an aligned attribute on it, it overrides any computed
2332 // alignment we have. This violates the GCC documentation (which says that
2333 // attribute(aligned) can only round up) but matches its implementation.
2334 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2335 Align = AttrAlign;
2336 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2337 } else {
2338 Align = Info.Align;
2339 AlignRequirement = Info.AlignRequirement;
2340 }
2341 Width = Info.Width;
2342 break;
2343 }
2344
2345 case Type::Elaborated:
2346 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2347
2348 case Type::Attributed:
2349 return getTypeInfo(
2350 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2351
2352 case Type::CountAttributed:
2353 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2354
2355 case Type::BTFTagAttributed:
2356 return getTypeInfo(
2357 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2358
2359 case Type::Atomic: {
2360 // Start with the base type information.
2361 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2362 Width = Info.Width;
2363 Align = Info.Align;
2364
2365 if (!Width) {
2366 // An otherwise zero-sized type should still generate an
2367 // atomic operation.
2368 Width = Target->getCharWidth();
2369 assert(Align);
2370 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2371 // If the size of the type doesn't exceed the platform's max
2372 // atomic promotion width, make the size and alignment more
2373 // favorable to atomic operations:
2374
2375 // Round the size up to a power of 2.
2376 Width = llvm::bit_ceil(Width);
2377
2378 // Set the alignment equal to the size.
2379 Align = static_cast<unsigned>(Width);
2380 }
2381 }
2382 break;
2383
2384 case Type::Pipe:
2385 Width = Target->getPointerWidth(LangAS::opencl_global);
2386 Align = Target->getPointerAlign(LangAS::opencl_global);
2387 break;
2388 }
2389
2390 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2391 return TypeInfo(Width, Align, AlignRequirement);
2392}
2393
2395 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2396 if (I != MemoizedUnadjustedAlign.end())
2397 return I->second;
2398
2399 unsigned UnadjustedAlign;
2400 if (const auto *RT = T->getAs<RecordType>()) {
2401 const RecordDecl *RD = RT->getDecl();
2402 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2403 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2404 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2405 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2406 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2407 } else {
2408 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2409 }
2410
2411 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2412 return UnadjustedAlign;
2413}
2414
2416 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2417 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2418 return SimdAlign;
2419}
2420
2421/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2423 return CharUnits::fromQuantity(BitSize / getCharWidth());
2424}
2425
2426/// toBits - Convert a size in characters to a size in characters.
2427int64_t ASTContext::toBits(CharUnits CharSize) const {
2428 return CharSize.getQuantity() * getCharWidth();
2429}
2430
2431/// getTypeSizeInChars - Return the size of the specified type, in characters.
2432/// This method does not work on incomplete types.
2434 return getTypeInfoInChars(T).Width;
2435}
2437 return getTypeInfoInChars(T).Width;
2438}
2439
2440/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2441/// characters. This method does not work on incomplete types.
2444}
2447}
2448
2449/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2450/// type, in characters, before alignment adjustments. This method does
2451/// not work on incomplete types.
2454}
2457}
2458
2459/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2460/// type for the current target in bits. This can be different than the ABI
2461/// alignment in cases where it is beneficial for performance or backwards
2462/// compatibility preserving to overalign a data type. (Note: despite the name,
2463/// the preferred alignment is ABI-impacting, and not an optimization.)
2465 TypeInfo TI = getTypeInfo(T);
2466 unsigned ABIAlign = TI.Align;
2467
2469
2470 // The preferred alignment of member pointers is that of a pointer.
2471 if (T->isMemberPointerType())
2472 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2473
2474 if (!Target->allowsLargerPreferedTypeAlignment())
2475 return ABIAlign;
2476
2477 if (const auto *RT = T->getAs<RecordType>()) {
2478 const RecordDecl *RD = RT->getDecl();
2479
2480 // When used as part of a typedef, or together with a 'packed' attribute,
2481 // the 'aligned' attribute can be used to decrease alignment. Note that the
2482 // 'packed' case is already taken into consideration when computing the
2483 // alignment, we only need to handle the typedef case here.
2485 RD->isInvalidDecl())
2486 return ABIAlign;
2487
2488 unsigned PreferredAlign = static_cast<unsigned>(
2489 toBits(getASTRecordLayout(RD).PreferredAlignment));
2490 assert(PreferredAlign >= ABIAlign &&
2491 "PreferredAlign should be at least as large as ABIAlign.");
2492 return PreferredAlign;
2493 }
2494
2495 // Double (and, for targets supporting AIX `power` alignment, long double) and
2496 // long long should be naturally aligned (despite requiring less alignment) if
2497 // possible.
2498 if (const auto *CT = T->getAs<ComplexType>())
2499 T = CT->getElementType().getTypePtr();
2500 if (const auto *ET = T->getAs<EnumType>())
2501 T = ET->getDecl()->getIntegerType().getTypePtr();
2502 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2503 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2504 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2505 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2506 Target->defaultsToAIXPowerAlignment()))
2507 // Don't increase the alignment if an alignment attribute was specified on a
2508 // typedef declaration.
2509 if (!TI.isAlignRequired())
2510 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2511
2512 return ABIAlign;
2513}
2514
2515/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2516/// for __attribute__((aligned)) on this target, to be used if no alignment
2517/// value is specified.
2520}
2521
2522/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2523/// to a global variable of the specified type.
2525 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2526 return std::max(getPreferredTypeAlign(T),
2527 getMinGlobalAlignOfVar(TypeSize, VD));
2528}
2529
2530/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2531/// should be given to a global variable of the specified type.
2533 const VarDecl *VD) const {
2535}
2536
2538 const VarDecl *VD) const {
2539 // Make the default handling as that of a non-weak definition in the
2540 // current translation unit.
2541 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2542 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2543}
2544
2546 CharUnits Offset = CharUnits::Zero();
2547 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2548 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2549 Offset += Layout->getBaseClassOffset(Base);
2550 Layout = &getASTRecordLayout(Base);
2551 }
2552 return Offset;
2553}
2554
2556 const ValueDecl *MPD = MP.getMemberPointerDecl();
2559 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2560 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2561 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2562 const CXXRecordDecl *Base = RD;
2563 const CXXRecordDecl *Derived = Path[I];
2564 if (DerivedMember)
2565 std::swap(Base, Derived);
2567 RD = Path[I];
2568 }
2569 if (DerivedMember)
2571 return ThisAdjustment;
2572}
2573
2574/// DeepCollectObjCIvars -
2575/// This routine first collects all declared, but not synthesized, ivars in
2576/// super class and then collects all ivars, including those synthesized for
2577/// current class. This routine is used for implementation of current class
2578/// when all ivars, declared and synthesized are known.
2580 bool leafClass,
2582 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2583 DeepCollectObjCIvars(SuperClass, false, Ivars);
2584 if (!leafClass) {
2585 llvm::append_range(Ivars, OI->ivars());
2586 } else {
2587 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2588 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2589 Iv= Iv->getNextIvar())
2590 Ivars.push_back(Iv);
2591 }
2592}
2593
2594/// CollectInheritedProtocols - Collect all protocols in current class and
2595/// those inherited by it.
2598 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2599 // We can use protocol_iterator here instead of
2600 // all_referenced_protocol_iterator since we are walking all categories.
2601 for (auto *Proto : OI->all_referenced_protocols()) {
2602 CollectInheritedProtocols(Proto, Protocols);
2603 }
2604
2605 // Categories of this Interface.
2606 for (const auto *Cat : OI->visible_categories())
2607 CollectInheritedProtocols(Cat, Protocols);
2608
2609 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2610 while (SD) {
2611 CollectInheritedProtocols(SD, Protocols);
2612 SD = SD->getSuperClass();
2613 }
2614 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2615 for (auto *Proto : OC->protocols()) {
2616 CollectInheritedProtocols(Proto, Protocols);
2617 }
2618 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2619 // Insert the protocol.
2620 if (!Protocols.insert(
2621 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2622 return;
2623
2624 for (auto *Proto : OP->protocols())
2625 CollectInheritedProtocols(Proto, Protocols);
2626 }
2627}
2628
2630 const RecordDecl *RD,
2631 bool CheckIfTriviallyCopyable) {
2632 assert(RD->isUnion() && "Must be union type");
2633 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2634
2635 for (const auto *Field : RD->fields()) {
2636 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2637 CheckIfTriviallyCopyable))
2638 return false;
2639 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2640 if (FieldSize != UnionSize)
2641 return false;
2642 }
2643 return !RD->field_empty();
2644}
2645
2646static int64_t getSubobjectOffset(const FieldDecl *Field,
2647 const ASTContext &Context,
2648 const clang::ASTRecordLayout & /*Layout*/) {
2649 return Context.getFieldOffset(Field);
2650}
2651
2652static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2653 const ASTContext &Context,
2654 const clang::ASTRecordLayout &Layout) {
2655 return Context.toBits(Layout.getBaseClassOffset(RD));
2656}
2657
2658static std::optional<int64_t>
2660 const RecordDecl *RD,
2661 bool CheckIfTriviallyCopyable);
2662
2663static std::optional<int64_t>
2664getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2665 bool CheckIfTriviallyCopyable) {
2666 if (Field->getType()->isRecordType()) {
2667 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2668 if (!RD->isUnion())
2669 return structHasUniqueObjectRepresentations(Context, RD,
2670 CheckIfTriviallyCopyable);
2671 }
2672
2673 // A _BitInt type may not be unique if it has padding bits
2674 // but if it is a bitfield the padding bits are not used.
2675 bool IsBitIntType = Field->getType()->isBitIntType();
2676 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2677 !Context.hasUniqueObjectRepresentations(Field->getType(),
2678 CheckIfTriviallyCopyable))
2679 return std::nullopt;
2680
2681 int64_t FieldSizeInBits =
2682 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2683 if (Field->isBitField()) {
2684 // If we have explicit padding bits, they don't contribute bits
2685 // to the actual object representation, so return 0.
2686 if (Field->isUnnamedBitField())
2687 return 0;
2688
2689 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2690 if (IsBitIntType) {
2691 if ((unsigned)BitfieldSize >
2692 cast<BitIntType>(Field->getType())->getNumBits())
2693 return std::nullopt;
2694 } else if (BitfieldSize > FieldSizeInBits) {
2695 return std::nullopt;
2696 }
2697 FieldSizeInBits = BitfieldSize;
2698 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2699 Field->getType(), CheckIfTriviallyCopyable)) {
2700 return std::nullopt;
2701 }
2702 return FieldSizeInBits;
2703}
2704
2705static std::optional<int64_t>
2707 bool CheckIfTriviallyCopyable) {
2708 return structHasUniqueObjectRepresentations(Context, RD,
2709 CheckIfTriviallyCopyable);
2710}
2711
2712template <typename RangeT>
2714 const RangeT &Subobjects, int64_t CurOffsetInBits,
2715 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2716 bool CheckIfTriviallyCopyable) {
2717 for (const auto *Subobject : Subobjects) {
2718 std::optional<int64_t> SizeInBits =
2719 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2720 if (!SizeInBits)
2721 return std::nullopt;
2722 if (*SizeInBits != 0) {
2723 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2724 if (Offset != CurOffsetInBits)
2725 return std::nullopt;
2726 CurOffsetInBits += *SizeInBits;
2727 }
2728 }
2729 return CurOffsetInBits;
2730}
2731
2732static std::optional<int64_t>
2734 const RecordDecl *RD,
2735 bool CheckIfTriviallyCopyable) {
2736 assert(!RD->isUnion() && "Must be struct/class type");
2737 const auto &Layout = Context.getASTRecordLayout(RD);
2738
2739 int64_t CurOffsetInBits = 0;
2740 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2741 if (ClassDecl->isDynamicClass())
2742 return std::nullopt;
2743
2745 for (const auto &Base : ClassDecl->bases()) {
2746 // Empty types can be inherited from, and non-empty types can potentially
2747 // have tail padding, so just make sure there isn't an error.
2748 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2749 }
2750
2751 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2752 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2753 });
2754
2755 std::optional<int64_t> OffsetAfterBases =
2757 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2758 if (!OffsetAfterBases)
2759 return std::nullopt;
2760 CurOffsetInBits = *OffsetAfterBases;
2761 }
2762
2763 std::optional<int64_t> OffsetAfterFields =
2765 RD->fields(), CurOffsetInBits, Context, Layout,
2766 CheckIfTriviallyCopyable);
2767 if (!OffsetAfterFields)
2768 return std::nullopt;
2769 CurOffsetInBits = *OffsetAfterFields;
2770
2771 return CurOffsetInBits;
2772}
2773
2775 QualType Ty, bool CheckIfTriviallyCopyable) const {
2776 // C++17 [meta.unary.prop]:
2777 // The predicate condition for a template specialization
2778 // has_unique_object_representations<T> shall be satisfied if and only if:
2779 // (9.1) - T is trivially copyable, and
2780 // (9.2) - any two objects of type T with the same value have the same
2781 // object representation, where:
2782 // - two objects of array or non-union class type are considered to have
2783 // the same value if their respective sequences of direct subobjects
2784 // have the same values, and
2785 // - two objects of union type are considered to have the same value if
2786 // they have the same active member and the corresponding members have
2787 // the same value.
2788 // The set of scalar types for which this condition holds is
2789 // implementation-defined. [ Note: If a type has padding bits, the condition
2790 // does not hold; otherwise, the condition holds true for unsigned integral
2791 // types. -- end note ]
2792 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2793
2794 // Arrays are unique only if their element type is unique.
2795 if (Ty->isArrayType())
2797 CheckIfTriviallyCopyable);
2798
2799 // (9.1) - T is trivially copyable...
2800 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2801 return false;
2802
2803 // All integrals and enums are unique.
2804 if (Ty->isIntegralOrEnumerationType()) {
2805 // Except _BitInt types that have padding bits.
2806 if (const auto *BIT = Ty->getAs<BitIntType>())
2807 return getTypeSize(BIT) == BIT->getNumBits();
2808
2809 return true;
2810 }
2811
2812 // All other pointers are unique.
2813 if (Ty->isPointerType())
2814 return true;
2815
2816 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2817 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2818
2819 if (Ty->isRecordType()) {
2820 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2821
2822 if (Record->isInvalidDecl())
2823 return false;
2824
2825 if (Record->isUnion())
2827 CheckIfTriviallyCopyable);
2828
2829 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2830 *this, Record, CheckIfTriviallyCopyable);
2831
2832 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2833 }
2834
2835 // FIXME: More cases to handle here (list by rsmith):
2836 // vectors (careful about, eg, vector of 3 foo)
2837 // _Complex int and friends
2838 // _Atomic T
2839 // Obj-C block pointers
2840 // Obj-C object pointers
2841 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2842 // clk_event_t, queue_t, reserve_id_t)
2843 // There're also Obj-C class types and the Obj-C selector type, but I think it
2844 // makes sense for those to return false here.
2845
2846 return false;
2847}
2848
2850 unsigned count = 0;
2851 // Count ivars declared in class extension.
2852 for (const auto *Ext : OI->known_extensions())
2853 count += Ext->ivar_size();
2854
2855 // Count ivar defined in this class's implementation. This
2856 // includes synthesized ivars.
2857 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2858 count += ImplDecl->ivar_size();
2859
2860 return count;
2861}
2862
2864 if (!E)
2865 return false;
2866
2867 // nullptr_t is always treated as null.
2868 if (E->getType()->isNullPtrType()) return true;
2869
2870 if (E->getType()->isAnyPointerType() &&
2873 return true;
2874
2875 // Unfortunately, __null has type 'int'.
2876 if (isa<GNUNullExpr>(E)) return true;
2877
2878 return false;
2879}
2880
2881/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2882/// exists.
2884 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2885 I = ObjCImpls.find(D);
2886 if (I != ObjCImpls.end())
2887 return cast<ObjCImplementationDecl>(I->second);
2888 return nullptr;
2889}
2890
2891/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2892/// exists.
2894 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2895 I = ObjCImpls.find(D);
2896 if (I != ObjCImpls.end())
2897 return cast<ObjCCategoryImplDecl>(I->second);
2898 return nullptr;
2899}
2900
2901/// Set the implementation of ObjCInterfaceDecl.
2903 ObjCImplementationDecl *ImplD) {
2904 assert(IFaceD && ImplD && "Passed null params");
2905 ObjCImpls[IFaceD] = ImplD;
2906}
2907
2908/// Set the implementation of ObjCCategoryDecl.
2910 ObjCCategoryImplDecl *ImplD) {
2911 assert(CatD && ImplD && "Passed null params");
2912 ObjCImpls[CatD] = ImplD;
2913}
2914
2915const ObjCMethodDecl *
2917 return ObjCMethodRedecls.lookup(MD);
2918}
2919
2921 const ObjCMethodDecl *Redecl) {
2922 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2923 ObjCMethodRedecls[MD] = Redecl;
2924}
2925
2927 const NamedDecl *ND) const {
2928 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2929 return ID;
2930 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2931 return CD->getClassInterface();
2932 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2933 return IMD->getClassInterface();
2934
2935 return nullptr;
2936}
2937
2938/// Get the copy initialization expression of VarDecl, or nullptr if
2939/// none exists.
2941 assert(VD && "Passed null params");
2942 assert(VD->hasAttr<BlocksAttr>() &&
2943 "getBlockVarCopyInits - not __block var");
2944 auto I = BlockVarCopyInits.find(VD);
2945 if (I != BlockVarCopyInits.end())
2946 return I->second;
2947 return {nullptr, false};
2948}
2949
2950/// Set the copy initialization expression of a block var decl.
2952 bool CanThrow) {
2953 assert(VD && CopyExpr && "Passed null params");
2954 assert(VD->hasAttr<BlocksAttr>() &&
2955 "setBlockVarCopyInits - not __block var");
2956 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2957}
2958
2960 unsigned DataSize) const {
2961 if (!DataSize)
2963 else
2964 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2965 "incorrect data size provided to CreateTypeSourceInfo!");
2966
2967 auto *TInfo =
2968 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2969 new (TInfo) TypeSourceInfo(T, DataSize);
2970 return TInfo;
2971}
2972
2974 SourceLocation L) const {
2976 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2977 return DI;
2978}
2979
2980const ASTRecordLayout &
2982 return getObjCLayout(D, nullptr);
2983}
2984
2985const ASTRecordLayout &
2987 const ObjCImplementationDecl *D) const {
2988 return getObjCLayout(D->getClassInterface(), D);
2989}
2990
2993 bool &AnyNonCanonArgs) {
2994 SmallVector<TemplateArgument, 16> CanonArgs(Args);
2995 for (auto &Arg : CanonArgs) {
2996 TemplateArgument OrigArg = Arg;
2997 Arg = C.getCanonicalTemplateArgument(Arg);
2998 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
2999 }
3000 return CanonArgs;
3001}
3002
3003//===----------------------------------------------------------------------===//
3004// Type creation/memoization methods
3005//===----------------------------------------------------------------------===//
3006
3008ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3009 unsigned fastQuals = quals.getFastQualifiers();
3010 quals.removeFastQualifiers();
3011
3012 // Check if we've already instantiated this type.
3013 llvm::FoldingSetNodeID ID;
3014 ExtQuals::Profile(ID, baseType, quals);
3015 void *insertPos = nullptr;
3016 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3017 assert(eq->getQualifiers() == quals);
3018 return QualType(eq, fastQuals);
3019 }
3020
3021 // If the base type is not canonical, make the appropriate canonical type.
3022 QualType canon;
3023 if (!baseType->isCanonicalUnqualified()) {
3024 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3025 canonSplit.Quals.addConsistentQualifiers(quals);
3026 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3027
3028 // Re-find the insert position.
3029 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3030 }
3031
3032 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3033 ExtQualNodes.InsertNode(eq, insertPos);
3034 return QualType(eq, fastQuals);
3035}
3036
3038 LangAS AddressSpace) const {
3039 QualType CanT = getCanonicalType(T);
3040 if (CanT.getAddressSpace() == AddressSpace)
3041 return T;
3042
3043 // If we are composing extended qualifiers together, merge together
3044 // into one ExtQuals node.
3045 QualifierCollector Quals;
3046 const Type *TypeNode = Quals.strip(T);
3047
3048 // If this type already has an address space specified, it cannot get
3049 // another one.
3050 assert(!Quals.hasAddressSpace() &&
3051 "Type cannot be in multiple addr spaces!");
3052 Quals.addAddressSpace(AddressSpace);
3053
3054 return getExtQualType(TypeNode, Quals);
3055}
3056
3058 // If the type is not qualified with an address space, just return it
3059 // immediately.
3060 if (!T.hasAddressSpace())
3061 return T;
3062
3063 // If we are composing extended qualifiers together, merge together
3064 // into one ExtQuals node.
3065 QualifierCollector Quals;
3066 const Type *TypeNode;
3067
3068 while (T.hasAddressSpace()) {
3069 TypeNode = Quals.strip(T);
3070
3071 // If the type no longer has an address space after stripping qualifiers,
3072 // jump out.
3073 if (!QualType(TypeNode, 0).hasAddressSpace())
3074 break;
3075
3076 // There might be sugar in the way. Strip it and try again.
3077 T = T.getSingleStepDesugaredType(*this);
3078 }
3079
3080 Quals.removeAddressSpace();
3081
3082 // Removal of the address space can mean there are no longer any
3083 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3084 // or required.
3085 if (Quals.hasNonFastQualifiers())
3086 return getExtQualType(TypeNode, Quals);
3087 else
3088 return QualType(TypeNode, Quals.getFastQualifiers());
3089}
3090
3092 Qualifiers::GC GCAttr) const {
3093 QualType CanT = getCanonicalType(T);
3094 if (CanT.getObjCGCAttr() == GCAttr)
3095 return T;
3096
3097 if (const auto *ptr = T->getAs<PointerType>()) {
3098 QualType Pointee = ptr->getPointeeType();
3099 if (Pointee->isAnyPointerType()) {
3100 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3101 return getPointerType(ResultType);
3102 }
3103 }
3104
3105 // If we are composing extended qualifiers together, merge together
3106 // into one ExtQuals node.
3107 QualifierCollector Quals;
3108 const Type *TypeNode = Quals.strip(T);
3109
3110 // If this type already has an ObjCGC specified, it cannot get
3111 // another one.
3112 assert(!Quals.hasObjCGCAttr() &&
3113 "Type cannot have multiple ObjCGCs!");
3114 Quals.addObjCGCAttr(GCAttr);
3115
3116 return getExtQualType(TypeNode, Quals);
3117}
3118
3120 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3121 QualType Pointee = Ptr->getPointeeType();
3122 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3123 return getPointerType(removeAddrSpaceQualType(Pointee));
3124 }
3125 }
3126 return T;
3127}
3128
3130 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3131 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3132 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3133
3134 llvm::FoldingSetNodeID ID;
3135 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3136
3137 void *InsertPos = nullptr;
3138 CountAttributedType *CATy =
3139 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3140 if (CATy)
3141 return QualType(CATy, 0);
3142
3143 QualType CanonTy = getCanonicalType(WrappedTy);
3144 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3145 DependentDecls.size());
3147 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3148 OrNull, DependentDecls);
3149 Types.push_back(CATy);
3150 CountAttributedTypes.InsertNode(CATy, InsertPos);
3151
3152 return QualType(CATy, 0);
3153}
3154
3156 FunctionType::ExtInfo Info) {
3157 if (T->getExtInfo() == Info)
3158 return T;
3159
3161 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3162 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3163 } else {
3164 const auto *FPT = cast<FunctionProtoType>(T);
3165 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3166 EPI.ExtInfo = Info;
3167 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3168 }
3169
3170 return cast<FunctionType>(Result.getTypePtr());
3171}
3172
3174 QualType ResultType) {
3175 FD = FD->getMostRecentDecl();
3176 while (true) {
3177 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3178 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3179 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3180 if (FunctionDecl *Next = FD->getPreviousDecl())
3181 FD = Next;
3182 else
3183 break;
3184 }
3186 L->DeducedReturnType(FD, ResultType);
3187}
3188
3189/// Get a function type and produce the equivalent function type with the
3190/// specified exception specification. Type sugar that can be present on a
3191/// declaration of a function with an exception specification is permitted
3192/// and preserved. Other type sugar (for instance, typedefs) is not.
3194 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3195 // Might have some parens.
3196 if (const auto *PT = dyn_cast<ParenType>(Orig))
3197 return getParenType(
3198 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3199
3200 // Might be wrapped in a macro qualified type.
3201 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3202 return getMacroQualifiedType(
3203 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3204 MQT->getMacroIdentifier());
3205
3206 // Might have a calling-convention attribute.
3207 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3208 return getAttributedType(
3209 AT->getAttrKind(),
3210 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3211 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3212
3213 // Anything else must be a function type. Rebuild it with the new exception
3214 // specification.
3215 const auto *Proto = Orig->castAs<FunctionProtoType>();
3216 return getFunctionType(
3217 Proto->getReturnType(), Proto->getParamTypes(),
3218 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3219}
3220
3222 QualType U) const {
3223 return hasSameType(T, U) ||
3224 (getLangOpts().CPlusPlus17 &&
3227}
3228
3230 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3231 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3232 SmallVector<QualType, 16> Args(Proto->param_types().size());
3233 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3234 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3235 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3236 }
3237
3238 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3239 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3240 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3241 }
3242
3243 return T;
3244}
3245
3247 return hasSameType(T, U) ||
3250}
3251
3254 bool AsWritten) {
3255 // Update the type.
3256 QualType Updated =
3258 FD->setType(Updated);
3259
3260 if (!AsWritten)
3261 return;
3262
3263 // Update the type in the type source information too.
3264 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3265 // If the type and the type-as-written differ, we may need to update
3266 // the type-as-written too.
3267 if (TSInfo->getType() != FD->getType())
3268 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3269
3270 // FIXME: When we get proper type location information for exceptions,
3271 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3272 // up the TypeSourceInfo;
3273 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3274 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3275 "TypeLoc size mismatch from updating exception specification");
3276 TSInfo->overrideType(Updated);
3277 }
3278}
3279
3280/// getComplexType - Return the uniqued reference to the type for a complex
3281/// number with the specified element type.
3283 // Unique pointers, to guarantee there is only one pointer of a particular
3284 // structure.
3285 llvm::FoldingSetNodeID ID;
3287
3288 void *InsertPos = nullptr;
3289 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3290 return QualType(CT, 0);
3291
3292 // If the pointee type isn't canonical, this won't be a canonical type either,
3293 // so fill in the canonical type field.
3294 QualType Canonical;
3295 if (!T.isCanonical()) {
3296 Canonical = getComplexType(getCanonicalType(T));
3297
3298 // Get the new insert position for the node we care about.
3299 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3300 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3301 }
3302 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3303 Types.push_back(New);
3304 ComplexTypes.InsertNode(New, InsertPos);
3305 return QualType(New, 0);
3306}
3307
3308/// getPointerType - Return the uniqued reference to the type for a pointer to
3309/// the specified type.
3311 // Unique pointers, to guarantee there is only one pointer of a particular
3312 // structure.
3313 llvm::FoldingSetNodeID ID;
3315
3316 void *InsertPos = nullptr;
3317 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3318 return QualType(PT, 0);
3319
3320 // If the pointee type isn't canonical, this won't be a canonical type either,
3321 // so fill in the canonical type field.
3322 QualType Canonical;
3323 if (!T.isCanonical()) {
3324 Canonical = getPointerType(getCanonicalType(T));
3325
3326 // Get the new insert position for the node we care about.
3327 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3328 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3329 }
3330 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3331 Types.push_back(New);
3332 PointerTypes.InsertNode(New, InsertPos);
3333 return QualType(New, 0);
3334}
3335
3337 llvm::FoldingSetNodeID ID;
3338 AdjustedType::Profile(ID, Orig, New);
3339 void *InsertPos = nullptr;
3340 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3341 if (AT)
3342 return QualType(AT, 0);
3343
3344 QualType Canonical = getCanonicalType(New);
3345
3346 // Get the new insert position for the node we care about.
3347 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3348 assert(!AT && "Shouldn't be in the map!");
3349
3350 AT = new (*this, alignof(AdjustedType))
3351 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3352 Types.push_back(AT);
3353 AdjustedTypes.InsertNode(AT, InsertPos);
3354 return QualType(AT, 0);
3355}
3356
3358 llvm::FoldingSetNodeID ID;
3359 AdjustedType::Profile(ID, Orig, Decayed);
3360 void *InsertPos = nullptr;
3361 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3362 if (AT)
3363 return QualType(AT, 0);
3364
3365 QualType Canonical = getCanonicalType(Decayed);
3366
3367 // Get the new insert position for the node we care about.
3368 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3369 assert(!AT && "Shouldn't be in the map!");
3370
3371 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3372 Types.push_back(AT);
3373 AdjustedTypes.InsertNode(AT, InsertPos);
3374 return QualType(AT, 0);
3375}
3376
3378 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3379
3380 QualType Decayed;
3381
3382 // C99 6.7.5.3p7:
3383 // A declaration of a parameter as "array of type" shall be
3384 // adjusted to "qualified pointer to type", where the type
3385 // qualifiers (if any) are those specified within the [ and ] of
3386 // the array type derivation.
3387 if (T->isArrayType())
3388 Decayed = getArrayDecayedType(T);
3389
3390 // C99 6.7.5.3p8:
3391 // A declaration of a parameter as "function returning type"
3392 // shall be adjusted to "pointer to function returning type", as
3393 // in 6.3.2.1.
3394 if (T->isFunctionType())
3395 Decayed = getPointerType(T);
3396
3397 return getDecayedType(T, Decayed);
3398}
3399
3401 if (Ty->isArrayParameterType())
3402 return Ty;
3403 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3404 const auto *ATy = cast<ConstantArrayType>(Ty);
3405 llvm::FoldingSetNodeID ID;
3406 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3407 ATy->getSizeExpr(), ATy->getSizeModifier(),
3408 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3409 void *InsertPos = nullptr;
3410 ArrayParameterType *AT =
3411 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3412 if (AT)
3413 return QualType(AT, 0);
3414
3415 QualType Canonical;
3416 if (!Ty.isCanonical()) {
3417 Canonical = getArrayParameterType(getCanonicalType(Ty));
3418
3419 // Get the new insert position for the node we care about.
3420 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3421 assert(!AT && "Shouldn't be in the map!");
3422 }
3423
3424 AT = new (*this, alignof(ArrayParameterType))
3425 ArrayParameterType(ATy, Canonical);
3426 Types.push_back(AT);
3427 ArrayParameterTypes.InsertNode(AT, InsertPos);
3428 return QualType(AT, 0);
3429}
3430
3431/// getBlockPointerType - Return the uniqued reference to the type for
3432/// a pointer to the specified block.
3434 assert(T->isFunctionType() && "block of function types only");
3435 // Unique pointers, to guarantee there is only one block of a particular
3436 // structure.
3437 llvm::FoldingSetNodeID ID;
3439
3440 void *InsertPos = nullptr;
3441 if (BlockPointerType *PT =
3442 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3443 return QualType(PT, 0);
3444
3445 // If the block pointee type isn't canonical, this won't be a canonical
3446 // type either so fill in the canonical type field.
3447 QualType Canonical;
3448 if (!T.isCanonical()) {
3450
3451 // Get the new insert position for the node we care about.
3452 BlockPointerType *NewIP =
3453 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3454 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3455 }
3456 auto *New =
3457 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3458 Types.push_back(New);
3459 BlockPointerTypes.InsertNode(New, InsertPos);
3460 return QualType(New, 0);
3461}
3462
3463/// getLValueReferenceType - Return the uniqued reference to the type for an
3464/// lvalue reference to the specified type.
3466ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3467 assert((!T->isPlaceholderType() ||
3468 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3469 "Unresolved placeholder type");
3470
3471 // Unique pointers, to guarantee there is only one pointer of a particular
3472 // structure.
3473 llvm::FoldingSetNodeID ID;
3474 ReferenceType::Profile(ID, T, SpelledAsLValue);
3475
3476 void *InsertPos = nullptr;
3477 if (LValueReferenceType *RT =
3478 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3479 return QualType(RT, 0);
3480
3481 const auto *InnerRef = T->getAs<ReferenceType>();
3482
3483 // If the referencee type isn't canonical, this won't be a canonical type
3484 // either, so fill in the canonical type field.
3485 QualType Canonical;
3486 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3487 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3488 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3489
3490 // Get the new insert position for the node we care about.
3491 LValueReferenceType *NewIP =
3492 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3493 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3494 }
3495
3496 auto *New = new (*this, alignof(LValueReferenceType))
3497 LValueReferenceType(T, Canonical, SpelledAsLValue);
3498 Types.push_back(New);
3499 LValueReferenceTypes.InsertNode(New, InsertPos);
3500
3501 return QualType(New, 0);
3502}
3503
3504/// getRValueReferenceType - Return the uniqued reference to the type for an
3505/// rvalue reference to the specified type.
3507 assert((!T->isPlaceholderType() ||
3508 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3509 "Unresolved placeholder type");
3510
3511 // Unique pointers, to guarantee there is only one pointer of a particular
3512 // structure.
3513 llvm::FoldingSetNodeID ID;
3514 ReferenceType::Profile(ID, T, false);
3515
3516 void *InsertPos = nullptr;
3517 if (RValueReferenceType *RT =
3518 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3519 return QualType(RT, 0);
3520
3521 const auto *InnerRef = T->getAs<ReferenceType>();
3522
3523 // If the referencee type isn't canonical, this won't be a canonical type
3524 // either, so fill in the canonical type field.
3525 QualType Canonical;
3526 if (InnerRef || !T.isCanonical()) {
3527 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3528 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3529
3530 // Get the new insert position for the node we care about.
3531 RValueReferenceType *NewIP =
3532 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3533 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3534 }
3535
3536 auto *New = new (*this, alignof(RValueReferenceType))
3537 RValueReferenceType(T, Canonical);
3538 Types.push_back(New);
3539 RValueReferenceTypes.InsertNode(New, InsertPos);
3540 return QualType(New, 0);
3541}
3542
3543/// getMemberPointerType - Return the uniqued reference to the type for a
3544/// member pointer to the specified type, in the specified class.
3546 // Unique pointers, to guarantee there is only one pointer of a particular
3547 // structure.
3548 llvm::FoldingSetNodeID ID;
3549 MemberPointerType::Profile(ID, T, Cls);
3550
3551 void *InsertPos = nullptr;
3552 if (MemberPointerType *PT =
3553 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3554 return QualType(PT, 0);
3555
3556 // If the pointee or class type isn't canonical, this won't be a canonical
3557 // type either, so fill in the canonical type field.
3558 QualType Canonical;
3559 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3561
3562 // Get the new insert position for the node we care about.
3563 MemberPointerType *NewIP =
3564 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3565 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3566 }
3567 auto *New = new (*this, alignof(MemberPointerType))
3568 MemberPointerType(T, Cls, Canonical);
3569 Types.push_back(New);
3570 MemberPointerTypes.InsertNode(New, InsertPos);
3571 return QualType(New, 0);
3572}
3573
3574/// getConstantArrayType - Return the unique reference to the type for an
3575/// array of the specified element type.
3577 const llvm::APInt &ArySizeIn,
3578 const Expr *SizeExpr,
3580 unsigned IndexTypeQuals) const {
3581 assert((EltTy->isDependentType() ||
3582 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3583 "Constant array of VLAs is illegal!");
3584
3585 // We only need the size as part of the type if it's instantiation-dependent.
3586 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3587 SizeExpr = nullptr;
3588
3589 // Convert the array size into a canonical width matching the pointer size for
3590 // the target.
3591 llvm::APInt ArySize(ArySizeIn);
3592 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3593
3594 llvm::FoldingSetNodeID ID;
3595 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
3596 ASM, IndexTypeQuals);
3597
3598 void *InsertPos = nullptr;
3599 if (ConstantArrayType *ATP =
3600 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3601 return QualType(ATP, 0);
3602
3603 // If the element type isn't canonical or has qualifiers, or the array bound
3604 // is instantiation-dependent, this won't be a canonical type either, so fill
3605 // in the canonical type field.
3606 QualType Canon;
3607 // FIXME: Check below should look for qualifiers behind sugar.
3608 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3609 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3610 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3611 ASM, IndexTypeQuals);
3612 Canon = getQualifiedType(Canon, canonSplit.Quals);
3613
3614 // Get the new insert position for the node we care about.
3615 ConstantArrayType *NewIP =
3616 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3617 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3618 }
3619
3620 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
3621 ASM, IndexTypeQuals);
3622 ConstantArrayTypes.InsertNode(New, InsertPos);
3623 Types.push_back(New);
3624 return QualType(New, 0);
3625}
3626
3627/// getVariableArrayDecayedType - Turns the given type, which may be
3628/// variably-modified, into the corresponding type with all the known
3629/// sizes replaced with [*].
3631 // Vastly most common case.
3632 if (!type->isVariablyModifiedType()) return type;
3633
3634 QualType result;
3635
3636 SplitQualType split = type.getSplitDesugaredType();
3637 const Type *ty = split.Ty;
3638 switch (ty->getTypeClass()) {
3639#define TYPE(Class, Base)
3640#define ABSTRACT_TYPE(Class, Base)
3641#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3642#include "clang/AST/TypeNodes.inc"
3643 llvm_unreachable("didn't desugar past all non-canonical types?");
3644
3645 // These types should never be variably-modified.
3646 case Type::Builtin:
3647 case Type::Complex:
3648 case Type::Vector:
3649 case Type::DependentVector:
3650 case Type::ExtVector:
3651 case Type::DependentSizedExtVector:
3652 case Type::ConstantMatrix:
3653 case Type::DependentSizedMatrix:
3654 case Type::DependentAddressSpace:
3655 case Type::ObjCObject:
3656 case Type::ObjCInterface:
3657 case Type::ObjCObjectPointer:
3658 case Type::Record:
3659 case Type::Enum:
3660 case Type::UnresolvedUsing:
3661 case Type::TypeOfExpr:
3662 case Type::TypeOf:
3663 case Type::Decltype:
3664 case Type::UnaryTransform:
3665 case Type::DependentName:
3666 case Type::InjectedClassName:
3667 case Type::TemplateSpecialization:
3668 case Type::DependentTemplateSpecialization:
3669 case Type::TemplateTypeParm:
3670 case Type::SubstTemplateTypeParmPack:
3671 case Type::Auto:
3672 case Type::DeducedTemplateSpecialization:
3673 case Type::PackExpansion:
3674 case Type::PackIndexing:
3675 case Type::BitInt:
3676 case Type::DependentBitInt:
3677 case Type::ArrayParameter:
3678 llvm_unreachable("type should never be variably-modified");
3679
3680 // These types can be variably-modified but should never need to
3681 // further decay.
3682 case Type::FunctionNoProto:
3683 case Type::FunctionProto:
3684 case Type::BlockPointer:
3685 case Type::MemberPointer:
3686 case Type::Pipe:
3687 return type;
3688
3689 // These types can be variably-modified. All these modifications
3690 // preserve structure except as noted by comments.
3691 // TODO: if we ever care about optimizing VLAs, there are no-op
3692 // optimizations available here.
3693 case Type::Pointer:
3695 cast<PointerType>(ty)->getPointeeType()));
3696 break;
3697
3698 case Type::LValueReference: {
3699 const auto *lv = cast<LValueReferenceType>(ty);
3700 result = getLValueReferenceType(
3701 getVariableArrayDecayedType(lv->getPointeeType()),
3702 lv->isSpelledAsLValue());
3703 break;
3704 }
3705
3706 case Type::RValueReference: {
3707 const auto *lv = cast<RValueReferenceType>(ty);
3708 result = getRValueReferenceType(
3709 getVariableArrayDecayedType(lv->getPointeeType()));
3710 break;
3711 }
3712
3713 case Type::Atomic: {
3714 const auto *at = cast<AtomicType>(ty);
3715 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3716 break;
3717 }
3718
3719 case Type::ConstantArray: {
3720 const auto *cat = cast<ConstantArrayType>(ty);
3721 result = getConstantArrayType(
3722 getVariableArrayDecayedType(cat->getElementType()),
3723 cat->getSize(),
3724 cat->getSizeExpr(),
3725 cat->getSizeModifier(),
3726 cat->getIndexTypeCVRQualifiers());
3727 break;
3728 }
3729
3730 case Type::DependentSizedArray: {
3731 const auto *dat = cast<DependentSizedArrayType>(ty);
3733 getVariableArrayDecayedType(dat->getElementType()),
3734 dat->getSizeExpr(),
3735 dat->getSizeModifier(),
3736 dat->getIndexTypeCVRQualifiers(),
3737 dat->getBracketsRange());
3738 break;
3739 }
3740
3741 // Turn incomplete types into [*] types.
3742 case Type::IncompleteArray: {
3743 const auto *iat = cast<IncompleteArrayType>(ty);
3744 result =
3746 /*size*/ nullptr, ArraySizeModifier::Normal,
3747 iat->getIndexTypeCVRQualifiers(), SourceRange());
3748 break;
3749 }
3750
3751 // Turn VLA types into [*] types.
3752 case Type::VariableArray: {
3753 const auto *vat = cast<VariableArrayType>(ty);
3754 result = getVariableArrayType(
3755 getVariableArrayDecayedType(vat->getElementType()),
3756 /*size*/ nullptr, ArraySizeModifier::Star,
3757 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
3758 break;
3759 }
3760 }
3761
3762 // Apply the top-level qualifiers from the original.
3763 return getQualifiedType(result, split.Quals);
3764}
3765
3766/// getVariableArrayType - Returns a non-unique reference to the type for a
3767/// variable array of the specified element type.
3770 unsigned IndexTypeQuals,
3771 SourceRange Brackets) const {
3772 // Since we don't unique expressions, it isn't possible to unique VLA's
3773 // that have an expression provided for their size.
3774 QualType Canon;
3775
3776 // Be sure to pull qualifiers off the element type.
3777 // FIXME: Check below should look for qualifiers behind sugar.
3778 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3779 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3780 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3781 IndexTypeQuals, Brackets);
3782 Canon = getQualifiedType(Canon, canonSplit.Quals);
3783 }
3784
3785 auto *New = new (*this, alignof(VariableArrayType))
3786 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3787
3788 VariableArrayTypes.push_back(New);
3789 Types.push_back(New);
3790 return QualType(New, 0);
3791}
3792
3793/// getDependentSizedArrayType - Returns a non-unique reference to
3794/// the type for a dependently-sized array of the specified element
3795/// type.
3797 Expr *numElements,
3799 unsigned elementTypeQuals,
3800 SourceRange brackets) const {
3801 assert((!numElements || numElements->isTypeDependent() ||
3802 numElements->isValueDependent()) &&
3803 "Size must be type- or value-dependent!");
3804
3805 // Dependently-sized array types that do not have a specified number
3806 // of elements will have their sizes deduced from a dependent
3807 // initializer. We do no canonicalization here at all, which is okay
3808 // because they can't be used in most locations.
3809 if (!numElements) {
3810 auto *newType = new (*this, alignof(DependentSizedArrayType))
3811 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
3812 elementTypeQuals, 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, alignof(DependentSizedArrayType))
3835 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
3836 numElements, ASM, elementTypeQuals, brackets);
3837 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3838 Types.push_back(canonTy);
3839 }
3840
3841 // Apply qualifiers from the element type to the array.
3842 QualType canon = getQualifiedType(QualType(canonTy,0),
3843 canonElementType.Quals);
3844
3845 // If we didn't need extra canonicalization for the element type or the size
3846 // expression, then just use that as our result.
3847 if (QualType(canonElementType.Ty, 0) == elementType &&
3848 canonTy->getSizeExpr() == numElements)
3849 return canon;
3850
3851 // Otherwise, we need to build a type which follows the spelling
3852 // of the element type.
3853 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
3854 DependentSizedArrayType(elementType, canon, numElements, ASM,
3855 elementTypeQuals, brackets);
3856 Types.push_back(sugaredType);
3857 return QualType(sugaredType, 0);
3858}
3859
3862 unsigned elementTypeQuals) const {
3863 llvm::FoldingSetNodeID ID;
3864 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3865
3866 void *insertPos = nullptr;
3867 if (IncompleteArrayType *iat =
3868 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3869 return QualType(iat, 0);
3870
3871 // If the element type isn't canonical, this won't be a canonical type
3872 // either, so fill in the canonical type field. We also have to pull
3873 // qualifiers off the element type.
3874 QualType canon;
3875
3876 // FIXME: Check below should look for qualifiers behind sugar.
3877 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3878 SplitQualType canonSplit = getCanonicalType(elementType).split();
3879 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3880 ASM, elementTypeQuals);
3881 canon = getQualifiedType(canon, canonSplit.Quals);
3882
3883 // Get the new insert position for the node we care about.
3884 IncompleteArrayType *existing =
3885 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3886 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3887 }
3888
3889 auto *newType = new (*this, alignof(IncompleteArrayType))
3890 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3891
3892 IncompleteArrayTypes.InsertNode(newType, insertPos);
3893 Types.push_back(newType);
3894 return QualType(newType, 0);
3895}
3896
3899#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
3900 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3901 NUMVECTORS};
3902
3903#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
3904 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3905
3906 switch (Ty->getKind()) {
3907 default:
3908 llvm_unreachable("Unsupported builtin vector type");
3909 case BuiltinType::SveInt8:
3910 return SVE_INT_ELTTY(8, 16, true, 1);
3911 case BuiltinType::SveUint8:
3912 return SVE_INT_ELTTY(8, 16, false, 1);
3913 case BuiltinType::SveInt8x2:
3914 return SVE_INT_ELTTY(8, 16, true, 2);
3915 case BuiltinType::SveUint8x2:
3916 return SVE_INT_ELTTY(8, 16, false, 2);
3917 case BuiltinType::SveInt8x3:
3918 return SVE_INT_ELTTY(8, 16, true, 3);
3919 case BuiltinType::SveUint8x3:
3920 return SVE_INT_ELTTY(8, 16, false, 3);
3921 case BuiltinType::SveInt8x4:
3922 return SVE_INT_ELTTY(8, 16, true, 4);
3923 case BuiltinType::SveUint8x4:
3924 return SVE_INT_ELTTY(8, 16, false, 4);
3925 case BuiltinType::SveInt16:
3926 return SVE_INT_ELTTY(16, 8, true, 1);
3927 case BuiltinType::SveUint16:
3928 return SVE_INT_ELTTY(16, 8, false, 1);
3929 case BuiltinType::SveInt16x2:
3930 return SVE_INT_ELTTY(16, 8, true, 2);
3931 case BuiltinType::SveUint16x2:
3932 return SVE_INT_ELTTY(16, 8, false, 2);
3933 case BuiltinType::SveInt16x3:
3934 return SVE_INT_ELTTY(16, 8, true, 3);
3935 case BuiltinType::SveUint16x3:
3936 return SVE_INT_ELTTY(16, 8, false, 3);
3937 case BuiltinType::SveInt16x4:
3938 return SVE_INT_ELTTY(16, 8, true, 4);
3939 case BuiltinType::SveUint16x4:
3940 return SVE_INT_ELTTY(16, 8, false, 4);
3941 case BuiltinType::SveInt32:
3942 return SVE_INT_ELTTY(32, 4, true, 1);
3943 case BuiltinType::SveUint32:
3944 return SVE_INT_ELTTY(32, 4, false, 1);
3945 case BuiltinType::SveInt32x2:
3946 return SVE_INT_ELTTY(32, 4, true, 2);
3947 case BuiltinType::SveUint32x2:
3948 return SVE_INT_ELTTY(32, 4, false, 2);
3949 case BuiltinType::SveInt32x3:
3950 return SVE_INT_ELTTY(32, 4, true, 3);
3951 case BuiltinType::SveUint32x3:
3952 return SVE_INT_ELTTY(32, 4, false, 3);
3953 case BuiltinType::SveInt32x4:
3954 return SVE_INT_ELTTY(32, 4, true, 4);
3955 case BuiltinType::SveUint32x4:
3956 return SVE_INT_ELTTY(32, 4, false, 4);
3957 case BuiltinType::SveInt64:
3958 return SVE_INT_ELTTY(64, 2, true, 1);
3959 case BuiltinType::SveUint64:
3960 return SVE_INT_ELTTY(64, 2, false, 1);
3961 case BuiltinType::SveInt64x2:
3962 return SVE_INT_ELTTY(64, 2, true, 2);
3963 case BuiltinType::SveUint64x2:
3964 return SVE_INT_ELTTY(64, 2, false, 2);
3965 case BuiltinType::SveInt64x3:
3966 return SVE_INT_ELTTY(64, 2, true, 3);
3967 case BuiltinType::SveUint64x3:
3968 return SVE_INT_ELTTY(64, 2, false, 3);
3969 case BuiltinType::SveInt64x4:
3970 return SVE_INT_ELTTY(64, 2, true, 4);
3971 case BuiltinType::SveUint64x4:
3972 return SVE_INT_ELTTY(64, 2, false, 4);
3973 case BuiltinType::SveBool:
3974 return SVE_ELTTY(BoolTy, 16, 1);
3975 case BuiltinType::SveBoolx2:
3976 return SVE_ELTTY(BoolTy, 16, 2);
3977 case BuiltinType::SveBoolx4:
3978 return SVE_ELTTY(BoolTy, 16, 4);
3979 case BuiltinType::SveFloat16:
3980 return SVE_ELTTY(HalfTy, 8, 1);
3981 case BuiltinType::SveFloat16x2:
3982 return SVE_ELTTY(HalfTy, 8, 2);
3983 case BuiltinType::SveFloat16x3:
3984 return SVE_ELTTY(HalfTy, 8, 3);
3985 case BuiltinType::SveFloat16x4:
3986 return SVE_ELTTY(HalfTy, 8, 4);
3987 case BuiltinType::SveFloat32:
3988 return SVE_ELTTY(FloatTy, 4, 1);
3989 case BuiltinType::SveFloat32x2:
3990 return SVE_ELTTY(FloatTy, 4, 2);
3991 case BuiltinType::SveFloat32x3:
3992 return SVE_ELTTY(FloatTy, 4, 3);
3993 case BuiltinType::SveFloat32x4:
3994 return SVE_ELTTY(FloatTy, 4, 4);
3995 case BuiltinType::SveFloat64:
3996 return SVE_ELTTY(DoubleTy, 2, 1);
3997 case BuiltinType::SveFloat64x2:
3998 return SVE_ELTTY(DoubleTy, 2, 2);
3999 case BuiltinType::SveFloat64x3:
4000 return SVE_ELTTY(DoubleTy, 2, 3);
4001 case BuiltinType::SveFloat64x4:
4002 return SVE_ELTTY(DoubleTy, 2, 4);
4003 case BuiltinType::SveBFloat16:
4004 return SVE_ELTTY(BFloat16Ty, 8, 1);
4005 case BuiltinType::SveBFloat16x2:
4006 return SVE_ELTTY(BFloat16Ty, 8, 2);
4007 case BuiltinType::SveBFloat16x3:
4008 return SVE_ELTTY(BFloat16Ty, 8, 3);
4009 case BuiltinType::SveBFloat16x4:
4010 return SVE_ELTTY(BFloat16Ty, 8, 4);
4011#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4012 IsSigned) \
4013 case BuiltinType::Id: \
4014 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4015 llvm::ElementCount::getScalable(NumEls), NF};
4016#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4017 case BuiltinType::Id: \
4018 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4019 llvm::ElementCount::getScalable(NumEls), NF};
4020#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4021 case BuiltinType::Id: \
4022 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4023#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4024 case BuiltinType::Id: \
4025 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4026#include "clang/Basic/RISCVVTypes.def"
4027 }
4028}
4029
4030/// getExternrefType - Return a WebAssembly externref type, which represents an
4031/// opaque reference to a host value.
4033 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4034#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4035 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4036 return SingletonId;
4037#include "clang/Basic/WebAssemblyReferenceTypes.def"
4038 }
4039 llvm_unreachable(
4040 "shouldn't try to generate type externref outside WebAssembly target");
4041}
4042
4043/// getScalableVectorType - Return the unique reference to a scalable vector
4044/// type of the specified element type and size. VectorType must be a built-in
4045/// type.
4047 unsigned NumFields) const {
4048 if (Target->hasAArch64SVETypes()) {
4049 uint64_t EltTySize = getTypeSize(EltTy);
4050#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4051 IsSigned, IsFP, IsBF) \
4052 if (!EltTy->isBooleanType() && \
4053 ((EltTy->hasIntegerRepresentation() && \
4054 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4055 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4056 IsFP && !IsBF) || \
4057 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4058 IsBF && !IsFP)) && \
4059 EltTySize == ElBits && NumElts == NumEls) { \
4060 return SingletonId; \
4061 }
4062#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4063 if (EltTy->isBooleanType() && NumElts == NumEls) \
4064 return SingletonId;
4065#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4066#include "clang/Basic/AArch64SVEACLETypes.def"
4067 } else if (Target->hasRISCVVTypes()) {
4068 uint64_t EltTySize = getTypeSize(EltTy);
4069#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4070 IsFP, IsBF) \
4071 if (!EltTy->isBooleanType() && \
4072 ((EltTy->hasIntegerRepresentation() && \
4073 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4074 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4075 IsFP && !IsBF) || \
4076 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4077 IsBF && !IsFP)) && \
4078 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4079 return SingletonId;
4080#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4081 if (EltTy->isBooleanType() && NumElts == NumEls) \
4082 return SingletonId;
4083#include "clang/Basic/RISCVVTypes.def"
4084 }
4085 return QualType();
4086}
4087
4088/// getVectorType - Return the unique reference to a vector type of
4089/// the specified element type and size. VectorType must be a built-in type.
4091 VectorKind VecKind) const {
4092 assert(vecType->isBuiltinType() ||
4093 (vecType->isBitIntType() &&
4094 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4095 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4096 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4097
4098 // Check if we've already instantiated a vector of this type.
4099 llvm::FoldingSetNodeID ID;
4100 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4101
4102 void *InsertPos = nullptr;
4103 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4104 return QualType(VTP, 0);
4105
4106 // If the element type isn't canonical, this won't be a canonical type either,
4107 // so fill in the canonical type field.
4108 QualType Canonical;
4109 if (!vecType.isCanonical()) {
4110 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4111
4112 // Get the new insert position for the node we care about.
4113 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4114 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4115 }
4116 auto *New = new (*this, alignof(VectorType))
4117 VectorType(vecType, NumElts, Canonical, VecKind);
4118 VectorTypes.InsertNode(New, InsertPos);
4119 Types.push_back(New);
4120 return QualType(New, 0);
4121}
4122
4124 SourceLocation AttrLoc,
4125 VectorKind VecKind) const {
4126 llvm::FoldingSetNodeID ID;
4127 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4128 VecKind);
4129 void *InsertPos = nullptr;
4130 DependentVectorType *Canon =
4131 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4133
4134 if (Canon) {
4135 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4136 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4137 } else {
4138 QualType CanonVecTy = getCanonicalType(VecType);
4139 if (CanonVecTy == VecType) {
4140 New = new (*this, alignof(DependentVectorType))
4141 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4142
4143 DependentVectorType *CanonCheck =
4144 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4145 assert(!CanonCheck &&
4146 "Dependent-sized vector_size canonical type broken");
4147 (void)CanonCheck;
4148 DependentVectorTypes.InsertNode(New, InsertPos);
4149 } else {
4150 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4151 SourceLocation(), VecKind);
4152 New = new (*this, alignof(DependentVectorType))
4153 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4154 }
4155 }
4156
4157 Types.push_back(New);
4158 return QualType(New, 0);
4159}
4160
4161/// getExtVectorType - Return the unique reference to an extended vector type of
4162/// the specified element type and size. VectorType must be a built-in type.
4164 unsigned NumElts) const {
4165 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4166 (vecType->isBitIntType() &&
4167 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4168 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4169 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4170
4171 // Check if we've already instantiated a vector of this type.
4172 llvm::FoldingSetNodeID ID;
4173 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4175 void *InsertPos = nullptr;
4176 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4177 return QualType(VTP, 0);
4178
4179 // If the element type isn't canonical, this won't be a canonical type either,
4180 // so fill in the canonical type field.
4181 QualType Canonical;
4182 if (!vecType.isCanonical()) {
4183 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4184
4185 // Get the new insert position for the node we care about.
4186 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4187 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4188 }
4189 auto *New = new (*this, alignof(ExtVectorType))
4190 ExtVectorType(vecType, NumElts, Canonical);
4191 VectorTypes.InsertNode(New, InsertPos);
4192 Types.push_back(New);
4193 return QualType(New, 0);
4194}
4195
4198 Expr *SizeExpr,
4199 SourceLocation AttrLoc) const {
4200 llvm::FoldingSetNodeID ID;
4202 SizeExpr);
4203
4204 void *InsertPos = nullptr;
4206 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4208 if (Canon) {
4209 // We already have a canonical version of this array type; use it as
4210 // the canonical type for a newly-built type.
4211 New = new (*this, alignof(DependentSizedExtVectorType))
4212 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4213 AttrLoc);
4214 } else {
4215 QualType CanonVecTy = getCanonicalType(vecType);
4216 if (CanonVecTy == vecType) {
4217 New = new (*this, alignof(DependentSizedExtVectorType))
4218 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4219
4220 DependentSizedExtVectorType *CanonCheck
4221 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4222 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4223 (void)CanonCheck;
4224 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4225 } else {
4226 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4227 SourceLocation());
4228 New = new (*this, alignof(DependentSizedExtVectorType))
4229 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4230 }
4231 }
4232
4233 Types.push_back(New);
4234 return QualType(New, 0);
4235}
4236
4238 unsigned NumColumns) const {
4239 llvm::FoldingSetNodeID ID;
4240 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4241 Type::ConstantMatrix);
4242
4243 assert(MatrixType::isValidElementType(ElementTy) &&
4244 "need a valid element type");
4245 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4247 "need valid matrix dimensions");
4248 void *InsertPos = nullptr;
4249 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4250 return QualType(MTP, 0);
4251
4252 QualType Canonical;
4253 if (!ElementTy.isCanonical()) {
4254 Canonical =
4255 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4256
4257 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4258 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4259 (void)NewIP;
4260 }
4261
4262 auto *New = new (*this, alignof(ConstantMatrixType))
4263 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4264 MatrixTypes.InsertNode(New, InsertPos);
4265 Types.push_back(New);
4266 return QualType(New, 0);
4267}
4268
4270 Expr *RowExpr,
4271 Expr *ColumnExpr,
4272 SourceLocation AttrLoc) const {
4273 QualType CanonElementTy = getCanonicalType(ElementTy);
4274 llvm::FoldingSetNodeID ID;
4275 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4276 ColumnExpr);
4277
4278 void *InsertPos = nullptr;
4280 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4281
4282 if (!Canon) {
4283 Canon = new (*this, alignof(DependentSizedMatrixType))
4284 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4285 ColumnExpr, AttrLoc);
4286#ifndef NDEBUG
4287 DependentSizedMatrixType *CanonCheck =
4288 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4289 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4290#endif
4291 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4292 Types.push_back(Canon);
4293 }
4294
4295 // Already have a canonical version of the matrix type
4296 //
4297 // If it exactly matches the requested type, use it directly.
4298 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4299 Canon->getRowExpr() == ColumnExpr)
4300 return QualType(Canon, 0);
4301
4302 // Use Canon as the canonical type for newly-built type.
4303 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4304 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4305 ColumnExpr, AttrLoc);
4306 Types.push_back(New);
4307 return QualType(New, 0);
4308}
4309
4311 Expr *AddrSpaceExpr,
4312 SourceLocation AttrLoc) const {
4313 assert(AddrSpaceExpr->isInstantiationDependent());
4314
4315 QualType canonPointeeType = getCanonicalType(PointeeType);
4316
4317 void *insertPos = nullptr;
4318 llvm::FoldingSetNodeID ID;
4319 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4320 AddrSpaceExpr);
4321
4322 DependentAddressSpaceType *canonTy =
4323 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4324
4325 if (!canonTy) {
4326 canonTy = new (*this, alignof(DependentAddressSpaceType))
4327 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4328 AttrLoc);
4329 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4330 Types.push_back(canonTy);
4331 }
4332
4333 if (canonPointeeType == PointeeType &&
4334 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4335 return QualType(canonTy, 0);
4336
4337 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4338 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4339 AddrSpaceExpr, AttrLoc);
4340 Types.push_back(sugaredType);
4341 return QualType(sugaredType, 0);
4342}
4343
4344/// Determine whether \p T is canonical as the result type of a function.
4346 return T.isCanonical() &&
4347 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4348 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4349}
4350
4351/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4354 const FunctionType::ExtInfo &Info) const {
4355 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4356 // functionality creates a function without a prototype regardless of
4357 // language mode (so it makes them even in C++). Once the rewriter has been
4358 // fixed, this assertion can be enabled again.
4359 //assert(!LangOpts.requiresStrictPrototypes() &&
4360 // "strict prototypes are disabled");
4361
4362 // Unique functions, to guarantee there is only one function of a particular
4363 // structure.
4364 llvm::FoldingSetNodeID ID;
4365 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4366
4367 void *InsertPos = nullptr;
4368 if (FunctionNoProtoType *FT =
4369 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4370 return QualType(FT, 0);
4371
4372 QualType Canonical;
4373 if (!isCanonicalResultType(ResultTy)) {
4374 Canonical =
4376
4377 // Get the new insert position for the node we care about.
4378 FunctionNoProtoType *NewIP =
4379 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4380 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4381 }
4382
4383 auto *New = new (*this, alignof(FunctionNoProtoType))
4384 FunctionNoProtoType(ResultTy, Canonical, Info);
4385 Types.push_back(New);
4386 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4387 return QualType(New, 0);
4388}
4389
4392 CanQualType CanResultType = getCanonicalType(ResultType);
4393
4394 // Canonical result types do not have ARC lifetime qualifiers.
4395 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4396 Qualifiers Qs = CanResultType.getQualifiers();
4397 Qs.removeObjCLifetime();
4399 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4400 }
4401
4402 return CanResultType;
4403}
4404
4406 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4407 if (ESI.Type == EST_None)
4408 return true;
4409 if (!NoexceptInType)
4410 return false;
4411
4412 // C++17 onwards: exception specification is part of the type, as a simple
4413 // boolean "can this function type throw".
4414 if (ESI.Type == EST_BasicNoexcept)
4415 return true;
4416
4417 // A noexcept(expr) specification is (possibly) canonical if expr is
4418 // value-dependent.
4419 if (ESI.Type == EST_DependentNoexcept)
4420 return true;
4421
4422 // A dynamic exception specification is canonical if it only contains pack
4423 // expansions (so we can't tell whether it's non-throwing) and all its
4424 // contained types are canonical.
4425 if (ESI.Type == EST_Dynamic) {
4426 bool AnyPackExpansions = false;
4427 for (QualType ET : ESI.Exceptions) {
4428 if (!ET.isCanonical())
4429 return false;
4430 if (ET->getAs<PackExpansionType>())
4431 AnyPackExpansions = true;
4432 }
4433 return AnyPackExpansions;
4434 }
4435
4436 return false;
4437}
4438
4439QualType ASTContext::getFunctionTypeInternal(
4440 QualType ResultTy, ArrayRef<QualType> ArgArray,
4441 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4442 size_t NumArgs = ArgArray.size();
4443
4444 // Unique functions, to guarantee there is only one function of a particular
4445 // structure.
4446 llvm::FoldingSetNodeID ID;
4447 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4448 *this, true);
4449
4450 QualType Canonical;
4451 bool Unique = false;
4452
4453 void *InsertPos = nullptr;
4454 if (FunctionProtoType *FPT =
4455 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4456 QualType Existing = QualType(FPT, 0);
4457
4458 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4459 // it so long as our exception specification doesn't contain a dependent
4460 // noexcept expression, or we're just looking for a canonical type.
4461 // Otherwise, we're going to need to create a type
4462 // sugar node to hold the concrete expression.
4463 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4464 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4465 return Existing;
4466
4467 // We need a new type sugar node for this one, to hold the new noexcept
4468 // expression. We do no canonicalization here, but that's OK since we don't
4469 // expect to see the same noexcept expression much more than once.
4470 Canonical = getCanonicalType(Existing);
4471 Unique = true;
4472 }
4473
4474 bool NoexceptInType = getLangOpts().CPlusPlus17;
4475 bool IsCanonicalExceptionSpec =
4477
4478 // Determine whether the type being created is already canonical or not.
4479 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4480 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4481 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4482 if (!ArgArray[i].isCanonicalAsParam())
4483 isCanonical = false;
4484
4485 if (OnlyWantCanonical)
4486 assert(isCanonical &&
4487 "given non-canonical parameters constructing canonical type");
4488
4489 // If this type isn't canonical, get the canonical version of it if we don't
4490 // already have it. The exception spec is only partially part of the
4491 // canonical type, and only in C++17 onwards.
4492 if (!isCanonical && Canonical.isNull()) {
4493 SmallVector<QualType, 16> CanonicalArgs;
4494 CanonicalArgs.reserve(NumArgs);
4495 for (unsigned i = 0; i != NumArgs; ++i)
4496 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4497
4498 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4499 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4500 CanonicalEPI.HasTrailingReturn = false;
4501
4502 if (IsCanonicalExceptionSpec) {
4503 // Exception spec is already OK.
4504 } else if (NoexceptInType) {
4505 switch (EPI.ExceptionSpec.Type) {
4507 // We don't know yet. It shouldn't matter what we pick here; no-one
4508 // should ever look at this.
4509 [[fallthrough]];
4510 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4511 CanonicalEPI.ExceptionSpec.Type = EST_None;
4512 break;
4513
4514 // A dynamic exception specification is almost always "not noexcept",
4515 // with the exception that a pack expansion might expand to no types.
4516 case EST_Dynamic: {
4517 bool AnyPacks = false;
4518 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4519 if (ET->getAs<PackExpansionType>())
4520 AnyPacks = true;
4521 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4522 }
4523 if (!AnyPacks)
4524 CanonicalEPI.ExceptionSpec.Type = EST_None;
4525 else {
4526 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4527 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4528 }
4529 break;
4530 }
4531
4532 case EST_DynamicNone:
4533 case EST_BasicNoexcept:
4534 case EST_NoexceptTrue:
4535 case EST_NoThrow:
4536 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4537 break;
4538
4540 llvm_unreachable("dependent noexcept is already canonical");
4541 }
4542 } else {
4544 }
4545
4546 // Adjust the canonical function result type.
4547 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4548 Canonical =
4549 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4550
4551 // Get the new insert position for the node we care about.
4552 FunctionProtoType *NewIP =
4553 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4554 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4555 }
4556
4557 // Compute the needed size to hold this FunctionProtoType and the
4558 // various trailing objects.
4559 auto ESH = FunctionProtoType::getExceptionSpecSize(
4560 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4561 size_t Size = FunctionProtoType::totalSizeToAlloc<
4566 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4567 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4568 EPI.ExtParameterInfos ? NumArgs : 0,
4569 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4570
4571 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4573 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4574 Types.push_back(FTP);
4575 if (!Unique)
4576 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4577 return QualType(FTP, 0);
4578}
4579
4580QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4581 llvm::FoldingSetNodeID ID;
4582 PipeType::Profile(ID, T, ReadOnly);
4583
4584 void *InsertPos = nullptr;
4585 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4586 return QualType(PT, 0);
4587
4588 // If the pipe element type isn't canonical, this won't be a canonical type
4589 // either, so fill in the canonical type field.
4590 QualType Canonical;
4591 if (!T.isCanonical()) {
4592 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4593
4594 // Get the new insert position for the node we care about.
4595 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4596 assert(!NewIP && "Shouldn't be in the map!");
4597 (void)NewIP;
4598 }
4599 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4600 Types.push_back(New);
4601 PipeTypes.InsertNode(New, InsertPos);
4602 return QualType(New, 0);
4603}
4604
4606 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4607 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4608 : Ty;
4609}
4610
4612 return getPipeType(T, true);
4613}
4614
4616 return getPipeType(T, false);
4617}
4618
4619QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4620 llvm::FoldingSetNodeID ID;
4621 BitIntType::Profile(ID, IsUnsigned, NumBits);
4622
4623 void *InsertPos = nullptr;
4624 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4625 return QualType(EIT, 0);
4626
4627 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4628 BitIntTypes.InsertNode(New, InsertPos);
4629 Types.push_back(New);
4630 return QualType(New, 0);
4631}
4632
4634 Expr *NumBitsExpr) const {
4635 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4636 llvm::FoldingSetNodeID ID;
4637 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4638
4639 void *InsertPos = nullptr;
4640 if (DependentBitIntType *Existing =
4641 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4642 return QualType(Existing, 0);
4643
4644 auto *New = new (*this, alignof(DependentBitIntType))
4645 DependentBitIntType(IsUnsigned, NumBitsExpr);
4646 DependentBitIntTypes.InsertNode(New, InsertPos);
4647
4648 Types.push_back(New);
4649 return QualType(New, 0);
4650}
4651
4652#ifndef NDEBUG
4654 if (!isa<CXXRecordDecl>(D)) return false;
4655 const auto *RD = cast<CXXRecordDecl>(D);
4656 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4657 return true;
4658 if (RD->getDescribedClassTemplate() &&
4659 !isa<ClassTemplateSpecializationDecl>(RD))
4660 return true;
4661 return false;
4662}
4663#endif
4664
4665/// getInjectedClassNameType - Return the unique reference to the
4666/// injected class name type for the specified templated declaration.
4668 QualType TST) const {
4670 if (Decl->TypeForDecl) {
4671 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4672 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4673 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4674 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4675 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4676 } else {
4677 Type *newType = new (*this, alignof(InjectedClassNameType))
4679 Decl->TypeForDecl = newType;
4680 Types.push_back(newType);
4681 }
4682 return QualType(Decl->TypeForDecl, 0);
4683}
4684
4685/// getTypeDeclType - Return the unique reference to the type for the
4686/// specified type declaration.
4687QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4688 assert(Decl && "Passed null for Decl param");
4689 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4690
4691 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4692 return getTypedefType(Typedef);
4693
4694 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4695 "Template type parameter types are always available.");
4696
4697 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4698 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4700 return getRecordType(Record);
4701 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4702 assert(Enum->isFirstDecl() && "enum has previous declaration");
4703 return getEnumType(Enum);
4704 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4705 return getUnresolvedUsingType(Using);
4706 } else
4707 llvm_unreachable("TypeDecl without a type?");
4708
4709 return QualType(Decl->TypeForDecl, 0);
4710}
4711
4712/// getTypedefType - Return the unique reference to the type for the
4713/// specified typedef name decl.
4715 QualType Underlying) const {
4716 if (!Decl->TypeForDecl) {
4717 if (Underlying.isNull())
4718 Underlying = Decl->getUnderlyingType();
4719 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
4720 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4721 Decl->TypeForDecl = NewType;
4722 Types.push_back(NewType);
4723 return QualType(NewType, 0);
4724 }
4725 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4726 return QualType(Decl->TypeForDecl, 0);
4727 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
4728
4729 llvm::FoldingSetNodeID ID;
4730 TypedefType::Profile(ID, Decl, Underlying);
4731
4732 void *InsertPos = nullptr;
4733 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4734 assert(!T->typeMatchesDecl() &&
4735 "non-divergent case should be handled with TypeDecl");
4736 return QualType(T, 0);
4737 }
4738
4739 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
4740 alignof(TypedefType));
4741 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4742 getCanonicalType(Underlying));
4743 TypedefTypes.InsertNode(NewType, InsertPos);
4744 Types.push_back(NewType);
4745 return QualType(NewType, 0);
4746}
4747
4749 QualType Underlying) const {
4750 llvm::FoldingSetNodeID ID;
4751 UsingType::Profile(ID, Found, Underlying);
4752
4753 void *InsertPos = nullptr;
4754 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4755 return QualType(T, 0);
4756
4757 const Type *TypeForDecl =
4758 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4759
4760 assert(!Underlying.hasLocalQualifiers());
4761 QualType Canon = Underlying->getCanonicalTypeInternal();
4762 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
4763
4764 if (Underlying.getTypePtr() == TypeForDecl)
4765 Underlying = QualType();
4766 void *Mem =
4767 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4768 alignof(UsingType));
4769 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4770 Types.push_back(NewType);
4771 UsingTypes.InsertNode(NewType, InsertPos);
4772 return QualType(NewType, 0);
4773}
4774
4776 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4777
4778 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4779 if (PrevDecl->TypeForDecl)
4780 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4781
4782 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
4783 Decl->TypeForDecl = newType;
4784 Types.push_back(newType);
4785 return QualType(newType, 0);
4786}
4787
4789 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4790
4791 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4792 if (PrevDecl->TypeForDecl)
4793 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4794
4795 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
4796 Decl->TypeForDecl = newType;
4797 Types.push_back(newType);
4798 return QualType(newType, 0);
4799}
4800
4802 const UnresolvedUsingTypenameDecl *Decl) const {
4803 if (Decl->TypeForDecl)
4804 return QualType(Decl->TypeForDecl, 0);
4805
4806 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4808 if (CanonicalDecl->TypeForDecl)
4809 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4810
4811 Type *newType =
4812 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
4813 Decl->TypeForDecl = newType;
4814 Types.push_back(newType);
4815 return QualType(newType, 0);
4816}
4817
4819 QualType modifiedType,
4820 QualType equivalentType) const {
4821 llvm::FoldingSetNodeID id;
4822 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4823
4824 void *insertPos = nullptr;
4825 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4826 if (type) return QualType(type, 0);
4827
4828 QualType canon = getCanonicalType(equivalentType);
4829 type = new (*this, alignof(AttributedType))
4830 AttributedType(canon, attrKind, modifiedType, equivalentType);
4831
4832 Types.push_back(type);
4833 AttributedTypes.InsertNode(type, insertPos);
4834
4835 return QualType(type, 0);
4836}
4837
4838QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4839 QualType Wrapped) {
4840 llvm::FoldingSetNodeID ID;
4841 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4842
4843 void *InsertPos = nullptr;
4845 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4846 if (Ty)
4847 return QualType(Ty, 0);
4848
4849 QualType Canon = getCanonicalType(Wrapped);
4850 Ty = new (*this, alignof(BTFTagAttributedType))
4851 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4852
4853 Types.push_back(Ty);
4854 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4855
4856 return QualType(Ty, 0);
4857}
4858
4859/// Retrieve a substitution-result type.
4861 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
4862 std::optional<unsigned> PackIndex) const {
4863 llvm::FoldingSetNodeID ID;
4864 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4865 PackIndex);
4866 void *InsertPos = nullptr;
4867 SubstTemplateTypeParmType *SubstParm =
4868 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4869
4870 if (!SubstParm) {
4871 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4872 !Replacement.isCanonical()),
4873 alignof(SubstTemplateTypeParmType));
4874 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4875 Index, PackIndex);
4876 Types.push_back(SubstParm);
4877 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4878 }
4879
4880 return QualType(SubstParm, 0);
4881}
4882
4883/// Retrieve a
4886 unsigned Index, bool Final,
4887 const TemplateArgument &ArgPack) {
4888#ifndef NDEBUG
4889 for (const auto &P : ArgPack.pack_elements())
4890 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
4891#endif
4892
4893 llvm::FoldingSetNodeID ID;
4894 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4895 ArgPack);
4896 void *InsertPos = nullptr;
4897 if (SubstTemplateTypeParmPackType *SubstParm =
4898 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4899 return QualType(SubstParm, 0);
4900
4901 QualType Canon;
4902 {
4903 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4904 if (!AssociatedDecl->isCanonicalDecl() ||
4905 !CanonArgPack.structurallyEquals(ArgPack)) {
4907 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4908 [[maybe_unused]] const auto *Nothing =
4909 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4910 assert(!Nothing);
4911 }
4912 }
4913
4914 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
4915 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
4916 ArgPack);
4917 Types.push_back(SubstParm);
4918 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4919 return QualType(SubstParm, 0);
4920}
4921
4922/// Retrieve the template type parameter type for a template
4923/// parameter or parameter pack with the given depth, index, and (optionally)
4924/// name.
4925QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4926 bool ParameterPack,
4927 TemplateTypeParmDecl *TTPDecl) const {
4928 llvm::FoldingSetNodeID ID;
4929 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4930 void *InsertPos = nullptr;
4931 TemplateTypeParmType *TypeParm
4932 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4933
4934 if (TypeParm)
4935 return QualType(TypeParm, 0);
4936
4937 if (TTPDecl) {
4938 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4939 TypeParm = new (*this, alignof(TemplateTypeParmType))
4940 TemplateTypeParmType(TTPDecl, Canon);
4941
4942 TemplateTypeParmType *TypeCheck
4943 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4944 assert(!TypeCheck && "Template type parameter canonical type broken");
4945 (void)TypeCheck;
4946 } else
4947 TypeParm = new (*this, alignof(TemplateTypeParmType))
4948 TemplateTypeParmType(Depth, Index, ParameterPack);
4949
4950 Types.push_back(TypeParm);
4951 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4952
4953 return QualType(TypeParm, 0);
4954}
4955
4958 SourceLocation NameLoc,
4959 const TemplateArgumentListInfo &Args,
4960 QualType Underlying) const {
4961 assert(!Name.getAsDependentTemplateName() &&
4962 "No dependent template names here!");
4963 QualType TST =
4964 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4965
4970 TL.setTemplateNameLoc(NameLoc);
4971 TL.setLAngleLoc(Args.getLAngleLoc());
4972 TL.setRAngleLoc(Args.getRAngleLoc());
4973 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4974 TL.setArgLocInfo(i, Args[i].getLocInfo());
4975 return DI;
4976}
4977
4981 QualType Underlying) const {
4982 assert(!Template.getAsDependentTemplateName() &&
4983 "No dependent template names here!");
4984
4986 ArgVec.reserve(Args.size());
4987 for (const TemplateArgumentLoc &Arg : Args)
4988 ArgVec.push_back(Arg.getArgument());
4989
4990 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4991}
4992
4993#ifndef NDEBUG
4995 for (const TemplateArgument &Arg : Args)
4996 if (Arg.isPackExpansion())
4997 return true;
4998
4999 return true;
5000}
5001#endif
5002
5006 QualType Underlying) const {
5007 assert(!Template.getAsDependentTemplateName() &&
5008 "No dependent template names here!");
5009 // Look through qualified template names.
5011 Template = QTN->getUnderlyingTemplate();
5012
5013 const auto *TD = Template.getAsTemplateDecl();
5014 bool IsTypeAlias = TD && TD->isTypeAlias();
5015 QualType CanonType;
5016 if (!Underlying.isNull())
5017 CanonType = getCanonicalType(Underlying);
5018 else {
5019 // We can get here with an alias template when the specialization contains
5020 // a pack expansion that does not match up with a parameter pack.
5021 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5022 "Caller must compute aliased type");
5023 IsTypeAlias = false;
5024 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5025 }
5026
5027 // Allocate the (non-canonical) template specialization type, but don't
5028 // try to unique it: these types typically have location information that
5029 // we don't unique and don't want to lose.
5030 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5031 sizeof(TemplateArgument) * Args.size() +
5032 (IsTypeAlias ? sizeof(QualType) : 0),
5034 auto *Spec
5035 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5036 IsTypeAlias ? Underlying : QualType());
5037
5038 Types.push_back(Spec);
5039 return QualType(Spec, 0);
5040}
5041
5043 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5044 assert(!Template.getAsDependentTemplateName() &&
5045 "No dependent template names here!");
5046
5047 // Look through qualified template names.
5049 Template = TemplateName(QTN->getUnderlyingTemplate());
5050
5051 // Build the canonical template specialization type.
5052 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5053 bool AnyNonCanonArgs = false;
5054 auto CanonArgs =
5055 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5056
5057 // Determine whether this canonical template specialization type already
5058 // exists.
5059 llvm::FoldingSetNodeID ID;
5060 TemplateSpecializationType::Profile(ID, CanonTemplate,
5061 CanonArgs, *this);
5062
5063 void *InsertPos = nullptr;
5065 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5066
5067 if (!Spec) {
5068 // Allocate a new canonical template specialization type.
5069 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5070 sizeof(TemplateArgument) * CanonArgs.size()),
5072 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5073 CanonArgs,
5074 QualType(), QualType());
5075 Types.push_back(Spec);
5076 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5077 }
5078
5079 assert(Spec->isDependentType() &&
5080 "Non-dependent template-id type must have a canonical type");
5081 return QualType(Spec, 0);
5082}
5083
5086 QualType NamedType,
5087 TagDecl *OwnedTagDecl) const {
5088 llvm::FoldingSetNodeID ID;
5089 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5090
5091 void *InsertPos = nullptr;
5092 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5093 if (T)
5094 return QualType(T, 0);
5095
5096 QualType Canon = NamedType;
5097 if (!Canon.isCanonical()) {
5098 Canon = getCanonicalType(NamedType);
5099 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5100 assert(!CheckT && "Elaborated canonical type broken");
5101 (void)CheckT;
5102 }
5103
5104 void *Mem =
5105 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5106 alignof(ElaboratedType));
5107 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5108
5109 Types.push_back(T);
5110 ElaboratedTypes.InsertNode(T, InsertPos);
5111 return QualType(T, 0);
5112}
5113
5116 llvm::FoldingSetNodeID ID;
5117 ParenType::Profile(ID, InnerType);
5118
5119 void *InsertPos = nullptr;
5120 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5121 if (T)
5122 return QualType(T, 0);
5123
5124 QualType Canon = InnerType;
5125 if (!Canon.isCanonical()) {
5126 Canon = getCanonicalType(InnerType);
5127 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5128 assert(!CheckT && "Paren canonical type broken");
5129 (void)CheckT;
5130 }
5131
5132 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5133 Types.push_back(T);
5134 ParenTypes.InsertNode(T, InsertPos);
5135 return QualType(T, 0);
5136}
5137
5140 const IdentifierInfo *MacroII) const {
5141 QualType Canon = UnderlyingTy;
5142 if (!Canon.isCanonical())
5143 Canon = getCanonicalType(UnderlyingTy);
5144
5145 auto *newType = new (*this, alignof(MacroQualifiedType))
5146 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5147 Types.push_back(newType);
5148 return QualType(newType, 0);
5149}
5150
5153 const IdentifierInfo *Name,
5154 QualType Canon) const {
5155 if (Canon.isNull()) {
5157 if (CanonNNS != NNS)
5158 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5159 }
5160
5161 llvm::FoldingSetNodeID ID;
5162 DependentNameType::Profile(ID, Keyword, NNS, Name);
5163
5164 void *InsertPos = nullptr;
5166 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5167 if (T)
5168 return QualType(T, 0);
5169
5170 T = new (*this, alignof(DependentNameType))
5171 DependentNameType(Keyword, NNS, Name, Canon);
5172 Types.push_back(T);
5173 DependentNameTypes.InsertNode(T, InsertPos);
5174 return QualType(T, 0);
5175}
5176
5179 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5180 // TODO: avoid this copy
5182 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5183 ArgCopy.push_back(Args[I].getArgument());
5184 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5185}
5186
5189 ElaboratedTypeKeyword Keyword,
5191 const IdentifierInfo *Name,
5192 ArrayRef<TemplateArgument> Args) const {
5193 assert((!NNS || NNS->isDependent()) &&
5194 "nested-name-specifier must be dependent");
5195
5196 llvm::FoldingSetNodeID ID;
5197 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5198 Name, Args);
5199
5200 void *InsertPos = nullptr;
5202 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5203 if (T)
5204 return QualType(T, 0);
5205
5207
5208 ElaboratedTypeKeyword CanonKeyword = Keyword;
5209 if (Keyword == ElaboratedTypeKeyword::None)
5210 CanonKeyword = ElaboratedTypeKeyword::Typename;
5211
5212 bool AnyNonCanonArgs = false;
5213 auto CanonArgs =
5214 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5215
5216 QualType Canon;
5217 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5218 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5219 Name,
5220 CanonArgs);
5221
5222 // Find the insert position again.
5223 [[maybe_unused]] auto *Nothing =
5224 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5225 assert(!Nothing && "canonical type broken");
5226 }
5227
5228 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5229 sizeof(TemplateArgument) * Args.size()),
5231 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5232 Name, Args, Canon);
5233 Types.push_back(T);
5234 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5235 return QualType(T, 0);
5236}
5237
5239 TemplateArgument Arg;
5240 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5241 QualType ArgType = getTypeDeclType(TTP);
5242 if (TTP->isParameterPack())
5243 ArgType = getPackExpansionType(ArgType, std::nullopt);
5244
5245 Arg = TemplateArgument(ArgType);
5246 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5247 QualType T =
5248 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5249 // For class NTTPs, ensure we include the 'const' so the type matches that
5250 // of a real template argument.
5251 // FIXME: It would be more faithful to model this as something like an
5252 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5253 if (T->isRecordType())
5254 T.addConst();
5255 Expr *E = new (*this) DeclRefExpr(
5256 *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5257 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5258
5259 if (NTTP->isParameterPack())
5260 E = new (*this)
5261 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5262 Arg = TemplateArgument(E);
5263 } else {
5264 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5265 if (TTP->isParameterPack())
5266 Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>());
5267 else
5268 Arg = TemplateArgument(TemplateName(TTP));
5269 }
5270
5271 if (Param->isTemplateParameterPack())
5272 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5273
5274 return Arg;
5275}
5276
5277void
5280 Args.reserve(Args.size() + Params->size());
5281
5282 for (NamedDecl *Param : *Params)
5283 Args.push_back(getInjectedTemplateArg(Param));
5284}
5285
5287 std::optional<unsigned> NumExpansions,
5288 bool ExpectPackInType) {
5289 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5290 "Pack expansions must expand one or more parameter packs");
5291
5292 llvm::FoldingSetNodeID ID;
5293 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5294
5295 void *InsertPos = nullptr;
5296 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5297 if (T)
5298 return QualType(T, 0);
5299
5300 QualType Canon;
5301 if (!Pattern.isCanonical()) {
5302 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5303 /*ExpectPackInType=*/false);
5304
5305 // Find the insert position again, in case we inserted an element into
5306 // PackExpansionTypes and invalidated our insert position.
5307 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5308 }
5309
5310 T = new (*this, alignof(PackExpansionType))
5311 PackExpansionType(Pattern, Canon, NumExpansions);
5312 Types.push_back(T);
5313 PackExpansionTypes.InsertNode(T, InsertPos);
5314 return QualType(T, 0);
5315}
5316
5317/// CmpProtocolNames - Comparison predicate for sorting protocols
5318/// alphabetically.
5319static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5320 ObjCProtocolDecl *const *RHS) {
5321 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5322}
5323
5325 if (Protocols.empty()) return true;
5326
5327 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5328 return false;
5329
5330 for (unsigned i = 1; i != Protocols.size(); ++i)
5331 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5332 Protocols[i]->getCanonicalDecl() != Protocols[i])
5333 return false;
5334 return true;
5335}
5336
5337static void
5339 // Sort protocols, keyed by name.
5340 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5341
5342 // Canonicalize.
5343 for (ObjCProtocolDecl *&P : Protocols)
5344 P = P->getCanonicalDecl();
5345
5346 // Remove duplicates.
5347 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5348 Protocols.erase(ProtocolsEnd, Protocols.end());
5349}
5350
5352 ObjCProtocolDecl * const *Protocols,
5353 unsigned NumProtocols) const {
5354 return getObjCObjectType(BaseType, {},
5355 llvm::ArrayRef(Protocols, NumProtocols),
5356 /*isKindOf=*/false);
5357}
5358
5360 QualType baseType,
5361 ArrayRef<QualType> typeArgs,
5363 bool isKindOf) const {
5364 // If the base type is an interface and there aren't any protocols or
5365 // type arguments to add, then the interface type will do just fine.
5366 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5367 isa<ObjCInterfaceType>(baseType))
5368 return baseType;
5369
5370 // Look in the folding set for an existing type.
5371 llvm::FoldingSetNodeID ID;
5372 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5373 void *InsertPos = nullptr;
5374 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5375 return QualType(QT, 0);
5376
5377 // Determine the type arguments to be used for canonicalization,
5378 // which may be explicitly specified here or written on the base
5379 // type.
5380 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5381 if (effectiveTypeArgs.empty()) {
5382 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5383 effectiveTypeArgs = baseObject->getTypeArgs();
5384 }
5385
5386 // Build the canonical type, which has the canonical base type and a
5387 // sorted-and-uniqued list of protocols and the type arguments
5388 // canonicalized.
5389 QualType canonical;
5390 bool typeArgsAreCanonical = llvm::all_of(
5391 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5392 bool protocolsSorted = areSortedAndUniqued(protocols);
5393 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5394 // Determine the canonical type arguments.
5395 ArrayRef<QualType> canonTypeArgs;
5396 SmallVector<QualType, 4> canonTypeArgsVec;
5397 if (!typeArgsAreCanonical) {
5398 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5399 for (auto typeArg : effectiveTypeArgs)
5400 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5401 canonTypeArgs = canonTypeArgsVec;
5402 } else {
5403 canonTypeArgs = effectiveTypeArgs;
5404 }
5405
5406 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5407 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5408 if (!protocolsSorted) {
5409 canonProtocolsVec.append(protocols.begin(), protocols.end());
5410 SortAndUniqueProtocols(canonProtocolsVec);
5411 canonProtocols = canonProtocolsVec;
5412 } else {
5413 canonProtocols = protocols;
5414 }
5415
5416 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5417 canonProtocols, isKindOf);
5418
5419 // Regenerate InsertPos.
5420 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5421 }
5422
5423 unsigned size = sizeof(ObjCObjectTypeImpl);
5424 size += typeArgs.size() * sizeof(QualType);
5425 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5426 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5427 auto *T =
5428 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5429 isKindOf);
5430
5431 Types.push_back(T);
5432 ObjCObjectTypes.InsertNode(T, InsertPos);
5433 return QualType(T, 0);
5434}
5435
5436/// Apply Objective-C protocol qualifiers to the given type.
5437/// If this is for the canonical type of a type parameter, we can apply
5438/// protocol qualifiers on the ObjCObjectPointerType.
5441 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5442 bool allowOnPointerType) const {
5443 hasError = false;
5444
5445 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5446 return getObjCTypeParamType(objT->getDecl(), protocols);
5447 }
5448
5449 // Apply protocol qualifiers to ObjCObjectPointerType.
5450 if (allowOnPointerType) {
5451 if (const auto *objPtr =
5452 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5453 const ObjCObjectType *objT = objPtr->getObjectType();
5454 // Merge protocol lists and construct ObjCObjectType.
5456 protocolsVec.append(objT->qual_begin(),
5457 objT->qual_end());
5458 protocolsVec.append(protocols.begin(), protocols.end());
5459 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5461 objT->getBaseType(),
5462 objT->getTypeArgsAsWritten(),
5463 protocols,
5464 objT->isKindOfTypeAsWritten());
5466 }
5467 }
5468
5469 // Apply protocol qualifiers to ObjCObjectType.
5470 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5471 // FIXME: Check for protocols to which the class type is already
5472 // known to conform.
5473
5474 return getObjCObjectType(objT->getBaseType(),
5475 objT->getTypeArgsAsWritten(),
5476 protocols,
5477 objT->isKindOfTypeAsWritten());
5478 }
5479
5480 // If the canonical type is ObjCObjectType, ...
5481 if (type->isObjCObjectType()) {
5482 // Silently overwrite any existing protocol qualifiers.
5483 // TODO: determine whether that's the right thing to do.
5484
5485 // FIXME: Check for protocols to which the class type is already
5486 // known to conform.
5487 return getObjCObjectType(type, {}, protocols, false);
5488 }
5489
5490 // id<protocol-list>
5491 if (type->isObjCIdType()) {
5492 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5493 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5494 objPtr->isKindOfType());
5496 }
5497
5498 // Class<protocol-list>
5499 if (type->isObjCClassType()) {
5500 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5501 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5502 objPtr->isKindOfType());
5504 }
5505
5506 hasError = true;
5507 return type;
5508}
5509
5512 ArrayRef<ObjCProtocolDecl *> protocols) const {
5513 // Look in the folding set for an existing type.
5514 llvm::FoldingSetNodeID ID;
5515 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5516 void *InsertPos = nullptr;
5517 if (ObjCTypeParamType *TypeParam =
5518 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5519 return QualType(TypeParam, 0);
5520
5521 // We canonicalize to the underlying type.
5522 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5523 if (!protocols.empty()) {
5524 // Apply the protocol qualifers.
5525 bool hasError;
5527 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5528 assert(!hasError && "Error when apply protocol qualifier to bound type");
5529 }
5530
5531 unsigned size = sizeof(ObjCTypeParamType);
5532 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5533 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5534 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5535
5536 Types.push_back(newType);
5537 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5538 return QualType(newType, 0);
5539}
5540
5542 ObjCTypeParamDecl *New) const {
5544 // Update TypeForDecl after updating TypeSourceInfo.
5545 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5547 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5548 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5549 New->setTypeForDecl(UpdatedTy.getTypePtr());
5550}
5551
5552/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5553/// protocol list adopt all protocols in QT's qualified-id protocol
5554/// list.
5556 ObjCInterfaceDecl *IC) {
5557 if (!QT->isObjCQualifiedIdType())
5558 return false;
5559
5560 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5561 // If both the right and left sides have qualifiers.
5562 for (auto *Proto : OPT->quals()) {
5563 if (!IC->ClassImplementsProtocol(Proto, false))
5564 return false;
5565 }
5566 return true;
5567 }
5568 return false;
5569}
5570
5571/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5572/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5573/// of protocols.
5575 ObjCInterfaceDecl *IDecl) {
5576 if (!QT->isObjCQualifiedIdType())
5577 return false;
5578 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5579 if (!OPT)
5580 return false;
5581 if (!IDecl->hasDefinition())
5582 return false;
5584 CollectInheritedProtocols(IDecl, InheritedProtocols);
5585 if (InheritedProtocols.empty())
5586 return false;
5587 // Check that if every protocol in list of id<plist> conforms to a protocol
5588 // of IDecl's, then bridge casting is ok.
5589 bool Conforms = false;
5590 for (auto *Proto : OPT->quals()) {
5591 Conforms = false;
5592 for (auto *PI : InheritedProtocols) {
5593 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5594 Conforms = true;
5595 break;
5596 }
5597 }
5598 if (!Conforms)
5599 break;
5600 }
5601 if (Conforms)
5602 return true;
5603
5604 for (auto *PI : InheritedProtocols) {
5605 // If both the right and left sides have qualifiers.
5606 bool Adopts = false;
5607 for (auto *Proto : OPT->quals()) {
5608 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5609 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5610 break;
5611 }
5612 if (!Adopts)
5613 return false;
5614 }
5615 return true;
5616}
5617
5618/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5619/// the given object type.
5621 llvm::FoldingSetNodeID ID;
5622 ObjCObjectPointerType::Profile(ID, ObjectT);
5623
5624 void *InsertPos = nullptr;
5625 if (ObjCObjectPointerType *QT =
5626 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5627 return QualType(QT, 0);
5628
5629 // Find the canonical object type.
5630 QualType Canonical;
5631 if (!ObjectT.isCanonical()) {
5632 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5633
5634 // Regenerate InsertPos.
5635 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5636 }
5637
5638 // No match.
5639 void *Mem =
5641 auto *QType =
5642 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5643
5644 Types.push_back(QType);
5645 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5646 return QualType(QType, 0);
5647}
5648
5649/// getObjCInterfaceType - Return the unique reference to the type for the
5650/// specified ObjC interface decl. The list of protocols is optional.
5652 ObjCInterfaceDecl *PrevDecl) const {
5653 if (Decl->TypeForDecl)
5654 return QualType(Decl->TypeForDecl, 0);
5655
5656 if (PrevDecl) {
5657 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5658 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5659 return QualType(PrevDecl->TypeForDecl, 0);
5660 }
5661
5662 // Prefer the definition, if there is one.
5663 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5664 Decl = Def;
5665
5666 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
5667 auto *T = new (Mem) ObjCInterfaceType(Decl);
5668 Decl->TypeForDecl = T;
5669 Types.push_back(T);
5670 return QualType(T, 0);
5671}
5672
5673/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5674/// TypeOfExprType AST's (since expression's are never shared). For example,
5675/// multiple declarations that refer to "typeof(x)" all contain different
5676/// DeclRefExpr's. This doesn't effect the type checker, since it operates
5677/// on canonical type's (which are always unique).
5679 TypeOfExprType *toe;
5680 if (tofExpr->isTypeDependent()) {
5681 llvm::FoldingSetNodeID ID;
5682 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
5683 Kind == TypeOfKind::Unqualified);
5684
5685 void *InsertPos = nullptr;
5687 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5688 if (Canon) {
5689 // We already have a "canonical" version of an identical, dependent
5690 // typeof(expr) type. Use that as our canonical type.
5691 toe = new (*this, alignof(TypeOfExprType))
5692 TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
5693 } else {
5694 // Build a new, canonical typeof(expr) type.
5695 Canon = new (*this, alignof(DependentTypeOfExprType))
5696 DependentTypeOfExprType(tofExpr, Kind);
5697 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5698 toe = Canon;
5699 }
5700 } else {
5701 QualType Canonical = getCanonicalType(tofExpr->getType());
5702 toe = new (*this, alignof(TypeOfExprType))
5703 TypeOfExprType(tofExpr, Kind, Canonical);
5704 }
5705 Types.push_back(toe);
5706 return QualType(toe, 0);
5707}
5708
5709/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5710/// TypeOfType nodes. The only motivation to unique these nodes would be
5711/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5712/// an issue. This doesn't affect the type checker, since it operates
5713/// on canonical types (which are always unique).
5715 QualType Canonical = getCanonicalType(tofType);
5716 auto *tot =
5717 new (*this, alignof(TypeOfType)) TypeOfType(tofType, Canonical, Kind);
5718 Types.push_back(tot);
5719 return QualType(tot, 0);
5720}
5721
5722/// getReferenceQualifiedType - Given an expr, will return the type for
5723/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5724/// and class member access into account.
5726 // C++11 [dcl.type.simple]p4:
5727 // [...]
5728 QualType T = E->getType();
5729 switch (E->getValueKind()) {
5730 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5731 // type of e;
5732 case VK_XValue:
5733 return getRValueReferenceType(T);
5734 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5735 // type of e;
5736 case VK_LValue:
5737 return getLValueReferenceType(T);
5738 // - otherwise, decltype(e) is the type of e.
5739 case VK_PRValue:
5740 return T;
5741 }
5742 llvm_unreachable("Unknown value kind");
5743}
5744
5745/// Unlike many "get<Type>" functions, we don't unique DecltypeType
5746/// nodes. This would never be helpful, since each such type has its own
5747/// expression, and would not give a significant memory saving, since there
5748/// is an Expr tree under each such type.
5750 DecltypeType *dt;
5751
5752 // C++11 [temp.type]p2:
5753 // If an expression e involves a template parameter, decltype(e) denotes a
5754 // unique dependent type. Two such decltype-specifiers refer to the same
5755 // type only if their expressions are equivalent (14.5.6.1).
5756 if (e->isInstantiationDependent()) {
5757 llvm::FoldingSetNodeID ID;
5758 DependentDecltypeType::Profile(ID, *this, e);
5759
5760 void *InsertPos = nullptr;
5762 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5763 if (!Canon) {
5764 // Build a new, canonical decltype(expr) type.
5765 Canon = new (*this, alignof(DependentDecltypeType))
5767 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5768 }
5769 dt = new (*this, alignof(DecltypeType))
5770 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5771 } else {
5772 dt = new (*this, alignof(DecltypeType))
5773 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5774 }
5775 Types.push_back(dt);
5776 return QualType(dt, 0);
5777}
5778
5780 bool FullySubstituted,
5781 ArrayRef<QualType> Expansions,
5782 int Index) const {
5783 QualType Canonical;
5784 if (FullySubstituted && Index != -1) {
5785 Canonical = getCanonicalType(Expansions[Index]);
5786 } else {
5787 llvm::FoldingSetNodeID ID;
5788 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr);
5789 void *InsertPos = nullptr;
5790 PackIndexingType *Canon =
5791 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
5792 if (!Canon) {
5793 void *Mem = Allocate(
5794 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5796 Canon = new (Mem)
5797 PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions);
5798 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
5799 }
5800 Canonical = QualType(Canon, 0);
5801 }
5802
5803 void *Mem =
5804 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5806 auto *T = new (Mem)
5807 PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions);
5808 Types.push_back(T);
5809 return QualType(T, 0);
5810}
5811
5812/// getUnaryTransformationType - We don't unique these, since the memory
5813/// savings are minimal and these are rare.
5815 QualType UnderlyingType,
5817 const {
5818 UnaryTransformType *ut = nullptr;
5819
5820 if (BaseType->isDependentType()) {
5821 // Look in the folding set for an existing type.
5822 llvm::FoldingSetNodeID ID;
5824
5825 void *InsertPos = nullptr;
5827 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5828
5829 if (!Canon) {
5830 // Build a new, canonical __underlying_type(type) type.
5831 Canon = new (*this, alignof(DependentUnaryTransformType))
5832 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
5833 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5834 }
5835 ut = new (*this, alignof(UnaryTransformType))
5836 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
5837 } else {
5838 QualType CanonType = getCanonicalType(UnderlyingType);
5839 ut = new (*this, alignof(UnaryTransformType))
5840 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
5841 }
5842 Types.push_back(ut);
5843 return QualType(ut, 0);
5844}
5845
5846QualType ASTContext::getAutoTypeInternal(
5847 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5848 bool IsPack, ConceptDecl *TypeConstraintConcept,
5849 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5850 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5851 !TypeConstraintConcept && !IsDependent)
5852 return getAutoDeductType();
5853
5854 // Look in the folding set for an existing type.
5855 void *InsertPos = nullptr;
5856 llvm::FoldingSetNodeID ID;
5857 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5858 TypeConstraintConcept, TypeConstraintArgs);
5859 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5860 return QualType(AT, 0);
5861
5862 QualType Canon;
5863 if (!IsCanon) {
5864 if (!DeducedType.isNull()) {
5865 Canon = DeducedType.getCanonicalType();
5866 } else if (TypeConstraintConcept) {
5867 bool AnyNonCanonArgs = false;
5868 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
5869 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
5870 *this, TypeConstraintArgs, AnyNonCanonArgs);
5871 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
5872 Canon =
5873 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5874 CanonicalConcept, CanonicalConceptArgs, true);
5875 // Find the insert position again.
5876 [[maybe_unused]] auto *Nothing =
5877 AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5878 assert(!Nothing && "canonical type broken");
5879 }
5880 }
5881 }
5882
5883 void *Mem = Allocate(sizeof(AutoType) +
5884 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5885 alignof(AutoType));
5886 auto *AT = new (Mem) AutoType(
5887 DeducedType, Keyword,
5888 (IsDependent ? TypeDependence::DependentInstantiation
5889 : TypeDependence::None) |
5890 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5891 Canon, TypeConstraintConcept, TypeConstraintArgs);
5892 Types.push_back(AT);
5893 AutoTypes.InsertNode(AT, InsertPos);
5894 return QualType(AT, 0);
5895}
5896
5897/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5898/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5899/// canonical deduced-but-dependent 'auto' type.
5902 bool IsDependent, bool IsPack,
5903 ConceptDecl *TypeConstraintConcept,
5904 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5905 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5906 assert((!IsDependent || DeducedType.isNull()) &&
5907 "A dependent auto should be undeduced");
5908 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5909 TypeConstraintConcept, TypeConstraintArgs);
5910}
5911
5913 QualType CanonT = T.getCanonicalType();
5914
5915 // Remove a type-constraint from a top-level auto or decltype(auto).
5916 if (auto *AT = CanonT->getAs<AutoType>()) {
5917 if (!AT->isConstrained())
5918 return T;
5919 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(), false,
5921 T.getQualifiers());
5922 }
5923
5924 // FIXME: We only support constrained auto at the top level in the type of a
5925 // non-type template parameter at the moment. Once we lift that restriction,
5926 // we'll need to recursively build types containing auto here.
5927 assert(!CanonT->getContainedAutoType() ||
5928 !CanonT->getContainedAutoType()->isConstrained());
5929 return T;
5930}
5931
5932/// Return the uniqued reference to the deduced template specialization type
5933/// which has been deduced to the given type, or to the canonical undeduced
5934/// such type, or the canonical deduced-but-dependent such type.
5936 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5937 // Look in the folding set for an existing type.
5938 void *InsertPos = nullptr;
5939 llvm::FoldingSetNodeID ID;
5941 IsDependent);
5943 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5944 return QualType(DTST, 0);
5945
5946 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
5947 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5948 llvm::FoldingSetNodeID TempID;
5949 DTST->Profile(TempID);
5950 assert(ID == TempID && "ID does not match");
5951 Types.push_back(DTST);
5952 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5953 return QualType(DTST, 0);
5954}
5955
5956/// getAtomicType - Return the uniqued reference to the atomic type for
5957/// the given value type.
5959 // Unique pointers, to guarantee there is only one pointer of a particular
5960 // structure.
5961 llvm::FoldingSetNodeID ID;
5963
5964 void *InsertPos = nullptr;
5965 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5966 return QualType(AT, 0);
5967
5968 // If the atomic value type isn't canonical, this won't be a canonical type
5969 // either, so fill in the canonical type field.
5970 QualType Canonical;
5971 if (!T.isCanonical()) {
5972 Canonical = getAtomicType(getCanonicalType(T));
5973
5974 // Get the new insert position for the node we care about.
5975 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5976 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5977 }
5978 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
5979 Types.push_back(New);
5980 AtomicTypes.InsertNode(New, InsertPos);
5981 return QualType(New, 0);
5982}
5983
5984/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5986 if (AutoDeductTy.isNull())
5987 AutoDeductTy = QualType(new (*this, alignof(AutoType))
5989 TypeDependence::None, QualType(),
5990 /*concept*/ nullptr, /*args*/ {}),
5991 0);
5992 return AutoDeductTy;
5993}
5994
5995/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5999 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6000 return AutoRRefDeductTy;
6001}
6002
6003/// getTagDeclType - Return the unique reference to the type for the
6004/// specified TagDecl (struct/union/class/enum) decl.
6006 assert(Decl);
6007 // FIXME: What is the design on getTagDeclType when it requires casting
6008 // away const? mutable?
6009 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6010}
6011
6012/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6013/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6014/// needs to agree with the definition in <stddef.h>.
6016 return getFromTargetType(Target->getSizeType());
6017}
6018
6019/// Return the unique signed counterpart of the integer type
6020/// corresponding to size_t.
6022 return getFromTargetType(Target->getSignedSizeType());
6023}
6024
6025/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6027 return getFromTargetType(Target->getIntMaxType());
6028}
6029
6030/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6032 return getFromTargetType(Target->getUIntMaxType());
6033}
6034
6035/// getSignedWCharType - Return the type of "signed wchar_t".
6036/// Used when in C++, as a GCC extension.
6038 // FIXME: derive from "Target" ?
6039 return WCharTy;
6040}
6041
6042/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6043/// Used when in C++, as a GCC extension.
6045 // FIXME: derive from "Target" ?
6046 return UnsignedIntTy;
6047}
6048
6050 return getFromTargetType(Target->getIntPtrType());
6051}
6052
6055}
6056
6057/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6058/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6060 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6061}
6062
6063/// Return the unique unsigned counterpart of "ptrdiff_t"
6064/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6065/// in the definition of %tu format specifier.
6067 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6068}
6069
6070/// Return the unique type for "pid_t" defined in
6071/// <sys/types.h>. We need this to compute the correct type for vfork().
6073 return getFromTargetType(Target->getProcessIDType());
6074}
6075
6076//===----------------------------------------------------------------------===//
6077// Type Operators
6078//===----------------------------------------------------------------------===//
6079
6081 // Push qualifiers into arrays, and then discard any remaining
6082 // qualifiers.
6083 T = getCanonicalType(T);
6085 const Type *Ty = T.getTypePtr();
6087 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6089 } else if (isa<ArrayType>(Ty)) {
6091 } else if (isa<FunctionType>(Ty)) {
6092 Result = getPointerType(QualType(Ty, 0));
6093 } else {
6094 Result = QualType(Ty, 0);
6095 }
6096
6098}
6099
6101 Qualifiers &quals) {
6102 SplitQualType splitType = type.getSplitUnqualifiedType();
6103
6104 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6105 // the unqualified desugared type and then drops it on the floor.
6106 // We then have to strip that sugar back off with
6107 // getUnqualifiedDesugaredType(), which is silly.
6108 const auto *AT =
6109 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6110
6111 // If we don't have an array, just use the results in splitType.
6112 if (!AT) {
6113 quals = splitType.Quals;
6114 return QualType(splitType.Ty, 0);
6115 }
6116
6117 // Otherwise, recurse on the array's element type.
6118 QualType elementType = AT->getElementType();
6119 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6120
6121 // If that didn't change the element type, AT has no qualifiers, so we
6122 // can just use the results in splitType.
6123 if (elementType == unqualElementType) {
6124 assert(quals.empty()); // from the recursive call
6125 quals = splitType.Quals;
6126 return QualType(splitType.Ty, 0);
6127 }
6128
6129 // Otherwise, add in the qualifiers from the outermost type, then
6130 // build the type back up.
6131 quals.addConsistentQualifiers(splitType.Quals);
6132
6133 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6134 return getConstantArrayType(unqualElementType, CAT->getSize(),
6135 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6136 }
6137
6138 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6139 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6140 }
6141
6142 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6143 return getVariableArrayType(unqualElementType,
6144 VAT->getSizeExpr(),
6145 VAT->getSizeModifier(),
6146 VAT->getIndexTypeCVRQualifiers(),
6147 VAT->getBracketsRange());
6148 }
6149
6150 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6151 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6152 DSAT->getSizeModifier(), 0,
6153 SourceRange());
6154}
6155
6156/// Attempt to unwrap two types that may both be array types with the same bound
6157/// (or both be array types of unknown bound) for the purpose of comparing the
6158/// cv-decomposition of two types per C++ [conv.qual].
6159///
6160/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6161/// C++20 [conv.qual], if permitted by the current language mode.
6163 bool AllowPiMismatch) {
6164 while (true) {
6165 auto *AT1 = getAsArrayType(T1);
6166 if (!AT1)
6167 return;
6168
6169 auto *AT2 = getAsArrayType(T2);
6170 if (!AT2)
6171 return;
6172
6173 // If we don't have two array types with the same constant bound nor two
6174 // incomplete array types, we've unwrapped everything we can.
6175 // C++20 also permits one type to be a constant array type and the other
6176 // to be an incomplete array type.
6177 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6178 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6179 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6180 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6181 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6182 isa<IncompleteArrayType>(AT2))))
6183 return;
6184 } else if (isa<IncompleteArrayType>(AT1)) {
6185 if (!(isa<IncompleteArrayType>(AT2) ||
6186 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6187 isa<ConstantArrayType>(AT2))))
6188 return;
6189 } else {
6190 return;
6191 }
6192
6193 T1 = AT1->getElementType();
6194 T2 = AT2->getElementType();
6195 }
6196}
6197
6198/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6199///
6200/// If T1 and T2 are both pointer types of the same kind, or both array types
6201/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6202/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6203///
6204/// This function will typically be called in a loop that successively
6205/// "unwraps" pointer and pointer-to-member types to compare them at each
6206/// level.
6207///
6208/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6209/// C++20 [conv.qual], if permitted by the current language mode.
6210///
6211/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6212/// pair of types that can't be unwrapped further.
6214 bool AllowPiMismatch) {
6215 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6216
6217 const auto *T1PtrType = T1->getAs<PointerType>();
6218 const auto *T2PtrType = T2->getAs<PointerType>();
6219 if (T1PtrType && T2PtrType) {
6220 T1 = T1PtrType->getPointeeType();
6221 T2 = T2PtrType->getPointeeType();
6222 return true;
6223 }
6224
6225 const auto *T1MPType = T1->getAs<MemberPointerType>();
6226 const auto *T2MPType = T2->getAs<MemberPointerType>();
6227 if (T1MPType && T2MPType &&
6228 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6229 QualType(T2MPType->getClass(), 0))) {
6230 T1 = T1MPType->getPointeeType();
6231 T2 = T2MPType->getPointeeType();
6232 return true;
6233 }
6234
6235 if (getLangOpts().ObjC) {
6236 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6237 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6238 if (T1OPType && T2OPType) {
6239 T1 = T1OPType->getPointeeType();
6240 T2 = T2OPType->getPointeeType();
6241 return true;
6242 }
6243 }
6244
6245 // FIXME: Block pointers, too?
6246
6247 return false;
6248}
6249
6251 while (true) {
6252 Qualifiers Quals;
6253 T1 = getUnqualifiedArrayType(T1, Quals);
6254 T2 = getUnqualifiedArrayType(T2, Quals);
6255 if (hasSameType(T1, T2))
6256 return true;
6257 if (!UnwrapSimilarTypes(T1, T2))
6258 return false;
6259 }
6260}
6261
6263 while (true) {
6264 Qualifiers Quals1, Quals2;
6265 T1 = getUnqualifiedArrayType(T1, Quals1);
6266 T2 = getUnqualifiedArrayType(T2, Quals2);
6267
6268 Quals1.removeCVRQualifiers();
6269 Quals2.removeCVRQualifiers();
6270 if (Quals1 != Quals2)
6271 return false;
6272
6273 if (hasSameType(T1, T2))
6274 return true;
6275
6276 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6277 return false;
6278 }
6279}
6280
6283 SourceLocation NameLoc) const {
6284 switch (Name.getKind()) {
6287 // DNInfo work in progress: CHECKME: what about DNLoc?
6288 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6289 NameLoc);
6290
6292 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6293 // DNInfo work in progress: CHECKME: what about DNLoc?
6294 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6295 }
6296
6298 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6299 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6300 }
6301
6303 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6304 DeclarationName DName;
6305 if (DTN->isIdentifier()) {
6307 return DeclarationNameInfo(DName, NameLoc);
6308 } else {
6310 // DNInfo work in progress: FIXME: source locations?
6311 DeclarationNameLoc DNLoc =
6313 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6314 }
6315 }
6316
6319 = Name.getAsSubstTemplateTemplateParm();
6320 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6321 NameLoc);
6322 }
6323
6326 = Name.getAsSubstTemplateTemplateParmPack();
6328 NameLoc);
6329 }
6331 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6332 NameLoc);
6333 }
6334
6335 llvm_unreachable("bad template name kind!");
6336}
6337
6340 switch (Name.getKind()) {
6344 TemplateDecl *Template = Name.getAsTemplateDecl();
6345 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6346 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6347
6348 // The canonical template name is the canonical template declaration.
6349 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6350 }
6351
6354 llvm_unreachable("cannot canonicalize unresolved template");
6355
6357 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6358 assert(DTN && "Non-dependent template names must refer to template decls.");
6359 return DTN->CanonicalTemplateName;
6360 }
6361
6364 = Name.getAsSubstTemplateTemplateParm();
6366 }
6367
6370 Name.getAsSubstTemplateTemplateParmPack();
6371 TemplateArgument canonArgPack =
6374 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6375 subst->getFinal(), subst->getIndex());
6376 }
6377 }
6378
6379 llvm_unreachable("bad template name!");
6380}
6381
6383 const TemplateName &Y) const {
6386}
6387
6388bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6389 if (!XCE != !YCE)
6390 return false;
6391
6392 if (!XCE)
6393 return true;
6394
6395 llvm::FoldingSetNodeID XCEID, YCEID;
6396 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6397 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6398 return XCEID == YCEID;
6399}
6400
6402 const TypeConstraint *YTC) const {
6403 if (!XTC != !YTC)
6404 return false;
6405
6406 if (!XTC)
6407 return true;
6408
6409 auto *NCX = XTC->getNamedConcept();
6410 auto *NCY = YTC->getNamedConcept();
6411 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6412 return false;
6415 return false;
6417 if (XTC->getConceptReference()
6419 ->NumTemplateArgs !=
6421 return false;
6422
6423 // Compare slowly by profiling.
6424 //
6425 // We couldn't compare the profiling result for the template
6426 // args here. Consider the following example in different modules:
6427 //
6428 // template <__integer_like _Tp, C<_Tp> Sentinel>
6429 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6430 // return __t;
6431 // }
6432 //
6433 // When we compare the profiling result for `C<_Tp>` in different
6434 // modules, it will compare the type of `_Tp` in different modules.
6435 // However, the type of `_Tp` in different modules refer to different
6436 // types here naturally. So we couldn't compare the profiling result
6437 // for the template args directly.
6440}
6441
6443 const NamedDecl *Y) const {
6444 if (X->getKind() != Y->getKind())
6445 return false;
6446
6447 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6448 auto *TY = cast<TemplateTypeParmDecl>(Y);
6449 if (TX->isParameterPack() != TY->isParameterPack())
6450 return false;
6451 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6452 return false;
6453 return isSameTypeConstraint(TX->getTypeConstraint(),
6454 TY->getTypeConstraint());
6455 }
6456
6457 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6458 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6459 return TX->isParameterPack() == TY->isParameterPack() &&
6460 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6461 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6462 TY->getPlaceholderTypeConstraint());
6463 }
6464
6465 auto *TX = cast<TemplateTemplateParmDecl>(X);
6466 auto *TY = cast<TemplateTemplateParmDecl>(Y);
6467 return TX->isParameterPack() == TY->isParameterPack() &&
6468 isSameTemplateParameterList(TX->getTemplateParameters(),
6469 TY->getTemplateParameters());
6470}
6471
6473 const TemplateParameterList *X, const TemplateParameterList *Y) const {
6474 if (X->size() != Y->size())
6475 return false;
6476
6477 for (unsigned I = 0, N = X->size(); I != N; ++I)
6478 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6479 return false;
6480
6481 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6482}
6483
6485 const NamedDecl *Y) const {
6486 // If the type parameter isn't the same already, we don't need to check the
6487 // default argument further.
6488 if (!isSameTemplateParameter(X, Y))
6489 return false;
6490
6491 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6492 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6493 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6494 return false;
6495
6496 return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
6497 }
6498
6499 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6500 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6501 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6502 return false;
6503
6504 Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
6505 Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
6506 llvm::FoldingSetNodeID XID, YID;
6507 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6508 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6509 return XID == YID;
6510 }
6511
6512 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6513 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6514
6515 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6516 return false;
6517
6518 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6519 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6520 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6521}
6522
6524 if (auto *NS = X->getAsNamespace())
6525 return NS;
6526 if (auto *NAS = X->getAsNamespaceAlias())
6527 return NAS->getNamespace();
6528 return nullptr;
6529}
6530
6532 const NestedNameSpecifier *Y) {
6533 if (auto *NSX = getNamespace(X)) {
6534 auto *NSY = getNamespace(Y);
6535 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6536 return false;
6537 } else if (X->getKind() != Y->getKind())
6538 return false;
6539
6540 // FIXME: For namespaces and types, we're permitted to check that the entity
6541 // is named via the same tokens. We should probably do so.
6542 switch (X->getKind()) {
6544 if (X->getAsIdentifier() != Y->getAsIdentifier())
6545 return false;
6546 break;
6549 // We've already checked that we named the same namespace.
6550 break;
6553 if (X->getAsType()->getCanonicalTypeInternal() !=
6555 return false;
6556 break;
6559 return true;
6560 }
6561
6562 // Recurse into earlier portion of NNS, if any.
6563 auto *PX = X->getPrefix();
6564 auto *PY = Y->getPrefix();
6565 if (PX && PY)
6566 return isSameQualifier(PX, PY);
6567 return !PX && !PY;
6568}
6569
6570/// Determine whether the attributes we can overload on are identical for A and
6571/// B. Will ignore any overloadable attrs represented in the type of A and B.
6573 const FunctionDecl *B) {
6574 // Note that pass_object_size attributes are represented in the function's
6575 // ExtParameterInfo, so we don't need to check them here.
6576
6577 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6578 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6579 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6580
6581 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6582 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6583 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6584
6585 // Return false if the number of enable_if attributes is different.
6586 if (!Cand1A || !Cand2A)
6587 return false;
6588
6589 Cand1ID.clear();
6590 Cand2ID.clear();
6591
6592 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6593 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6594
6595 // Return false if any of the enable_if expressions of A and B are
6596 // different.
6597 if (Cand1ID != Cand2ID)
6598 return false;
6599 }
6600 return true;
6601}
6602
6603bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6604 // Caution: this function is called by the AST reader during deserialization,
6605 // so it cannot rely on AST invariants being met. Non-trivial accessors
6606 // should be avoided, along with any traversal of redeclaration chains.
6607
6608 if (X == Y)
6609 return true;
6610
6611 if (X->getDeclName() != Y->getDeclName())
6612 return false;
6613
6614 // Must be in the same context.
6615 //
6616 // Note that we can't use DeclContext::Equals here, because the DeclContexts
6617 // could be two different declarations of the same function. (We will fix the
6618 // semantic DC to refer to the primary definition after merging.)
6619 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6620 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6621 return false;
6622
6623 // Two typedefs refer to the same entity if they have the same underlying
6624 // type.
6625 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6626 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6627 return hasSameType(TypedefX->getUnderlyingType(),
6628 TypedefY->getUnderlyingType());
6629
6630 // Must have the same kind.
6631 if (X->getKind() != Y->getKind())
6632 return false;
6633
6634 // Objective-C classes and protocols with the same name always match.
6635 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6636 return true;
6637
6638 if (isa<ClassTemplateSpecializationDecl>(X)) {
6639 // No need to handle these here: we merge them when adding them to the
6640 // template.
6641 return false;
6642 }
6643
6644 // Compatible tags match.
6645 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6646 const auto *TagY = cast<TagDecl>(Y);
6647 return (TagX->getTagKind() == TagY->getTagKind()) ||
6648 ((TagX->getTagKind() == TagTypeKind::Struct ||
6649 TagX->getTagKind() == TagTypeKind::Class ||
6650 TagX->getTagKind() == TagTypeKind::Interface) &&
6651 (TagY->getTagKind() == TagTypeKind::Struct ||
6652 TagY->getTagKind() == TagTypeKind::Class ||
6653 TagY->getTagKind() == TagTypeKind::Interface));
6654 }
6655
6656 // Functions with the same type and linkage match.
6657 // FIXME: This needs to cope with merging of prototyped/non-prototyped
6658 // functions, etc.
6659 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6660 const auto *FuncY = cast<FunctionDecl>(Y);
6661 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6662 const auto *CtorY = cast<CXXConstructorDecl>(Y);
6663 if (CtorX->getInheritedConstructor() &&
6664 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6665 CtorY->getInheritedConstructor().getConstructor()))
6666 return false;
6667 }
6668
6669 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6670 return false;
6671
6672 // Multiversioned functions with different feature strings are represented
6673 // as separate declarations.
6674 if (FuncX->isMultiVersion()) {
6675 const auto *TAX = FuncX->getAttr<TargetAttr>();
6676 const auto *TAY = FuncY->getAttr<TargetAttr>();
6677 assert(TAX && TAY && "Multiversion Function without target attribute");
6678
6679 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6680 return false;
6681 }
6682
6683 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
6684 // not the same entity if they are constrained.
6685 if ((FuncX->isMemberLikeConstrainedFriend() ||
6686 FuncY->isMemberLikeConstrainedFriend()) &&
6687 !FuncX->getLexicalDeclContext()->Equals(
6688 FuncY->getLexicalDeclContext())) {
6689 return false;
6690 }
6691
6692 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
6693 FuncY->getTrailingRequiresClause()))
6694 return false;
6695
6696 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6697 // Map to the first declaration that we've already merged into this one.
6698 // The TSI of redeclarations might not match (due to calling conventions
6699 // being inherited onto the type but not the TSI), but the TSI type of
6700 // the first declaration of the function should match across modules.
6701 FD = FD->getCanonicalDecl();
6702 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6703 : FD->getType();
6704 };
6705 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6706 if (!hasSameType(XT, YT)) {
6707 // We can get functions with different types on the redecl chain in C++17
6708 // if they have differing exception specifications and at least one of
6709 // the excpetion specs is unresolved.
6710 auto *XFPT = XT->getAs<FunctionProtoType>();
6711 auto *YFPT = YT->getAs<FunctionProtoType>();
6712 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6713 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6716 return true;
6717 return false;
6718 }
6719
6720 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6721 hasSameOverloadableAttrs(FuncX, FuncY);
6722 }
6723
6724 // Variables with the same type and linkage match.
6725 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6726 const auto *VarY = cast<VarDecl>(Y);
6727 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6728 // During deserialization, we might compare variables before we load
6729 // their types. Assume the types will end up being the same.
6730 if (VarX->getType().isNull() || VarY->getType().isNull())
6731 return true;
6732
6733 if (hasSameType(VarX->getType(), VarY->getType()))
6734 return true;
6735
6736 // We can get decls with different types on the redecl chain. Eg.
6737 // template <typename T> struct S { static T Var[]; }; // #1
6738 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6739 // Only? happens when completing an incomplete array type. In this case
6740 // when comparing #1 and #2 we should go through their element type.
6741 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6742 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6743 if (!VarXTy || !VarYTy)
6744 return false;
6745 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6746 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6747 }
6748 return false;
6749 }
6750
6751 // Namespaces with the same name and inlinedness match.
6752 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6753 const auto *NamespaceY = cast<NamespaceDecl>(Y);
6754 return NamespaceX->isInline() == NamespaceY->isInline();
6755 }
6756
6757 // Identical template names and kinds match if their template parameter lists
6758 // and patterns match.
6759 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6760 const auto *TemplateY = cast<TemplateDecl>(Y);
6761
6762 // ConceptDecl wouldn't be the same if their constraint expression differs.
6763 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
6764 const auto *ConceptY = cast<ConceptDecl>(Y);
6765 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
6766 ConceptY->getConstraintExpr()))
6767 return false;
6768 }
6769
6770 return isSameEntity(TemplateX->getTemplatedDecl(),
6771 TemplateY->getTemplatedDecl()) &&
6772 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6773 TemplateY->getTemplateParameters());
6774 }
6775
6776 // Fields with the same name and the same type match.
6777 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6778 const auto *FDY = cast<FieldDecl>(Y);
6779 // FIXME: Also check the bitwidth is odr-equivalent, if any.
6780 return hasSameType(FDX->getType(), FDY->getType());
6781 }
6782
6783 // Indirect fields with the same target field match.
6784 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6785 const auto *IFDY = cast<IndirectFieldDecl>(Y);
6786 return IFDX->getAnonField()->getCanonicalDecl() ==
6787 IFDY->getAnonField()->getCanonicalDecl();
6788 }
6789
6790 // Enumerators with the same name match.
6791 if (isa<EnumConstantDecl>(X))
6792 // FIXME: Also check the value is odr-equivalent.
6793 return true;
6794
6795 // Using shadow declarations with the same target match.
6796 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6797 const auto *USY = cast<UsingShadowDecl>(Y);
6798 return USX->getTargetDecl() == USY->getTargetDecl();
6799 }
6800
6801 // Using declarations with the same qualifier match. (We already know that
6802 // the name matches.)
6803 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6804 const auto *UY = cast<UsingDecl>(Y);
6805 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6806 UX->hasTypename() == UY->hasTypename() &&
6807 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6808 }
6809 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6810 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6811 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6812 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6813 }
6814 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6815 return isSameQualifier(
6816 UX->getQualifier(),
6817 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6818 }
6819
6820 // Using-pack declarations are only created by instantiation, and match if
6821 // they're instantiated from matching UnresolvedUsing...Decls.
6822 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6823 return declaresSameEntity(
6824 UX->getInstantiatedFromUsingDecl(),
6825 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6826 }
6827
6828 // Namespace alias definitions with the same target match.
6829 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6830 const auto *NAY = cast<NamespaceAliasDecl>(Y);
6831 return NAX->getNamespace()->Equals(NAY->getNamespace());
6832 }
6833
6834 return false;
6835}
6836
6839 switch (Arg.getKind()) {
6841 return Arg;
6842
6844 return Arg;
6845
6847 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6849 Arg.getIsDefaulted());
6850 }
6851
6854 /*isNullPtr*/ true, Arg.getIsDefaulted());
6855
6858 Arg.getIsDefaulted());
6859
6861 return TemplateArgument(
6864
6867
6869 return TemplateArgument(*this,
6871 Arg.getAsStructuralValue());
6872
6875 /*isNullPtr*/ false, Arg.getIsDefaulted());
6876
6878 bool AnyNonCanonArgs = false;
6879 auto CanonArgs = ::getCanonicalTemplateArguments(
6880 *this, Arg.pack_elements(), AnyNonCanonArgs);
6881 if (!AnyNonCanonArgs)
6882 return Arg;
6883 return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
6884 CanonArgs);
6885 }
6886 }
6887
6888 // Silence GCC warning
6889 llvm_unreachable("Unhandled template argument kind");
6890}
6891
6894 if (!NNS)
6895 return nullptr;
6896
6897 switch (NNS->getKind()) {
6899 // Canonicalize the prefix but keep the identifier the same.
6900 return NestedNameSpecifier::Create(*this,
6902 NNS->getAsIdentifier());
6903
6905 // A namespace is canonical; build a nested-name-specifier with
6906 // this namespace and no prefix.
6907 return NestedNameSpecifier::Create(*this, nullptr,
6909
6911 // A namespace is canonical; build a nested-name-specifier with
6912 // this namespace and no prefix.
6913 return NestedNameSpecifier::Create(*this, nullptr,
6916
6917 // The difference between TypeSpec and TypeSpecWithTemplate is that the
6918 // latter will have the 'template' keyword when printed.
6921 const Type *T = getCanonicalType(NNS->getAsType());
6922
6923 // If we have some kind of dependent-named type (e.g., "typename T::type"),
6924 // break it apart into its prefix and identifier, then reconsititute those
6925 // as the canonical nested-name-specifier. This is required to canonicalize
6926 // a dependent nested-name-specifier involving typedefs of dependent-name
6927 // types, e.g.,
6928 // typedef typename T::type T1;
6929 // typedef typename T1::type T2;
6930 if (const auto *DNT = T->getAs<DependentNameType>())
6931 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6932 DNT->getIdentifier());
6933 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6934 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
6935
6936 // TODO: Set 'Template' parameter to true for other template types.
6937 return NestedNameSpecifier::Create(*this, nullptr, false, T);
6938 }
6939
6942 // The global specifier and __super specifer are canonical and unique.
6943 return NNS;
6944 }
6945
6946 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6947}
6948
6950 // Handle the non-qualified case efficiently.
6951 if (!T.hasLocalQualifiers()) {
6952 // Handle the common positive case fast.
6953 if (const auto *AT = dyn_cast<ArrayType>(T))
6954 return AT;
6955 }
6956
6957 // Handle the common negative case fast.
6958 if (!isa<ArrayType>(T.getCanonicalType()))
6959 return nullptr;
6960
6961 // Apply any qualifiers from the array type to the element type. This
6962 // implements C99 6.7.3p8: "If the specification of an array type includes
6963 // any type qualifiers, the element type is so qualified, not the array type."
6964
6965 // If we get here, we either have type qualifiers on the type, or we have
6966 // sugar such as a typedef in the way. If we have type qualifiers on the type
6967 // we must propagate them down into the element type.
6968
6969 SplitQualType split = T.getSplitDesugaredType();
6970 Qualifiers qs = split.Quals;
6971
6972 // If we have a simple case, just return now.
6973 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6974 if (!ATy || qs.empty())
6975 return ATy;
6976
6977 // Otherwise, we have an array and we have qualifiers on it. Push the
6978 // qualifiers into the array element type and return a new array type.
6979 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6980
6981 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6982 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6983 CAT->getSizeExpr(),
6984 CAT->getSizeModifier(),
6985 CAT->getIndexTypeCVRQualifiers()));
6986 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6987 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6988 IAT->getSizeModifier(),
6989 IAT->getIndexTypeCVRQualifiers()));
6990
6991 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6992 return cast<ArrayType>(
6994 DSAT->getSizeExpr(),
6995 DSAT->getSizeModifier(),
6996 DSAT->getIndexTypeCVRQualifiers(),
6997 DSAT->getBracketsRange()));
6998
6999 const auto *VAT = cast<VariableArrayType>(ATy);
7000 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7001 VAT->getSizeExpr(),
7002 VAT->getSizeModifier(),
7003 VAT->getIndexTypeCVRQualifiers(),
7004 VAT->getBracketsRange()));
7005}
7006
7009 return getArrayParameterType(T);
7010 if (T->isArrayType() || T->isFunctionType())
7011 return getDecayedType(T);
7012 return T;
7013}
7014
7018 return T.getUnqualifiedType();
7019}
7020
7022 // C++ [except.throw]p3:
7023 // A throw-expression initializes a temporary object, called the exception
7024 // object, the type of which is determined by removing any top-level
7025 // cv-qualifiers from the static type of the operand of throw and adjusting
7026 // the type from "array of T" or "function returning T" to "pointer to T"
7027 // or "pointer to function returning T", [...]
7029 if (T->isArrayType() || T->isFunctionType())
7030 T = getDecayedType(T);
7031 return T.getUnqualifiedType();
7032}
7033
7034/// getArrayDecayedType - Return the properly qualified result of decaying the
7035/// specified array type to a pointer. This operation is non-trivial when
7036/// handling typedefs etc. The canonical type of "T" must be an array type,
7037/// this returns a pointer to a properly qualified element of the array.
7038///
7039/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7041 // Get the element type with 'getAsArrayType' so that we don't lose any
7042 // typedefs in the element type of the array. This also handles propagation
7043 // of type qualifiers from the array type into the element type if present
7044 // (C99 6.7.3p8).
7045 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7046 assert(PrettyArrayType && "Not an array type!");
7047
7048 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7049
7050 // int x[restrict 4] -> int *restrict
7052 PrettyArrayType->getIndexTypeQualifiers());
7053
7054 // int x[_Nullable] -> int * _Nullable
7055 if (auto Nullability = Ty->getNullability()) {
7056 Result = const_cast<ASTContext *>(this)->getAttributedType(
7058 }
7059 return Result;
7060}
7061
7063 return getBaseElementType(array->getElementType());
7064}
7065
7067 Qualifiers qs;
7068 while (true) {
7069 SplitQualType split = type.getSplitDesugaredType();
7070 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7071 if (!array) break;
7072
7073 type = array->getElementType();
7075 }
7076
7077 return getQualifiedType(type, qs);
7078}
7079
7080/// getConstantArrayElementCount - Returns number of constant array elements.
7081uint64_t
7083 uint64_t ElementCount = 1;
7084 do {
7085 ElementCount *= CA->getZExtSize();
7086 CA = dyn_cast_or_null<ConstantArrayType>(
7088 } while (CA);
7089 return ElementCount;
7090}
7091
7093 const ArrayInitLoopExpr *AILE) const {
7094 if (!AILE)
7095 return 0;
7096
7097 uint64_t ElementCount = 1;
7098
7099 do {
7100 ElementCount *= AILE->getArraySize().getZExtValue();
7101 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7102 } while (AILE);
7103
7104 return ElementCount;
7105}
7106
7107/// getFloatingRank - Return a relative rank for floating point types.
7108/// This routine will assert if passed a built-in type that isn't a float.
7110 if (const auto *CT = T->getAs<ComplexType>())
7111 return getFloatingRank(CT->getElementType());
7112
7113 switch (T->castAs<BuiltinType>()->getKind()) {
7114 default: llvm_unreachable("getFloatingRank(): not a floating type");
7115 case BuiltinType::Float16: return Float16Rank;
7116 case BuiltinType::Half: return HalfRank;
7117 case BuiltinType::Float: return FloatRank;
7118 case BuiltinType::Double: return DoubleRank;
7119 case BuiltinType::LongDouble: return LongDoubleRank;
7120 case BuiltinType::Float128: return Float128Rank;
7121 case BuiltinType::BFloat16: return BFloat16Rank;
7122 case BuiltinType::Ibm128: return Ibm128Rank;
7123 }
7124}
7125
7126/// getFloatingTypeOrder - Compare the rank of the two specified floating
7127/// point types, ignoring the domain of the type (i.e. 'double' ==
7128/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7129/// LHS < RHS, return -1.
7131 FloatingRank LHSR = getFloatingRank(LHS);
7132 FloatingRank RHSR = getFloatingRank(RHS);
7133
7134 if (LHSR == RHSR)
7135 return 0;
7136 if (LHSR > RHSR)
7137 return 1;
7138 return -1;
7139}
7140
7143 return 0;
7144 return getFloatingTypeOrder(LHS, RHS);
7145}
7146
7147/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7148/// routine will assert if passed a built-in type that isn't an integer or enum,
7149/// or if it is not canonicalized.
7150unsigned ASTContext::getIntegerRank(const Type *T) const {
7151 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7152
7153 // Results in this 'losing' to any type of the same size, but winning if
7154 // larger.
7155 if (const auto *EIT = dyn_cast<BitIntType>(T))
7156 return 0 + (EIT->getNumBits() << 3);
7157
7158 switch (cast<BuiltinType>(T)->getKind()) {
7159 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7160 case BuiltinType::Bool:
7161 return 1 + (getIntWidth(BoolTy) << 3);
7162 case BuiltinType::Char_S:
7163 case BuiltinType::Char_U:
7164 case BuiltinType::SChar:
7165 case BuiltinType::UChar:
7166 return 2 + (getIntWidth(CharTy) << 3);
7167 case BuiltinType::Short:
7168 case BuiltinType::UShort:
7169 return 3 + (getIntWidth(ShortTy) << 3);
7170 case BuiltinType::Int:
7171 case BuiltinType::UInt:
7172 return 4 + (getIntWidth(IntTy) << 3);
7173 case BuiltinType::Long:
7174 case BuiltinType::ULong:
7175 return 5 + (getIntWidth(LongTy) << 3);
7176 case BuiltinType::LongLong:
7177 case BuiltinType::ULongLong:
7178 return 6 + (getIntWidth(LongLongTy) << 3);
7179 case BuiltinType::Int128:
7180 case BuiltinType::UInt128:
7181 return 7 + (getIntWidth(Int128Ty) << 3);
7182
7183 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7184 // their underlying types" [c++20 conv.rank]
7185 case BuiltinType::Char8:
7186 return getIntegerRank(UnsignedCharTy.getTypePtr());
7187 case BuiltinType::Char16:
7188 return getIntegerRank(
7189 getFromTargetType(Target->getChar16Type()).getTypePtr());
7190 case BuiltinType::Char32:
7191 return getIntegerRank(
7192 getFromTargetType(Target->getChar32Type()).getTypePtr());
7193 case BuiltinType::WChar_S:
7194 case BuiltinType::WChar_U:
7195 return getIntegerRank(
7196 getFromTargetType(Target->getWCharType()).getTypePtr());
7197 }
7198}
7199
7200/// Whether this is a promotable bitfield reference according
7201/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7202///
7203/// \returns the type this bit-field will promote to, or NULL if no
7204/// promotion occurs.
7206 if (E->isTypeDependent() || E->isValueDependent())
7207 return {};
7208
7209 // C++ [conv.prom]p5:
7210 // If the bit-field has an enumerated type, it is treated as any other
7211 // value of that type for promotion purposes.
7213 return {};
7214
7215 // FIXME: We should not do this unless E->refersToBitField() is true. This
7216 // matters in C where getSourceBitField() will find bit-fields for various
7217 // cases where the source expression is not a bit-field designator.
7218
7219 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7220 if (!Field)
7221 return {};
7222
7223 QualType FT = Field->getType();
7224
7225 uint64_t BitWidth = Field->getBitWidthValue(*this);
7226 uint64_t IntSize = getTypeSize(IntTy);
7227 // C++ [conv.prom]p5:
7228 // A prvalue for an integral bit-field can be converted to a prvalue of type
7229 // int if int can represent all the values of the bit-field; otherwise, it
7230 // can be converted to unsigned int if unsigned int can represent all the
7231 // values of the bit-field. If the bit-field is larger yet, no integral
7232 // promotion applies to it.
7233 // C11 6.3.1.1/2:
7234 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7235 // If an int can represent all values of the original type (as restricted by
7236 // the width, for a bit-field), the value is converted to an int; otherwise,
7237 // it is converted to an unsigned int.
7238 //
7239 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7240 // We perform that promotion here to match GCC and C++.
7241 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7242 // greater than that of 'int'. We perform that promotion to match GCC.
7243 //
7244 // C23 6.3.1.1p2:
7245 // The value from a bit-field of a bit-precise integer type is converted to
7246 // the corresponding bit-precise integer type. (The rest is the same as in
7247 // C11.)
7248 if (QualType QT = Field->getType(); QT->isBitIntType())
7249 return QT;
7250
7251 if (BitWidth < IntSize)
7252 return IntTy;
7253
7254 if (BitWidth == IntSize)
7255 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7256
7257 // Bit-fields wider than int are not subject to promotions, and therefore act
7258 // like the base type. GCC has some weird bugs in this area that we
7259 // deliberately do not follow (GCC follows a pre-standard resolution to
7260 // C's DR315 which treats bit-width as being part of the type, and this leaks
7261 // into their semantics in some cases).
7262 return {};
7263}
7264
7265/// getPromotedIntegerType - Returns the type that Promotable will
7266/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7267/// integer type.
7269 assert(!Promotable.isNull());
7270 assert(isPromotableIntegerType(Promotable));
7271 if (const auto *ET = Promotable->getAs<EnumType>())
7272 return ET->getDecl()->getPromotionType();
7273
7274 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7275 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7276 // (3.9.1) can be converted to a prvalue of the first of the following
7277 // types that can represent all the values of its underlying type:
7278 // int, unsigned int, long int, unsigned long int, long long int, or
7279 // unsigned long long int [...]
7280 // FIXME: Is there some better way to compute this?
7281 if (BT->getKind() == BuiltinType::WChar_S ||
7282 BT->getKind() == BuiltinType::WChar_U ||
7283 BT->getKind() == BuiltinType::Char8 ||
7284 BT->getKind() == BuiltinType::Char16 ||
7285 BT->getKind() == BuiltinType::Char32) {
7286 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7287 uint64_t FromSize = getTypeSize(BT);
7288 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7290 for (const auto &PT : PromoteTypes) {
7291 uint64_t ToSize = getTypeSize(PT);
7292 if (FromSize < ToSize ||
7293 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7294 return PT;
7295 }
7296 llvm_unreachable("char type should fit into long long");
7297 }
7298 }
7299
7300 // At this point, we should have a signed or unsigned integer type.
7301 if (Promotable->isSignedIntegerType())
7302 return IntTy;
7303 uint64_t PromotableSize = getIntWidth(Promotable);
7304 uint64_t IntSize = getIntWidth(IntTy);
7305 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7306 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7307}
7308
7309/// Recurses in pointer/array types until it finds an objc retainable
7310/// type and returns its ownership.
7312 while (!T.isNull()) {
7313 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7314 return T.getObjCLifetime();
7315 if (T->isArrayType())
7317 else if (const auto *PT = T->getAs<PointerType>())
7318 T = PT->getPointeeType();
7319 else if (const auto *RT = T->getAs<ReferenceType>())
7320 T = RT->getPointeeType();
7321 else
7322 break;
7323 }
7324
7325 return Qualifiers::OCL_None;
7326}
7327
7328static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7329 // Incomplete enum types are not treated as integer types.
7330 // FIXME: In C++, enum types are never integer types.
7331 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7332 return ET->getDecl()->getIntegerType().getTypePtr();
7333 return nullptr;
7334}
7335
7336/// getIntegerTypeOrder - Returns the highest ranked integer type:
7337/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7338/// LHS < RHS, return -1.
7340 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7341 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7342
7343 // Unwrap enums to their underlying type.
7344 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7345 LHSC = getIntegerTypeForEnum(ET);
7346 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7347 RHSC = getIntegerTypeForEnum(ET);
7348
7349 if (LHSC == RHSC) return 0;
7350
7351 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7352 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7353
7354 unsigned LHSRank = getIntegerRank(LHSC);
7355 unsigned RHSRank = getIntegerRank(RHSC);
7356
7357 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7358 if (LHSRank == RHSRank) return 0;
7359 return LHSRank > RHSRank ? 1 : -1;
7360 }
7361
7362 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7363 if (LHSUnsigned) {
7364 // If the unsigned [LHS] type is larger, return it.
7365 if (LHSRank >= RHSRank)
7366 return 1;
7367
7368 // If the signed type can represent all values of the unsigned type, it
7369 // wins. Because we are dealing with 2's complement and types that are
7370 // powers of two larger than each other, this is always safe.
7371 return -1;
7372 }
7373
7374 // If the unsigned [RHS] type is larger, return it.
7375 if (RHSRank >= LHSRank)
7376 return -1;
7377
7378 // If the signed type can represent all values of the unsigned type, it
7379 // wins. Because we are dealing with 2's complement and types that are
7380 // powers of two larger than each other, this is always safe.
7381 return 1;
7382}
7383
7385 if (CFConstantStringTypeDecl)
7386 return CFConstantStringTypeDecl;
7387
7388 assert(!CFConstantStringTagDecl &&
7389 "tag and typedef should be initialized together");
7390 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7391 CFConstantStringTagDecl->startDefinition();
7392
7393 struct {
7394 QualType Type;
7395 const char *Name;
7396 } Fields[5];
7397 unsigned Count = 0;
7398
7399 /// Objective-C ABI
7400 ///
7401 /// typedef struct __NSConstantString_tag {
7402 /// const int *isa;
7403 /// int flags;
7404 /// const char *str;
7405 /// long length;
7406 /// } __NSConstantString;
7407 ///
7408 /// Swift ABI (4.1, 4.2)
7409 ///
7410 /// typedef struct __NSConstantString_tag {
7411 /// uintptr_t _cfisa;
7412 /// uintptr_t _swift_rc;
7413 /// _Atomic(uint64_t) _cfinfoa;
7414 /// const char *_ptr;
7415 /// uint32_t _length;
7416 /// } __NSConstantString;
7417 ///
7418 /// Swift ABI (5.0)
7419 ///
7420 /// typedef struct __NSConstantString_tag {
7421 /// uintptr_t _cfisa;
7422 /// uintptr_t _swift_rc;
7423 /// _Atomic(uint64_t) _cfinfoa;
7424 /// const char *_ptr;
7425 /// uintptr_t _length;
7426 /// } __NSConstantString;
7427
7428 const auto CFRuntime = getLangOpts().CFRuntime;
7429 if (static_cast<unsigned>(CFRuntime) <
7430 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7431 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7432 Fields[Count++] = { IntTy, "flags" };
7433 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7434 Fields[Count++] = { LongTy, "length" };
7435 } else {
7436 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7437 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7438 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7439 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7442 Fields[Count++] = { IntTy, "_ptr" };
7443 else
7444 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7445 }
7446
7447 // Create fields
7448 for (unsigned i = 0; i < Count; ++i) {
7449 FieldDecl *Field =
7450 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7451 SourceLocation(), &Idents.get(Fields[i].Name),
7452 Fields[i].Type, /*TInfo=*/nullptr,
7453 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7454 Field->setAccess(AS_public);
7455 CFConstantStringTagDecl->addDecl(Field);
7456 }
7457
7458 CFConstantStringTagDecl->completeDefinition();
7459 // This type is designed to be compatible with NSConstantString, but cannot
7460 // use the same name, since NSConstantString is an interface.
7461 auto tagType = getTagDeclType(CFConstantStringTagDecl);
7462 CFConstantStringTypeDecl =
7463 buildImplicitTypedef(tagType, "__NSConstantString");
7464
7465 return CFConstantStringTypeDecl;
7466}
7467
7469 if (!CFConstantStringTagDecl)
7470 getCFConstantStringDecl(); // Build the tag and the typedef.
7471 return CFConstantStringTagDecl;
7472}
7473
7474// getCFConstantStringType - Return the type used for constant CFStrings.
7477}
7478
7480 if (ObjCSuperType.isNull()) {
7481 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7482 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7483 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7484 }
7485 return ObjCSuperType;
7486}
7487
7489 const auto *TD = T->castAs<TypedefType>();
7490 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7491 const auto *TagType =
7492 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7493 CFConstantStringTagDecl = TagType->getDecl();
7494}
7495
7497 if (BlockDescriptorType)
7498 return getTagDeclType(BlockDescriptorType);
7499
7500 RecordDecl *RD;
7501 // FIXME: Needs the FlagAppleBlock bit.
7502 RD = buildImplicitRecord("__block_descriptor");
7503 RD->startDefinition();
7504
7505 QualType FieldTypes[] = {
7508 };
7509
7510 static const char *const FieldNames[] = {
7511 "reserved",
7512 "Size"
7513 };
7514
7515 for (size_t i = 0; i < 2; ++i) {
7517 *this, RD, SourceLocation(), SourceLocation(),
7518 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7519 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7520 Field->setAccess(AS_public);
7521 RD->addDecl(Field);
7522 }
7523
7524 RD->completeDefinition();
7525
7526 BlockDescriptorType = RD;
7527
7528 return getTagDeclType(BlockDescriptorType);
7529}
7530
7532 if (BlockDescriptorExtendedType)
7533 return getTagDeclType(BlockDescriptorExtendedType);
7534
7535 RecordDecl *RD;
7536 // FIXME: Needs the FlagAppleBlock bit.
7537 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7538 RD->startDefinition();
7539
7540 QualType FieldTypes[] = {
7545 };
7546
7547 static const char *const FieldNames[] = {
7548 "reserved",
7549 "Size",
7550 "CopyFuncPtr",
7551 "DestroyFuncPtr"
7552 };
7553
7554 for (size_t i = 0; i < 4; ++i) {
7556 *this, RD, SourceLocation(), SourceLocation(),
7557 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7558 /*BitWidth=*/nullptr,
7559 /*Mutable=*/false, ICIS_NoInit);
7560 Field->setAccess(AS_public);
7561 RD->addDecl(Field);
7562 }
7563
7564 RD->completeDefinition();
7565
7566 BlockDescriptorExtendedType = RD;
7567 return getTagDeclType(BlockDescriptorExtendedType);
7568}
7569
7571 const auto *BT = dyn_cast<BuiltinType>(T);
7572
7573 if (!BT) {
7574 if (isa<PipeType>(T))
7575 return OCLTK_Pipe;
7576
7577 return OCLTK_Default;
7578 }
7579
7580 switch (BT->getKind()) {
7581#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7582 case BuiltinType::Id: \
7583 return OCLTK_Image;
7584#include "clang/Basic/OpenCLImageTypes.def"
7585
7586 case BuiltinType::OCLClkEvent:
7587 return OCLTK_ClkEvent;
7588
7589 case BuiltinType::OCLEvent:
7590 return OCLTK_Event;
7591
7592 case BuiltinType::OCLQueue:
7593 return OCLTK_Queue;
7594
7595 case BuiltinType::OCLReserveID:
7596 return OCLTK_ReserveID;
7597
7598 case BuiltinType::OCLSampler:
7599 return OCLTK_Sampler;
7600
7601 default:
7602 return OCLTK_Default;
7603 }
7604}
7605
7607 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7608}
7609
7610/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7611/// requires copy/dispose. Note that this must match the logic
7612/// in buildByrefHelpers.
7614 const VarDecl *D) {
7615 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7616 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7617 if (!copyExpr && record->hasTrivialDestructor()) return false;
7618
7619 return true;
7620 }
7621
7622 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7623 // move or destroy.
7625 return true;
7626
7627 if (!Ty->isObjCRetainableType()) return false;
7628
7629 Qualifiers qs = Ty.getQualifiers();
7630
7631 // If we have lifetime, that dominates.
7632 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7633 switch (lifetime) {
7634 case Qualifiers::OCL_None: llvm_unreachable("impossible");
7635
7636 // These are just bits as far as the runtime is concerned.
7639 return false;
7640
7641 // These cases should have been taken care of when checking the type's
7642 // non-triviality.
7645 llvm_unreachable("impossible");
7646 }
7647 llvm_unreachable("fell out of lifetime switch!");
7648 }
7649 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7651}
7652
7654 Qualifiers::ObjCLifetime &LifeTime,
7655 bool &HasByrefExtendedLayout) const {
7656 if (!getLangOpts().ObjC ||
7657 getLangOpts().getGC() != LangOptions::NonGC)
7658 return false;
7659
7660 HasByrefExtendedLayout = false;
7661 if (Ty->isRecordType()) {
7662 HasByrefExtendedLayout = true;
7663 LifeTime = Qualifiers::OCL_None;
7664 } else if ((LifeTime = Ty.getObjCLifetime())) {
7665 // Honor the ARC qualifiers.
7666 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7667 // The MRR rule.
7669 } else {
7670 LifeTime = Qualifiers::OCL_None;
7671 }
7672 return true;
7673}
7674
7676 assert(Target && "Expected target to be initialized");
7677 const llvm::Triple &T = Target->getTriple();
7678 // Windows is LLP64 rather than LP64
7679 if (T.isOSWindows() && T.isArch64Bit())
7680 return UnsignedLongLongTy;
7681 return UnsignedLongTy;
7682}
7683
7685 assert(Target && "Expected target to be initialized");
7686 const llvm::Triple &T = Target->getTriple();
7687 // Windows is LLP64 rather than LP64
7688 if (T.isOSWindows() && T.isArch64Bit())
7689 return LongLongTy;
7690 return LongTy;
7691}
7692
7694 if (!ObjCInstanceTypeDecl)
7695 ObjCInstanceTypeDecl =
7696 buildImplicitTypedef(getObjCIdType(), "instancetype");
7697 return ObjCInstanceTypeDecl;
7698}
7699
7700// This returns true if a type has been typedefed to BOOL:
7701// typedef <type> BOOL;
7703 if (const auto *TT = dyn_cast<TypedefType>(T))
7704 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7705 return II->isStr("BOOL");
7706
7707 return false;
7708}
7709
7710/// getObjCEncodingTypeSize returns size of type for objective-c encoding
7711/// purpose.
7713 if (!type->isIncompleteArrayType() && type->isIncompleteType())
7714 return CharUnits::Zero();
7715
7717
7718 // Make all integer and enum types at least as large as an int
7719 if (sz.isPositive() && type->isIntegralOrEnumerationType())
7720 sz = std::max(sz, getTypeSizeInChars(IntTy));
7721 // Treat arrays as pointers, since that's how they're passed in.
7722 else if (type->isArrayType())
7724 return sz;
7725}
7726
7728 return getTargetInfo().getCXXABI().isMicrosoft() &&
7729 VD->isStaticDataMember() &&
7731 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7732}
7733
7736 if (!VD->isInline())
7738
7739 // In almost all cases, it's a weak definition.
7740 auto *First = VD->getFirstDecl();
7741 if (First->isInlineSpecified() || !First->isStaticDataMember())
7743
7744 // If there's a file-context declaration in this translation unit, it's a
7745 // non-discardable definition.
7746 for (auto *D : VD->redecls())
7747 if (D->getLexicalDeclContext()->isFileContext() &&
7748 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7750
7751 // If we've not seen one yet, we don't know.
7753}
7754
7755static std::string charUnitsToString(const CharUnits &CU) {
7756 return llvm::itostr(CU.getQuantity());
7757}
7758
7759/// getObjCEncodingForBlock - Return the encoded type for this block
7760/// declaration.
7762 std::string S;
7763
7764 const BlockDecl *Decl = Expr->getBlockDecl();
7765 QualType BlockTy =
7766 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7767 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7768 // Encode result type.
7769 if (getLangOpts().EncodeExtendedBlockSig)
7771 true /*Extended*/);
7772 else
7773 getObjCEncodingForType(BlockReturnTy, S);
7774 // Compute size of all parameters.
7775 // Start with computing size of a pointer in number of bytes.
7776 // FIXME: There might(should) be a better way of doing this computation!
7778 CharUnits ParmOffset = PtrSize;
7779 for (auto *PI : Decl->parameters()) {
7780 QualType PType = PI->getType();
7782 if (sz.isZero())
7783 continue;
7784 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7785 ParmOffset += sz;
7786 }
7787 // Size of the argument frame
7788 S += charUnitsToString(ParmOffset);
7789 // Block pointer and offset.
7790 S += "@?0";
7791
7792 // Argument types.
7793 ParmOffset = PtrSize;
7794 for (auto *PVDecl : Decl->parameters()) {
7795 QualType PType = PVDecl->getOriginalType();
7796 if (const auto *AT =
7797 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7798 // Use array's original type only if it has known number of
7799 // elements.
7800 if (!isa<ConstantArrayType>(AT))
7801 PType = PVDecl->getType();
7802 } else if (PType->isFunctionType())
7803 PType = PVDecl->getType();
7804 if (getLangOpts().EncodeExtendedBlockSig)
7806 S, true /*Extended*/);
7807 else
7808 getObjCEncodingForType(PType, S);
7809 S += charUnitsToString(ParmOffset);
7810 ParmOffset += getObjCEncodingTypeSize(PType);
7811 }
7812
7813 return S;
7814}
7815
7816std::string
7818 std::string S;
7819 // Encode result type.
7820 getObjCEncodingForType(Decl->getReturnType(), S);
7821 CharUnits ParmOffset;
7822 // Compute size of all parameters.
7823 for (auto *PI : Decl->parameters()) {
7824 QualType PType = PI->getType();
7826 if (sz.isZero())
7827 continue;
7828
7829 assert(sz.isPositive() &&
7830 "getObjCEncodingForFunctionDecl - Incomplete param type");
7831 ParmOffset += sz;
7832 }
7833 S += charUnitsToString(ParmOffset);
7834 ParmOffset = CharUnits::Zero();
7835
7836 // Argument types.
7837 for (auto *PVDecl : Decl->parameters()) {
7838 QualType PType = PVDecl->getOriginalType();
7839 if (const auto *AT =
7840 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7841 // Use array's original type only if it has known number of
7842 // elements.
7843 if (!isa<ConstantArrayType>(AT))
7844 PType = PVDecl->getType();
7845 } else if (PType->isFunctionType())
7846 PType = PVDecl->getType();
7847 getObjCEncodingForType(PType, S);
7848 S += charUnitsToString(ParmOffset);
7849 ParmOffset += getObjCEncodingTypeSize(PType);
7850 }
7851
7852 return S;
7853}
7854
7855/// getObjCEncodingForMethodParameter - Return the encoded type for a single
7856/// method parameter or return type. If Extended, include class names and
7857/// block object types.
7859 QualType T, std::string& S,
7860 bool Extended) const {
7861 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7863 // Encode parameter type.
7864 ObjCEncOptions Options = ObjCEncOptions()
7865 .setExpandPointedToStructures()
7866 .setExpandStructures()
7867 .setIsOutermostType();
7868 if (Extended)
7869 Options.setEncodeBlockParameters().setEncodeClassNames();
7870 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7871}
7872
7873/// getObjCEncodingForMethodDecl - Return the encoded type for this method
7874/// declaration.
7876 bool Extended) const {
7877 // FIXME: This is not very efficient.
7878 // Encode return type.
7879 std::string S;
7880 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7881 Decl->getReturnType(), S, Extended);
7882 // Compute size of all parameters.
7883 // Start with computing size of a pointer in number of bytes.
7884 // FIXME: There might(should) be a better way of doing this computation!
7886 // The first two arguments (self and _cmd) are pointers; account for
7887 // their size.
7888 CharUnits ParmOffset = 2 * PtrSize;
7889 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7890 E = Decl->sel_param_end(); PI != E; ++PI) {
7891 QualType PType = (*PI)->getType();
7893 if (sz.isZero())
7894 continue;
7895
7896 assert(sz.isPositive() &&
7897 "getObjCEncodingForMethodDecl - Incomplete param type");
7898 ParmOffset += sz;
7899 }
7900 S += charUnitsToString(ParmOffset);
7901 S += "@0:";
7902 S += charUnitsToString(PtrSize);
7903
7904 // Argument types.
7905 ParmOffset = 2 * PtrSize;
7906 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7907 E = Decl->sel_param_end(); PI != E; ++PI) {
7908 const ParmVarDecl *PVDecl = *PI;
7909 QualType PType = PVDecl->getOriginalType();
7910 if (const auto *AT =
7911 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7912 // Use array's original type only if it has known number of
7913 // elements.
7914 if (!isa<ConstantArrayType>(AT))
7915 PType = PVDecl->getType();
7916 } else if (PType->isFunctionType())
7917 PType = PVDecl->getType();
7919 PType, S, Extended);
7920 S += charUnitsToString(ParmOffset);
7921 ParmOffset += getObjCEncodingTypeSize(PType);
7922 }
7923
7924 return S;
7925}
7926
7929 const ObjCPropertyDecl *PD,
7930 const Decl *Container) const {
7931 if (!Container)
7932 return nullptr;
7933 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7934 for (auto *PID : CID->property_impls())
7935 if (PID->getPropertyDecl() == PD)
7936 return PID;
7937 } else {
7938 const auto *OID = cast<ObjCImplementationDecl>(Container);
7939 for (auto *PID : OID->property_impls())
7940 if (PID->getPropertyDecl() == PD)
7941 return PID;
7942 }
7943 return nullptr;
7944}
7945
7946/// getObjCEncodingForPropertyDecl - Return the encoded type for this
7947/// property declaration. If non-NULL, Container must be either an
7948/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7949/// NULL when getting encodings for protocol properties.
7950/// Property attributes are stored as a comma-delimited C string. The simple
7951/// attributes readonly and bycopy are encoded as single characters. The
7952/// parametrized attributes, getter=name, setter=name, and ivar=name, are
7953/// encoded as single characters, followed by an identifier. Property types
7954/// are also encoded as a parametrized attribute. The characters used to encode
7955/// these attributes are defined by the following enumeration:
7956/// @code
7957/// enum PropertyAttributes {
7958/// kPropertyReadOnly = 'R', // property is read-only.
7959/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
7960/// kPropertyByref = '&', // property is a reference to the value last assigned
7961/// kPropertyDynamic = 'D', // property is dynamic
7962/// kPropertyGetter = 'G', // followed by getter selector name
7963/// kPropertySetter = 'S', // followed by setter selector name
7964/// kPropertyInstanceVariable = 'V' // followed by instance variable name
7965/// kPropertyType = 'T' // followed by old-style type encoding.
7966/// kPropertyWeak = 'W' // 'weak' property
7967/// kPropertyStrong = 'P' // property GC'able
7968/// kPropertyNonAtomic = 'N' // property non-atomic
7969/// kPropertyOptional = '?' // property optional
7970/// };
7971/// @endcode
7972std::string
7974 const Decl *Container) const {
7975 // Collect information from the property implementation decl(s).
7976 bool Dynamic = false;
7977 ObjCPropertyImplDecl *SynthesizePID = nullptr;
7978
7979 if (ObjCPropertyImplDecl *PropertyImpDecl =
7981 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7982 Dynamic = true;
7983 else
7984 SynthesizePID = PropertyImpDecl;
7985 }
7986
7987 // FIXME: This is not very efficient.
7988 std::string S = "T";
7989
7990 // Encode result type.
7991 // GCC has some special rules regarding encoding of properties which
7992 // closely resembles encoding of ivars.
7994
7995 if (PD->isOptional())
7996 S += ",?";
7997
7998 if (PD->isReadOnly()) {
7999 S += ",R";
8001 S += ",C";
8003 S += ",&";
8005 S += ",W";
8006 } else {
8007 switch (PD->getSetterKind()) {
8008 case ObjCPropertyDecl::Assign: break;
8009 case ObjCPropertyDecl::Copy: S += ",C"; break;
8010 case ObjCPropertyDecl::Retain: S += ",&"; break;
8011 case ObjCPropertyDecl::Weak: S += ",W"; break;
8012 }
8013 }
8014
8015 // It really isn't clear at all what this means, since properties
8016 // are "dynamic by default".
8017 if (Dynamic)
8018 S += ",D";
8019
8021 S += ",N";
8022
8024 S += ",G";
8025 S += PD->getGetterName().getAsString();
8026 }
8027
8029 S += ",S";
8030 S += PD->getSetterName().getAsString();
8031 }
8032
8033 if (SynthesizePID) {
8034 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8035 S += ",V";
8036 S += OID->getNameAsString();
8037 }
8038
8039 // FIXME: OBJCGC: weak & strong
8040 return S;
8041}
8042
8043/// getLegacyIntegralTypeEncoding -
8044/// Another legacy compatibility encoding: 32-bit longs are encoded as
8045/// 'l' or 'L' , but not always. For typedefs, we need to use
8046/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8048 if (PointeeTy->getAs<TypedefType>()) {
8049 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8050 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8051 PointeeTy = UnsignedIntTy;
8052 else
8053 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8054 PointeeTy = IntTy;
8055 }
8056 }
8057}
8058
8060 const FieldDecl *Field,
8061 QualType *NotEncodedT) const {
8062 // We follow the behavior of gcc, expanding structures which are
8063 // directly pointed to, and expanding embedded structures. Note that
8064 // these rules are sufficient to prevent recursive encoding of the
8065 // same type.
8066 getObjCEncodingForTypeImpl(T, S,
8067 ObjCEncOptions()
8068 .setExpandPointedToStructures()
8069 .setExpandStructures()
8070 .setIsOutermostType(),
8071 Field, NotEncodedT);
8072}
8073
8075 std::string& S) const {
8076 // Encode result type.
8077 // GCC has some special rules regarding encoding of properties which
8078 // closely resembles encoding of ivars.
8079 getObjCEncodingForTypeImpl(T, S,
8080 ObjCEncOptions()
8081 .setExpandPointedToStructures()
8082 .setExpandStructures()
8083 .setIsOutermostType()
8084 .setEncodingProperty(),
8085 /*Field=*/nullptr);
8086}
8087
8089 const BuiltinType *BT) {
8090 BuiltinType::Kind kind = BT->getKind();
8091 switch (kind) {
8092 case BuiltinType::Void: return 'v';
8093 case BuiltinType::Bool: return 'B';
8094 case BuiltinType::Char8:
8095 case BuiltinType::Char_U:
8096 case BuiltinType::UChar: return 'C';
8097 case BuiltinType::Char16:
8098 case BuiltinType::UShort: return 'S';
8099 case BuiltinType::Char32:
8100 case BuiltinType::UInt: return 'I';
8101 case BuiltinType::ULong:
8102 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8103 case BuiltinType::UInt128: return 'T';
8104 case BuiltinType::ULongLong: return 'Q';
8105 case BuiltinType::Char_S:
8106 case BuiltinType::SChar: return 'c';
8107 case BuiltinType::Short: return 's';
8108 case BuiltinType::WChar_S:
8109 case BuiltinType::WChar_U:
8110 case BuiltinType::Int: return 'i';
8111 case BuiltinType::Long:
8112 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8113 case BuiltinType::LongLong: return 'q';
8114 case BuiltinType::Int128: return 't';
8115 case BuiltinType::Float: return 'f';
8116 case BuiltinType::Double: return 'd';
8117 case BuiltinType::LongDouble: return 'D';
8118 case BuiltinType::NullPtr: return '*'; // like char*
8119
8120 case BuiltinType::BFloat16:
8121 case BuiltinType::Float16:
8122 case BuiltinType::Float128:
8123 case BuiltinType::Ibm128:
8124 case BuiltinType::Half:
8125 case BuiltinType::ShortAccum:
8126 case BuiltinType::Accum:
8127 case BuiltinType::LongAccum:
8128 case BuiltinType::UShortAccum:
8129 case BuiltinType::UAccum:
8130 case BuiltinType::ULongAccum:
8131 case BuiltinType::ShortFract:
8132 case BuiltinType::Fract:
8133 case BuiltinType::LongFract:
8134 case BuiltinType::UShortFract:
8135 case BuiltinType::UFract:
8136 case BuiltinType::ULongFract:
8137 case BuiltinType::SatShortAccum:
8138 case BuiltinType::SatAccum:
8139 case BuiltinType::SatLongAccum:
8140 case BuiltinType::SatUShortAccum:
8141 case BuiltinType::SatUAccum:
8142 case BuiltinType::SatULongAccum:
8143 case BuiltinType::SatShortFract:
8144 case BuiltinType::SatFract:
8145 case BuiltinType::SatLongFract:
8146 case BuiltinType::SatUShortFract:
8147 case BuiltinType::SatUFract:
8148 case BuiltinType::SatULongFract:
8149 // FIXME: potentially need @encodes for these!
8150 return ' ';
8151
8152#define SVE_TYPE(Name, Id, SingletonId) \
8153 case BuiltinType::Id:
8154#include "clang/Basic/AArch64SVEACLETypes.def"
8155#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8156#include "clang/Basic/RISCVVTypes.def"
8157#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8158#include "clang/Basic/WebAssemblyReferenceTypes.def"
8159 {
8160 DiagnosticsEngine &Diags = C->getDiagnostics();
8161 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8162 "cannot yet @encode type %0");
8163 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8164 return ' ';
8165 }
8166
8167 case BuiltinType::ObjCId:
8168 case BuiltinType::ObjCClass:
8169 case BuiltinType::ObjCSel:
8170 llvm_unreachable("@encoding ObjC primitive type");
8171
8172 // OpenCL and placeholder types don't need @encodings.
8173#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8174 case BuiltinType::Id:
8175#include "clang/Basic/OpenCLImageTypes.def"
8176#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8177 case BuiltinType::Id:
8178#include "clang/Basic/OpenCLExtensionTypes.def"
8179 case BuiltinType::OCLEvent:
8180 case BuiltinType::OCLClkEvent:
8181 case BuiltinType::OCLQueue:
8182 case BuiltinType::OCLReserveID:
8183 case BuiltinType::OCLSampler:
8184 case BuiltinType::Dependent:
8185#define PPC_VECTOR_TYPE(Name, Id, Size) \
8186 case BuiltinType::Id:
8187#include "clang/Basic/PPCTypes.def"
8188#define BUILTIN_TYPE(KIND, ID)
8189#define PLACEHOLDER_TYPE(KIND, ID) \
8190 case BuiltinType::KIND:
8191#include "clang/AST/BuiltinTypes.def"
8192 llvm_unreachable("invalid builtin type for @encode");
8193 }
8194 llvm_unreachable("invalid BuiltinType::Kind value");
8195}
8196
8197static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8198 EnumDecl *Enum = ET->getDecl();
8199
8200 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8201 if (!Enum->isFixed())
8202 return 'i';
8203
8204 // The encoding of a fixed enum type matches its fixed underlying type.
8205 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8207}
8208
8209static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8210 QualType T, const FieldDecl *FD) {
8211 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8212 S += 'b';
8213 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8214 // The GNU runtime requires more information; bitfields are encoded as b,
8215 // then the offset (in bits) of the first element, then the type of the
8216 // bitfield, then the size in bits. For example, in this structure:
8217 //
8218 // struct
8219 // {
8220 // int integer;
8221 // int flags:2;
8222 // };
8223 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8224 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8225 // information is not especially sensible, but we're stuck with it for
8226 // compatibility with GCC, although providing it breaks anything that
8227 // actually uses runtime introspection and wants to work on both runtimes...
8228 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8229 uint64_t Offset;
8230
8231 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8232 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8233 IVD);
8234 } else {
8235 const RecordDecl *RD = FD->getParent();
8236 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8237 Offset = RL.getFieldOffset(FD->getFieldIndex());
8238 }
8239
8240 S += llvm::utostr(Offset);
8241
8242 if (const auto *ET = T->getAs<EnumType>())
8243 S += ObjCEncodingForEnumType(Ctx, ET);
8244 else {
8245 const auto *BT = T->castAs<BuiltinType>();
8246 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8247 }
8248 }
8249 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8250}
8251
8252// Helper function for determining whether the encoded type string would include
8253// a template specialization type.
8255 bool VisitBasesAndFields) {
8257
8258 if (auto *PT = T->getAs<PointerType>())
8260 PT->getPointeeType().getTypePtr(), false);
8261
8262 auto *CXXRD = T->getAsCXXRecordDecl();
8263
8264 if (!CXXRD)
8265 return false;
8266
8267 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8268 return true;
8269
8270 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8271 return false;
8272
8273 for (const auto &B : CXXRD->bases())
8274 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8275 true))
8276 return true;
8277
8278 for (auto *FD : CXXRD->fields())
8279 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8280 true))
8281 return true;
8282
8283 return false;
8284}
8285
8286// FIXME: Use SmallString for accumulating string.
8287void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8288 const ObjCEncOptions Options,
8289 const FieldDecl *FD,
8290 QualType *NotEncodedT) const {
8292 switch (CT->getTypeClass()) {
8293 case Type::Builtin:
8294 case Type::Enum:
8295 if (FD && FD->isBitField())
8296 return EncodeBitField(this, S, T, FD);
8297 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8298 S += getObjCEncodingForPrimitiveType(this, BT);
8299 else
8300 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8301 return;
8302
8303 case Type::Complex:
8304 S += 'j';
8305 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8306 ObjCEncOptions(),
8307 /*Field=*/nullptr);
8308 return;
8309
8310 case Type::Atomic:
8311 S += 'A';
8312 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8313 ObjCEncOptions(),
8314 /*Field=*/nullptr);
8315 return;
8316
8317 // encoding for pointer or reference types.
8318 case Type::Pointer:
8319 case Type::LValueReference:
8320 case Type::RValueReference: {
8321 QualType PointeeTy;
8322 if (isa<PointerType>(CT)) {
8323 const auto *PT = T->castAs<PointerType>();
8324 if (PT->isObjCSelType()) {
8325 S += ':';
8326 return;
8327 }
8328 PointeeTy = PT->getPointeeType();
8329 } else {
8330 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8331 }
8332
8333 bool isReadOnly = false;
8334 // For historical/compatibility reasons, the read-only qualifier of the
8335 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8336 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8337 // Also, do not emit the 'r' for anything but the outermost type!
8338 if (T->getAs<TypedefType>()) {
8339 if (Options.IsOutermostType() && T.isConstQualified()) {
8340 isReadOnly = true;
8341 S += 'r';
8342 }
8343 } else if (Options.IsOutermostType()) {
8344 QualType P = PointeeTy;
8345 while (auto PT = P->getAs<PointerType>())
8346 P = PT->getPointeeType();
8347 if (P.isConstQualified()) {
8348 isReadOnly = true;
8349 S += 'r';
8350 }
8351 }
8352 if (isReadOnly) {
8353 // Another legacy compatibility encoding. Some ObjC qualifier and type
8354 // combinations need to be rearranged.
8355 // Rewrite "in const" from "nr" to "rn"
8356 if (StringRef(S).ends_with("nr"))
8357 S.replace(S.end()-2, S.end(), "rn");
8358 }
8359
8360 if (PointeeTy->isCharType()) {
8361 // char pointer types should be encoded as '*' unless it is a
8362 // type that has been typedef'd to 'BOOL'.
8363 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8364 S += '*';
8365 return;
8366 }
8367 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8368 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8369 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8370 S += '#';
8371 return;
8372 }
8373 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8374 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8375 S += '@';
8376 return;
8377 }
8378 // If the encoded string for the class includes template names, just emit
8379 // "^v" for pointers to the class.
8380 if (getLangOpts().CPlusPlus &&
8381 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8383 RTy, Options.ExpandPointedToStructures()))) {
8384 S += "^v";
8385 return;
8386 }
8387 // fall through...
8388 }
8389 S += '^';
8391
8392 ObjCEncOptions NewOptions;
8393 if (Options.ExpandPointedToStructures())
8394 NewOptions.setExpandStructures();
8395 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8396 /*Field=*/nullptr, NotEncodedT);
8397 return;
8398 }
8399
8400 case Type::ConstantArray:
8401 case Type::IncompleteArray:
8402 case Type::VariableArray: {
8403 const auto *AT = cast<ArrayType>(CT);
8404
8405 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8406 // Incomplete arrays are encoded as a pointer to the array element.
8407 S += '^';
8408
8409 getObjCEncodingForTypeImpl(
8410 AT->getElementType(), S,
8411 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8412 } else {
8413 S += '[';
8414
8415 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8416 S += llvm::utostr(CAT->getZExtSize());
8417 else {
8418 //Variable length arrays are encoded as a regular array with 0 elements.
8419 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8420 "Unknown array type!");
8421 S += '0';
8422 }
8423
8424 getObjCEncodingForTypeImpl(
8425 AT->getElementType(), S,
8426 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8427 NotEncodedT);
8428 S += ']';
8429 }
8430 return;
8431 }
8432
8433 case Type::FunctionNoProto:
8434 case Type::FunctionProto:
8435 S += '?';
8436 return;
8437
8438 case Type::Record: {
8439 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8440 S += RDecl->isUnion() ? '(' : '{';
8441 // Anonymous structures print as '?'
8442 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8443 S += II->getName();
8444 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8445 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8446 llvm::raw_string_ostream OS(S);
8447 printTemplateArgumentList(OS, TemplateArgs.asArray(),
8449 }
8450 } else {
8451 S += '?';
8452 }
8453 if (Options.ExpandStructures()) {
8454 S += '=';
8455 if (!RDecl->isUnion()) {
8456 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8457 } else {
8458 for (const auto *Field : RDecl->fields()) {
8459 if (FD) {
8460 S += '"';
8461 S += Field->getNameAsString();
8462 S += '"';
8463 }
8464
8465 // Special case bit-fields.
8466 if (Field->isBitField()) {
8467 getObjCEncodingForTypeImpl(Field->getType(), S,
8468 ObjCEncOptions().setExpandStructures(),
8469 Field);
8470 } else {
8471 QualType qt = Field->getType();
8473 getObjCEncodingForTypeImpl(
8474 qt, S,
8475 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8476 NotEncodedT);
8477 }
8478 }
8479 }
8480 }
8481 S += RDecl->isUnion() ? ')' : '}';
8482 return;
8483 }
8484
8485 case Type::BlockPointer: {
8486 const auto *BT = T->castAs<BlockPointerType>();
8487 S += "@?"; // Unlike a pointer-to-function, which is "^?".
8488 if (Options.EncodeBlockParameters()) {
8489 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8490
8491 S += '<';
8492 // Block return type
8493 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8494 Options.forComponentType(), FD, NotEncodedT);
8495 // Block self
8496 S += "@?";
8497 // Block parameters
8498 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8499 for (const auto &I : FPT->param_types())
8500 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8501 NotEncodedT);
8502 }
8503 S += '>';
8504 }
8505 return;
8506 }
8507
8508 case Type::ObjCObject: {
8509 // hack to match legacy encoding of *id and *Class
8511 if (Ty->isObjCIdType()) {
8512 S += "{objc_object=}";
8513 return;
8514 }
8515 else if (Ty->isObjCClassType()) {
8516 S += "{objc_class=}";
8517 return;
8518 }
8519 // TODO: Double check to make sure this intentionally falls through.
8520 [[fallthrough]];
8521 }
8522
8523 case Type::ObjCInterface: {
8524 // Ignore protocol qualifiers when mangling at this level.
8525 // @encode(class_name)
8526 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8527 S += '{';
8528 S += OI->getObjCRuntimeNameAsString();
8529 if (Options.ExpandStructures()) {
8530 S += '=';
8532 DeepCollectObjCIvars(OI, true, Ivars);
8533 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8534 const FieldDecl *Field = Ivars[i];
8535 if (Field->isBitField())
8536 getObjCEncodingForTypeImpl(Field->getType(), S,
8537 ObjCEncOptions().setExpandStructures(),
8538 Field);
8539 else
8540 getObjCEncodingForTypeImpl(Field->getType(), S,
8541 ObjCEncOptions().setExpandStructures(), FD,
8542 NotEncodedT);
8543 }
8544 }
8545 S += '}';
8546 return;
8547 }
8548
8549 case Type::ObjCObjectPointer: {
8550 const auto *OPT = T->castAs<ObjCObjectPointerType>();
8551 if (OPT->isObjCIdType()) {
8552 S += '@';
8553 return;
8554 }
8555
8556 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8557 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8558 // Since this is a binary compatibility issue, need to consult with
8559 // runtime folks. Fortunately, this is a *very* obscure construct.
8560 S += '#';
8561 return;
8562 }
8563
8564 if (OPT->isObjCQualifiedIdType()) {
8565 getObjCEncodingForTypeImpl(
8566 getObjCIdType(), S,
8567 Options.keepingOnly(ObjCEncOptions()
8568 .setExpandPointedToStructures()
8569 .setExpandStructures()),
8570 FD);
8571 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8572 // Note that we do extended encoding of protocol qualifier list
8573 // Only when doing ivar or property encoding.
8574 S += '"';
8575 for (const auto *I : OPT->quals()) {
8576 S += '<';
8577 S += I->getObjCRuntimeNameAsString();
8578 S += '>';
8579 }
8580 S += '"';
8581 }
8582 return;
8583 }
8584
8585 S += '@';
8586 if (OPT->getInterfaceDecl() &&
8587 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8588 S += '"';
8589 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8590 for (const auto *I : OPT->quals()) {
8591 S += '<';
8592 S += I->getObjCRuntimeNameAsString();
8593 S += '>';
8594 }
8595 S += '"';
8596 }
8597 return;
8598 }
8599
8600 // gcc just blithely ignores member pointers.
8601 // FIXME: we should do better than that. 'M' is available.
8602 case Type::MemberPointer:
8603 // This matches gcc's encoding, even though technically it is insufficient.
8604 //FIXME. We should do a better job than gcc.
8605 case Type::Vector:
8606 case Type::ExtVector:
8607 // Until we have a coherent encoding of these three types, issue warning.
8608 if (NotEncodedT)
8609 *NotEncodedT = T;
8610 return;
8611
8612 case Type::ConstantMatrix:
8613 if (NotEncodedT)
8614 *NotEncodedT = T;
8615 return;
8616
8617 case Type::BitInt:
8618 if (NotEncodedT)
8619 *NotEncodedT = T;
8620 return;
8621
8622 // We could see an undeduced auto type here during error recovery.
8623 // Just ignore it.
8624 case Type::Auto:
8625 case Type::DeducedTemplateSpecialization:
8626 return;
8627
8628 case Type::ArrayParameter:
8629 case Type::Pipe:
8630#define ABSTRACT_TYPE(KIND, BASE)
8631#define TYPE(KIND, BASE)
8632#define DEPENDENT_TYPE(KIND, BASE) \
8633 case Type::KIND:
8634#define NON_CANONICAL_TYPE(KIND, BASE) \
8635 case Type::KIND:
8636#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8637 case Type::KIND:
8638#include "clang/AST/TypeNodes.inc"
8639 llvm_unreachable("@encode for dependent type!");
8640 }
8641 llvm_unreachable("bad type kind!");
8642}
8643
8644void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8645 std::string &S,
8646 const FieldDecl *FD,
8647 bool includeVBases,
8648 QualType *NotEncodedT) const {
8649 assert(RDecl && "Expected non-null RecordDecl");
8650 assert(!RDecl->isUnion() && "Should not be called for unions");
8651 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8652 return;
8653
8654 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8655 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8656 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8657
8658 if (CXXRec) {
8659 for (const auto &BI : CXXRec->bases()) {
8660 if (!BI.isVirtual()) {
8661 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8662 if (base->isEmpty())
8663 continue;
8664 uint64_t offs = toBits(layout.getBaseClassOffset(base));
8665 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8666 std::make_pair(offs, base));
8667 }
8668 }
8669 }
8670
8671 for (FieldDecl *Field : RDecl->fields()) {
8672 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8673 continue;
8674 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
8675 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8676 std::make_pair(offs, Field));
8677 }
8678
8679 if (CXXRec && includeVBases) {
8680 for (const auto &BI : CXXRec->vbases()) {
8681 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8682 if (base->isEmpty())
8683 continue;
8684 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8685 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8686 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8687 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8688 std::make_pair(offs, base));
8689 }
8690 }
8691
8692 CharUnits size;
8693 if (CXXRec) {
8694 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8695 } else {
8696 size = layout.getSize();
8697 }
8698
8699#ifndef NDEBUG
8700 uint64_t CurOffs = 0;
8701#endif
8702 std::multimap<uint64_t, NamedDecl *>::iterator
8703 CurLayObj = FieldOrBaseOffsets.begin();
8704
8705 if (CXXRec && CXXRec->isDynamicClass() &&
8706 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8707 if (FD) {
8708 S += "\"_vptr$";
8709 std::string recname = CXXRec->getNameAsString();
8710 if (recname.empty()) recname = "?";
8711 S += recname;
8712 S += '"';
8713 }
8714 S += "^^?";
8715#ifndef NDEBUG
8716 CurOffs += getTypeSize(VoidPtrTy);
8717#endif
8718 }
8719
8720 if (!RDecl->hasFlexibleArrayMember()) {
8721 // Mark the end of the structure.
8722 uint64_t offs = toBits(size);
8723 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8724 std::make_pair(offs, nullptr));
8725 }
8726
8727 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8728#ifndef NDEBUG
8729 assert(CurOffs <= CurLayObj->first);
8730 if (CurOffs < CurLayObj->first) {
8731 uint64_t padding = CurLayObj->first - CurOffs;
8732 // FIXME: There doesn't seem to be a way to indicate in the encoding that
8733 // packing/alignment of members is different that normal, in which case
8734 // the encoding will be out-of-sync with the real layout.
8735 // If the runtime switches to just consider the size of types without
8736 // taking into account alignment, we could make padding explicit in the
8737 // encoding (e.g. using arrays of chars). The encoding strings would be
8738 // longer then though.
8739 CurOffs += padding;
8740 }
8741#endif
8742
8743 NamedDecl *dcl = CurLayObj->second;
8744 if (!dcl)
8745 break; // reached end of structure.
8746
8747 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8748 // We expand the bases without their virtual bases since those are going
8749 // in the initial structure. Note that this differs from gcc which
8750 // expands virtual bases each time one is encountered in the hierarchy,
8751 // making the encoding type bigger than it really is.
8752 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8753 NotEncodedT);
8754 assert(!base->isEmpty());
8755#ifndef NDEBUG
8756 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8757#endif
8758 } else {
8759 const auto *field = cast<FieldDecl>(dcl);
8760 if (FD) {
8761 S += '"';
8762 S += field->getNameAsString();
8763 S += '"';
8764 }
8765
8766 if (field->isBitField()) {
8767 EncodeBitField(this, S, field->getType(), field);
8768#ifndef NDEBUG
8769 CurOffs += field->getBitWidthValue(*this);
8770#endif
8771 } else {
8772 QualType qt = field->getType();
8774 getObjCEncodingForTypeImpl(
8775 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8776 FD, NotEncodedT);
8777#ifndef NDEBUG
8778 CurOffs += getTypeSize(field->getType());
8779#endif
8780 }
8781 }
8782 }
8783}
8784
8786 std::string& S) const {
8787 if (QT & Decl::OBJC_TQ_In)
8788 S += 'n';
8789 if (QT & Decl::OBJC_TQ_Inout)
8790 S += 'N';
8791 if (QT & Decl::OBJC_TQ_Out)
8792 S += 'o';
8793 if (QT & Decl::OBJC_TQ_Bycopy)
8794 S += 'O';
8795 if (QT & Decl::OBJC_TQ_Byref)
8796 S += 'R';
8797 if (QT & Decl::OBJC_TQ_Oneway)
8798 S += 'V';
8799}
8800
8802 if (!ObjCIdDecl) {
8805 ObjCIdDecl = buildImplicitTypedef(T, "id");
8806 }
8807 return ObjCIdDecl;
8808}
8809
8811 if (!ObjCSelDecl) {
8813 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8814 }
8815 return ObjCSelDecl;
8816}
8817
8819 if (!ObjCClassDecl) {
8822 ObjCClassDecl = buildImplicitTypedef(T, "Class");
8823 }
8824 return ObjCClassDecl;
8825}
8826
8828 if (!ObjCProtocolClassDecl) {
8829 ObjCProtocolClassDecl
8832 &Idents.get("Protocol"),
8833 /*typeParamList=*/nullptr,
8834 /*PrevDecl=*/nullptr,
8835 SourceLocation(), true);
8836 }
8837
8838 return ObjCProtocolClassDecl;
8839}
8840
8841//===----------------------------------------------------------------------===//
8842// __builtin_va_list Construction Functions
8843//===----------------------------------------------------------------------===//
8844
8846 StringRef Name) {
8847 // typedef char* __builtin[_ms]_va_list;
8848 QualType T = Context->getPointerType(Context->CharTy);
8849 return Context->buildImplicitTypedef(T, Name);
8850}
8851
8853 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8854}
8855
8857 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8858}
8859
8861 // typedef void* __builtin_va_list;
8862 QualType T = Context->getPointerType(Context->VoidTy);
8863 return Context->buildImplicitTypedef(T, "__builtin_va_list");
8864}
8865
8866static TypedefDecl *
8868 // struct __va_list
8869 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8870 if (Context->getLangOpts().CPlusPlus) {
8871 // namespace std { struct __va_list {
8872 auto *NS = NamespaceDecl::Create(
8873 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8874 /*Inline=*/false, SourceLocation(), SourceLocation(),
8875 &Context->Idents.get("std"),
8876 /*PrevDecl=*/nullptr, /*Nested=*/false);
8877 NS->setImplicit();
8878 VaListTagDecl->setDeclContext(NS);
8879 }
8880
8881 VaListTagDecl->startDefinition();
8882
8883 const size_t NumFields = 5;
8884 QualType FieldTypes[NumFields];
8885 const char *FieldNames[NumFields];
8886
8887 // void *__stack;
8888 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8889 FieldNames[0] = "__stack";
8890
8891 // void *__gr_top;
8892 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8893 FieldNames[1] = "__gr_top";
8894
8895 // void *__vr_top;
8896 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8897 FieldNames[2] = "__vr_top";
8898
8899 // int __gr_offs;
8900 FieldTypes[3] = Context->IntTy;
8901 FieldNames[3] = "__gr_offs";
8902
8903 // int __vr_offs;
8904 FieldTypes[4] = Context->IntTy;
8905 FieldNames[4] = "__vr_offs";
8906
8907 // Create fields
8908 for (unsigned i = 0; i < NumFields; ++i) {
8909 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8910 VaListTagDecl,
8913 &Context->Idents.get(FieldNames[i]),
8914 FieldTypes[i], /*TInfo=*/nullptr,
8915 /*BitWidth=*/nullptr,
8916 /*Mutable=*/false,
8917 ICIS_NoInit);
8918 Field->setAccess(AS_public);
8919 VaListTagDecl->addDecl(Field);
8920 }
8921 VaListTagDecl->completeDefinition();
8922 Context->VaListTagDecl = VaListTagDecl;
8923 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8924
8925 // } __builtin_va_list;
8926 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8927}
8928
8930 // typedef struct __va_list_tag {
8931 RecordDecl *VaListTagDecl;
8932
8933 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8934 VaListTagDecl->startDefinition();
8935
8936 const size_t NumFields = 5;
8937 QualType FieldTypes[NumFields];
8938 const char *FieldNames[NumFields];
8939
8940 // unsigned char gpr;
8941 FieldTypes[0] = Context->UnsignedCharTy;
8942 FieldNames[0] = "gpr";
8943
8944 // unsigned char fpr;
8945 FieldTypes[1] = Context->UnsignedCharTy;
8946 FieldNames[1] = "fpr";
8947
8948 // unsigned short reserved;
8949 FieldTypes[2] = Context->UnsignedShortTy;
8950 FieldNames[2] = "reserved";
8951
8952 // void* overflow_arg_area;
8953 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8954 FieldNames[3] = "overflow_arg_area";
8955
8956 // void* reg_save_area;
8957 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8958 FieldNames[4] = "reg_save_area";
8959
8960 // Create fields
8961 for (unsigned i = 0; i < NumFields; ++i) {
8962 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8965 &Context->Idents.get(FieldNames[i]),
8966 FieldTypes[i], /*TInfo=*/nullptr,
8967 /*BitWidth=*/nullptr,
8968 /*Mutable=*/false,
8969 ICIS_NoInit);
8970 Field->setAccess(AS_public);
8971 VaListTagDecl->addDecl(Field);
8972 }
8973 VaListTagDecl->completeDefinition();
8974 Context->VaListTagDecl = VaListTagDecl;
8975 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8976
8977 // } __va_list_tag;
8978 TypedefDecl *VaListTagTypedefDecl =
8979 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8980
8981 QualType VaListTagTypedefType =
8982 Context->getTypedefType(VaListTagTypedefDecl);
8983
8984 // typedef __va_list_tag __builtin_va_list[1];
8985 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8986 QualType VaListTagArrayType = Context->getConstantArrayType(
8987 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
8988 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8989}
8990
8991static TypedefDecl *
8993 // struct __va_list_tag {
8994 RecordDecl *VaListTagDecl;
8995 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8996 VaListTagDecl->startDefinition();
8997
8998 const size_t NumFields = 4;
8999 QualType FieldTypes[NumFields];
9000 const char *FieldNames[NumFields];
9001
9002 // unsigned gp_offset;
9003 FieldTypes[0] = Context->UnsignedIntTy;
9004 FieldNames[0] = "gp_offset";
9005
9006 // unsigned fp_offset;
9007 FieldTypes[1] = Context->UnsignedIntTy;
9008 FieldNames[1] = "fp_offset";
9009
9010 // void* overflow_arg_area;
9011 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9012 FieldNames[2] = "overflow_arg_area";
9013
9014 // void* reg_save_area;
9015 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9016 FieldNames[3] = "reg_save_area";
9017
9018 // Create fields
9019 for (unsigned i = 0; i < NumFields; ++i) {
9020 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9021 VaListTagDecl,
9024 &Context->Idents.get(FieldNames[i]),
9025 FieldTypes[i], /*TInfo=*/nullptr,
9026 /*BitWidth=*/nullptr,
9027 /*Mutable=*/false,
9028 ICIS_NoInit);
9029 Field->setAccess(AS_public);
9030 VaListTagDecl->addDecl(Field);
9031 }
9032 VaListTagDecl->completeDefinition();
9033 Context->VaListTagDecl = VaListTagDecl;
9034 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9035
9036 // };
9037
9038 // typedef struct __va_list_tag __builtin_va_list[1];
9039 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9040 QualType VaListTagArrayType = Context->getConstantArrayType(
9041 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9042 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9043}
9044
9046 // typedef int __builtin_va_list[4];
9047 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9048 QualType IntArrayType = Context->getConstantArrayType(
9049 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9050 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9051}
9052
9053static TypedefDecl *
9055 // struct __va_list
9056 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9057 if (Context->getLangOpts().CPlusPlus) {
9058 // namespace std { struct __va_list {
9059 NamespaceDecl *NS;
9060 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9061 Context->getTranslationUnitDecl(),
9062 /*Inline=*/false, SourceLocation(),
9063 SourceLocation(), &Context->Idents.get("std"),
9064 /*PrevDecl=*/nullptr, /*Nested=*/false);
9065 NS->setImplicit();
9066 VaListDecl->setDeclContext(NS);
9067 }
9068
9069 VaListDecl->startDefinition();
9070
9071 // void * __ap;
9072 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9073 VaListDecl,
9076 &Context->Idents.get("__ap"),
9077 Context->getPointerType(Context->VoidTy),
9078 /*TInfo=*/nullptr,
9079 /*BitWidth=*/nullptr,
9080 /*Mutable=*/false,
9081 ICIS_NoInit);
9082 Field->setAccess(AS_public);
9083 VaListDecl->addDecl(Field);
9084
9085 // };
9086 VaListDecl->completeDefinition();
9087 Context->VaListTagDecl = VaListDecl;
9088
9089 // typedef struct __va_list __builtin_va_list;
9090 QualType T = Context->getRecordType(VaListDecl);
9091 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9092}
9093
9094static TypedefDecl *
9096 // struct __va_list_tag {
9097 RecordDecl *VaListTagDecl;
9098 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9099 VaListTagDecl->startDefinition();
9100
9101 const size_t NumFields = 4;
9102 QualType FieldTypes[NumFields];
9103 const char *FieldNames[NumFields];
9104
9105 // long __gpr;
9106 FieldTypes[0] = Context->LongTy;
9107 FieldNames[0] = "__gpr";
9108
9109 // long __fpr;
9110 FieldTypes[1] = Context->LongTy;
9111 FieldNames[1] = "__fpr";
9112
9113 // void *__overflow_arg_area;
9114 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9115 FieldNames[2] = "__overflow_arg_area";
9116
9117 // void *__reg_save_area;
9118 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9119 FieldNames[3] = "__reg_save_area";
9120
9121 // Create fields
9122 for (unsigned i = 0; i < NumFields; ++i) {
9123 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9124 VaListTagDecl,
9127 &Context->Idents.get(FieldNames[i]),
9128 FieldTypes[i], /*TInfo=*/nullptr,
9129 /*BitWidth=*/nullptr,
9130 /*Mutable=*/false,
9131 ICIS_NoInit);
9132 Field->setAccess(AS_public);
9133 VaListTagDecl->addDecl(Field);
9134 }
9135 VaListTagDecl->completeDefinition();
9136 Context->VaListTagDecl = VaListTagDecl;
9137 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9138
9139 // };
9140
9141 // typedef __va_list_tag __builtin_va_list[1];
9142 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9143 QualType VaListTagArrayType = Context->getConstantArrayType(
9144 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9145
9146 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9147}
9148
9150 // typedef struct __va_list_tag {
9151 RecordDecl *VaListTagDecl;
9152 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9153 VaListTagDecl->startDefinition();
9154
9155 const size_t NumFields = 3;
9156 QualType FieldTypes[NumFields];
9157 const char *FieldNames[NumFields];
9158
9159 // void *CurrentSavedRegisterArea;
9160 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9161 FieldNames[0] = "__current_saved_reg_area_pointer";
9162
9163 // void *SavedRegAreaEnd;
9164 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9165 FieldNames[1] = "__saved_reg_area_end_pointer";
9166
9167 // void *OverflowArea;
9168 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9169 FieldNames[2] = "__overflow_area_pointer";
9170
9171 // Create fields
9172 for (unsigned i = 0; i < NumFields; ++i) {
9174 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9175 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9176 /*TInfo=*/nullptr,
9177 /*BitWidth=*/nullptr,
9178 /*Mutable=*/false, ICIS_NoInit);
9179 Field->setAccess(AS_public);
9180 VaListTagDecl->addDecl(Field);
9181 }
9182 VaListTagDecl->completeDefinition();
9183 Context->VaListTagDecl = VaListTagDecl;
9184 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9185
9186 // } __va_list_tag;
9187 TypedefDecl *VaListTagTypedefDecl =
9188 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9189
9190 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9191
9192 // typedef __va_list_tag __builtin_va_list[1];
9193 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9194 QualType VaListTagArrayType = Context->getConstantArrayType(
9195 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9196
9197 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9198}
9199
9202 switch (Kind) {
9204 return CreateCharPtrBuiltinVaListDecl(Context);
9206 return CreateVoidPtrBuiltinVaListDecl(Context);
9208 return CreateAArch64ABIBuiltinVaListDecl(Context);
9210 return CreatePowerABIBuiltinVaListDecl(Context);
9212 return CreateX86_64ABIBuiltinVaListDecl(Context);
9214 return CreatePNaClABIBuiltinVaListDecl(Context);
9216 return CreateAAPCSABIBuiltinVaListDecl(Context);
9218 return CreateSystemZBuiltinVaListDecl(Context);
9220 return CreateHexagonBuiltinVaListDecl(Context);
9221 }
9222
9223 llvm_unreachable("Unhandled __builtin_va_list type kind");
9224}
9225
9227 if (!BuiltinVaListDecl) {
9228 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9229 assert(BuiltinVaListDecl->isImplicit());
9230 }
9231
9232 return BuiltinVaListDecl;
9233}
9234
9236 // Force the creation of VaListTagDecl by building the __builtin_va_list
9237 // declaration.
9238 if (!VaListTagDecl)
9239 (void)getBuiltinVaListDecl();
9240
9241 return VaListTagDecl;
9242}
9243
9245 if (!BuiltinMSVaListDecl)
9246 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9247
9248 return BuiltinMSVaListDecl;
9249}
9250
9252 // Allow redecl custom type checking builtin for HLSL.
9253 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9255 return true;
9257}
9258
9260 assert(ObjCConstantStringType.isNull() &&
9261 "'NSConstantString' type already set!");
9262
9263 ObjCConstantStringType = getObjCInterfaceType(Decl);
9264}
9265
9266/// Retrieve the template name that corresponds to a non-empty
9267/// lookup.
9270 UnresolvedSetIterator End) const {
9271 unsigned size = End - Begin;
9272 assert(size > 1 && "set is not overloaded!");
9273
9274 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9275 size * sizeof(FunctionTemplateDecl*));
9276 auto *OT = new (memory) OverloadedTemplateStorage(size);
9277
9278 NamedDecl **Storage = OT->getStorage();
9279 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9280 NamedDecl *D = *I;
9281 assert(isa<FunctionTemplateDecl>(D) ||
9282 isa<UnresolvedUsingValueDecl>(D) ||
9283 (isa<UsingShadowDecl>(D) &&
9284 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9285 *Storage++ = D;
9286 }
9287
9288 return TemplateName(OT);
9289}
9290
9291/// Retrieve a template name representing an unqualified-id that has been
9292/// assumed to name a template for ADL purposes.
9294 auto *OT = new (*this) AssumedTemplateStorage(Name);
9295 return TemplateName(OT);
9296}
9297
9298/// Retrieve the template name that represents a qualified
9299/// template name such as \c std::vector.
9301 bool TemplateKeyword,
9302 TemplateName Template) const {
9303 assert(NNS && "Missing nested-name-specifier in qualified template name");
9304
9305 // FIXME: Canonicalization?
9306 llvm::FoldingSetNodeID ID;
9307 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9308
9309 void *InsertPos = nullptr;
9311 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9312 if (!QTN) {
9313 QTN = new (*this, alignof(QualifiedTemplateName))
9314 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9315 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9316 }
9317
9318 return TemplateName(QTN);
9319}
9320
9321/// Retrieve the template name that represents a dependent
9322/// template name such as \c MetaFun::template apply.
9325 const IdentifierInfo *Name) const {
9326 assert((!NNS || NNS->isDependent()) &&
9327 "Nested name specifier must be dependent");
9328
9329 llvm::FoldingSetNodeID ID;
9330 DependentTemplateName::Profile(ID, NNS, Name);
9331
9332 void *InsertPos = nullptr;
9334 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9335
9336 if (QTN)
9337 return TemplateName(QTN);
9338
9340 if (CanonNNS == NNS) {
9341 QTN = new (*this, alignof(DependentTemplateName))
9342 DependentTemplateName(NNS, Name);
9343 } else {
9344 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9345 QTN = new (*this, alignof(DependentTemplateName))
9346 DependentTemplateName(NNS, Name, Canon);
9347 DependentTemplateName *CheckQTN =
9348 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9349 assert(!CheckQTN && "Dependent type name canonicalization broken");
9350 (void)CheckQTN;
9351 }
9352
9353 DependentTemplateNames.InsertNode(QTN, InsertPos);
9354 return TemplateName(QTN);
9355}
9356
9357/// Retrieve the template name that represents a dependent
9358/// template name such as \c MetaFun::template operator+.
9361 OverloadedOperatorKind Operator) const {
9362 assert((!NNS || NNS->isDependent()) &&
9363 "Nested name specifier must be dependent");
9364
9365 llvm::FoldingSetNodeID ID;
9366 DependentTemplateName::Profile(ID, NNS, Operator);
9367
9368 void *InsertPos = nullptr;
9370 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9371
9372 if (QTN)
9373 return TemplateName(QTN);
9374
9376 if (CanonNNS == NNS) {
9377 QTN = new (*this, alignof(DependentTemplateName))
9378 DependentTemplateName(NNS, Operator);
9379 } else {
9380 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9381 QTN = new (*this, alignof(DependentTemplateName))
9382 DependentTemplateName(NNS, Operator, Canon);
9383
9384 DependentTemplateName *CheckQTN
9385 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9386 assert(!CheckQTN && "Dependent template name canonicalization broken");
9387 (void)CheckQTN;
9388 }
9389
9390 DependentTemplateNames.InsertNode(QTN, InsertPos);
9391 return TemplateName(QTN);
9392}
9393
9395 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9396 std::optional<unsigned> PackIndex) const {
9397 llvm::FoldingSetNodeID ID;
9398 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9399 Index, PackIndex);
9400
9401 void *insertPos = nullptr;
9403 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9404
9405 if (!subst) {
9406 subst = new (*this) SubstTemplateTemplateParmStorage(
9407 Replacement, AssociatedDecl, Index, PackIndex);
9408 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9409 }
9410
9411 return TemplateName(subst);
9412}
9413
9416 Decl *AssociatedDecl,
9417 unsigned Index, bool Final) const {
9418 auto &Self = const_cast<ASTContext &>(*this);
9419 llvm::FoldingSetNodeID ID;
9421 AssociatedDecl, Index, Final);
9422
9423 void *InsertPos = nullptr;
9425 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9426
9427 if (!Subst) {
9428 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9429 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9430 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9431 }
9432
9433 return TemplateName(Subst);
9434}
9435
9436/// getFromTargetType - Given one of the integer types provided by
9437/// TargetInfo, produce the corresponding type. The unsigned @p Type
9438/// is actually a value of type @c TargetInfo::IntType.
9439CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9440 switch (Type) {
9441 case TargetInfo::NoInt: return {};
9444 case TargetInfo::SignedShort: return ShortTy;
9446 case TargetInfo::SignedInt: return IntTy;
9448 case TargetInfo::SignedLong: return LongTy;
9452 }
9453
9454 llvm_unreachable("Unhandled TargetInfo::IntType value");
9455}
9456
9457//===----------------------------------------------------------------------===//
9458// Type Predicates.
9459//===----------------------------------------------------------------------===//
9460
9461/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9462/// garbage collection attribute.
9463///
9465 if (getLangOpts().getGC() == LangOptions::NonGC)
9466 return Qualifiers::GCNone;
9467
9468 assert(getLangOpts().ObjC);
9469 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9470
9471 // Default behaviour under objective-C's gc is for ObjC pointers
9472 // (or pointers to them) be treated as though they were declared
9473 // as __strong.
9474 if (GCAttrs == Qualifiers::GCNone) {
9476 return Qualifiers::Strong;
9477 else if (Ty->isPointerType())
9479 } else {
9480 // It's not valid to set GC attributes on anything that isn't a
9481 // pointer.
9482#ifndef NDEBUG
9484 while (const auto *AT = dyn_cast<ArrayType>(CT))
9485 CT = AT->getElementType();
9486 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9487#endif
9488 }
9489 return GCAttrs;
9490}
9491
9492//===----------------------------------------------------------------------===//
9493// Type Compatibility Testing
9494//===----------------------------------------------------------------------===//
9495
9496/// areCompatVectorTypes - Return true if the two specified vector types are
9497/// compatible.
9498static bool areCompatVectorTypes(const VectorType *LHS,
9499 const VectorType *RHS) {
9500 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9501 return LHS->getElementType() == RHS->getElementType() &&
9502 LHS->getNumElements() == RHS->getNumElements();
9503}
9504
9505/// areCompatMatrixTypes - Return true if the two specified matrix types are
9506/// compatible.
9508 const ConstantMatrixType *RHS) {
9509 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9510 return LHS->getElementType() == RHS->getElementType() &&
9511 LHS->getNumRows() == RHS->getNumRows() &&
9512 LHS->getNumColumns() == RHS->getNumColumns();
9513}
9514
9516 QualType SecondVec) {
9517 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9518 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9519
9520 if (hasSameUnqualifiedType(FirstVec, SecondVec))
9521 return true;
9522
9523 // Treat Neon vector types and most AltiVec vector types as if they are the
9524 // equivalent GCC vector types.
9525 const auto *First = FirstVec->castAs<VectorType>();
9526 const auto *Second = SecondVec->castAs<VectorType>();
9527 if (First->getNumElements() == Second->getNumElements() &&
9528 hasSameType(First->getElementType(), Second->getElementType()) &&
9529 First->getVectorKind() != VectorKind::AltiVecPixel &&
9530 First->getVectorKind() != VectorKind::AltiVecBool &&
9533 First->getVectorKind() != VectorKind::SveFixedLengthData &&
9534 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9537 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9539 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
9541 return true;
9542
9543 return false;
9544}
9545
9546/// getSVETypeSize - Return SVE vector or predicate register size.
9547static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9548 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9549 if (Ty->getKind() == BuiltinType::SveBool ||
9550 Ty->getKind() == BuiltinType::SveCount)
9551 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9552 return Context.getLangOpts().VScaleMin * 128;
9553}
9554
9556 QualType SecondType) {
9557 assert(
9558 ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9559 (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9560 "Expected SVE builtin type and vector type!");
9561
9562 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9563 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9564 if (const auto *VT = SecondType->getAs<VectorType>()) {
9565 // Predicates have the same representation as uint8 so we also have to
9566 // check the kind to make these types incompatible.
9567 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9568 return BT->getKind() == BuiltinType::SveBool;
9569 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9570 return VT->getElementType().getCanonicalType() ==
9571 FirstType->getSveEltType(*this);
9572 else if (VT->getVectorKind() == VectorKind::Generic)
9573 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9574 hasSameType(VT->getElementType(),
9575 getBuiltinVectorTypeInfo(BT).ElementType);
9576 }
9577 }
9578 return false;
9579 };
9580
9581 return IsValidCast(FirstType, SecondType) ||
9582 IsValidCast(SecondType, FirstType);
9583}
9584
9586 QualType SecondType) {
9587 assert(
9588 ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9589 (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9590 "Expected SVE builtin type and vector type!");
9591
9592 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9593 const auto *BT = FirstType->getAs<BuiltinType>();
9594 if (!BT)
9595 return false;
9596
9597 const auto *VecTy = SecondType->getAs<VectorType>();
9598 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9599 VecTy->getVectorKind() == VectorKind::Generic)) {
9601 getLangOpts().getLaxVectorConversions();
9602
9603 // Can not convert between sve predicates and sve vectors because of
9604 // different size.
9605 if (BT->getKind() == BuiltinType::SveBool &&
9606 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9607 return false;
9608
9609 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9610 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9611 // converts to VLAT and VLAT implicitly converts to GNUT."
9612 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9613 // predicates.
9614 if (VecTy->getVectorKind() == VectorKind::Generic &&
9615 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9616 return false;
9617
9618 // If -flax-vector-conversions=all is specified, the types are
9619 // certainly compatible.
9621 return true;
9622
9623 // If -flax-vector-conversions=integer is specified, the types are
9624 // compatible if the elements are integer types.
9626 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9627 FirstType->getSveEltType(*this)->isIntegerType();
9628 }
9629
9630 return false;
9631 };
9632
9633 return IsLaxCompatible(FirstType, SecondType) ||
9634 IsLaxCompatible(SecondType, FirstType);
9635}
9636
9637/// getRVVTypeSize - Return RVV vector register size.
9638static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
9639 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
9640 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
9641 if (!VScale)
9642 return 0;
9643
9645
9646 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
9647 if (Info.ElementType == Context.BoolTy)
9648 EltSize = 1;
9649
9650 uint64_t MinElts = Info.EC.getKnownMinValue();
9651 return VScale->first * MinElts * EltSize;
9652}
9653
9655 QualType SecondType) {
9656 assert(
9657 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9658 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9659 "Expected RVV builtin type and vector type!");
9660
9661 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9662 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9663 if (const auto *VT = SecondType->getAs<VectorType>()) {
9664 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
9666 return FirstType->isRVVVLSBuiltinType() &&
9667 Info.ElementType == BoolTy &&
9668 getTypeSize(SecondType) == getRVVTypeSize(*this, BT);
9669 }
9670 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
9671 VT->getVectorKind() == VectorKind::Generic)
9672 return FirstType->isRVVVLSBuiltinType() &&
9673 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
9674 hasSameType(VT->getElementType(),
9675 getBuiltinVectorTypeInfo(BT).ElementType);
9676 }
9677 }
9678 return false;
9679 };
9680
9681 return IsValidCast(FirstType, SecondType) ||
9682 IsValidCast(SecondType, FirstType);
9683}
9684
9686 QualType SecondType) {
9687 assert(
9688 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9689 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9690 "Expected RVV builtin type and vector type!");
9691
9692 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9693 const auto *BT = FirstType->getAs<BuiltinType>();
9694 if (!BT)
9695 return false;
9696
9697 if (!BT->isRVVVLSBuiltinType())
9698 return false;
9699
9700 const auto *VecTy = SecondType->getAs<VectorType>();
9701 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
9703 getLangOpts().getLaxVectorConversions();
9704
9705 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
9706 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
9707 return false;
9708
9709 // If -flax-vector-conversions=all is specified, the types are
9710 // certainly compatible.
9712 return true;
9713
9714 // If -flax-vector-conversions=integer is specified, the types are
9715 // compatible if the elements are integer types.
9717 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9718 FirstType->getRVVEltType(*this)->isIntegerType();
9719 }
9720
9721 return false;
9722 };
9723
9724 return IsLaxCompatible(FirstType, SecondType) ||
9725 IsLaxCompatible(SecondType, FirstType);
9726}
9727
9729 while (true) {
9730 // __strong id
9731 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9732 if (Attr->getAttrKind() == attr::ObjCOwnership)
9733 return true;
9734
9735 Ty = Attr->getModifiedType();
9736
9737 // X *__strong (...)
9738 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9739 Ty = Paren->getInnerType();
9740
9741 // We do not want to look through typedefs, typeof(expr),
9742 // typeof(type), or any other way that the type is somehow
9743 // abstracted.
9744 } else {
9745 return false;
9746 }
9747 }
9748}
9749
9750//===----------------------------------------------------------------------===//
9751// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9752//===----------------------------------------------------------------------===//
9753
9754/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9755/// inheritance hierarchy of 'rProto'.
9756bool
9758 ObjCProtocolDecl *rProto) const {
9759 if (declaresSameEntity(lProto, rProto))
9760 return true;
9761 for (auto *PI : rProto->protocols())
9762 if (ProtocolCompatibleWithProtocol(lProto, PI))
9763 return true;
9764 return false;
9765}
9766
9767/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
9768/// Class<pr1, ...>.
9770 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9771 for (auto *lhsProto : lhs->quals()) {
9772 bool match = false;
9773 for (auto *rhsProto : rhs->quals()) {
9774 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9775 match = true;
9776 break;
9777 }
9778 }
9779 if (!match)
9780 return false;
9781 }
9782 return true;
9783}
9784
9785/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9786/// ObjCQualifiedIDType.
9788 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9789 bool compare) {
9790 // Allow id<P..> and an 'id' in all cases.
9791 if (lhs->isObjCIdType() || rhs->isObjCIdType())
9792 return true;
9793
9794 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9795 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9797 return false;
9798
9799 if (lhs->isObjCQualifiedIdType()) {
9800 if (rhs->qual_empty()) {
9801 // If the RHS is a unqualified interface pointer "NSString*",
9802 // make sure we check the class hierarchy.
9803 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9804 for (auto *I : lhs->quals()) {
9805 // when comparing an id<P> on lhs with a static type on rhs,
9806 // see if static class implements all of id's protocols, directly or
9807 // through its super class and categories.
9808 if (!rhsID->ClassImplementsProtocol(I, true))
9809 return false;
9810 }
9811 }
9812 // If there are no qualifiers and no interface, we have an 'id'.
9813 return true;
9814 }
9815 // Both the right and left sides have qualifiers.
9816 for (auto *lhsProto : lhs->quals()) {
9817 bool match = false;
9818
9819 // when comparing an id<P> on lhs with a static type on rhs,
9820 // see if static class implements all of id's protocols, directly or
9821 // through its super class and categories.
9822 for (auto *rhsProto : rhs->quals()) {
9823 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9824 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9825 match = true;
9826 break;
9827 }
9828 }
9829 // If the RHS is a qualified interface pointer "NSString<P>*",
9830 // make sure we check the class hierarchy.
9831 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9832 for (auto *I : lhs->quals()) {
9833 // when comparing an id<P> on lhs with a static type on rhs,
9834 // see if static class implements all of id's protocols, directly or
9835 // through its super class and categories.
9836 if (rhsID->ClassImplementsProtocol(I, true)) {
9837 match = true;
9838 break;
9839 }
9840 }
9841 }
9842 if (!match)
9843 return false;
9844 }
9845
9846 return true;
9847 }
9848
9849 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9850
9851 if (lhs->getInterfaceType()) {
9852 // If both the right and left sides have qualifiers.
9853 for (auto *lhsProto : lhs->quals()) {
9854 bool match = false;
9855
9856 // when comparing an id<P> on rhs with a static type on lhs,
9857 // see if static class implements all of id's protocols, directly or
9858 // through its super class and categories.
9859 // First, lhs protocols in the qualifier list must be found, direct
9860 // or indirect in rhs's qualifier list or it is a mismatch.
9861 for (auto *rhsProto : rhs->quals()) {
9862 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9863 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9864 match = true;
9865 break;
9866 }
9867 }
9868 if (!match)
9869 return false;
9870 }
9871
9872 // Static class's protocols, or its super class or category protocols
9873 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9874 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9875 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9876 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9877 // This is rather dubious but matches gcc's behavior. If lhs has
9878 // no type qualifier and its class has no static protocol(s)
9879 // assume that it is mismatch.
9880 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9881 return false;
9882 for (auto *lhsProto : LHSInheritedProtocols) {
9883 bool match = false;
9884 for (auto *rhsProto : rhs->quals()) {
9885 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9886 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9887 match = true;
9888 break;
9889 }
9890 }
9891 if (!match)
9892 return false;
9893 }
9894 }
9895 return true;
9896 }
9897 return false;
9898}
9899
9900/// canAssignObjCInterfaces - Return true if the two interface types are
9901/// compatible for assignment from RHS to LHS. This handles validation of any
9902/// protocol qualifiers on the LHS or RHS.
9904 const ObjCObjectPointerType *RHSOPT) {
9905 const ObjCObjectType* LHS = LHSOPT->getObjectType();
9906 const ObjCObjectType* RHS = RHSOPT->getObjectType();
9907
9908 // If either type represents the built-in 'id' type, return true.
9909 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9910 return true;
9911
9912 // Function object that propagates a successful result or handles
9913 // __kindof types.
9914 auto finish = [&](bool succeeded) -> bool {
9915 if (succeeded)
9916 return true;
9917
9918 if (!RHS->isKindOfType())
9919 return false;
9920
9921 // Strip off __kindof and protocol qualifiers, then check whether
9922 // we can assign the other way.
9924 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9925 };
9926
9927 // Casts from or to id<P> are allowed when the other side has compatible
9928 // protocols.
9929 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9930 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9931 }
9932
9933 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9934 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9935 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9936 }
9937
9938 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9939 if (LHS->isObjCClass() && RHS->isObjCClass()) {
9940 return true;
9941 }
9942
9943 // If we have 2 user-defined types, fall into that path.
9944 if (LHS->getInterface() && RHS->getInterface()) {
9945 return finish(canAssignObjCInterfaces(LHS, RHS));
9946 }
9947
9948 return false;
9949}
9950
9951/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9952/// for providing type-safety for objective-c pointers used to pass/return
9953/// arguments in block literals. When passed as arguments, passing 'A*' where
9954/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9955/// not OK. For the return type, the opposite is not OK.
9957 const ObjCObjectPointerType *LHSOPT,
9958 const ObjCObjectPointerType *RHSOPT,
9959 bool BlockReturnType) {
9960
9961 // Function object that propagates a successful result or handles
9962 // __kindof types.
9963 auto finish = [&](bool succeeded) -> bool {
9964 if (succeeded)
9965 return true;
9966
9967 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9968 if (!Expected->isKindOfType())
9969 return false;
9970
9971 // Strip off __kindof and protocol qualifiers, then check whether
9972 // we can assign the other way.
9974 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9975 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9976 BlockReturnType);
9977 };
9978
9979 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9980 return true;
9981
9982 if (LHSOPT->isObjCBuiltinType()) {
9983 return finish(RHSOPT->isObjCBuiltinType() ||
9984 RHSOPT->isObjCQualifiedIdType());
9985 }
9986
9987 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9988 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9989 // Use for block parameters previous type checking for compatibility.
9990 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9991 // Or corrected type checking as in non-compat mode.
9992 (!BlockReturnType &&
9993 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9994 else
9996 (BlockReturnType ? LHSOPT : RHSOPT),
9997 (BlockReturnType ? RHSOPT : LHSOPT), false));
9998 }
9999
10000 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10001 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10002 if (LHS && RHS) { // We have 2 user-defined types.
10003 if (LHS != RHS) {
10004 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10005 return finish(BlockReturnType);
10006 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10007 return finish(!BlockReturnType);
10008 }
10009 else
10010 return true;
10011 }
10012 return false;
10013}
10014
10015/// Comparison routine for Objective-C protocols to be used with
10016/// llvm::array_pod_sort.
10018 ObjCProtocolDecl * const *rhs) {
10019 return (*lhs)->getName().compare((*rhs)->getName());
10020}
10021
10022/// getIntersectionOfProtocols - This routine finds the intersection of set
10023/// of protocols inherited from two distinct objective-c pointer objects with
10024/// the given common base.
10025/// It is used to build composite qualifier list of the composite type of
10026/// the conditional expression involving two objective-c pointer objects.
10027static
10029 const ObjCInterfaceDecl *CommonBase,
10030 const ObjCObjectPointerType *LHSOPT,
10031 const ObjCObjectPointerType *RHSOPT,
10032 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10033
10034 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10035 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10036 assert(LHS->getInterface() && "LHS must have an interface base");
10037 assert(RHS->getInterface() && "RHS must have an interface base");
10038
10039 // Add all of the protocols for the LHS.
10041
10042 // Start with the protocol qualifiers.
10043 for (auto *proto : LHS->quals()) {
10044 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10045 }
10046
10047 // Also add the protocols associated with the LHS interface.
10048 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10049
10050 // Add all of the protocols for the RHS.
10052
10053 // Start with the protocol qualifiers.
10054 for (auto *proto : RHS->quals()) {
10055 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10056 }
10057
10058 // Also add the protocols associated with the RHS interface.
10059 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10060
10061 // Compute the intersection of the collected protocol sets.
10062 for (auto *proto : LHSProtocolSet) {
10063 if (RHSProtocolSet.count(proto))
10064 IntersectionSet.push_back(proto);
10065 }
10066
10067 // Compute the set of protocols that is implied by either the common type or
10068 // the protocols within the intersection.
10070 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10071
10072 // Remove any implied protocols from the list of inherited protocols.
10073 if (!ImpliedProtocols.empty()) {
10074 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10075 return ImpliedProtocols.contains(proto);
10076 });
10077 }
10078
10079 // Sort the remaining protocols by name.
10080 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10082}
10083
10084/// Determine whether the first type is a subtype of the second.
10086 QualType rhs) {
10087 // Common case: two object pointers.
10088 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10089 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10090 if (lhsOPT && rhsOPT)
10091 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10092
10093 // Two block pointers.
10094 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10095 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10096 if (lhsBlock && rhsBlock)
10097 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10098
10099 // If either is an unqualified 'id' and the other is a block, it's
10100 // acceptable.
10101 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10102 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10103 return true;
10104
10105 return false;
10106}
10107
10108// Check that the given Objective-C type argument lists are equivalent.
10110 const ObjCInterfaceDecl *iface,
10111 ArrayRef<QualType> lhsArgs,
10112 ArrayRef<QualType> rhsArgs,
10113 bool stripKindOf) {
10114 if (lhsArgs.size() != rhsArgs.size())
10115 return false;
10116
10117 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10118 if (!typeParams)
10119 return false;
10120
10121 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10122 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10123 continue;
10124
10125 switch (typeParams->begin()[i]->getVariance()) {
10127 if (!stripKindOf ||
10128 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10129 rhsArgs[i].stripObjCKindOfType(ctx))) {
10130 return false;
10131 }
10132 break;
10133
10135 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10136 return false;
10137 break;
10138
10140 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10141 return false;
10142 break;
10143 }
10144 }
10145
10146 return true;
10147}
10148
10150 const ObjCObjectPointerType *Lptr,
10151 const ObjCObjectPointerType *Rptr) {
10152 const ObjCObjectType *LHS = Lptr->getObjectType();
10153 const ObjCObjectType *RHS = Rptr->getObjectType();
10154 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10155 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10156
10157 if (!LDecl || !RDecl)
10158 return {};
10159
10160 // When either LHS or RHS is a kindof type, we should return a kindof type.
10161 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10162 // kindof(A).
10163 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10164
10165 // Follow the left-hand side up the class hierarchy until we either hit a
10166 // root or find the RHS. Record the ancestors in case we don't find it.
10167 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10168 LHSAncestors;
10169 while (true) {
10170 // Record this ancestor. We'll need this if the common type isn't in the
10171 // path from the LHS to the root.
10172 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10173
10174 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10175 // Get the type arguments.
10176 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10177 bool anyChanges = false;
10178 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10179 // Both have type arguments, compare them.
10180 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10181 LHS->getTypeArgs(), RHS->getTypeArgs(),
10182 /*stripKindOf=*/true))
10183 return {};
10184 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10185 // If only one has type arguments, the result will not have type
10186 // arguments.
10187 LHSTypeArgs = {};
10188 anyChanges = true;
10189 }
10190
10191 // Compute the intersection of protocols.
10193 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10194 Protocols);
10195 if (!Protocols.empty())
10196 anyChanges = true;
10197
10198 // If anything in the LHS will have changed, build a new result type.
10199 // If we need to return a kindof type but LHS is not a kindof type, we
10200 // build a new result type.
10201 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10203 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10204 anyKindOf || LHS->isKindOfType());
10206 }
10207
10208 return getObjCObjectPointerType(QualType(LHS, 0));
10209 }
10210
10211 // Find the superclass.
10212 QualType LHSSuperType = LHS->getSuperClassType();
10213 if (LHSSuperType.isNull())
10214 break;
10215
10216 LHS = LHSSuperType->castAs<ObjCObjectType>();
10217 }
10218
10219 // We didn't find anything by following the LHS to its root; now check
10220 // the RHS against the cached set of ancestors.
10221 while (true) {
10222 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10223 if (KnownLHS != LHSAncestors.end()) {
10224 LHS = KnownLHS->second;
10225
10226 // Get the type arguments.
10227 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10228 bool anyChanges = false;
10229 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10230 // Both have type arguments, compare them.
10231 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10232 LHS->getTypeArgs(), RHS->getTypeArgs(),
10233 /*stripKindOf=*/true))
10234 return {};
10235 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10236 // If only one has type arguments, the result will not have type
10237 // arguments.
10238 RHSTypeArgs = {};
10239 anyChanges = true;
10240 }
10241
10242 // Compute the intersection of protocols.
10244 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10245 Protocols);
10246 if (!Protocols.empty())
10247 anyChanges = true;
10248
10249 // If we need to return a kindof type but RHS is not a kindof type, we
10250 // build a new result type.
10251 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10253 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10254 anyKindOf || RHS->isKindOfType());
10256 }
10257
10258 return getObjCObjectPointerType(QualType(RHS, 0));
10259 }
10260
10261 // Find the superclass of the RHS.
10262 QualType RHSSuperType = RHS->getSuperClassType();
10263 if (RHSSuperType.isNull())
10264 break;
10265
10266 RHS = RHSSuperType->castAs<ObjCObjectType>();
10267 }
10268
10269 return {};
10270}
10271
10273 const ObjCObjectType *RHS) {
10274 assert(LHS->getInterface() && "LHS is not an interface type");
10275 assert(RHS->getInterface() && "RHS is not an interface type");
10276
10277 // Verify that the base decls are compatible: the RHS must be a subclass of
10278 // the LHS.
10279 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10280 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10281 if (!IsSuperClass)
10282 return false;
10283
10284 // If the LHS has protocol qualifiers, determine whether all of them are
10285 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10286 // LHS).
10287 if (LHS->getNumProtocols() > 0) {
10288 // OK if conversion of LHS to SuperClass results in narrowing of types
10289 // ; i.e., SuperClass may implement at least one of the protocols
10290 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10291 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10292 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10293 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10294 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10295 // qualifiers.
10296 for (auto *RHSPI : RHS->quals())
10297 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10298 // If there is no protocols associated with RHS, it is not a match.
10299 if (SuperClassInheritedProtocols.empty())
10300 return false;
10301
10302 for (const auto *LHSProto : LHS->quals()) {
10303 bool SuperImplementsProtocol = false;
10304 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10305 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10306 SuperImplementsProtocol = true;
10307 break;
10308 }
10309 if (!SuperImplementsProtocol)
10310 return false;
10311 }
10312 }
10313
10314 // If the LHS is specialized, we may need to check type arguments.
10315 if (LHS->isSpecialized()) {
10316 // Follow the superclass chain until we've matched the LHS class in the
10317 // hierarchy. This substitutes type arguments through.
10318 const ObjCObjectType *RHSSuper = RHS;
10319 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10320 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10321
10322 // If the RHS is specializd, compare type arguments.
10323 if (RHSSuper->isSpecialized() &&
10324 !sameObjCTypeArgs(*this, LHS->getInterface(),
10325 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10326 /*stripKindOf=*/true)) {
10327 return false;
10328 }
10329 }
10330
10331 return true;
10332}
10333
10335 // get the "pointed to" types
10336 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10337 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10338
10339 if (!LHSOPT || !RHSOPT)
10340 return false;
10341
10342 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10343 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10344}
10345
10348 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10349 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10350}
10351
10352/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10353/// both shall have the identically qualified version of a compatible type.
10354/// C99 6.2.7p1: Two types have compatible types if their types are the
10355/// same. See 6.7.[2,3,5] for additional rules.
10357 bool CompareUnqualified) {
10358 if (getLangOpts().CPlusPlus)
10359 return hasSameType(LHS, RHS);
10360
10361 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10362}
10363
10365 return typesAreCompatible(LHS, RHS);
10366}
10367
10369 return !mergeTypes(LHS, RHS, true).isNull();
10370}
10371
10372/// mergeTransparentUnionType - if T is a transparent union type and a member
10373/// of T is compatible with SubType, return the merged type, else return
10374/// QualType()
10376 bool OfBlockPointer,
10377 bool Unqualified) {
10378 if (const RecordType *UT = T->getAsUnionType()) {
10379 RecordDecl *UD = UT->getDecl();
10380 if (UD->hasAttr<TransparentUnionAttr>()) {
10381 for (const auto *I : UD->fields()) {
10382 QualType ET = I->getType().getUnqualifiedType();
10383 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10384 if (!MT.isNull())
10385 return MT;
10386 }
10387 }
10388 }
10389
10390 return {};
10391}
10392
10393/// mergeFunctionParameterTypes - merge two types which appear as function
10394/// parameter types
10396 bool OfBlockPointer,
10397 bool Unqualified) {
10398 // GNU extension: two types are compatible if they appear as a function
10399 // argument, one of the types is a transparent union type and the other
10400 // type is compatible with a union member
10401 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10402 Unqualified);
10403 if (!lmerge.isNull())
10404 return lmerge;
10405
10406 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10407 Unqualified);
10408 if (!rmerge.isNull())
10409 return rmerge;
10410
10411 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10412}
10413
10415 bool OfBlockPointer, bool Unqualified,
10416 bool AllowCXX,
10417 bool IsConditionalOperator) {
10418 const auto *lbase = lhs->castAs<FunctionType>();
10419 const auto *rbase = rhs->castAs<FunctionType>();
10420 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10421 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10422 bool allLTypes = true;
10423 bool allRTypes = true;
10424
10425 // Check return type
10426 QualType retType;
10427 if (OfBlockPointer) {
10428 QualType RHS = rbase->getReturnType();
10429 QualType LHS = lbase->getReturnType();
10430 bool UnqualifiedResult = Unqualified;
10431 if (!UnqualifiedResult)
10432 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10433 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10434 }
10435 else
10436 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10437 Unqualified);
10438 if (retType.isNull())
10439 return {};
10440
10441 if (Unqualified)
10442 retType = retType.getUnqualifiedType();
10443
10444 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10445 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10446 if (Unqualified) {
10447 LRetType = LRetType.getUnqualifiedType();
10448 RRetType = RRetType.getUnqualifiedType();
10449 }
10450
10451 if (getCanonicalType(retType) != LRetType)
10452 allLTypes = false;
10453 if (getCanonicalType(retType) != RRetType)
10454 allRTypes = false;
10455
10456 // FIXME: double check this
10457 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10458 // rbase->getRegParmAttr() != 0 &&
10459 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10460 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10461 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10462
10463 // Compatible functions must have compatible calling conventions
10464 if (lbaseInfo.getCC() != rbaseInfo.getCC())
10465 return {};
10466
10467 // Regparm is part of the calling convention.
10468 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10469 return {};
10470 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10471 return {};
10472
10473 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10474 return {};
10475 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10476 return {};
10477 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10478 return {};
10479
10480 // When merging declarations, it's common for supplemental information like
10481 // attributes to only be present in one of the declarations, and we generally
10482 // want type merging to preserve the union of information. So a merged
10483 // function type should be noreturn if it was noreturn in *either* operand
10484 // type.
10485 //
10486 // But for the conditional operator, this is backwards. The result of the
10487 // operator could be either operand, and its type should conservatively
10488 // reflect that. So a function type in a composite type is noreturn only
10489 // if it's noreturn in *both* operand types.
10490 //
10491 // Arguably, noreturn is a kind of subtype, and the conditional operator
10492 // ought to produce the most specific common supertype of its operand types.
10493 // That would differ from this rule in contravariant positions. However,
10494 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
10495 // as a practical matter, it would only affect C code that does abstraction of
10496 // higher-order functions (taking noreturn callbacks!), which is uncommon to
10497 // say the least. So we use the simpler rule.
10498 bool NoReturn = IsConditionalOperator
10499 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10500 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10501 if (lbaseInfo.getNoReturn() != NoReturn)
10502 allLTypes = false;
10503 if (rbaseInfo.getNoReturn() != NoReturn)
10504 allRTypes = false;
10505
10506 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10507
10508 if (lproto && rproto) { // two C99 style function prototypes
10509 assert((AllowCXX ||
10510 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10511 "C++ shouldn't be here");
10512 // Compatible functions must have the same number of parameters
10513 if (lproto->getNumParams() != rproto->getNumParams())
10514 return {};
10515
10516 // Variadic and non-variadic functions aren't compatible
10517 if (lproto->isVariadic() != rproto->isVariadic())
10518 return {};
10519
10520 if (lproto->getMethodQuals() != rproto->getMethodQuals())
10521 return {};
10522
10524 bool canUseLeft, canUseRight;
10525 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10526 newParamInfos))
10527 return {};
10528
10529 if (!canUseLeft)
10530 allLTypes = false;
10531 if (!canUseRight)
10532 allRTypes = false;
10533
10534 // Check parameter type compatibility
10536 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10537 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10538 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10540 lParamType, rParamType, OfBlockPointer, Unqualified);
10541 if (paramType.isNull())
10542 return {};
10543
10544 if (Unqualified)
10545 paramType = paramType.getUnqualifiedType();
10546
10547 types.push_back(paramType);
10548 if (Unqualified) {
10549 lParamType = lParamType.getUnqualifiedType();
10550 rParamType = rParamType.getUnqualifiedType();
10551 }
10552
10553 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10554 allLTypes = false;
10555 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10556 allRTypes = false;
10557 }
10558
10559 if (allLTypes) return lhs;
10560 if (allRTypes) return rhs;
10561
10562 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10563 EPI.ExtInfo = einfo;
10564 EPI.ExtParameterInfos =
10565 newParamInfos.empty() ? nullptr : newParamInfos.data();
10566 return getFunctionType(retType, types, EPI);
10567 }
10568
10569 if (lproto) allRTypes = false;
10570 if (rproto) allLTypes = false;
10571
10572 const FunctionProtoType *proto = lproto ? lproto : rproto;
10573 if (proto) {
10574 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10575 if (proto->isVariadic())
10576 return {};
10577 // Check that the types are compatible with the types that
10578 // would result from default argument promotions (C99 6.7.5.3p15).
10579 // The only types actually affected are promotable integer
10580 // types and floats, which would be passed as a different
10581 // type depending on whether the prototype is visible.
10582 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10583 QualType paramTy = proto->getParamType(i);
10584
10585 // Look at the converted type of enum types, since that is the type used
10586 // to pass enum values.
10587 if (const auto *Enum = paramTy->getAs<EnumType>()) {
10588 paramTy = Enum->getDecl()->getIntegerType();
10589 if (paramTy.isNull())
10590 return {};
10591 }
10592
10593 if (isPromotableIntegerType(paramTy) ||
10594 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10595 return {};
10596 }
10597
10598 if (allLTypes) return lhs;
10599 if (allRTypes) return rhs;
10600
10602 EPI.ExtInfo = einfo;
10603 return getFunctionType(retType, proto->getParamTypes(), EPI);
10604 }
10605
10606 if (allLTypes) return lhs;
10607 if (allRTypes) return rhs;
10608 return getFunctionNoProtoType(retType, einfo);
10609}
10610
10611/// Given that we have an enum type and a non-enum type, try to merge them.
10613 QualType other, bool isBlockReturnType) {
10614 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10615 // a signed integer type, or an unsigned integer type.
10616 // Compatibility is based on the underlying type, not the promotion
10617 // type.
10618 QualType underlyingType = ET->getDecl()->getIntegerType();
10619 if (underlyingType.isNull())
10620 return {};
10621 if (Context.hasSameType(underlyingType, other))
10622 return other;
10623
10624 // In block return types, we're more permissive and accept any
10625 // integral type of the same size.
10626 if (isBlockReturnType && other->isIntegerType() &&
10627 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10628 return other;
10629
10630 return {};
10631}
10632
10633QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
10634 bool Unqualified, bool BlockReturnType,
10635 bool IsConditionalOperator) {
10636 // For C++ we will not reach this code with reference types (see below),
10637 // for OpenMP variant call overloading we might.
10638 //
10639 // C++ [expr]: If an expression initially has the type "reference to T", the
10640 // type is adjusted to "T" prior to any further analysis, the expression
10641 // designates the object or function denoted by the reference, and the
10642 // expression is an lvalue unless the reference is an rvalue reference and
10643 // the expression is a function call (possibly inside parentheses).
10644 auto *LHSRefTy = LHS->getAs<ReferenceType>();
10645 auto *RHSRefTy = RHS->getAs<ReferenceType>();
10646 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10647 LHS->getTypeClass() == RHS->getTypeClass())
10648 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10649 OfBlockPointer, Unqualified, BlockReturnType);
10650 if (LHSRefTy || RHSRefTy)
10651 return {};
10652
10653 if (Unqualified) {
10654 LHS = LHS.getUnqualifiedType();
10655 RHS = RHS.getUnqualifiedType();
10656 }
10657
10658 QualType LHSCan = getCanonicalType(LHS),
10659 RHSCan = getCanonicalType(RHS);
10660
10661 // If two types are identical, they are compatible.
10662 if (LHSCan == RHSCan)
10663 return LHS;
10664
10665 // If the qualifiers are different, the types aren't compatible... mostly.
10666 Qualifiers LQuals = LHSCan.getLocalQualifiers();
10667 Qualifiers RQuals = RHSCan.getLocalQualifiers();
10668 if (LQuals != RQuals) {
10669 // If any of these qualifiers are different, we have a type
10670 // mismatch.
10671 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10672 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10673 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10674 LQuals.hasUnaligned() != RQuals.hasUnaligned())
10675 return {};
10676
10677 // Exactly one GC qualifier difference is allowed: __strong is
10678 // okay if the other type has no GC qualifier but is an Objective
10679 // C object pointer (i.e. implicitly strong by default). We fix
10680 // this by pretending that the unqualified type was actually
10681 // qualified __strong.
10682 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10683 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10684 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10685
10686 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10687 return {};
10688
10689 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10691 }
10692 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10694 }
10695 return {};
10696 }
10697
10698 // Okay, qualifiers are equal.
10699
10700 Type::TypeClass LHSClass = LHSCan->getTypeClass();
10701 Type::TypeClass RHSClass = RHSCan->getTypeClass();
10702
10703 // We want to consider the two function types to be the same for these
10704 // comparisons, just force one to the other.
10705 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10706 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10707
10708 // Same as above for arrays
10709 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10710 LHSClass = Type::ConstantArray;
10711 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10712 RHSClass = Type::ConstantArray;
10713
10714 // ObjCInterfaces are just specialized ObjCObjects.
10715 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10716 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10717
10718 // Canonicalize ExtVector -> Vector.
10719 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10720 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10721
10722 // If the canonical type classes don't match.
10723 if (LHSClass != RHSClass) {
10724 // Note that we only have special rules for turning block enum
10725 // returns into block int returns, not vice-versa.
10726 if (const auto *ETy = LHS->getAs<EnumType>()) {
10727 return mergeEnumWithInteger(*this, ETy, RHS, false);
10728 }
10729 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10730 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10731 }
10732 // allow block pointer type to match an 'id' type.
10733 if (OfBlockPointer && !BlockReturnType) {
10734 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10735 return LHS;
10736 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10737 return RHS;
10738 }
10739 // Allow __auto_type to match anything; it merges to the type with more
10740 // information.
10741 if (const auto *AT = LHS->getAs<AutoType>()) {
10742 if (!AT->isDeduced() && AT->isGNUAutoType())
10743 return RHS;
10744 }
10745 if (const auto *AT = RHS->getAs<AutoType>()) {
10746 if (!AT->isDeduced() && AT->isGNUAutoType())
10747 return LHS;
10748 }
10749 return {};
10750 }
10751
10752 // The canonical type classes match.
10753 switch (LHSClass) {
10754#define TYPE(Class, Base)
10755#define ABSTRACT_TYPE(Class, Base)
10756#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10757#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10758#define DEPENDENT_TYPE(Class, Base) case Type::Class:
10759#include "clang/AST/TypeNodes.inc"
10760 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10761
10762 case Type::Auto:
10763 case Type::DeducedTemplateSpecialization:
10764 case Type::LValueReference:
10765 case Type::RValueReference:
10766 case Type::MemberPointer:
10767 llvm_unreachable("C++ should never be in mergeTypes");
10768
10769 case Type::ObjCInterface:
10770 case Type::IncompleteArray:
10771 case Type::VariableArray:
10772 case Type::FunctionProto:
10773 case Type::ExtVector:
10774 llvm_unreachable("Types are eliminated above");
10775
10776 case Type::Pointer:
10777 {
10778 // Merge two pointer types, while trying to preserve typedef info
10779 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10780 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10781 if (Unqualified) {
10782 LHSPointee = LHSPointee.getUnqualifiedType();
10783 RHSPointee = RHSPointee.getUnqualifiedType();
10784 }
10785 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10786 Unqualified);
10787 if (ResultType.isNull())
10788 return {};
10789 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10790 return LHS;
10791 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10792 return RHS;
10793 return getPointerType(ResultType);
10794 }
10795 case Type::BlockPointer:
10796 {
10797 // Merge two block pointer types, while trying to preserve typedef info
10798 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10799 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10800 if (Unqualified) {
10801 LHSPointee = LHSPointee.getUnqualifiedType();
10802 RHSPointee = RHSPointee.getUnqualifiedType();
10803 }
10804 if (getLangOpts().OpenCL) {
10805 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10806 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10807 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10808 // 6.12.5) thus the following check is asymmetric.
10809 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10810 return {};
10811 LHSPteeQual.removeAddressSpace();
10812 RHSPteeQual.removeAddressSpace();
10813 LHSPointee =
10814 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10815 RHSPointee =
10816 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10817 }
10818 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10819 Unqualified);
10820 if (ResultType.isNull())
10821 return {};
10822 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10823 return LHS;
10824 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10825 return RHS;
10826 return getBlockPointerType(ResultType);
10827 }
10828 case Type::Atomic:
10829 {
10830 // Merge two pointer types, while trying to preserve typedef info
10831 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10832 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10833 if (Unqualified) {
10834 LHSValue = LHSValue.getUnqualifiedType();
10835 RHSValue = RHSValue.getUnqualifiedType();
10836 }
10837 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10838 Unqualified);
10839 if (ResultType.isNull())
10840 return {};
10841 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10842 return LHS;
10843 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10844 return RHS;
10845 return getAtomicType(ResultType);
10846 }
10847 case Type::ConstantArray:
10848 {
10849 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10850 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10851 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
10852 return {};
10853
10854 QualType LHSElem = getAsArrayType(LHS)->getElementType();
10855 QualType RHSElem = getAsArrayType(RHS)->getElementType();
10856 if (Unqualified) {
10857 LHSElem = LHSElem.getUnqualifiedType();
10858 RHSElem = RHSElem.getUnqualifiedType();
10859 }
10860
10861 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10862 if (ResultType.isNull())
10863 return {};
10864
10865 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10866 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10867
10868 // If either side is a variable array, and both are complete, check whether
10869 // the current dimension is definite.
10870 if (LVAT || RVAT) {
10871 auto SizeFetch = [this](const VariableArrayType* VAT,
10872 const ConstantArrayType* CAT)
10873 -> std::pair<bool,llvm::APInt> {
10874 if (VAT) {
10875 std::optional<llvm::APSInt> TheInt;
10876 Expr *E = VAT->getSizeExpr();
10877 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10878 return std::make_pair(true, *TheInt);
10879 return std::make_pair(false, llvm::APSInt());
10880 }
10881 if (CAT)
10882 return std::make_pair(true, CAT->getSize());
10883 return std::make_pair(false, llvm::APInt());
10884 };
10885
10886 bool HaveLSize, HaveRSize;
10887 llvm::APInt LSize, RSize;
10888 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10889 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10890 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10891 return {}; // Definite, but unequal, array dimension
10892 }
10893
10894 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10895 return LHS;
10896 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10897 return RHS;
10898 if (LCAT)
10899 return getConstantArrayType(ResultType, LCAT->getSize(),
10900 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
10901 if (RCAT)
10902 return getConstantArrayType(ResultType, RCAT->getSize(),
10903 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
10904 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10905 return LHS;
10906 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10907 return RHS;
10908 if (LVAT) {
10909 // FIXME: This isn't correct! But tricky to implement because
10910 // the array's size has to be the size of LHS, but the type
10911 // has to be different.
10912 return LHS;
10913 }
10914 if (RVAT) {
10915 // FIXME: This isn't correct! But tricky to implement because
10916 // the array's size has to be the size of RHS, but the type
10917 // has to be different.
10918 return RHS;
10919 }
10920 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10921 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10922 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
10923 }
10924 case Type::FunctionNoProto:
10925 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
10926 /*AllowCXX=*/false, IsConditionalOperator);
10927 case Type::Record:
10928 case Type::Enum:
10929 return {};
10930 case Type::Builtin:
10931 // Only exactly equal builtin types are compatible, which is tested above.
10932 return {};
10933 case Type::Complex:
10934 // Distinct complex types are incompatible.
10935 return {};
10936 case Type::Vector:
10937 // FIXME: The merged type should be an ExtVector!
10938 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10939 RHSCan->castAs<VectorType>()))
10940 return LHS;
10941 return {};
10942 case Type::ConstantMatrix:
10944 RHSCan->castAs<ConstantMatrixType>()))
10945 return LHS;
10946 return {};
10947 case Type::ObjCObject: {
10948 // Check if the types are assignment compatible.
10949 // FIXME: This should be type compatibility, e.g. whether
10950 // "LHS x; RHS x;" at global scope is legal.
10952 RHS->castAs<ObjCObjectType>()))
10953 return LHS;
10954 return {};
10955 }
10956 case Type::ObjCObjectPointer:
10957 if (OfBlockPointer) {
10960 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10961 return LHS;
10962 return {};
10963 }
10966 return LHS;
10967 return {};
10968 case Type::Pipe:
10969 assert(LHS != RHS &&
10970 "Equivalent pipe types should have already been handled!");
10971 return {};
10972 case Type::ArrayParameter:
10973 assert(LHS != RHS &&
10974 "Equivalent ArrayParameter types should have already been handled!");
10975 return {};
10976 case Type::BitInt: {
10977 // Merge two bit-precise int types, while trying to preserve typedef info.
10978 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10979 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10980 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10981 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10982
10983 // Like unsigned/int, shouldn't have a type if they don't match.
10984 if (LHSUnsigned != RHSUnsigned)
10985 return {};
10986
10987 if (LHSBits != RHSBits)
10988 return {};
10989 return LHS;
10990 }
10991 }
10992
10993 llvm_unreachable("Invalid Type::Class!");
10994}
10995
10997 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10998 bool &CanUseFirst, bool &CanUseSecond,
11000 assert(NewParamInfos.empty() && "param info list not empty");
11001 CanUseFirst = CanUseSecond = true;
11002 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11003 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11004
11005 // Fast path: if the first type doesn't have ext parameter infos,
11006 // we match if and only if the second type also doesn't have them.
11007 if (!FirstHasInfo && !SecondHasInfo)
11008 return true;
11009
11010 bool NeedParamInfo = false;
11011 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11012 : SecondFnType->getExtParameterInfos().size();
11013
11014 for (size_t I = 0; I < E; ++I) {
11015 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11016 if (FirstHasInfo)
11017 FirstParam = FirstFnType->getExtParameterInfo(I);
11018 if (SecondHasInfo)
11019 SecondParam = SecondFnType->getExtParameterInfo(I);
11020
11021 // Cannot merge unless everything except the noescape flag matches.
11022 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11023 return false;
11024
11025 bool FirstNoEscape = FirstParam.isNoEscape();
11026 bool SecondNoEscape = SecondParam.isNoEscape();
11027 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11028 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11029 if (NewParamInfos.back().getOpaqueValue())
11030 NeedParamInfo = true;
11031 if (FirstNoEscape != IsNoEscape)
11032 CanUseFirst = false;
11033 if (SecondNoEscape != IsNoEscape)
11034 CanUseSecond = false;
11035 }
11036
11037 if (!NeedParamInfo)
11038 NewParamInfos.clear();
11039
11040 return true;
11041}
11042
11044 ObjCLayouts[CD] = nullptr;
11045}
11046
11047/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11048/// 'RHS' attributes and returns the merged version; including for function
11049/// return types.
11051 QualType LHSCan = getCanonicalType(LHS),
11052 RHSCan = getCanonicalType(RHS);
11053 // If two types are identical, they are compatible.
11054 if (LHSCan == RHSCan)
11055 return LHS;
11056 if (RHSCan->isFunctionType()) {
11057 if (!LHSCan->isFunctionType())
11058 return {};
11059 QualType OldReturnType =
11060 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11061 QualType NewReturnType =
11062 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11063 QualType ResReturnType =
11064 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11065 if (ResReturnType.isNull())
11066 return {};
11067 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11068 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11069 // In either case, use OldReturnType to build the new function type.
11070 const auto *F = LHS->castAs<FunctionType>();
11071 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11072 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11073 EPI.ExtInfo = getFunctionExtInfo(LHS);
11074 QualType ResultType =
11075 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11076 return ResultType;
11077 }
11078 }
11079 return {};
11080 }
11081
11082 // If the qualifiers are different, the types can still be merged.
11083 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11084 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11085 if (LQuals != RQuals) {
11086 // If any of these qualifiers are different, we have a type mismatch.
11087 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11088 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11089 return {};
11090
11091 // Exactly one GC qualifier difference is allowed: __strong is
11092 // okay if the other type has no GC qualifier but is an Objective
11093 // C object pointer (i.e. implicitly strong by default). We fix
11094 // this by pretending that the unqualified type was actually
11095 // qualified __strong.
11096 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11097 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11098 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11099
11100 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11101 return {};
11102
11103 if (GC_L == Qualifiers::Strong)
11104 return LHS;
11105 if (GC_R == Qualifiers::Strong)
11106 return RHS;
11107 return {};
11108 }
11109
11110 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11111 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11112 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11113 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11114 if (ResQT == LHSBaseQT)
11115 return LHS;
11116 if (ResQT == RHSBaseQT)
11117 return RHS;
11118 }
11119 return {};
11120}
11121
11122//===----------------------------------------------------------------------===//
11123// Integer Predicates
11124//===----------------------------------------------------------------------===//
11125
11127 if (const auto *ET = T->getAs<EnumType>())
11128 T = ET->getDecl()->getIntegerType();
11129 if (T->isBooleanType())
11130 return 1;
11131 if (const auto *EIT = T->getAs<BitIntType>())
11132 return EIT->getNumBits();
11133 // For builtin types, just use the standard type sizing method
11134 return (unsigned)getTypeSize(T);
11135}
11136
11138 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11139 T->isFixedPointType()) &&
11140 "Unexpected type");
11141
11142 // Turn <4 x signed int> -> <4 x unsigned int>
11143 if (const auto *VTy = T->getAs<VectorType>())
11144 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11145 VTy->getNumElements(), VTy->getVectorKind());
11146
11147 // For _BitInt, return an unsigned _BitInt with same width.
11148 if (const auto *EITy = T->getAs<BitIntType>())
11149 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11150
11151 // For enums, get the underlying integer type of the enum, and let the general
11152 // integer type signchanging code handle it.
11153 if (const auto *ETy = T->getAs<EnumType>())
11154 T = ETy->getDecl()->getIntegerType();
11155
11156 switch (T->castAs<BuiltinType>()->getKind()) {
11157 case BuiltinType::Char_U:
11158 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11159 case BuiltinType::Char_S:
11160 case BuiltinType::SChar:
11161 case BuiltinType::Char8:
11162 return UnsignedCharTy;
11163 case BuiltinType::Short:
11164 return UnsignedShortTy;
11165 case BuiltinType::Int:
11166 return UnsignedIntTy;
11167 case BuiltinType::Long:
11168 return UnsignedLongTy;
11169 case BuiltinType::LongLong:
11170 return UnsignedLongLongTy;
11171 case BuiltinType::Int128:
11172 return UnsignedInt128Ty;
11173 // wchar_t is special. It is either signed or not, but when it's signed,
11174 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11175 // version of its underlying type instead.
11176 case BuiltinType::WChar_S:
11177 return getUnsignedWCharType();
11178
11179 case BuiltinType::ShortAccum:
11180 return UnsignedShortAccumTy;
11181 case BuiltinType::Accum:
11182 return UnsignedAccumTy;
11183 case BuiltinType::LongAccum:
11184 return UnsignedLongAccumTy;
11185 case BuiltinType::SatShortAccum:
11187 case BuiltinType::SatAccum:
11188 return SatUnsignedAccumTy;
11189 case BuiltinType::SatLongAccum:
11191 case BuiltinType::ShortFract:
11192 return UnsignedShortFractTy;
11193 case BuiltinType::Fract:
11194 return UnsignedFractTy;
11195 case BuiltinType::LongFract:
11196 return UnsignedLongFractTy;
11197 case BuiltinType::SatShortFract:
11199 case BuiltinType::SatFract:
11200 return SatUnsignedFractTy;
11201 case BuiltinType::SatLongFract:
11203 default:
11206 "Unexpected signed integer or fixed point type");
11207 return T;
11208 }
11209}
11210
11212 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11213 T->isFixedPointType()) &&
11214 "Unexpected type");
11215
11216 // Turn <4 x unsigned int> -> <4 x signed int>
11217 if (const auto *VTy = T->getAs<VectorType>())
11218 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11219 VTy->getNumElements(), VTy->getVectorKind());
11220
11221 // For _BitInt, return a signed _BitInt with same width.
11222 if (const auto *EITy = T->getAs<BitIntType>())
11223 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11224
11225 // For enums, get the underlying integer type of the enum, and let the general
11226 // integer type signchanging code handle it.
11227 if (const auto *ETy = T->getAs<EnumType>())
11228 T = ETy->getDecl()->getIntegerType();
11229
11230 switch (T->castAs<BuiltinType>()->getKind()) {
11231 case BuiltinType::Char_S:
11232 // Plain `char` is mapped to `signed char` even if it's already signed
11233 case BuiltinType::Char_U:
11234 case BuiltinType::UChar:
11235 case BuiltinType::Char8:
11236 return SignedCharTy;
11237 case BuiltinType::UShort:
11238 return ShortTy;
11239 case BuiltinType::UInt:
11240 return IntTy;
11241 case BuiltinType::ULong:
11242 return LongTy;
11243 case BuiltinType::ULongLong:
11244 return LongLongTy;
11245 case BuiltinType::UInt128:
11246 return Int128Ty;
11247 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11248 // there's no matching "signed wchar_t". Therefore we return the signed
11249 // version of its underlying type instead.
11250 case BuiltinType::WChar_U:
11251 return getSignedWCharType();
11252
11253 case BuiltinType::UShortAccum:
11254 return ShortAccumTy;
11255 case BuiltinType::UAccum:
11256 return AccumTy;
11257 case BuiltinType::ULongAccum:
11258 return LongAccumTy;
11259 case BuiltinType::SatUShortAccum:
11260 return SatShortAccumTy;
11261 case BuiltinType::SatUAccum:
11262 return SatAccumTy;
11263 case BuiltinType::SatULongAccum:
11264 return SatLongAccumTy;
11265 case BuiltinType::UShortFract:
11266 return ShortFractTy;
11267 case BuiltinType::UFract:
11268 return FractTy;
11269 case BuiltinType::ULongFract:
11270 return LongFractTy;
11271 case BuiltinType::SatUShortFract:
11272 return SatShortFractTy;
11273 case BuiltinType::SatUFract:
11274 return SatFractTy;
11275 case BuiltinType::SatULongFract:
11276 return SatLongFractTy;
11277 default:
11278 assert(
11280 "Unexpected signed integer or fixed point type");
11281 return T;
11282 }
11283}
11284
11286
11288 QualType ReturnType) {}
11289
11290//===----------------------------------------------------------------------===//
11291// Builtin Type Computation
11292//===----------------------------------------------------------------------===//
11293
11294/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11295/// pointer over the consumed characters. This returns the resultant type. If
11296/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11297/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11298/// a vector of "i*".
11299///
11300/// RequiresICE is filled in on return to indicate whether the value is required
11301/// to be an Integer Constant Expression.
11302static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11304 bool &RequiresICE,
11305 bool AllowTypeModifiers) {
11306 // Modifiers.
11307 int HowLong = 0;
11308 bool Signed = false, Unsigned = false;
11309 RequiresICE = false;
11310
11311 // Read the prefixed modifiers first.
11312 bool Done = false;
11313 #ifndef NDEBUG
11314 bool IsSpecial = false;
11315 #endif
11316 while (!Done) {
11317 switch (*Str++) {
11318 default: Done = true; --Str; break;
11319 case 'I':
11320 RequiresICE = true;
11321 break;
11322 case 'S':
11323 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11324 assert(!Signed && "Can't use 'S' modifier multiple times!");
11325 Signed = true;
11326 break;
11327 case 'U':
11328 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11329 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11330 Unsigned = true;
11331 break;
11332 case 'L':
11333 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11334 assert(HowLong <= 2 && "Can't have LLLL modifier");
11335 ++HowLong;
11336 break;
11337 case 'N':
11338 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11339 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11340 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11341 #ifndef NDEBUG
11342 IsSpecial = true;
11343 #endif
11344 if (Context.getTargetInfo().getLongWidth() == 32)
11345 ++HowLong;
11346 break;
11347 case 'W':
11348 // This modifier represents int64 type.
11349 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11350 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11351 #ifndef NDEBUG
11352 IsSpecial = true;
11353 #endif
11354 switch (Context.getTargetInfo().getInt64Type()) {
11355 default:
11356 llvm_unreachable("Unexpected integer type");
11358 HowLong = 1;
11359 break;
11361 HowLong = 2;
11362 break;
11363 }
11364 break;
11365 case 'Z':
11366 // This modifier represents int32 type.
11367 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11368 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11369 #ifndef NDEBUG
11370 IsSpecial = true;
11371 #endif
11372 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11373 default:
11374 llvm_unreachable("Unexpected integer type");
11376 HowLong = 0;
11377 break;
11379 HowLong = 1;
11380 break;
11382 HowLong = 2;
11383 break;
11384 }
11385 break;
11386 case 'O':
11387 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11388 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11389 #ifndef NDEBUG
11390 IsSpecial = true;
11391 #endif
11392 if (Context.getLangOpts().OpenCL)
11393 HowLong = 1;
11394 else
11395 HowLong = 2;
11396 break;
11397 }
11398 }
11399
11400 QualType Type;
11401
11402 // Read the base type.
11403 switch (*Str++) {
11404 default: llvm_unreachable("Unknown builtin type letter!");
11405 case 'x':
11406 assert(HowLong == 0 && !Signed && !Unsigned &&
11407 "Bad modifiers used with 'x'!");
11408 Type = Context.Float16Ty;
11409 break;
11410 case 'y':
11411 assert(HowLong == 0 && !Signed && !Unsigned &&
11412 "Bad modifiers used with 'y'!");
11413 Type = Context.BFloat16Ty;
11414 break;
11415 case 'v':
11416 assert(HowLong == 0 && !Signed && !Unsigned &&
11417 "Bad modifiers used with 'v'!");
11418 Type = Context.VoidTy;
11419 break;
11420 case 'h':
11421 assert(HowLong == 0 && !Signed && !Unsigned &&
11422 "Bad modifiers used with 'h'!");
11423 Type = Context.HalfTy;
11424 break;
11425 case 'f':
11426 assert(HowLong == 0 && !Signed && !Unsigned &&
11427 "Bad modifiers used with 'f'!");
11428 Type = Context.FloatTy;
11429 break;
11430 case 'd':
11431 assert(HowLong < 3 && !Signed && !Unsigned &&
11432 "Bad modifiers used with 'd'!");
11433 if (HowLong == 1)
11434 Type = Context.LongDoubleTy;
11435 else if (HowLong == 2)
11436 Type = Context.Float128Ty;
11437 else
11438 Type = Context.DoubleTy;
11439 break;
11440 case 's':
11441 assert(HowLong == 0 && "Bad modifiers used with 's'!");
11442 if (Unsigned)
11443 Type = Context.UnsignedShortTy;
11444 else
11445 Type = Context.ShortTy;
11446 break;
11447 case 'i':
11448 if (HowLong == 3)
11449 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11450 else if (HowLong == 2)
11451 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11452 else if (HowLong == 1)
11453 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11454 else
11455 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11456 break;
11457 case 'c':
11458 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11459 if (Signed)
11460 Type = Context.SignedCharTy;
11461 else if (Unsigned)
11462 Type = Context.UnsignedCharTy;
11463 else
11464 Type = Context.CharTy;
11465 break;
11466 case 'b': // boolean
11467 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11468 Type = Context.BoolTy;
11469 break;
11470 case 'z': // size_t.
11471 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11472 Type = Context.getSizeType();
11473 break;
11474 case 'w': // wchar_t.
11475 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11476 Type = Context.getWideCharType();
11477 break;
11478 case 'F':
11479 Type = Context.getCFConstantStringType();
11480 break;
11481 case 'G':
11482 Type = Context.getObjCIdType();
11483 break;
11484 case 'H':
11485 Type = Context.getObjCSelType();
11486 break;
11487 case 'M':
11488 Type = Context.getObjCSuperType();
11489 break;
11490 case 'a':
11491 Type = Context.getBuiltinVaListType();
11492 assert(!Type.isNull() && "builtin va list type not initialized!");
11493 break;
11494 case 'A':
11495 // This is a "reference" to a va_list; however, what exactly
11496 // this means depends on how va_list is defined. There are two
11497 // different kinds of va_list: ones passed by value, and ones
11498 // passed by reference. An example of a by-value va_list is
11499 // x86, where va_list is a char*. An example of by-ref va_list
11500 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11501 // we want this argument to be a char*&; for x86-64, we want
11502 // it to be a __va_list_tag*.
11503 Type = Context.getBuiltinVaListType();
11504 assert(!Type.isNull() && "builtin va list type not initialized!");
11505 if (Type->isArrayType())
11506 Type = Context.getArrayDecayedType(Type);
11507 else
11508 Type = Context.getLValueReferenceType(Type);
11509 break;
11510 case 'q': {
11511 char *End;
11512 unsigned NumElements = strtoul(Str, &End, 10);
11513 assert(End != Str && "Missing vector size");
11514 Str = End;
11515
11516 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11517 RequiresICE, false);
11518 assert(!RequiresICE && "Can't require vector ICE");
11519
11520 Type = Context.getScalableVectorType(ElementType, NumElements);
11521 break;
11522 }
11523 case 'Q': {
11524 switch (*Str++) {
11525 case 'a': {
11526 Type = Context.SveCountTy;
11527 break;
11528 }
11529 default:
11530 llvm_unreachable("Unexpected target builtin type");
11531 }
11532 break;
11533 }
11534 case 'V': {
11535 char *End;
11536 unsigned NumElements = strtoul(Str, &End, 10);
11537 assert(End != Str && "Missing vector size");
11538 Str = End;
11539
11540 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11541 RequiresICE, false);
11542 assert(!RequiresICE && "Can't require vector ICE");
11543
11544 // TODO: No way to make AltiVec vectors in builtins yet.
11545 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11546 break;
11547 }
11548 case 'E': {
11549 char *End;
11550
11551 unsigned NumElements = strtoul(Str, &End, 10);
11552 assert(End != Str && "Missing vector size");
11553
11554 Str = End;
11555
11556 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11557 false);
11558 Type = Context.getExtVectorType(ElementType, NumElements);
11559 break;
11560 }
11561 case 'X': {
11562 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11563 false);
11564 assert(!RequiresICE && "Can't require complex ICE");
11565 Type = Context.getComplexType(ElementType);
11566 break;
11567 }
11568 case 'Y':
11569 Type = Context.getPointerDiffType();
11570 break;
11571 case 'P':
11572 Type = Context.getFILEType();
11573 if (Type.isNull()) {
11575 return {};
11576 }
11577 break;
11578 case 'J':
11579 if (Signed)
11580 Type = Context.getsigjmp_bufType();
11581 else
11582 Type = Context.getjmp_bufType();
11583
11584 if (Type.isNull()) {
11586 return {};
11587 }
11588 break;
11589 case 'K':
11590 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11591 Type = Context.getucontext_tType();
11592
11593 if (Type.isNull()) {
11595 return {};
11596 }
11597 break;
11598 case 'p':
11599 Type = Context.getProcessIDType();
11600 break;
11601 }
11602
11603 // If there are modifiers and if we're allowed to parse them, go for it.
11604 Done = !AllowTypeModifiers;
11605 while (!Done) {
11606 switch (char c = *Str++) {
11607 default: Done = true; --Str; break;
11608 case '*':
11609 case '&': {
11610 // Both pointers and references can have their pointee types
11611 // qualified with an address space.
11612 char *End;
11613 unsigned AddrSpace = strtoul(Str, &End, 10);
11614 if (End != Str) {
11615 // Note AddrSpace == 0 is not the same as an unspecified address space.
11616 Type = Context.getAddrSpaceQualType(
11617 Type,
11618 Context.getLangASForBuiltinAddressSpace(AddrSpace));
11619 Str = End;
11620 }
11621 if (c == '*')
11622 Type = Context.getPointerType(Type);
11623 else
11624 Type = Context.getLValueReferenceType(Type);
11625 break;
11626 }
11627 // FIXME: There's no way to have a built-in with an rvalue ref arg.
11628 case 'C':
11629 Type = Type.withConst();
11630 break;
11631 case 'D':
11632 Type = Context.getVolatileType(Type);
11633 break;
11634 case 'R':
11635 Type = Type.withRestrict();
11636 break;
11637 }
11638 }
11639
11640 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11641 "Integer constant 'I' type must be an integer");
11642
11643 return Type;
11644}
11645
11646// On some targets such as PowerPC, some of the builtins are defined with custom
11647// type descriptors for target-dependent types. These descriptors are decoded in
11648// other functions, but it may be useful to be able to fall back to default
11649// descriptor decoding to define builtins mixing target-dependent and target-
11650// independent types. This function allows decoding one type descriptor with
11651// default decoding.
11652QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11653 GetBuiltinTypeError &Error, bool &RequireICE,
11654 bool AllowTypeModifiers) const {
11655 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11656}
11657
11658/// GetBuiltinType - Return the type for the specified builtin.
11660 GetBuiltinTypeError &Error,
11661 unsigned *IntegerConstantArgs) const {
11662 const char *TypeStr = BuiltinInfo.getTypeString(Id);
11663 if (TypeStr[0] == '\0') {
11664 Error = GE_Missing_type;
11665 return {};
11666 }
11667
11668 SmallVector<QualType, 8> ArgTypes;
11669
11670 bool RequiresICE = false;
11671 Error = GE_None;
11672 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11673 RequiresICE, true);
11674 if (Error != GE_None)
11675 return {};
11676
11677 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11678
11679 while (TypeStr[0] && TypeStr[0] != '.') {
11680 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11681 if (Error != GE_None)
11682 return {};
11683
11684 // If this argument is required to be an IntegerConstantExpression and the
11685 // caller cares, fill in the bitmask we return.
11686 if (RequiresICE && IntegerConstantArgs)
11687 *IntegerConstantArgs |= 1 << ArgTypes.size();
11688
11689 // Do array -> pointer decay. The builtin should use the decayed type.
11690 if (Ty->isArrayType())
11691 Ty = getArrayDecayedType(Ty);
11692
11693 ArgTypes.push_back(Ty);
11694 }
11695
11696 if (Id == Builtin::BI__GetExceptionInfo)
11697 return {};
11698
11699 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11700 "'.' should only occur at end of builtin type list!");
11701
11702 bool Variadic = (TypeStr[0] == '.');
11703
11705 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11706 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11707
11708
11709 // We really shouldn't be making a no-proto type here.
11710 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
11711 return getFunctionNoProtoType(ResType, EI);
11712
11714 EPI.ExtInfo = EI;
11715 EPI.Variadic = Variadic;
11717 EPI.ExceptionSpec.Type =
11719
11720 return getFunctionType(ResType, ArgTypes, EPI);
11721}
11722
11724 const FunctionDecl *FD) {
11725 if (!FD->isExternallyVisible())
11726 return GVA_Internal;
11727
11728 // Non-user-provided functions get emitted as weak definitions with every
11729 // use, no matter whether they've been explicitly instantiated etc.
11730 if (!FD->isUserProvided())
11731 return GVA_DiscardableODR;
11732
11734 switch (FD->getTemplateSpecializationKind()) {
11735 case TSK_Undeclared:
11738 break;
11739
11741 return GVA_StrongODR;
11742
11743 // C++11 [temp.explicit]p10:
11744 // [ Note: The intent is that an inline function that is the subject of
11745 // an explicit instantiation declaration will still be implicitly
11746 // instantiated when used so that the body can be considered for
11747 // inlining, but that no out-of-line copy of the inline function would be
11748 // generated in the translation unit. -- end note ]
11751
11754 break;
11755 }
11756
11757 if (!FD->isInlined())
11758 return External;
11759
11760 if ((!Context.getLangOpts().CPlusPlus &&
11761 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11762 !FD->hasAttr<DLLExportAttr>()) ||
11763 FD->hasAttr<GNUInlineAttr>()) {
11764 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11765
11766 // GNU or C99 inline semantics. Determine whether this symbol should be
11767 // externally visible.
11769 return External;
11770
11771 // C99 inline semantics, where the symbol is not externally visible.
11773 }
11774
11775 // Functions specified with extern and inline in -fms-compatibility mode
11776 // forcibly get emitted. While the body of the function cannot be later
11777 // replaced, the function definition cannot be discarded.
11778 if (FD->isMSExternInline())
11779 return GVA_StrongODR;
11780
11781 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11782 isa<CXXConstructorDecl>(FD) &&
11783 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
11784 // Our approach to inheriting constructors is fundamentally different from
11785 // that used by the MS ABI, so keep our inheriting constructor thunks
11786 // internal rather than trying to pick an unambiguous mangling for them.
11787 return GVA_Internal;
11788
11789 return GVA_DiscardableODR;
11790}
11791
11793 const Decl *D, GVALinkage L) {
11794 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11795 // dllexport/dllimport on inline functions.
11796 if (D->hasAttr<DLLImportAttr>()) {
11797 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11799 } else if (D->hasAttr<DLLExportAttr>()) {
11800 if (L == GVA_DiscardableODR)
11801 return GVA_StrongODR;
11802 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11803 // Device-side functions with __global__ attribute must always be
11804 // visible externally so they can be launched from host.
11805 if (D->hasAttr<CUDAGlobalAttr>() &&
11806 (L == GVA_DiscardableODR || L == GVA_Internal))
11807 return GVA_StrongODR;
11808 // Single source offloading languages like CUDA/HIP need to be able to
11809 // access static device variables from host code of the same compilation
11810 // unit. This is done by externalizing the static variable with a shared
11811 // name between the host and device compilation which is the same for the
11812 // same compilation unit whereas different among different compilation
11813 // units.
11814 if (Context.shouldExternalize(D))
11815 return GVA_StrongExternal;
11816 }
11817 return L;
11818}
11819
11820/// Adjust the GVALinkage for a declaration based on what an external AST source
11821/// knows about whether there can be other definitions of this declaration.
11822static GVALinkage
11824 GVALinkage L) {
11825 ExternalASTSource *Source = Ctx.getExternalSource();
11826 if (!Source)
11827 return L;
11828
11829 switch (Source->hasExternalDefinitions(D)) {
11831 // Other translation units rely on us to provide the definition.
11832 if (L == GVA_DiscardableODR)
11833 return GVA_StrongODR;
11834 break;
11835
11838
11840 break;
11841 }
11842 return L;
11843}
11844
11848 basicGVALinkageForFunction(*this, FD)));
11849}
11850
11852 const VarDecl *VD) {
11853 // As an extension for interactive REPLs, make sure constant variables are
11854 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
11855 // marking them as internal.
11856 if (Context.getLangOpts().CPlusPlus &&
11857 Context.getLangOpts().IncrementalExtensions &&
11858 VD->getType().isConstQualified() &&
11859 !VD->getType().isVolatileQualified() && !VD->isInline() &&
11860 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
11861 return GVA_DiscardableODR;
11862
11863 if (!VD->isExternallyVisible())
11864 return GVA_Internal;
11865
11866 if (VD->isStaticLocal()) {
11867 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11868 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11869 LexicalContext = LexicalContext->getLexicalParent();
11870
11871 // ObjC Blocks can create local variables that don't have a FunctionDecl
11872 // LexicalContext.
11873 if (!LexicalContext)
11874 return GVA_DiscardableODR;
11875
11876 // Otherwise, let the static local variable inherit its linkage from the
11877 // nearest enclosing function.
11878 auto StaticLocalLinkage =
11879 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11880
11881 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11882 // be emitted in any object with references to the symbol for the object it
11883 // contains, whether inline or out-of-line."
11884 // Similar behavior is observed with MSVC. An alternative ABI could use
11885 // StrongODR/AvailableExternally to match the function, but none are
11886 // known/supported currently.
11887 if (StaticLocalLinkage == GVA_StrongODR ||
11888 StaticLocalLinkage == GVA_AvailableExternally)
11889 return GVA_DiscardableODR;
11890 return StaticLocalLinkage;
11891 }
11892
11893 // MSVC treats in-class initialized static data members as definitions.
11894 // By giving them non-strong linkage, out-of-line definitions won't
11895 // cause link errors.
11897 return GVA_DiscardableODR;
11898
11899 // Most non-template variables have strong linkage; inline variables are
11900 // linkonce_odr or (occasionally, for compatibility) weak_odr.
11901 GVALinkage StrongLinkage;
11902 switch (Context.getInlineVariableDefinitionKind(VD)) {
11904 StrongLinkage = GVA_StrongExternal;
11905 break;
11908 StrongLinkage = GVA_DiscardableODR;
11909 break;
11911 StrongLinkage = GVA_StrongODR;
11912 break;
11913 }
11914
11915 switch (VD->getTemplateSpecializationKind()) {
11916 case TSK_Undeclared:
11917 return StrongLinkage;
11918
11920 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11921 VD->isStaticDataMember()
11923 : StrongLinkage;
11924
11926 return GVA_StrongODR;
11927
11930
11932 return GVA_DiscardableODR;
11933 }
11934
11935 llvm_unreachable("Invalid Linkage!");
11936}
11937
11941 basicGVALinkageForVariable(*this, VD)));
11942}
11943
11945 if (const auto *VD = dyn_cast<VarDecl>(D)) {
11946 if (!VD->isFileVarDecl())
11947 return false;
11948 // Global named register variables (GNU extension) are never emitted.
11949 if (VD->getStorageClass() == SC_Register)
11950 return false;
11951 if (VD->getDescribedVarTemplate() ||
11952 isa<VarTemplatePartialSpecializationDecl>(VD))
11953 return false;
11954 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11955 // We never need to emit an uninstantiated function template.
11956 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11957 return false;
11958 } else if (isa<PragmaCommentDecl>(D))
11959 return true;
11960 else if (isa<PragmaDetectMismatchDecl>(D))
11961 return true;
11962 else if (isa<OMPRequiresDecl>(D))
11963 return true;
11964 else if (isa<OMPThreadPrivateDecl>(D))
11965 return !D->getDeclContext()->isDependentContext();
11966 else if (isa<OMPAllocateDecl>(D))
11967 return !D->getDeclContext()->isDependentContext();
11968 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11969 return !D->getDeclContext()->isDependentContext();
11970 else if (isa<ImportDecl>(D))
11971 return true;
11972 else
11973 return false;
11974
11975 // If this is a member of a class template, we do not need to emit it.
11977 return false;
11978
11979 // Weak references don't produce any output by themselves.
11980 if (D->hasAttr<WeakRefAttr>())
11981 return false;
11982
11983 // Aliases and used decls are required.
11984 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11985 return true;
11986
11987 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11988 // Forward declarations aren't required.
11989 if (!FD->doesThisDeclarationHaveABody())
11990 return FD->doesDeclarationForceExternallyVisibleDefinition();
11991
11992 // Constructors and destructors are required.
11993 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11994 return true;
11995
11996 // The key function for a class is required. This rule only comes
11997 // into play when inline functions can be key functions, though.
11998 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11999 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12000 const CXXRecordDecl *RD = MD->getParent();
12001 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12002 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12003 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12004 return true;
12005 }
12006 }
12007 }
12008
12010
12011 // static, static inline, always_inline, and extern inline functions can
12012 // always be deferred. Normal inline functions can be deferred in C99/C++.
12013 // Implicit template instantiations can also be deferred in C++.
12015 }
12016
12017 const auto *VD = cast<VarDecl>(D);
12018 assert(VD->isFileVarDecl() && "Expected file scoped var");
12019
12020 // If the decl is marked as `declare target to`, it should be emitted for the
12021 // host and for the device.
12022 if (LangOpts.OpenMP &&
12023 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12024 return true;
12025
12026 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12028 return false;
12029
12030 // Variables in other module units shouldn't be forced to be emitted.
12031 if (VD->isInAnotherModuleUnit())
12032 return false;
12033
12034 // Variables that can be needed in other TUs are required.
12037 return true;
12038
12039 // We never need to emit a variable that is available in another TU.
12041 return false;
12042
12043 // Variables that have destruction with side-effects are required.
12044 if (VD->needsDestruction(*this))
12045 return true;
12046
12047 // Variables that have initialization with side-effects are required.
12048 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12049 // We can get a value-dependent initializer during error recovery.
12050 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12051 return true;
12052
12053 // Likewise, variables with tuple-like bindings are required if their
12054 // bindings have side-effects.
12055 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12056 for (const auto *BD : DD->bindings())
12057 if (const auto *BindingVD = BD->getHoldingVar())
12058 if (DeclMustBeEmitted(BindingVD))
12059 return true;
12060
12061 return false;
12062}
12063
12065 const FunctionDecl *FD,
12066 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12067 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12068 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12069 FD = FD->getMostRecentDecl();
12070 // FIXME: The order of traversal here matters and depends on the order of
12071 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12072 // shouldn't rely on that.
12073 for (auto *CurDecl :
12075 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12076 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12077 !SeenDecls.contains(CurFD)) {
12078 SeenDecls.insert(CurFD);
12079 Pred(CurFD);
12080 }
12081 }
12082}
12083
12085 bool IsCXXMethod,
12086 bool IsBuiltin) const {
12087 // Pass through to the C++ ABI object
12088 if (IsCXXMethod)
12089 return ABI->getDefaultMethodCallConv(IsVariadic);
12090
12091 // Builtins ignore user-specified default calling convention and remain the
12092 // Target's default calling convention.
12093 if (!IsBuiltin) {
12094 switch (LangOpts.getDefaultCallingConv()) {
12096 break;
12098 return CC_C;
12100 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12101 return CC_X86FastCall;
12102 break;
12104 if (!IsVariadic)
12105 return CC_X86StdCall;
12106 break;
12108 // __vectorcall cannot be applied to variadic functions.
12109 if (!IsVariadic)
12110 return CC_X86VectorCall;
12111 break;
12113 // __regcall cannot be applied to variadic functions.
12114 if (!IsVariadic)
12115 return CC_X86RegCall;
12116 break;
12118 if (!IsVariadic)
12119 return CC_M68kRTD;
12120 break;
12121 }
12122 }
12123 return Target->getDefaultCallingConv();
12124}
12125
12127 // Pass through to the C++ ABI object
12128 return ABI->isNearlyEmpty(RD);
12129}
12130
12132 if (!VTContext.get()) {
12133 auto ABI = Target->getCXXABI();
12134 if (ABI.isMicrosoft())
12135 VTContext.reset(new MicrosoftVTableContext(*this));
12136 else {
12137 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12140 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12141 }
12142 }
12143 return VTContext.get();
12144}
12145
12147 if (!T)
12148 T = Target;
12149 switch (T->getCXXABI().getKind()) {
12150 case TargetCXXABI::AppleARM64:
12151 case TargetCXXABI::Fuchsia:
12152 case TargetCXXABI::GenericAArch64:
12153 case TargetCXXABI::GenericItanium:
12154 case TargetCXXABI::GenericARM:
12155 case TargetCXXABI::GenericMIPS:
12156 case TargetCXXABI::iOS:
12157 case TargetCXXABI::WebAssembly:
12158 case TargetCXXABI::WatchOS:
12159 case TargetCXXABI::XL:
12161 case TargetCXXABI::Microsoft:
12163 }
12164 llvm_unreachable("Unsupported ABI");
12165}
12166
12168 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12169 "Device mangle context does not support Microsoft mangling.");
12170 switch (T.getCXXABI().getKind()) {
12171 case TargetCXXABI::AppleARM64:
12172 case TargetCXXABI::Fuchsia:
12173 case TargetCXXABI::GenericAArch64:
12174 case TargetCXXABI::GenericItanium:
12175 case TargetCXXABI::GenericARM:
12176 case TargetCXXABI::GenericMIPS:
12177 case TargetCXXABI::iOS:
12178 case TargetCXXABI::WebAssembly:
12179 case TargetCXXABI::WatchOS:
12180 case TargetCXXABI::XL:
12182 *this, getDiagnostics(),
12183 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12184 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12185 return RD->getDeviceLambdaManglingNumber();
12186 return std::nullopt;
12187 },
12188 /*IsAux=*/true);
12189 case TargetCXXABI::Microsoft:
12191 /*IsAux=*/true);
12192 }
12193 llvm_unreachable("Unsupported ABI");
12194}
12195
12196CXXABI::~CXXABI() = default;
12197
12199 return ASTRecordLayouts.getMemorySize() +
12200 llvm::capacity_in_bytes(ObjCLayouts) +
12201 llvm::capacity_in_bytes(KeyFunctions) +
12202 llvm::capacity_in_bytes(ObjCImpls) +
12203 llvm::capacity_in_bytes(BlockVarCopyInits) +
12204 llvm::capacity_in_bytes(DeclAttrs) +
12205 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12206 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12207 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12208 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12209 llvm::capacity_in_bytes(OverriddenMethods) +
12210 llvm::capacity_in_bytes(Types) +
12211 llvm::capacity_in_bytes(VariableArrayTypes);
12212}
12213
12214/// getIntTypeForBitwidth -
12215/// sets integer QualTy according to specified details:
12216/// bitwidth, signed/unsigned.
12217/// Returns empty type if there is no appropriate target types.
12219 unsigned Signed) const {
12221 CanQualType QualTy = getFromTargetType(Ty);
12222 if (!QualTy && DestWidth == 128)
12223 return Signed ? Int128Ty : UnsignedInt128Ty;
12224 return QualTy;
12225}
12226
12227/// getRealTypeForBitwidth -
12228/// sets floating point QualTy according to specified bitwidth.
12229/// Returns empty type if there is no appropriate target types.
12231 FloatModeKind ExplicitType) const {
12232 FloatModeKind Ty =
12233 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12234 switch (Ty) {
12236 return HalfTy;
12238 return FloatTy;
12240 return DoubleTy;
12242 return LongDoubleTy;
12244 return Float128Ty;
12246 return Ibm128Ty;
12248 return {};
12249 }
12250
12251 llvm_unreachable("Unhandled TargetInfo::RealType value");
12252}
12253
12254void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12255 if (Number <= 1)
12256 return;
12257
12258 MangleNumbers[ND] = Number;
12259
12260 if (Listener)
12261 Listener->AddedManglingNumber(ND, Number);
12262}
12263
12265 bool ForAuxTarget) const {
12266 auto I = MangleNumbers.find(ND);
12267 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12268 // CUDA/HIP host compilation encodes host and device mangling numbers
12269 // as lower and upper half of 32 bit integer.
12270 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12271 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12272 } else {
12273 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12274 "number for aux target");
12275 }
12276 return Res > 1 ? Res : 1;
12277}
12278
12279void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12280 if (Number <= 1)
12281 return;
12282
12283 StaticLocalNumbers[VD] = Number;
12284
12285 if (Listener)
12286 Listener->AddedStaticLocalNumbers(VD, Number);
12287}
12288
12290 auto I = StaticLocalNumbers.find(VD);
12291 return I != StaticLocalNumbers.end() ? I->second : 1;
12292}
12293
12296 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12297 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12298 if (!MCtx)
12300 return *MCtx;
12301}
12302
12305 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12306 std::unique_ptr<MangleNumberingContext> &MCtx =
12307 ExtraMangleNumberingContexts[D];
12308 if (!MCtx)
12310 return *MCtx;
12311}
12312
12313std::unique_ptr<MangleNumberingContext>
12315 return ABI->createMangleNumberingContext();
12316}
12317
12318const CXXConstructorDecl *
12320 return ABI->getCopyConstructorForExceptionObject(
12321 cast<CXXRecordDecl>(RD->getFirstDecl()));
12322}
12323
12325 CXXConstructorDecl *CD) {
12326 return ABI->addCopyConstructorForExceptionObject(
12327 cast<CXXRecordDecl>(RD->getFirstDecl()),
12328 cast<CXXConstructorDecl>(CD->getFirstDecl()));
12329}
12330
12332 TypedefNameDecl *DD) {
12333 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12334}
12335
12338 return ABI->getTypedefNameForUnnamedTagDecl(TD);
12339}
12340
12342 DeclaratorDecl *DD) {
12343 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12344}
12345
12347 return ABI->getDeclaratorForUnnamedTagDecl(TD);
12348}
12349
12350void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12351 ParamIndices[D] = index;
12352}
12353
12355 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12356 assert(I != ParamIndices.end() &&
12357 "ParmIndices lacks entry set by ParmVarDecl");
12358 return I->second;
12359}
12360
12362 unsigned Length) const {
12363 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12364 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12365 EltTy = EltTy.withConst();
12366
12367 EltTy = adjustStringLiteralBaseType(EltTy);
12368
12369 // Get an array type for the string, according to C99 6.4.5. This includes
12370 // the null terminator character.
12371 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12372 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12373}
12374
12377 StringLiteral *&Result = StringLiteralCache[Key];
12378 if (!Result)
12380 *this, Key, StringLiteralKind::Ordinary,
12381 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12382 SourceLocation());
12383 return Result;
12384}
12385
12386MSGuidDecl *
12388 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12389
12390 llvm::FoldingSetNodeID ID;
12391 MSGuidDecl::Profile(ID, Parts);
12392
12393 void *InsertPos;
12394 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12395 return Existing;
12396
12397 QualType GUIDType = getMSGuidType().withConst();
12398 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12399 MSGuidDecls.InsertNode(New, InsertPos);
12400 return New;
12401}
12402
12405 const APValue &APVal) const {
12406 llvm::FoldingSetNodeID ID;
12408
12409 void *InsertPos;
12410 if (UnnamedGlobalConstantDecl *Existing =
12411 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12412 return Existing;
12413
12415 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12416 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12417 return New;
12418}
12419
12422 assert(T->isRecordType() && "template param object of unexpected type");
12423
12424 // C++ [temp.param]p8:
12425 // [...] a static storage duration object of type 'const T' [...]
12426 T.addConst();
12427
12428 llvm::FoldingSetNodeID ID;
12430
12431 void *InsertPos;
12432 if (TemplateParamObjectDecl *Existing =
12433 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12434 return Existing;
12435
12436 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12437 TemplateParamObjectDecls.InsertNode(New, InsertPos);
12438 return New;
12439}
12440
12442 const llvm::Triple &T = getTargetInfo().getTriple();
12443 if (!T.isOSDarwin())
12444 return false;
12445
12446 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12447 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12448 return false;
12449
12450 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12451 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12452 uint64_t Size = sizeChars.getQuantity();
12453 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12454 unsigned Align = alignChars.getQuantity();
12455 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12456 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12457}
12458
12459bool
12461 const ObjCMethodDecl *MethodImpl) {
12462 // No point trying to match an unavailable/deprecated mothod.
12463 if (MethodDecl->hasAttr<UnavailableAttr>()
12464 || MethodDecl->hasAttr<DeprecatedAttr>())
12465 return false;
12466 if (MethodDecl->getObjCDeclQualifier() !=
12467 MethodImpl->getObjCDeclQualifier())
12468 return false;
12469 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12470 return false;
12471
12472 if (MethodDecl->param_size() != MethodImpl->param_size())
12473 return false;
12474
12475 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12476 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12477 EF = MethodDecl->param_end();
12478 IM != EM && IF != EF; ++IM, ++IF) {
12479 const ParmVarDecl *DeclVar = (*IF);
12480 const ParmVarDecl *ImplVar = (*IM);
12481 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12482 return false;
12483 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12484 return false;
12485 }
12486
12487 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12488}
12489
12491 LangAS AS;
12493 AS = LangAS::Default;
12494 else
12495 AS = QT->getPointeeType().getAddressSpace();
12496
12498}
12499
12502}
12503
12504bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12505 if (X == Y)
12506 return true;
12507 if (!X || !Y)
12508 return false;
12509 llvm::FoldingSetNodeID IDX, IDY;
12510 X->Profile(IDX, *this, /*Canonical=*/true);
12511 Y->Profile(IDY, *this, /*Canonical=*/true);
12512 return IDX == IDY;
12513}
12514
12515// The getCommon* helpers return, for given 'same' X and Y entities given as
12516// inputs, another entity which is also the 'same' as the inputs, but which
12517// is closer to the canonical form of the inputs, each according to a given
12518// criteria.
12519// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12520// the regular ones.
12521
12523 if (!declaresSameEntity(X, Y))
12524 return nullptr;
12525 for (const Decl *DX : X->redecls()) {
12526 // If we reach Y before reaching the first decl, that means X is older.
12527 if (DX == Y)
12528 return X;
12529 // If we reach the first decl, then Y is older.
12530 if (DX->isFirstDecl())
12531 return Y;
12532 }
12533 llvm_unreachable("Corrupt redecls chain");
12534}
12535
12536template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12537static T *getCommonDecl(T *X, T *Y) {
12538 return cast_or_null<T>(
12539 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12540 const_cast<Decl *>(cast_or_null<Decl>(Y))));
12541}
12542
12543template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12544static T *getCommonDeclChecked(T *X, T *Y) {
12545 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12546 const_cast<Decl *>(cast<Decl>(Y))));
12547}
12548
12550 TemplateName Y) {
12551 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12552 return X;
12553 // FIXME: There are cases here where we could find a common template name
12554 // with more sugar. For example one could be a SubstTemplateTemplate*
12555 // replacing the other.
12557 if (CX.getAsVoidPointer() !=
12559 return TemplateName();
12560 return CX;
12561}
12562
12563static TemplateName
12566 assert(R.getAsVoidPointer() != nullptr);
12567 return R;
12568}
12569
12571 ArrayRef<QualType> Ys, bool Unqualified = false) {
12572 assert(Xs.size() == Ys.size());
12573 SmallVector<QualType, 8> Rs(Xs.size());
12574 for (size_t I = 0; I < Rs.size(); ++I)
12575 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
12576 return Rs;
12577}
12578
12579template <class T>
12580static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
12581 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
12582 : SourceLocation();
12583}
12584
12586 const TemplateArgument &X,
12587 const TemplateArgument &Y) {
12588 if (X.getKind() != Y.getKind())
12589 return TemplateArgument();
12590
12591 switch (X.getKind()) {
12593 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
12594 return TemplateArgument();
12595 return TemplateArgument(
12596 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
12598 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
12599 return TemplateArgument();
12600 return TemplateArgument(
12601 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
12602 /*Unqualified=*/true);
12604 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
12605 return TemplateArgument();
12606 // FIXME: Try to keep the common sugar.
12607 return X;
12609 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
12610 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12611 if (!CTN.getAsVoidPointer())
12612 return TemplateArgument();
12613 return TemplateArgument(CTN);
12614 }
12616 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
12618 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12619 if (!CTN.getAsVoidPointer())
12620 return TemplateName();
12621 auto NExpX = X.getNumTemplateExpansions();
12622 assert(NExpX == Y.getNumTemplateExpansions());
12623 return TemplateArgument(CTN, NExpX);
12624 }
12625 default:
12626 // FIXME: Handle the other argument kinds.
12627 return X;
12628 }
12629}
12630
12635 if (Xs.size() != Ys.size())
12636 return true;
12637 R.resize(Xs.size());
12638 for (size_t I = 0; I < R.size(); ++I) {
12639 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
12640 if (R[I].isNull())
12641 return true;
12642 }
12643 return false;
12644}
12645
12650 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
12651 assert(!Different);
12652 (void)Different;
12653 return R;
12654}
12655
12656template <class T>
12658 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
12660}
12661
12662template <class T>
12664 const T *Y) {
12665 // FIXME: Try to keep the common NNS sugar.
12666 return X->getQualifier() == Y->getQualifier()
12667 ? X->getQualifier()
12668 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
12669}
12670
12671template <class T>
12672static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
12673 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
12674}
12675
12676template <class T>
12678 Qualifiers &QX, const T *Y,
12679 Qualifiers &QY) {
12680 QualType EX = X->getElementType(), EY = Y->getElementType();
12681 QualType R = Ctx.getCommonSugaredType(EX, EY,
12682 /*Unqualified=*/true);
12683 Qualifiers RQ = R.getQualifiers();
12684 QX += EX.getQualifiers() - RQ;
12685 QY += EY.getQualifiers() - RQ;
12686 return R;
12687}
12688
12689template <class T>
12690static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
12691 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
12692}
12693
12694template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
12695 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
12696 return X->getSizeExpr();
12697}
12698
12699static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
12700 assert(X->getSizeModifier() == Y->getSizeModifier());
12701 return X->getSizeModifier();
12702}
12703
12705 const ArrayType *Y) {
12706 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
12707 return X->getIndexTypeCVRQualifiers();
12708}
12709
12710// Merges two type lists such that the resulting vector will contain
12711// each type (in a canonical sense) only once, in the order they appear
12712// from X to Y. If they occur in both X and Y, the result will contain
12713// the common sugared type between them.
12716 llvm::DenseMap<QualType, unsigned> Found;
12717 for (auto Ts : {X, Y}) {
12718 for (QualType T : Ts) {
12719 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
12720 if (!Res.second) {
12721 QualType &U = Out[Res.first->second];
12722 U = Ctx.getCommonSugaredType(U, T);
12723 } else {
12724 Out.emplace_back(T);
12725 }
12726 }
12727 }
12728}
12729
12733 SmallVectorImpl<QualType> &ExceptionTypeStorage,
12734 bool AcceptDependent) {
12735 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
12736
12737 // If either of them can throw anything, that is the result.
12738 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
12739 if (EST1 == I)
12740 return ESI1;
12741 if (EST2 == I)
12742 return ESI2;
12743 }
12744
12745 // If either of them is non-throwing, the result is the other.
12746 for (auto I :
12748 if (EST1 == I)
12749 return ESI2;
12750 if (EST2 == I)
12751 return ESI1;
12752 }
12753
12754 // If we're left with value-dependent computed noexcept expressions, we're
12755 // stuck. Before C++17, we can just drop the exception specification entirely,
12756 // since it's not actually part of the canonical type. And this should never
12757 // happen in C++17, because it would mean we were computing the composite
12758 // pointer type of dependent types, which should never happen.
12759 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
12760 assert(AcceptDependent &&
12761 "computing composite pointer type of dependent types");
12763 }
12764
12765 // Switch over the possibilities so that people adding new values know to
12766 // update this function.
12767 switch (EST1) {
12768 case EST_None:
12769 case EST_DynamicNone:
12770 case EST_MSAny:
12771 case EST_BasicNoexcept:
12773 case EST_NoexceptFalse:
12774 case EST_NoexceptTrue:
12775 case EST_NoThrow:
12776 llvm_unreachable("These ESTs should be handled above");
12777
12778 case EST_Dynamic: {
12779 // This is the fun case: both exception specifications are dynamic. Form
12780 // the union of the two lists.
12781 assert(EST2 == EST_Dynamic && "other cases should already be handled");
12782 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
12783 ESI2.Exceptions);
12785 Result.Exceptions = ExceptionTypeStorage;
12786 return Result;
12787 }
12788
12789 case EST_Unevaluated:
12790 case EST_Uninstantiated:
12791 case EST_Unparsed:
12792 llvm_unreachable("shouldn't see unresolved exception specifications here");
12793 }
12794
12795 llvm_unreachable("invalid ExceptionSpecificationType");
12796}
12797
12799 Qualifiers &QX, const Type *Y,
12800 Qualifiers &QY) {
12801 Type::TypeClass TC = X->getTypeClass();
12802 assert(TC == Y->getTypeClass());
12803 switch (TC) {
12804#define UNEXPECTED_TYPE(Class, Kind) \
12805 case Type::Class: \
12806 llvm_unreachable("Unexpected " Kind ": " #Class);
12807
12808#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
12809#define TYPE(Class, Base)
12810#include "clang/AST/TypeNodes.inc"
12811
12812#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
12813 SUGAR_FREE_TYPE(Builtin)
12814 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
12815 SUGAR_FREE_TYPE(DependentBitInt)
12818 SUGAR_FREE_TYPE(ObjCInterface)
12820 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
12821 SUGAR_FREE_TYPE(UnresolvedUsing)
12822#undef SUGAR_FREE_TYPE
12823#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
12824 NON_UNIQUE_TYPE(TypeOfExpr)
12825 NON_UNIQUE_TYPE(VariableArray)
12826#undef NON_UNIQUE_TYPE
12827
12828 UNEXPECTED_TYPE(TypeOf, "sugar")
12829
12830#undef UNEXPECTED_TYPE
12831
12832 case Type::Auto: {
12833 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
12834 assert(AX->getDeducedType().isNull());
12835 assert(AY->getDeducedType().isNull());
12836 assert(AX->getKeyword() == AY->getKeyword());
12837 assert(AX->isInstantiationDependentType() ==
12838 AY->isInstantiationDependentType());
12839 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
12840 AY->getTypeConstraintArguments());
12841 return Ctx.getAutoType(QualType(), AX->getKeyword(),
12843 AX->containsUnexpandedParameterPack(),
12844 getCommonDeclChecked(AX->getTypeConstraintConcept(),
12845 AY->getTypeConstraintConcept()),
12846 As);
12847 }
12848 case Type::IncompleteArray: {
12849 const auto *AX = cast<IncompleteArrayType>(X),
12850 *AY = cast<IncompleteArrayType>(Y);
12851 return Ctx.getIncompleteArrayType(
12852 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12854 }
12855 case Type::DependentSizedArray: {
12856 const auto *AX = cast<DependentSizedArrayType>(X),
12857 *AY = cast<DependentSizedArrayType>(Y);
12858 return Ctx.getDependentSizedArrayType(
12859 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12860 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
12862 AX->getBracketsRange() == AY->getBracketsRange()
12863 ? AX->getBracketsRange()
12864 : SourceRange());
12865 }
12866 case Type::ConstantArray: {
12867 const auto *AX = cast<ConstantArrayType>(X),
12868 *AY = cast<ConstantArrayType>(Y);
12869 assert(AX->getSize() == AY->getSize());
12870 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12871 ? AX->getSizeExpr()
12872 : nullptr;
12873 return Ctx.getConstantArrayType(
12874 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12876 }
12877 case Type::ArrayParameter: {
12878 const auto *AX = cast<ArrayParameterType>(X),
12879 *AY = cast<ArrayParameterType>(Y);
12880 assert(AX->getSize() == AY->getSize());
12881 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12882 ? AX->getSizeExpr()
12883 : nullptr;
12884 auto ArrayTy = Ctx.getConstantArrayType(
12885 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12887 return Ctx.getArrayParameterType(ArrayTy);
12888 }
12889 case Type::Atomic: {
12890 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
12891 return Ctx.getAtomicType(
12892 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
12893 }
12894 case Type::Complex: {
12895 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
12896 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
12897 }
12898 case Type::Pointer: {
12899 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
12900 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
12901 }
12902 case Type::BlockPointer: {
12903 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
12904 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
12905 }
12906 case Type::ObjCObjectPointer: {
12907 const auto *PX = cast<ObjCObjectPointerType>(X),
12908 *PY = cast<ObjCObjectPointerType>(Y);
12909 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
12910 }
12911 case Type::MemberPointer: {
12912 const auto *PX = cast<MemberPointerType>(X),
12913 *PY = cast<MemberPointerType>(Y);
12914 return Ctx.getMemberPointerType(
12915 getCommonPointeeType(Ctx, PX, PY),
12916 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
12917 QualType(PY->getClass(), 0))
12918 .getTypePtr());
12919 }
12920 case Type::LValueReference: {
12921 const auto *PX = cast<LValueReferenceType>(X),
12922 *PY = cast<LValueReferenceType>(Y);
12923 // FIXME: Preserve PointeeTypeAsWritten.
12924 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
12925 PX->isSpelledAsLValue() ||
12926 PY->isSpelledAsLValue());
12927 }
12928 case Type::RValueReference: {
12929 const auto *PX = cast<RValueReferenceType>(X),
12930 *PY = cast<RValueReferenceType>(Y);
12931 // FIXME: Preserve PointeeTypeAsWritten.
12932 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
12933 }
12934 case Type::DependentAddressSpace: {
12935 const auto *PX = cast<DependentAddressSpaceType>(X),
12936 *PY = cast<DependentAddressSpaceType>(Y);
12937 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
12938 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
12939 PX->getAddrSpaceExpr(),
12940 getCommonAttrLoc(PX, PY));
12941 }
12942 case Type::FunctionNoProto: {
12943 const auto *FX = cast<FunctionNoProtoType>(X),
12944 *FY = cast<FunctionNoProtoType>(Y);
12945 assert(FX->getExtInfo() == FY->getExtInfo());
12946 return Ctx.getFunctionNoProtoType(
12947 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
12948 FX->getExtInfo());
12949 }
12950 case Type::FunctionProto: {
12951 const auto *FX = cast<FunctionProtoType>(X),
12952 *FY = cast<FunctionProtoType>(Y);
12953 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
12954 EPIY = FY->getExtProtoInfo();
12955 assert(EPIX.ExtInfo == EPIY.ExtInfo);
12956 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
12957 assert(EPIX.RefQualifier == EPIY.RefQualifier);
12958 assert(EPIX.TypeQuals == EPIY.TypeQuals);
12959 assert(EPIX.Variadic == EPIY.Variadic);
12960
12961 // FIXME: Can we handle an empty EllipsisLoc?
12962 // Use emtpy EllipsisLoc if X and Y differ.
12963
12964 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
12965
12966 QualType R =
12967 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
12968 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
12969 /*Unqualified=*/true);
12970
12971 SmallVector<QualType, 8> Exceptions;
12973 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
12974 return Ctx.getFunctionType(R, P, EPIX);
12975 }
12976 case Type::ObjCObject: {
12977 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
12978 assert(
12979 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
12980 OY->getProtocols().begin(), OY->getProtocols().end(),
12981 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
12982 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
12983 }) &&
12984 "protocol lists must be the same");
12985 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
12986 OY->getTypeArgsAsWritten());
12987 return Ctx.getObjCObjectType(
12988 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
12989 OX->getProtocols(),
12990 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
12991 }
12992 case Type::ConstantMatrix: {
12993 const auto *MX = cast<ConstantMatrixType>(X),
12994 *MY = cast<ConstantMatrixType>(Y);
12995 assert(MX->getNumRows() == MY->getNumRows());
12996 assert(MX->getNumColumns() == MY->getNumColumns());
12997 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
12998 MX->getNumRows(), MX->getNumColumns());
12999 }
13000 case Type::DependentSizedMatrix: {
13001 const auto *MX = cast<DependentSizedMatrixType>(X),
13002 *MY = cast<DependentSizedMatrixType>(Y);
13003 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13004 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13005 return Ctx.getDependentSizedMatrixType(
13006 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13007 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13008 }
13009 case Type::Vector: {
13010 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13011 assert(VX->getNumElements() == VY->getNumElements());
13012 assert(VX->getVectorKind() == VY->getVectorKind());
13013 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13014 VX->getNumElements(), VX->getVectorKind());
13015 }
13016 case Type::ExtVector: {
13017 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13018 assert(VX->getNumElements() == VY->getNumElements());
13019 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13020 VX->getNumElements());
13021 }
13022 case Type::DependentSizedExtVector: {
13023 const auto *VX = cast<DependentSizedExtVectorType>(X),
13024 *VY = cast<DependentSizedExtVectorType>(Y);
13026 getCommonSizeExpr(Ctx, VX, VY),
13027 getCommonAttrLoc(VX, VY));
13028 }
13029 case Type::DependentVector: {
13030 const auto *VX = cast<DependentVectorType>(X),
13031 *VY = cast<DependentVectorType>(Y);
13032 assert(VX->getVectorKind() == VY->getVectorKind());
13033 return Ctx.getDependentVectorType(
13034 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13035 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13036 }
13037 case Type::InjectedClassName: {
13038 const auto *IX = cast<InjectedClassNameType>(X),
13039 *IY = cast<InjectedClassNameType>(Y);
13040 return Ctx.getInjectedClassNameType(
13041 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13042 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13043 IY->getInjectedSpecializationType()));
13044 }
13045 case Type::TemplateSpecialization: {
13046 const auto *TX = cast<TemplateSpecializationType>(X),
13047 *TY = cast<TemplateSpecializationType>(Y);
13048 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13049 TY->template_arguments());
13051 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13052 TY->getTemplateName()),
13053 As, X->getCanonicalTypeInternal());
13054 }
13055 case Type::Decltype: {
13056 const auto *DX = cast<DecltypeType>(X);
13057 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13058 assert(DX->isDependentType());
13059 assert(DY->isDependentType());
13060 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13061 // As Decltype is not uniqued, building a common type would be wasteful.
13062 return QualType(DX, 0);
13063 }
13064 case Type::PackIndexing: {
13065 const auto *DX = cast<PackIndexingType>(X);
13066 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13067 assert(DX->isDependentType());
13068 assert(DY->isDependentType());
13069 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13070 return QualType(DX, 0);
13071 }
13072 case Type::DependentName: {
13073 const auto *NX = cast<DependentNameType>(X),
13074 *NY = cast<DependentNameType>(Y);
13075 assert(NX->getIdentifier() == NY->getIdentifier());
13076 return Ctx.getDependentNameType(
13077 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13078 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13079 }
13080 case Type::DependentTemplateSpecialization: {
13081 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13082 *TY = cast<DependentTemplateSpecializationType>(Y);
13083 assert(TX->getIdentifier() == TY->getIdentifier());
13084 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13085 TY->template_arguments());
13087 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13088 TX->getIdentifier(), As);
13089 }
13090 case Type::UnaryTransform: {
13091 const auto *TX = cast<UnaryTransformType>(X),
13092 *TY = cast<UnaryTransformType>(Y);
13093 assert(TX->getUTTKind() == TY->getUTTKind());
13094 return Ctx.getUnaryTransformType(
13095 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13096 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13097 TY->getUnderlyingType()),
13098 TX->getUTTKind());
13099 }
13100 case Type::PackExpansion: {
13101 const auto *PX = cast<PackExpansionType>(X),
13102 *PY = cast<PackExpansionType>(Y);
13103 assert(PX->getNumExpansions() == PY->getNumExpansions());
13104 return Ctx.getPackExpansionType(
13105 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13106 PX->getNumExpansions(), false);
13107 }
13108 case Type::Pipe: {
13109 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13110 assert(PX->isReadOnly() == PY->isReadOnly());
13111 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13113 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13114 }
13115 case Type::TemplateTypeParm: {
13116 const auto *TX = cast<TemplateTypeParmType>(X),
13117 *TY = cast<TemplateTypeParmType>(Y);
13118 assert(TX->getDepth() == TY->getDepth());
13119 assert(TX->getIndex() == TY->getIndex());
13120 assert(TX->isParameterPack() == TY->isParameterPack());
13121 return Ctx.getTemplateTypeParmType(
13122 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13123 getCommonDecl(TX->getDecl(), TY->getDecl()));
13124 }
13125 }
13126 llvm_unreachable("Unknown Type Class");
13127}
13128
13130 const Type *Y,
13131 SplitQualType Underlying) {
13132 Type::TypeClass TC = X->getTypeClass();
13133 if (TC != Y->getTypeClass())
13134 return QualType();
13135 switch (TC) {
13136#define UNEXPECTED_TYPE(Class, Kind) \
13137 case Type::Class: \
13138 llvm_unreachable("Unexpected " Kind ": " #Class);
13139#define TYPE(Class, Base)
13140#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13141#include "clang/AST/TypeNodes.inc"
13142
13143#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13146 CANONICAL_TYPE(BlockPointer)
13147 CANONICAL_TYPE(Builtin)
13149 CANONICAL_TYPE(ConstantArray)
13150 CANONICAL_TYPE(ArrayParameter)
13151 CANONICAL_TYPE(ConstantMatrix)
13153 CANONICAL_TYPE(ExtVector)
13154 CANONICAL_TYPE(FunctionNoProto)
13155 CANONICAL_TYPE(FunctionProto)
13156 CANONICAL_TYPE(IncompleteArray)
13157 CANONICAL_TYPE(LValueReference)
13158 CANONICAL_TYPE(MemberPointer)
13159 CANONICAL_TYPE(ObjCInterface)
13160 CANONICAL_TYPE(ObjCObject)
13161 CANONICAL_TYPE(ObjCObjectPointer)
13165 CANONICAL_TYPE(RValueReference)
13166 CANONICAL_TYPE(VariableArray)
13168#undef CANONICAL_TYPE
13169
13170#undef UNEXPECTED_TYPE
13171
13172 case Type::Adjusted: {
13173 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13174 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13175 if (!Ctx.hasSameType(OX, OY))
13176 return QualType();
13177 // FIXME: It's inefficient to have to unify the original types.
13178 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13179 Ctx.getQualifiedType(Underlying));
13180 }
13181 case Type::Decayed: {
13182 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13183 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13184 if (!Ctx.hasSameType(OX, OY))
13185 return QualType();
13186 // FIXME: It's inefficient to have to unify the original types.
13187 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13188 Ctx.getQualifiedType(Underlying));
13189 }
13190 case Type::Attributed: {
13191 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13192 AttributedType::Kind Kind = AX->getAttrKind();
13193 if (Kind != AY->getAttrKind())
13194 return QualType();
13195 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13196 if (!Ctx.hasSameType(MX, MY))
13197 return QualType();
13198 // FIXME: It's inefficient to have to unify the modified types.
13199 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13200 Ctx.getQualifiedType(Underlying));
13201 }
13202 case Type::BTFTagAttributed: {
13203 const auto *BX = cast<BTFTagAttributedType>(X);
13204 const BTFTypeTagAttr *AX = BX->getAttr();
13205 // The attribute is not uniqued, so just compare the tag.
13206 if (AX->getBTFTypeTag() !=
13207 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13208 return QualType();
13209 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13210 }
13211 case Type::Auto: {
13212 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13213
13214 AutoTypeKeyword KW = AX->getKeyword();
13215 if (KW != AY->getKeyword())
13216 return QualType();
13217
13218 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13219 AY->getTypeConstraintConcept());
13221 if (CD &&
13222 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13223 AY->getTypeConstraintArguments())) {
13224 CD = nullptr; // The arguments differ, so make it unconstrained.
13225 As.clear();
13226 }
13227
13228 // Both auto types can't be dependent, otherwise they wouldn't have been
13229 // sugar. This implies they can't contain unexpanded packs either.
13230 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13231 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13232 }
13233 case Type::PackIndexing:
13234 case Type::Decltype:
13235 return QualType();
13236 case Type::DeducedTemplateSpecialization:
13237 // FIXME: Try to merge these.
13238 return QualType();
13239
13240 case Type::Elaborated: {
13241 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13242 return Ctx.getElaboratedType(
13243 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13244 Ctx.getQualifiedType(Underlying),
13245 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13246 }
13247 case Type::MacroQualified: {
13248 const auto *MX = cast<MacroQualifiedType>(X),
13249 *MY = cast<MacroQualifiedType>(Y);
13250 const IdentifierInfo *IX = MX->getMacroIdentifier();
13251 if (IX != MY->getMacroIdentifier())
13252 return QualType();
13253 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13254 }
13255 case Type::SubstTemplateTypeParm: {
13256 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13257 *SY = cast<SubstTemplateTypeParmType>(Y);
13258 Decl *CD =
13259 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13260 if (!CD)
13261 return QualType();
13262 unsigned Index = SX->getIndex();
13263 if (Index != SY->getIndex())
13264 return QualType();
13265 auto PackIndex = SX->getPackIndex();
13266 if (PackIndex != SY->getPackIndex())
13267 return QualType();
13268 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13269 CD, Index, PackIndex);
13270 }
13271 case Type::ObjCTypeParam:
13272 // FIXME: Try to merge these.
13273 return QualType();
13274 case Type::Paren:
13275 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13276
13277 case Type::TemplateSpecialization: {
13278 const auto *TX = cast<TemplateSpecializationType>(X),
13279 *TY = cast<TemplateSpecializationType>(Y);
13280 TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13281 TY->getTemplateName());
13282 if (!CTN.getAsVoidPointer())
13283 return QualType();
13285 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13286 TY->template_arguments()))
13287 return QualType();
13288 return Ctx.getTemplateSpecializationType(CTN, Args,
13289 Ctx.getQualifiedType(Underlying));
13290 }
13291 case Type::Typedef: {
13292 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13293 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13294 if (!CD)
13295 return QualType();
13296 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13297 }
13298 case Type::TypeOf: {
13299 // The common sugar between two typeof expressions, where one is
13300 // potentially a typeof_unqual and the other is not, we unify to the
13301 // qualified type as that retains the most information along with the type.
13302 // We only return a typeof_unqual type when both types are unqual types.
13304 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13305 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13307 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13308 }
13309 case Type::TypeOfExpr:
13310 return QualType();
13311
13312 case Type::UnaryTransform: {
13313 const auto *UX = cast<UnaryTransformType>(X),
13314 *UY = cast<UnaryTransformType>(Y);
13315 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13316 if (KX != UY->getUTTKind())
13317 return QualType();
13318 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13319 if (!Ctx.hasSameType(BX, BY))
13320 return QualType();
13321 // FIXME: It's inefficient to have to unify the base types.
13322 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13323 Ctx.getQualifiedType(Underlying), KX);
13324 }
13325 case Type::Using: {
13326 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13327 const UsingShadowDecl *CD =
13328 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13329 if (!CD)
13330 return QualType();
13331 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13332 }
13333 case Type::CountAttributed: {
13334 const auto *DX = cast<CountAttributedType>(X),
13335 *DY = cast<CountAttributedType>(Y);
13336 if (DX->isCountInBytes() != DY->isCountInBytes())
13337 return QualType();
13338 if (DX->isOrNull() != DY->isOrNull())
13339 return QualType();
13340 Expr *CEX = DX->getCountExpr();
13341 Expr *CEY = DY->getCountExpr();
13342 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
13343 if (Ctx.hasSameExpr(CEX, CEY))
13344 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13345 DX->isCountInBytes(), DX->isOrNull(),
13346 CDX);
13347 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
13348 return QualType();
13349 // Two declarations with the same integer constant may still differ in their
13350 // expression pointers, so we need to evaluate them.
13351 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
13352 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
13353 if (VX != VY)
13354 return QualType();
13355 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13356 DX->isCountInBytes(), DX->isOrNull(),
13357 CDX);
13358 }
13359 }
13360 llvm_unreachable("Unhandled Type Class");
13361}
13362
13363static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13365 while (true) {
13366 QTotal.addConsistentQualifiers(T.Quals);
13368 if (NT == QualType(T.Ty, 0))
13369 break;
13370 R.push_back(T);
13371 T = NT.split();
13372 }
13373 return R;
13374}
13375
13377 bool Unqualified) {
13378 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13379 if (X == Y)
13380 return X;
13381 if (!Unqualified) {
13382 if (X.isCanonical())
13383 return X;
13384 if (Y.isCanonical())
13385 return Y;
13386 }
13387
13388 SplitQualType SX = X.split(), SY = Y.split();
13389 Qualifiers QX, QY;
13390 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13391 // until we reach their underlying "canonical nodes". Note these are not
13392 // necessarily canonical types, as they may still have sugared properties.
13393 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13394 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13395 if (SX.Ty != SY.Ty) {
13396 // The canonical nodes differ. Build a common canonical node out of the two,
13397 // unifying their sugar. This may recurse back here.
13398 SX.Ty =
13399 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13400 } else {
13401 // The canonical nodes were identical: We may have desugared too much.
13402 // Add any common sugar back in.
13403 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13404 QX -= SX.Quals;
13405 QY -= SY.Quals;
13406 SX = Xs.pop_back_val();
13407 SY = Ys.pop_back_val();
13408 }
13409 }
13410 if (Unqualified)
13412 else
13413 assert(QX == QY);
13414
13415 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13416 // related. Walk up these nodes, unifying them and adding the result.
13417 while (!Xs.empty() && !Ys.empty()) {
13418 auto Underlying = SplitQualType(
13419 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13420 SX = Xs.pop_back_val();
13421 SY = Ys.pop_back_val();
13422 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13424 // Stop at the first pair which is unrelated.
13425 if (!SX.Ty) {
13426 SX.Ty = Underlying.Ty;
13427 break;
13428 }
13429 QX -= Underlying.Quals;
13430 };
13431
13432 // Add back the missing accumulated qualifiers, which were stripped off
13433 // with the sugar nodes we could not unify.
13434 QualType R = getQualifiedType(SX.Ty, QX);
13435 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13436 return R;
13437}
13438
13440 assert(Ty->isFixedPointType());
13441
13443 return Ty;
13444
13445 switch (Ty->castAs<BuiltinType>()->getKind()) {
13446 default:
13447 llvm_unreachable("Not a saturated fixed point type!");
13448 case BuiltinType::SatShortAccum:
13449 return ShortAccumTy;
13450 case BuiltinType::SatAccum:
13451 return AccumTy;
13452 case BuiltinType::SatLongAccum:
13453 return LongAccumTy;
13454 case BuiltinType::SatUShortAccum:
13455 return UnsignedShortAccumTy;
13456 case BuiltinType::SatUAccum:
13457 return UnsignedAccumTy;
13458 case BuiltinType::SatULongAccum:
13459 return UnsignedLongAccumTy;
13460 case BuiltinType::SatShortFract:
13461 return ShortFractTy;
13462 case BuiltinType::SatFract:
13463 return FractTy;
13464 case BuiltinType::SatLongFract:
13465 return LongFractTy;
13466 case BuiltinType::SatUShortFract:
13467 return UnsignedShortFractTy;
13468 case BuiltinType::SatUFract:
13469 return UnsignedFractTy;
13470 case BuiltinType::SatULongFract:
13471 return UnsignedLongFractTy;
13472 }
13473}
13474
13476 assert(Ty->isFixedPointType());
13477
13478 if (Ty->isSaturatedFixedPointType()) return Ty;
13479
13480 switch (Ty->castAs<BuiltinType>()->getKind()) {
13481 default:
13482 llvm_unreachable("Not a fixed point type!");
13483 case BuiltinType::ShortAccum:
13484 return SatShortAccumTy;
13485 case BuiltinType::Accum:
13486 return SatAccumTy;
13487 case BuiltinType::LongAccum:
13488 return SatLongAccumTy;
13489 case BuiltinType::UShortAccum:
13491 case BuiltinType::UAccum:
13492 return SatUnsignedAccumTy;
13493 case BuiltinType::ULongAccum:
13495 case BuiltinType::ShortFract:
13496 return SatShortFractTy;
13497 case BuiltinType::Fract:
13498 return SatFractTy;
13499 case BuiltinType::LongFract:
13500 return SatLongFractTy;
13501 case BuiltinType::UShortFract:
13503 case BuiltinType::UFract:
13504 return SatUnsignedFractTy;
13505 case BuiltinType::ULongFract:
13507 }
13508}
13509
13511 if (LangOpts.OpenCL)
13513
13514 if (LangOpts.CUDA)
13516
13517 return getLangASFromTargetAS(AS);
13518}
13519
13520// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13521// doesn't include ASTContext.h
13522template
13524 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13526 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13527 const clang::ASTContext &Ctx, Decl *Value);
13528
13530 assert(Ty->isFixedPointType());
13531
13532 const TargetInfo &Target = getTargetInfo();
13533 switch (Ty->castAs<BuiltinType>()->getKind()) {
13534 default:
13535 llvm_unreachable("Not a fixed point type!");
13536 case BuiltinType::ShortAccum:
13537 case BuiltinType::SatShortAccum:
13538 return Target.getShortAccumScale();
13539 case BuiltinType::Accum:
13540 case BuiltinType::SatAccum:
13541 return Target.getAccumScale();
13542 case BuiltinType::LongAccum:
13543 case BuiltinType::SatLongAccum:
13544 return Target.getLongAccumScale();
13545 case BuiltinType::UShortAccum:
13546 case BuiltinType::SatUShortAccum:
13547 return Target.getUnsignedShortAccumScale();
13548 case BuiltinType::UAccum:
13549 case BuiltinType::SatUAccum:
13550 return Target.getUnsignedAccumScale();
13551 case BuiltinType::ULongAccum:
13552 case BuiltinType::SatULongAccum:
13553 return Target.getUnsignedLongAccumScale();
13554 case BuiltinType::ShortFract:
13555 case BuiltinType::SatShortFract:
13556 return Target.getShortFractScale();
13557 case BuiltinType::Fract:
13558 case BuiltinType::SatFract:
13559 return Target.getFractScale();
13560 case BuiltinType::LongFract:
13561 case BuiltinType::SatLongFract:
13562 return Target.getLongFractScale();
13563 case BuiltinType::UShortFract:
13564 case BuiltinType::SatUShortFract:
13565 return Target.getUnsignedShortFractScale();
13566 case BuiltinType::UFract:
13567 case BuiltinType::SatUFract:
13568 return Target.getUnsignedFractScale();
13569 case BuiltinType::ULongFract:
13570 case BuiltinType::SatULongFract:
13571 return Target.getUnsignedLongFractScale();
13572 }
13573}
13574
13576 assert(Ty->isFixedPointType());
13577
13578 const TargetInfo &Target = getTargetInfo();
13579 switch (Ty->castAs<BuiltinType>()->getKind()) {
13580 default:
13581 llvm_unreachable("Not a fixed point type!");
13582 case BuiltinType::ShortAccum:
13583 case BuiltinType::SatShortAccum:
13584 return Target.getShortAccumIBits();
13585 case BuiltinType::Accum:
13586 case BuiltinType::SatAccum:
13587 return Target.getAccumIBits();
13588 case BuiltinType::LongAccum:
13589 case BuiltinType::SatLongAccum:
13590 return Target.getLongAccumIBits();
13591 case BuiltinType::UShortAccum:
13592 case BuiltinType::SatUShortAccum:
13593 return Target.getUnsignedShortAccumIBits();
13594 case BuiltinType::UAccum:
13595 case BuiltinType::SatUAccum:
13596 return Target.getUnsignedAccumIBits();
13597 case BuiltinType::ULongAccum:
13598 case BuiltinType::SatULongAccum:
13599 return Target.getUnsignedLongAccumIBits();
13600 case BuiltinType::ShortFract:
13601 case BuiltinType::SatShortFract:
13602 case BuiltinType::Fract:
13603 case BuiltinType::SatFract:
13604 case BuiltinType::LongFract:
13605 case BuiltinType::SatLongFract:
13606 case BuiltinType::UShortFract:
13607 case BuiltinType::SatUShortFract:
13608 case BuiltinType::UFract:
13609 case BuiltinType::SatUFract:
13610 case BuiltinType::ULongFract:
13611 case BuiltinType::SatULongFract:
13612 return 0;
13613 }
13614}
13615
13616llvm::FixedPointSemantics
13618 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
13619 "Can only get the fixed point semantics for a "
13620 "fixed point or integer type.");
13621 if (Ty->isIntegerType())
13622 return llvm::FixedPointSemantics::GetIntegerSemantics(
13623 getIntWidth(Ty), Ty->isSignedIntegerType());
13624
13625 bool isSigned = Ty->isSignedFixedPointType();
13626 return llvm::FixedPointSemantics(
13627 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
13629 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
13630}
13631
13632llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
13633 assert(Ty->isFixedPointType());
13634 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
13635}
13636
13637llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
13638 assert(Ty->isFixedPointType());
13639 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
13640}
13641
13643 assert(Ty->isUnsignedFixedPointType() &&
13644 "Expected unsigned fixed point type");
13645
13646 switch (Ty->castAs<BuiltinType>()->getKind()) {
13647 case BuiltinType::UShortAccum:
13648 return ShortAccumTy;
13649 case BuiltinType::UAccum:
13650 return AccumTy;
13651 case BuiltinType::ULongAccum:
13652 return LongAccumTy;
13653 case BuiltinType::SatUShortAccum:
13654 return SatShortAccumTy;
13655 case BuiltinType::SatUAccum:
13656 return SatAccumTy;
13657 case BuiltinType::SatULongAccum:
13658 return SatLongAccumTy;
13659 case BuiltinType::UShortFract:
13660 return ShortFractTy;
13661 case BuiltinType::UFract:
13662 return FractTy;
13663 case BuiltinType::ULongFract:
13664 return LongFractTy;
13665 case BuiltinType::SatUShortFract:
13666 return SatShortFractTy;
13667 case BuiltinType::SatUFract:
13668 return SatFractTy;
13669 case BuiltinType::SatULongFract:
13670 return SatLongFractTy;
13671 default:
13672 llvm_unreachable("Unexpected unsigned fixed point type");
13673 }
13674}
13675
13677 const TargetVersionAttr *TV) const {
13678 assert(TV != nullptr);
13680 std::vector<std::string> ResFeats;
13681 TV->getFeatures(Feats);
13682 for (auto &Feature : Feats)
13683 if (Target->validateCpuSupports(Feature.str()))
13684 // Use '?' to mark features that came from TargetVersion.
13685 ResFeats.push_back("?" + Feature.str());
13686 return ResFeats;
13687}
13688
13690ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
13691 assert(TD != nullptr);
13692 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
13693
13694 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
13695 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
13696 });
13697 return ParsedAttr;
13698}
13699
13700void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13701 const FunctionDecl *FD) const {
13702 if (FD)
13703 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
13704 else
13705 Target->initFeatureMap(FeatureMap, getDiagnostics(),
13706 Target->getTargetOpts().CPU,
13707 Target->getTargetOpts().Features);
13708}
13709
13710// Fills in the supplied string map with the set of target features for the
13711// passed in function.
13712void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13713 GlobalDecl GD) const {
13714 StringRef TargetCPU = Target->getTargetOpts().CPU;
13715 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
13716 if (const auto *TD = FD->getAttr<TargetAttr>()) {
13718
13719 // Make a copy of the features as passed on the command line into the
13720 // beginning of the additional features from the function to override.
13721 ParsedAttr.Features.insert(
13722 ParsedAttr.Features.begin(),
13723 Target->getTargetOpts().FeaturesAsWritten.begin(),
13724 Target->getTargetOpts().FeaturesAsWritten.end());
13725
13726 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
13727 TargetCPU = ParsedAttr.CPU;
13728
13729 // Now populate the feature map, first with the TargetCPU which is either
13730 // the default or a new one from the target attribute string. Then we'll use
13731 // the passed in features (FeaturesAsWritten) along with the new ones from
13732 // the attribute.
13733 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
13734 ParsedAttr.Features);
13735 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
13737 Target->getCPUSpecificCPUDispatchFeatures(
13738 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
13739 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
13740 Features.insert(Features.begin(),
13741 Target->getTargetOpts().FeaturesAsWritten.begin(),
13742 Target->getTargetOpts().FeaturesAsWritten.end());
13743 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13744 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
13745 std::vector<std::string> Features;
13746 if (Target->getTriple().isAArch64()) {
13747 // TargetClones for AArch64
13749 TC->getFeatures(Feats, GD.getMultiVersionIndex());
13750 for (StringRef Feat : Feats)
13751 if (Target->validateCpuSupports(Feat.str()))
13752 // Use '?' to mark features that came from AArch64 TargetClones.
13753 Features.push_back("?" + Feat.str());
13754 Features.insert(Features.begin(),
13755 Target->getTargetOpts().FeaturesAsWritten.begin(),
13756 Target->getTargetOpts().FeaturesAsWritten.end());
13757 } else {
13758 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
13759 if (VersionStr.starts_with("arch="))
13760 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
13761 else if (VersionStr != "default")
13762 Features.push_back((StringRef{"+"} + VersionStr).str());
13763 }
13764 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13765 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
13766 std::vector<std::string> Feats = filterFunctionTargetVersionAttrs(TV);
13767 Feats.insert(Feats.begin(),
13768 Target->getTargetOpts().FeaturesAsWritten.begin(),
13769 Target->getTargetOpts().FeaturesAsWritten.end());
13770 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Feats);
13771 } else {
13772 FeatureMap = Target->getTargetOpts().FeatureMap;
13773 }
13774}
13775
13777 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
13778 return *OMPTraitInfoVector.back();
13779}
13780
13783 const ASTContext::SectionInfo &Section) {
13784 if (Section.Decl)
13785 return DB << Section.Decl;
13786 return DB << "a prior #pragma section";
13787}
13788
13789bool ASTContext::mayExternalize(const Decl *D) const {
13790 bool IsInternalVar =
13791 isa<VarDecl>(D) &&
13792 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
13793 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
13794 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
13795 (D->hasAttr<CUDAConstantAttr>() &&
13796 !D->getAttr<CUDAConstantAttr>()->isImplicit());
13797 // CUDA/HIP: managed variables need to be externalized since it is
13798 // a declaration in IR, therefore cannot have internal linkage. Kernels in
13799 // anonymous name space needs to be externalized to avoid duplicate symbols.
13800 return (IsInternalVar &&
13801 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
13802 (D->hasAttr<CUDAGlobalAttr>() &&
13803 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
13804 GVA_Internal);
13805}
13806
13808 return mayExternalize(D) &&
13809 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
13810 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
13811}
13812
13813StringRef ASTContext::getCUIDHash() const {
13814 if (!CUIDHash.empty())
13815 return CUIDHash;
13816 if (LangOpts.CUID.empty())
13817 return StringRef();
13818 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
13819 return CUIDHash;
13820}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:335
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:857
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:105
@ FloatRank
Definition: ASTContext.cpp:109
@ LongDoubleRank
Definition: ASTContext.cpp:111
@ Float16Rank
Definition: ASTContext.cpp:107
@ Ibm128Rank
Definition: ASTContext.cpp:113
@ Float128Rank
Definition: ASTContext.cpp:112
@ BFloat16Rank
Definition: ASTContext.cpp:106
@ HalfRank
Definition: ASTContext.cpp:108
@ DoubleRank
Definition: ASTContext.cpp:110
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y)
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:479
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:119
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3284
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:82
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2679
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
StringRef Text
Definition: Format.cpp:2972
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:143
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:48
llvm::MachO::Record Record
Definition: MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:100
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
This file defines OpenACC AST classes for statement-level contructs.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1064
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1071
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1104
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1122
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:476
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:851
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1121
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:834
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1100
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped)
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1096
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1100
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1113
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1106
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2118
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:558
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1109
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1992
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1104
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1203
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3234
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2379
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1103
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3248
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1103
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1109
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
std::vector< std::string > filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1956
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2431
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1131
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:870
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1098
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:326
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2140
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1108
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1930
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1936
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1118
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1590
CanQualType WideCharTy
Definition: ASTContext.h:1095
CanQualType OMPIteratorTy
Definition: ASTContext.h:1131
IdentifierTable & Idents
Definition: ASTContext.h:644
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1001
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:805
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1112
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1103
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1110
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1130
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1122
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1148
CanQualType BoolTy
Definition: ASTContext.h:1092
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:470
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:496
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2073
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1108
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1968
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1980
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1122
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3213
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1106
QualType AutoRRefDeductTy
Definition: ASTContext.h:1149
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1107
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1113
CanQualType CharTy
Definition: ASTContext.h:1093
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:808
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3227
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3220
CanQualType IntTy
Definition: ASTContext.h:1100
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1162
CanQualType PseudoObjectTy
Definition: ASTContext.h:1121
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:937
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
void PrintStats() const
Definition: ASTContext.cpp:951
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:573
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3244
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1156
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType SignedCharTy
Definition: ASTContext.h:1100
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:650
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1123
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1119
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1127
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1110
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:402
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2320
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2063
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:578
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2340
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3209
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3241
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:814
CanQualType OCLSamplerTy
Definition: ASTContext.h:1127
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1108
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:718
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3223
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1287
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1128
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1568
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1114
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:293
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2770
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:947
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1100
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1107
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1105
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:844
CanQualType Char32Ty
Definition: ASTContext.h:1099
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1112
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
CanQualType SatLongFractTy
Definition: ASTContext.h:1112
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1128
CanQualType LongFractTy
Definition: ASTContext.h:1107
CanQualType SatShortAccumTy
Definition: ASTContext.h:1109
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1116
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3216
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1129
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:818
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1188
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1111
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1100
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition: ASTContext.h:830
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1793
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
void addTranslationUnitDecl()
Definition: ASTContext.h:1076
CanQualType WCharTy
Definition: ASTContext.h:1094
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3230
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition: ASTContext.h:821
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2242
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2248
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2245
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2254
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2251
QualType adjustStringLiteralBaseType(QualType StrLTy) const
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1097
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1115
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1106
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
CanQualType OCLEventTy
Definition: ASTContext.h:1127
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:942
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:991
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:215
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2371
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2344
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3237
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3294
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3313
Represents a loop initializing the elements of an array.
Definition: Expr.h:5511
llvm::APInt getArraySize() const
Definition: Expr.h:5533
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5531
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3684
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3528
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3532
QualType getElementType() const
Definition: Type.h:3526
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3536
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6437
Expr * getPtr() const
Definition: Expr.h:6469
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7185
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7190
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5600
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5655
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5683
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5977
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5015
bool isConstrained() const
Definition: Type.h:5996
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5718
A fixed int type of a specified bitwidth.
Definition: Type.h:7238
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7255
unsigned getNumBits() const
Definition: Type.h:7250
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3345
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3362
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition: Type.h:2977
Kind getKind() const
Definition: Type.h:3019
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3271
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:106
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:236
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:132
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool isDynamicClass() const
Definition: DeclCXX.h:585
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:97
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3082
QualType getElementType() const
Definition: Type.h:3092
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3097
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition: ASTConcept.h:213
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:207
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3648
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3608
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3667
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3628
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4163
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4184
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4201
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4181
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4192
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3243
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3279
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3328
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:295
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1003
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:974
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setImplicit(bool I=true)
Definition: DeclBase.h:600
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:454
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Represents the type decltype(expr) (C++11).
Definition: Type.h:5354
Represents a C++17 deduced template specialization type.
Definition: Type.h:6025
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6047
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3855
Expr * getAddrSpaceExpr() const
Definition: Type.h:3866
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3877
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7283
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5382
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5386
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6448
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6480
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3797
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3834
Expr * getSizeExpr() const
Definition: Type.h:3817
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3895
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3920
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4222
Expr * getRowExpr() const
Definition: Type.h:4234
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4242
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:560
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:547
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:550
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:566
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6500
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6527
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5303
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5307
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:5505
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5510
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4017
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4042
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6367
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6420
Represents an enum.
Definition: Decl.h:3868
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4073
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4087
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4028
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4940
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EnumDecl * getDecl() const
Definition: Type.h:5578
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4079
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3918
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1697
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1744
ExtVectorType - Extended vector type.
Definition: Type.h:4057
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5334
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3149
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4646
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4594
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4547
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition: Decl.h:1971
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2600
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2831
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3757
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4268
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2373
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3927
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4607
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4623
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5097
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4911
unsigned getNumParams() const
Definition: Type.h:4885
QualType getParamType(unsigned i) const
Definition: Type.h:4887
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3760
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4917
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5073
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5069
Declaration of a template function.
Definition: DeclTemplate.h:958
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4363
CallingConv getCC() const
Definition: Type.h:4425
bool getNoCfCheck() const
Definition: Type.h:4415
unsigned getRegParm() const
Definition: Type.h:4418
bool getNoCallerSavedRegs() const
Definition: Type.h:4414
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4437
bool getHasRegParm() const
Definition: Type.h:4416
bool getNoReturn() const
Definition: Type.h:4411
bool getProducesResult() const
Definition: Type.h:4412
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4278
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4318
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
ExtInfo getExtInfo() const
Definition: Type.h:4581
QualType getReturnType() const
Definition: Type.h:4569
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4800
Represents a C array with an unspecified size.
Definition: Type.h:3699
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3716
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6217
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3420
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:549
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
CoreFoundationABI CFRuntime
Definition: LangOptions.h:498
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:525
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:545
A global _GUID constant.
Definition: DeclCXX.h:4289
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4326
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5238
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4141
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4148
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3492
QualType getPointeeType() const
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3486
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
bool isExternallyVisible() const
Definition: Decl.h:408
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3192
Represent a C++ namespace.
Definition: Decl.h:547
NamespaceDecl * getOriginalNamespace()
Get the original (first) namespace declaration.
Definition: DeclCXX.cpp:2996
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:2982
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:322
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1542
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1788
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1613
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1913
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1808
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6948
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:892
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1985
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition: Type.h:7004
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7085
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:899
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7079
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7161
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7041
bool qual_empty() const
Definition: Type.h:7133
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7062
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7016
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7056
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1787
qual_range quals() const
Definition: Type.h:7123
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7068
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:6901
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4302
Represents a class type in Objective C.
Definition: Type.h:6750
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:6865
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:821
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:6860
bool isObjCQualifiedClass() const
Definition: Type.h:6832
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:6812
bool isObjCClass() const
Definition: Type.h:6818
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:857
bool isObjCQualifiedId() const
Definition: Type.h:6831
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:839
bool isObjCUnqualifiedId() const
Definition: Type.h:6822
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6983
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:6876
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2876
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
protocol_range protocols() const
Definition: DeclObjC.h:2158
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:6656
qual_iterator qual_end() const
Definition: Type.h:6650
qual_iterator qual_begin() const
Definition: Type.h:6649
qual_range quals() const
Definition: Type.h:6648
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:6676
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4319
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4149
Represents a pack expansion of types.
Definition: Type.h:6565
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6599
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5441
Sugar for parentheses used when specifying types.
Definition: Type.h:3109
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3123
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1761
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1825
QualType getOriginalType() const
Definition: Decl.cpp:2924
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
PipeType - OpenCL20.
Definition: Type.h:7204
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7221
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3150
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2716
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:7486
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
QualType withConst() const
Definition: Type.h:1154
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1067
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7376
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool isCanonical() const
Definition: Type.h:7412
const Type * getTypePtrOrNull() const
Definition: Type.h:7359
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2876
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7387
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:431
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:468
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7295
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7302
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:505
void addAddressSpace(LangAS space)
Definition: Type.h:583
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:370
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
void removeObjCLifetime()
Definition: Type.h:537
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:624
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:675
void removeFastQualifiers(unsigned mask)
Definition: Type.h:610
bool hasUnaligned() const
Definition: Type.h:497
bool hasAddressSpace() const
Definition: Type.h:556
unsigned getFastQualifiers() const
Definition: Type.h:605
void removeAddressSpace()
Definition: Type.h:582
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasObjCGCAttr() const
Definition: Type.h:504
uint64_t getAsOpaqueValue() const
Definition: Type.h:441
bool hasObjCLifetime() const
Definition: Type.h:530
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
bool empty() const
Definition: Type.h:633
void addObjCGCAttr(GC type)
Definition: Type.h:510
LangAS getAddressSpace() const
Definition: Type.h:557
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4169
bool hasFlexibleArrayMember() const
Definition: Decl.h:4202
field_range fields() const
Definition: Decl.h:4375
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5017
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5083
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4360
bool field_empty() const
Definition: Decl.h:4383
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
QualType getPointeeType() const
Definition: Type.h:3394
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3402
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1115
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:156
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:373
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5885
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4165
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5815
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5854
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4739
bool isUnion() const
Definition: Decl.h:3791
TagDecl * getDecl() const
Definition: Type.cpp:3993
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:213
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:307
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
IntType getInt64Type() const
Definition: TargetInfo.h:400
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:813
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1603
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1597
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:706
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:751
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:314
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:323
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:327
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:332
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:341
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:316
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:319
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:336
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:483
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:467
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:370
unsigned getHalfAlign() const
Definition: TargetInfo.h:742
unsigned getBFloat16Align() const
Definition: TargetInfo.h:752
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:316
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:286
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:741
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:926
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:714
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1584
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:770
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:764
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:977
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:509
unsigned getFloat128Align() const
Definition: TargetInfo.h:771
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:678
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:772
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:762
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:763
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:996
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:357
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:247
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:222
@ Template
A single template declaration.
Definition: TemplateName.h:219
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:234
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:238
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:243
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:230
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:226
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6085
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4254
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5787
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:254
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:250
Represents a declaration of a type.
Definition: Decl.h:3391
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3416
const Type * getTypeForDecl() const
Definition: Decl.h:3415
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5270
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5318
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBlockPointerType() const
Definition: Type.h:7616
bool isBooleanType() const
Definition: Type.h:8029
bool isObjCBuiltinType() const
Definition: Type.h:7791
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2544
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isIncompleteArrayType() const
Definition: Type.h:7682
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:7877
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isConstantArrayType() const
Definition: Type.h:7678
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2009
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2340
bool isArrayType() const
Definition: Type.h:7674
bool isCharType() const
Definition: Type.cpp:2077
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:475
bool isPointerType() const
Definition: Type.h:7608
bool isArrayParameterType() const
Definition: Type.h:7690
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:7890
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7982
bool isEnumeralType() const
Definition: Type.h:7706
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isObjCQualifiedIdType() const
Definition: Type.h:7761
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8016
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2224
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2754
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isBitIntType() const
Definition: Type.h:7836
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7870
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7698
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7954
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7970
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2174
QualType getCanonicalTypeInternal() const
Definition: Type.h:2932
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isMemberPointerType() const
Definition: Type.h:7656
bool isObjCIdType() const
Definition: Type.h:7773
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7978
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8172
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7996
bool isVectorType() const
Definition: Type.h:7714
bool isObjCClassType() const
Definition: Type.h:7779
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2526
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2184
bool isAnyPointerType() const
Definition: Type.h:7612
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2326
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:604
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
bool isObjCRetainableType() const
Definition: Type.cpp:4862
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3535
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5505
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
QualType getUnderlyingType() const
Definition: Decl.h:3488
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3495
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5223
A unary type transform, which is a type constructed from another.
Definition: Type.h:5462
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4374
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5140
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5191
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5367
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
bool hasInit() const
Definition: Decl.cpp:2395
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2438
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1531
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1282
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2372
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2756
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3743
Expr * getSizeExpr() const
Definition: Type.h:3762
Represents a GCC generic vector type.
Definition: Type.h:3965
unsigned getNumElements() const
Definition: Type.h:3980
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3989
VectorKind getVectorKind() const
Definition: Type.h:3985
QualType getElementType() const
Definition: Type.h:3979
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:72
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1772
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:199
@ OCLTK_ReserveID
Definition: TargetInfo.h:206
@ OCLTK_Sampler
Definition: TargetInfo.h:207
@ OCLTK_Pipe
Definition: TargetInfo.h:204
@ OCLTK_ClkEvent
Definition: TargetInfo.h:201
@ OCLTK_Event
Definition: TargetInfo.h:202
@ OCLTK_Default
Definition: TargetInfo.h:200
@ OCLTK_Queue
Definition: TargetInfo.h:205
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:7508
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:921
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3511
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition: Type.h:6295
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:302
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:304
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1036
@ TypeAlignment
Definition: Type.h:73
FloatModeKind
Definition: TargetInfo.h:71
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3928
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:138
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6270
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:121
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6219
Expr * getCopyExpr() const
Definition: Expr.h:6226
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Holds information about the various types of exception specification.
Definition: Type.h:4703
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4708
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4711
Extra information about a function prototype.
Definition: Type.h:4731
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:4761
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4739
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:4756
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4490
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4546
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4495
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:56
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:873
const Type * Ty
The locally-unqualified type.
Definition: Type.h:875
Qualifiers Quals
The local qualifiers.
Definition: Type.h:878
A this pointer adjustment.
Definition: Thunk.h:91
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:137
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:169
bool isAlignRequired()
Definition: ASTContext.h:161
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:155
uint64_t Width
Definition: ASTContext.h:153
unsigned Align
Definition: ASTContext.h:154
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965