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 {
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 unresolved templates.
1311 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1312
1313 // Placeholder type for pseudo-objects.
1314 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1315
1316 // "any" type; useful for debugger-like clients.
1317 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1318
1319 // Placeholder type for unbridged ARC casts.
1320 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1321
1322 // Placeholder type for builtin functions.
1323 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1324
1325 // Placeholder type for OMP array sections.
1326 if (LangOpts.OpenMP) {
1327 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1328 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1329 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1330 }
1331 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1332 // don't bother, as we're just using the same type as OMP.
1333 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1334 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1335 }
1336 if (LangOpts.MatrixTypes)
1337 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1338
1339 // Builtin types for 'id', 'Class', and 'SEL'.
1340 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1341 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1342 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1343
1344 if (LangOpts.OpenCL) {
1345#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1346 InitBuiltinType(SingletonId, BuiltinType::Id);
1347#include "clang/Basic/OpenCLImageTypes.def"
1348
1349 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1350 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1351 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1352 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1353 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1354
1355#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1356 InitBuiltinType(Id##Ty, BuiltinType::Id);
1357#include "clang/Basic/OpenCLExtensionTypes.def"
1358 }
1359
1360 if (Target.hasAArch64SVETypes()) {
1361#define SVE_TYPE(Name, Id, SingletonId) \
1362 InitBuiltinType(SingletonId, BuiltinType::Id);
1363#include "clang/Basic/AArch64SVEACLETypes.def"
1364 }
1365
1366 if (Target.getTriple().isPPC64()) {
1367#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1368 InitBuiltinType(Id##Ty, BuiltinType::Id);
1369#include "clang/Basic/PPCTypes.def"
1370#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1371 InitBuiltinType(Id##Ty, BuiltinType::Id);
1372#include "clang/Basic/PPCTypes.def"
1373 }
1374
1375 if (Target.hasRISCVVTypes()) {
1376#define RVV_TYPE(Name, Id, SingletonId) \
1377 InitBuiltinType(SingletonId, BuiltinType::Id);
1378#include "clang/Basic/RISCVVTypes.def"
1379 }
1380
1381 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1382#define WASM_TYPE(Name, Id, SingletonId) \
1383 InitBuiltinType(SingletonId, BuiltinType::Id);
1384#include "clang/Basic/WebAssemblyReferenceTypes.def"
1385 }
1386
1387 // Builtin type for __objc_yes and __objc_no
1388 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1390
1391 ObjCConstantStringType = QualType();
1392
1393 ObjCSuperType = QualType();
1394
1395 // void * type
1396 if (LangOpts.OpenCLGenericAddressSpace) {
1397 auto Q = VoidTy.getQualifiers();
1401 } else {
1403 }
1404
1405 // nullptr type (C++0x 2.14.7)
1406 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1407
1408 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1409 InitBuiltinType(HalfTy, BuiltinType::Half);
1410
1411 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1412
1413 // Builtin type used to help define __builtin_va_list.
1414 VaListTagDecl = nullptr;
1415
1416 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1417 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1420 }
1421}
1422
1424 return SourceMgr.getDiagnostics();
1425}
1426
1428 AttrVec *&Result = DeclAttrs[D];
1429 if (!Result) {
1430 void *Mem = Allocate(sizeof(AttrVec));
1431 Result = new (Mem) AttrVec;
1432 }
1433
1434 return *Result;
1435}
1436
1437/// Erase the attributes corresponding to the given declaration.
1439 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1440 if (Pos != DeclAttrs.end()) {
1441 Pos->second->~AttrVec();
1442 DeclAttrs.erase(Pos);
1443 }
1444}
1445
1446// FIXME: Remove ?
1449 assert(Var->isStaticDataMember() && "Not a static data member");
1451 .dyn_cast<MemberSpecializationInfo *>();
1452}
1453
1456 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1457 TemplateOrInstantiation.find(Var);
1458 if (Pos == TemplateOrInstantiation.end())
1459 return {};
1460
1461 return Pos->second;
1462}
1463
1464void
1467 SourceLocation PointOfInstantiation) {
1468 assert(Inst->isStaticDataMember() && "Not a static data member");
1469 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1471 Tmpl, TSK, PointOfInstantiation));
1472}
1473
1474void
1477 assert(!TemplateOrInstantiation[Inst] &&
1478 "Already noted what the variable was instantiated from");
1479 TemplateOrInstantiation[Inst] = TSI;
1480}
1481
1482NamedDecl *
1484 return InstantiatedFromUsingDecl.lookup(UUD);
1485}
1486
1487void
1489 assert((isa<UsingDecl>(Pattern) ||
1490 isa<UnresolvedUsingValueDecl>(Pattern) ||
1491 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1492 "pattern decl is not a using decl");
1493 assert((isa<UsingDecl>(Inst) ||
1494 isa<UnresolvedUsingValueDecl>(Inst) ||
1495 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1496 "instantiation did not produce a using decl");
1497 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1498 InstantiatedFromUsingDecl[Inst] = Pattern;
1499}
1500
1503 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1504}
1505
1507 UsingEnumDecl *Pattern) {
1508 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1509 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1510}
1511
1514 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1515}
1516
1517void
1519 UsingShadowDecl *Pattern) {
1520 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1521 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1522}
1523
1525 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1526}
1527
1529 FieldDecl *Tmpl) {
1530 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1531 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1532 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1533 "Already noted what unnamed field was instantiated from");
1534
1535 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1536}
1537
1540 return overridden_methods(Method).begin();
1541}
1542
1545 return overridden_methods(Method).end();
1546}
1547
1548unsigned
1550 auto Range = overridden_methods(Method);
1551 return Range.end() - Range.begin();
1552}
1553
1556 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1557 OverriddenMethods.find(Method->getCanonicalDecl());
1558 if (Pos == OverriddenMethods.end())
1559 return overridden_method_range(nullptr, nullptr);
1560 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1561}
1562
1564 const CXXMethodDecl *Overridden) {
1565 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1566 OverriddenMethods[Method].push_back(Overridden);
1567}
1568
1570 const NamedDecl *D,
1571 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1572 assert(D);
1573
1574 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1575 Overridden.append(overridden_methods_begin(CXXMethod),
1576 overridden_methods_end(CXXMethod));
1577 return;
1578 }
1579
1580 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1581 if (!Method)
1582 return;
1583
1585 Method->getOverriddenMethods(OverDecls);
1586 Overridden.append(OverDecls.begin(), OverDecls.end());
1587}
1588
1590 assert(!Import->getNextLocalImport() &&
1591 "Import declaration already in the chain");
1592 assert(!Import->isFromASTFile() && "Non-local import declaration");
1593 if (!FirstLocalImport) {
1594 FirstLocalImport = Import;
1595 LastLocalImport = Import;
1596 return;
1597 }
1598
1599 LastLocalImport->setNextLocalImport(Import);
1600 LastLocalImport = Import;
1601}
1602
1603//===----------------------------------------------------------------------===//
1604// Type Sizing and Analysis
1605//===----------------------------------------------------------------------===//
1606
1607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1608/// scalar floating point type.
1609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1610 switch (T->castAs<BuiltinType>()->getKind()) {
1611 default:
1612 llvm_unreachable("Not a floating point type!");
1613 case BuiltinType::BFloat16:
1614 return Target->getBFloat16Format();
1615 case BuiltinType::Float16:
1616 return Target->getHalfFormat();
1617 case BuiltinType::Half:
1618 return Target->getHalfFormat();
1619 case BuiltinType::Float: return Target->getFloatFormat();
1620 case BuiltinType::Double: return Target->getDoubleFormat();
1621 case BuiltinType::Ibm128:
1622 return Target->getIbm128Format();
1623 case BuiltinType::LongDouble:
1624 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1625 return AuxTarget->getLongDoubleFormat();
1626 return Target->getLongDoubleFormat();
1627 case BuiltinType::Float128:
1628 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1629 return AuxTarget->getFloat128Format();
1630 return Target->getFloat128Format();
1631 }
1632}
1633
1634CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1635 unsigned Align = Target->getCharWidth();
1636
1637 const unsigned AlignFromAttr = D->getMaxAlignment();
1638 if (AlignFromAttr)
1639 Align = AlignFromAttr;
1640
1641 // __attribute__((aligned)) can increase or decrease alignment
1642 // *except* on a struct or struct member, where it only increases
1643 // alignment unless 'packed' is also specified.
1644 //
1645 // It is an error for alignas to decrease alignment, so we can
1646 // ignore that possibility; Sema should diagnose it.
1647 bool UseAlignAttrOnly;
1648 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1649 UseAlignAttrOnly =
1650 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1651 else
1652 UseAlignAttrOnly = AlignFromAttr != 0;
1653 // If we're using the align attribute only, just ignore everything
1654 // else about the declaration and its type.
1655 if (UseAlignAttrOnly) {
1656 // do nothing
1657 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1658 QualType T = VD->getType();
1659 if (const auto *RT = T->getAs<ReferenceType>()) {
1660 if (ForAlignof)
1661 T = RT->getPointeeType();
1662 else
1663 T = getPointerType(RT->getPointeeType());
1664 }
1665 QualType BaseT = getBaseElementType(T);
1666 if (T->isFunctionType())
1667 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1668 else if (!BaseT->isIncompleteType()) {
1669 // Adjust alignments of declarations with array type by the
1670 // large-array alignment on the target.
1671 if (const ArrayType *arrayType = getAsArrayType(T)) {
1672 unsigned MinWidth = Target->getLargeArrayMinWidth();
1673 if (!ForAlignof && MinWidth) {
1674 if (isa<VariableArrayType>(arrayType))
1675 Align = std::max(Align, Target->getLargeArrayAlign());
1676 else if (isa<ConstantArrayType>(arrayType) &&
1677 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1678 Align = std::max(Align, Target->getLargeArrayAlign());
1679 }
1680 }
1681 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1682 if (BaseT.getQualifiers().hasUnaligned())
1683 Align = Target->getCharWidth();
1684 }
1685
1686 // Ensure miminum alignment for global variables.
1687 if (const auto *VD = dyn_cast<VarDecl>(D))
1688 if (VD->hasGlobalStorage() && !ForAlignof) {
1689 uint64_t TypeSize =
1690 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1691 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1692 }
1693
1694 // Fields can be subject to extra alignment constraints, like if
1695 // the field is packed, the struct is packed, or the struct has a
1696 // a max-field-alignment constraint (#pragma pack). So calculate
1697 // the actual alignment of the field within the struct, and then
1698 // (as we're expected to) constrain that by the alignment of the type.
1699 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1700 const RecordDecl *Parent = Field->getParent();
1701 // We can only produce a sensible answer if the record is valid.
1702 if (!Parent->isInvalidDecl()) {
1703 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1704
1705 // Start with the record's overall alignment.
1706 unsigned FieldAlign = toBits(Layout.getAlignment());
1707
1708 // Use the GCD of that and the offset within the record.
1709 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1710 if (Offset > 0) {
1711 // Alignment is always a power of 2, so the GCD will be a power of 2,
1712 // which means we get to do this crazy thing instead of Euclid's.
1713 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1714 if (LowBitOfOffset < FieldAlign)
1715 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1716 }
1717
1718 Align = std::min(Align, FieldAlign);
1719 }
1720 }
1721 }
1722
1723 // Some targets have hard limitation on the maximum requestable alignment in
1724 // aligned attribute for static variables.
1725 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1726 const auto *VD = dyn_cast<VarDecl>(D);
1727 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1728 Align = std::min(Align, MaxAlignedAttr);
1729
1730 return toCharUnitsFromBits(Align);
1731}
1732
1734 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1735}
1736
1737// getTypeInfoDataSizeInChars - Return the size of a type, in
1738// chars. If the type is a record, its data size is returned. This is
1739// the size of the memcpy that's performed when assigning this type
1740// using a trivial copy/move assignment operator.
1743
1744 // In C++, objects can sometimes be allocated into the tail padding
1745 // of a base-class subobject. We decide whether that's possible
1746 // during class layout, so here we can just trust the layout results.
1747 if (getLangOpts().CPlusPlus) {
1748 if (const auto *RT = T->getAs<RecordType>();
1749 RT && !RT->getDecl()->isInvalidDecl()) {
1750 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1751 Info.Width = layout.getDataSize();
1752 }
1753 }
1754
1755 return Info;
1756}
1757
1758/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1759/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1762 const ConstantArrayType *CAT) {
1763 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1764 uint64_t Size = CAT->getZExtSize();
1765 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1766 (uint64_t)(-1)/Size) &&
1767 "Overflow in array type char size evaluation");
1768 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1769 unsigned Align = EltInfo.Align.getQuantity();
1770 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1772 Width = llvm::alignTo(Width, Align);
1775 EltInfo.AlignRequirement);
1776}
1777
1779 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1780 return getConstantArrayInfoInChars(*this, CAT);
1781 TypeInfo Info = getTypeInfo(T);
1784}
1785
1787 return getTypeInfoInChars(T.getTypePtr());
1788}
1789
1791 // HLSL doesn't promote all small integer types to int, it
1792 // just uses the rank-based promotion rules for all types.
1793 if (getLangOpts().HLSL)
1794 return false;
1795
1796 if (const auto *BT = T->getAs<BuiltinType>())
1797 switch (BT->getKind()) {
1798 case BuiltinType::Bool:
1799 case BuiltinType::Char_S:
1800 case BuiltinType::Char_U:
1801 case BuiltinType::SChar:
1802 case BuiltinType::UChar:
1803 case BuiltinType::Short:
1804 case BuiltinType::UShort:
1805 case BuiltinType::WChar_S:
1806 case BuiltinType::WChar_U:
1807 case BuiltinType::Char8:
1808 case BuiltinType::Char16:
1809 case BuiltinType::Char32:
1810 return true;
1811 default:
1812 return false;
1813 }
1814
1815 // Enumerated types are promotable to their compatible integer types
1816 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1817 if (const auto *ET = T->getAs<EnumType>()) {
1818 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1819 ET->getDecl()->isScoped())
1820 return false;
1821
1822 return true;
1823 }
1824
1825 return false;
1826}
1827
1830}
1831
1833 return isAlignmentRequired(T.getTypePtr());
1834}
1835
1837 bool NeedsPreferredAlignment) const {
1838 // An alignment on a typedef overrides anything else.
1839 if (const auto *TT = T->getAs<TypedefType>())
1840 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1841 return Align;
1842
1843 // If we have an (array of) complete type, we're done.
1845 if (!T->isIncompleteType())
1846 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1847
1848 // If we had an array type, its element type might be a typedef
1849 // type with an alignment attribute.
1850 if (const auto *TT = T->getAs<TypedefType>())
1851 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1852 return Align;
1853
1854 // Otherwise, see if the declaration of the type had an attribute.
1855 if (const auto *TT = T->getAs<TagType>())
1856 return TT->getDecl()->getMaxAlignment();
1857
1858 return 0;
1859}
1860
1862 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1863 if (I != MemoizedTypeInfo.end())
1864 return I->second;
1865
1866 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1867 TypeInfo TI = getTypeInfoImpl(T);
1868 MemoizedTypeInfo[T] = TI;
1869 return TI;
1870}
1871
1872/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1873/// method does not work on incomplete types.
1874///
1875/// FIXME: Pointers into different addr spaces could have different sizes and
1876/// alignment requirements: getPointerInfo should take an AddrSpace, this
1877/// should take a QualType, &c.
1878TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1879 uint64_t Width = 0;
1880 unsigned Align = 8;
1883 switch (T->getTypeClass()) {
1884#define TYPE(Class, Base)
1885#define ABSTRACT_TYPE(Class, Base)
1886#define NON_CANONICAL_TYPE(Class, Base)
1887#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1888#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1889 case Type::Class: \
1890 assert(!T->isDependentType() && "should not see dependent types here"); \
1891 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1892#include "clang/AST/TypeNodes.inc"
1893 llvm_unreachable("Should not see dependent types");
1894
1895 case Type::FunctionNoProto:
1896 case Type::FunctionProto:
1897 // GCC extension: alignof(function) = 32 bits
1898 Width = 0;
1899 Align = 32;
1900 break;
1901
1902 case Type::IncompleteArray:
1903 case Type::VariableArray:
1904 case Type::ConstantArray:
1905 case Type::ArrayParameter: {
1906 // Model non-constant sized arrays as size zero, but track the alignment.
1907 uint64_t Size = 0;
1908 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1909 Size = CAT->getZExtSize();
1910
1911 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1912 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1913 "Overflow in array type bit size evaluation");
1914 Width = EltInfo.Width * Size;
1915 Align = EltInfo.Align;
1916 AlignRequirement = EltInfo.AlignRequirement;
1917 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1918 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1919 Width = llvm::alignTo(Width, Align);
1920 break;
1921 }
1922
1923 case Type::ExtVector:
1924 case Type::Vector: {
1925 const auto *VT = cast<VectorType>(T);
1926 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1927 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1928 : EltInfo.Width * VT->getNumElements();
1929 // Enforce at least byte size and alignment.
1930 Width = std::max<unsigned>(8, Width);
1931 Align = std::max<unsigned>(8, Width);
1932
1933 // If the alignment is not a power of 2, round up to the next power of 2.
1934 // This happens for non-power-of-2 length vectors.
1935 if (Align & (Align-1)) {
1936 Align = llvm::bit_ceil(Align);
1937 Width = llvm::alignTo(Width, Align);
1938 }
1939 // Adjust the alignment based on the target max.
1940 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1941 if (TargetVectorAlign && TargetVectorAlign < Align)
1942 Align = TargetVectorAlign;
1943 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1944 // Adjust the alignment for fixed-length SVE vectors. This is important
1945 // for non-power-of-2 vector lengths.
1946 Align = 128;
1947 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1948 // Adjust the alignment for fixed-length SVE predicates.
1949 Align = 16;
1950 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1951 VT->getVectorKind() == VectorKind::RVVFixedLengthMask)
1952 // Adjust the alignment for fixed-length RVV vectors.
1953 Align = std::min<unsigned>(64, Width);
1954 break;
1955 }
1956
1957 case Type::ConstantMatrix: {
1958 const auto *MT = cast<ConstantMatrixType>(T);
1959 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1960 // The internal layout of a matrix value is implementation defined.
1961 // Initially be ABI compatible with arrays with respect to alignment and
1962 // size.
1963 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1964 Align = ElementInfo.Align;
1965 break;
1966 }
1967
1968 case Type::Builtin:
1969 switch (cast<BuiltinType>(T)->getKind()) {
1970 default: llvm_unreachable("Unknown builtin type!");
1971 case BuiltinType::Void:
1972 // GCC extension: alignof(void) = 8 bits.
1973 Width = 0;
1974 Align = 8;
1975 break;
1976 case BuiltinType::Bool:
1977 Width = Target->getBoolWidth();
1978 Align = Target->getBoolAlign();
1979 break;
1980 case BuiltinType::Char_S:
1981 case BuiltinType::Char_U:
1982 case BuiltinType::UChar:
1983 case BuiltinType::SChar:
1984 case BuiltinType::Char8:
1985 Width = Target->getCharWidth();
1986 Align = Target->getCharAlign();
1987 break;
1988 case BuiltinType::WChar_S:
1989 case BuiltinType::WChar_U:
1990 Width = Target->getWCharWidth();
1991 Align = Target->getWCharAlign();
1992 break;
1993 case BuiltinType::Char16:
1994 Width = Target->getChar16Width();
1995 Align = Target->getChar16Align();
1996 break;
1997 case BuiltinType::Char32:
1998 Width = Target->getChar32Width();
1999 Align = Target->getChar32Align();
2000 break;
2001 case BuiltinType::UShort:
2002 case BuiltinType::Short:
2003 Width = Target->getShortWidth();
2004 Align = Target->getShortAlign();
2005 break;
2006 case BuiltinType::UInt:
2007 case BuiltinType::Int:
2008 Width = Target->getIntWidth();
2009 Align = Target->getIntAlign();
2010 break;
2011 case BuiltinType::ULong:
2012 case BuiltinType::Long:
2013 Width = Target->getLongWidth();
2014 Align = Target->getLongAlign();
2015 break;
2016 case BuiltinType::ULongLong:
2017 case BuiltinType::LongLong:
2018 Width = Target->getLongLongWidth();
2019 Align = Target->getLongLongAlign();
2020 break;
2021 case BuiltinType::Int128:
2022 case BuiltinType::UInt128:
2023 Width = 128;
2024 Align = Target->getInt128Align();
2025 break;
2026 case BuiltinType::ShortAccum:
2027 case BuiltinType::UShortAccum:
2028 case BuiltinType::SatShortAccum:
2029 case BuiltinType::SatUShortAccum:
2030 Width = Target->getShortAccumWidth();
2031 Align = Target->getShortAccumAlign();
2032 break;
2033 case BuiltinType::Accum:
2034 case BuiltinType::UAccum:
2035 case BuiltinType::SatAccum:
2036 case BuiltinType::SatUAccum:
2037 Width = Target->getAccumWidth();
2038 Align = Target->getAccumAlign();
2039 break;
2040 case BuiltinType::LongAccum:
2041 case BuiltinType::ULongAccum:
2042 case BuiltinType::SatLongAccum:
2043 case BuiltinType::SatULongAccum:
2044 Width = Target->getLongAccumWidth();
2045 Align = Target->getLongAccumAlign();
2046 break;
2047 case BuiltinType::ShortFract:
2048 case BuiltinType::UShortFract:
2049 case BuiltinType::SatShortFract:
2050 case BuiltinType::SatUShortFract:
2051 Width = Target->getShortFractWidth();
2052 Align = Target->getShortFractAlign();
2053 break;
2054 case BuiltinType::Fract:
2055 case BuiltinType::UFract:
2056 case BuiltinType::SatFract:
2057 case BuiltinType::SatUFract:
2058 Width = Target->getFractWidth();
2059 Align = Target->getFractAlign();
2060 break;
2061 case BuiltinType::LongFract:
2062 case BuiltinType::ULongFract:
2063 case BuiltinType::SatLongFract:
2064 case BuiltinType::SatULongFract:
2065 Width = Target->getLongFractWidth();
2066 Align = Target->getLongFractAlign();
2067 break;
2068 case BuiltinType::BFloat16:
2069 if (Target->hasBFloat16Type()) {
2070 Width = Target->getBFloat16Width();
2071 Align = Target->getBFloat16Align();
2072 } else if ((getLangOpts().SYCLIsDevice ||
2073 (getLangOpts().OpenMP &&
2074 getLangOpts().OpenMPIsTargetDevice)) &&
2075 AuxTarget->hasBFloat16Type()) {
2076 Width = AuxTarget->getBFloat16Width();
2077 Align = AuxTarget->getBFloat16Align();
2078 }
2079 break;
2080 case BuiltinType::Float16:
2081 case BuiltinType::Half:
2082 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2083 !getLangOpts().OpenMPIsTargetDevice) {
2084 Width = Target->getHalfWidth();
2085 Align = Target->getHalfAlign();
2086 } else {
2087 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2088 "Expected OpenMP device compilation.");
2089 Width = AuxTarget->getHalfWidth();
2090 Align = AuxTarget->getHalfAlign();
2091 }
2092 break;
2093 case BuiltinType::Float:
2094 Width = Target->getFloatWidth();
2095 Align = Target->getFloatAlign();
2096 break;
2097 case BuiltinType::Double:
2098 Width = Target->getDoubleWidth();
2099 Align = Target->getDoubleAlign();
2100 break;
2101 case BuiltinType::Ibm128:
2102 Width = Target->getIbm128Width();
2103 Align = Target->getIbm128Align();
2104 break;
2105 case BuiltinType::LongDouble:
2106 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2107 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2108 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2109 Width = AuxTarget->getLongDoubleWidth();
2110 Align = AuxTarget->getLongDoubleAlign();
2111 } else {
2112 Width = Target->getLongDoubleWidth();
2113 Align = Target->getLongDoubleAlign();
2114 }
2115 break;
2116 case BuiltinType::Float128:
2117 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2118 !getLangOpts().OpenMPIsTargetDevice) {
2119 Width = Target->getFloat128Width();
2120 Align = Target->getFloat128Align();
2121 } else {
2122 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2123 "Expected OpenMP device compilation.");
2124 Width = AuxTarget->getFloat128Width();
2125 Align = AuxTarget->getFloat128Align();
2126 }
2127 break;
2128 case BuiltinType::NullPtr:
2129 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2130 Width = Target->getPointerWidth(LangAS::Default);
2131 Align = Target->getPointerAlign(LangAS::Default);
2132 break;
2133 case BuiltinType::ObjCId:
2134 case BuiltinType::ObjCClass:
2135 case BuiltinType::ObjCSel:
2136 Width = Target->getPointerWidth(LangAS::Default);
2137 Align = Target->getPointerAlign(LangAS::Default);
2138 break;
2139 case BuiltinType::OCLSampler:
2140 case BuiltinType::OCLEvent:
2141 case BuiltinType::OCLClkEvent:
2142 case BuiltinType::OCLQueue:
2143 case BuiltinType::OCLReserveID:
2144#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2145 case BuiltinType::Id:
2146#include "clang/Basic/OpenCLImageTypes.def"
2147#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2148 case BuiltinType::Id:
2149#include "clang/Basic/OpenCLExtensionTypes.def"
2150 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2151 Width = Target->getPointerWidth(AS);
2152 Align = Target->getPointerAlign(AS);
2153 break;
2154 // The SVE types are effectively target-specific. The length of an
2155 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2156 // of 128 bits. There is one predicate bit for each vector byte, so the
2157 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2158 //
2159 // Because the length is only known at runtime, we use a dummy value
2160 // of 0 for the static length. The alignment values are those defined
2161 // by the Procedure Call Standard for the Arm Architecture.
2162#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2163 IsSigned, IsFP, IsBF) \
2164 case BuiltinType::Id: \
2165 Width = 0; \
2166 Align = 128; \
2167 break;
2168#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2169 case BuiltinType::Id: \
2170 Width = 0; \
2171 Align = 16; \
2172 break;
2173#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2174 case BuiltinType::Id: \
2175 Width = 0; \
2176 Align = 16; \
2177 break;
2178#include "clang/Basic/AArch64SVEACLETypes.def"
2179#define PPC_VECTOR_TYPE(Name, Id, Size) \
2180 case BuiltinType::Id: \
2181 Width = Size; \
2182 Align = Size; \
2183 break;
2184#include "clang/Basic/PPCTypes.def"
2185#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2186 IsFP, IsBF) \
2187 case BuiltinType::Id: \
2188 Width = 0; \
2189 Align = ElBits; \
2190 break;
2191#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2192 case BuiltinType::Id: \
2193 Width = 0; \
2194 Align = 8; \
2195 break;
2196#include "clang/Basic/RISCVVTypes.def"
2197#define WASM_TYPE(Name, Id, SingletonId) \
2198 case BuiltinType::Id: \
2199 Width = 0; \
2200 Align = 8; \
2201 break;
2202#include "clang/Basic/WebAssemblyReferenceTypes.def"
2203 }
2204 break;
2205 case Type::ObjCObjectPointer:
2206 Width = Target->getPointerWidth(LangAS::Default);
2207 Align = Target->getPointerAlign(LangAS::Default);
2208 break;
2209 case Type::BlockPointer:
2210 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2211 Width = Target->getPointerWidth(AS);
2212 Align = Target->getPointerAlign(AS);
2213 break;
2214 case Type::LValueReference:
2215 case Type::RValueReference:
2216 // alignof and sizeof should never enter this code path here, so we go
2217 // the pointer route.
2218 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2219 Width = Target->getPointerWidth(AS);
2220 Align = Target->getPointerAlign(AS);
2221 break;
2222 case Type::Pointer:
2223 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2224 Width = Target->getPointerWidth(AS);
2225 Align = Target->getPointerAlign(AS);
2226 break;
2227 case Type::MemberPointer: {
2228 const auto *MPT = cast<MemberPointerType>(T);
2229 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2230 Width = MPI.Width;
2231 Align = MPI.Align;
2232 break;
2233 }
2234 case Type::Complex: {
2235 // Complex types have the same alignment as their elements, but twice the
2236 // size.
2237 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2238 Width = EltInfo.Width * 2;
2239 Align = EltInfo.Align;
2240 break;
2241 }
2242 case Type::ObjCObject:
2243 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2244 case Type::Adjusted:
2245 case Type::Decayed:
2246 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2247 case Type::ObjCInterface: {
2248 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2249 if (ObjCI->getDecl()->isInvalidDecl()) {
2250 Width = 8;
2251 Align = 8;
2252 break;
2253 }
2254 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2255 Width = toBits(Layout.getSize());
2256 Align = toBits(Layout.getAlignment());
2257 break;
2258 }
2259 case Type::BitInt: {
2260 const auto *EIT = cast<BitIntType>(T);
2261 Align = Target->getBitIntAlign(EIT->getNumBits());
2262 Width = Target->getBitIntWidth(EIT->getNumBits());
2263 break;
2264 }
2265 case Type::Record:
2266 case Type::Enum: {
2267 const auto *TT = cast<TagType>(T);
2268
2269 if (TT->getDecl()->isInvalidDecl()) {
2270 Width = 8;
2271 Align = 8;
2272 break;
2273 }
2274
2275 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2276 const EnumDecl *ED = ET->getDecl();
2277 TypeInfo Info =
2279 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2280 Info.Align = AttrAlign;
2282 }
2283 return Info;
2284 }
2285
2286 const auto *RT = cast<RecordType>(TT);
2287 const RecordDecl *RD = RT->getDecl();
2288 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2289 Width = toBits(Layout.getSize());
2290 Align = toBits(Layout.getAlignment());
2291 AlignRequirement = RD->hasAttr<AlignedAttr>()
2294 break;
2295 }
2296
2297 case Type::SubstTemplateTypeParm:
2298 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2299 getReplacementType().getTypePtr());
2300
2301 case Type::Auto:
2302 case Type::DeducedTemplateSpecialization: {
2303 const auto *A = cast<DeducedType>(T);
2304 assert(!A->getDeducedType().isNull() &&
2305 "cannot request the size of an undeduced or dependent auto type");
2306 return getTypeInfo(A->getDeducedType().getTypePtr());
2307 }
2308
2309 case Type::Paren:
2310 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2311
2312 case Type::MacroQualified:
2313 return getTypeInfo(
2314 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2315
2316 case Type::ObjCTypeParam:
2317 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2318
2319 case Type::Using:
2320 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2321
2322 case Type::Typedef: {
2323 const auto *TT = cast<TypedefType>(T);
2324 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2325 // If the typedef has an aligned attribute on it, it overrides any computed
2326 // alignment we have. This violates the GCC documentation (which says that
2327 // attribute(aligned) can only round up) but matches its implementation.
2328 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2329 Align = AttrAlign;
2330 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2331 } else {
2332 Align = Info.Align;
2333 AlignRequirement = Info.AlignRequirement;
2334 }
2335 Width = Info.Width;
2336 break;
2337 }
2338
2339 case Type::Elaborated:
2340 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2341
2342 case Type::Attributed:
2343 return getTypeInfo(
2344 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2345
2346 case Type::CountAttributed:
2347 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2348
2349 case Type::BTFTagAttributed:
2350 return getTypeInfo(
2351 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2352
2353 case Type::Atomic: {
2354 // Start with the base type information.
2355 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2356 Width = Info.Width;
2357 Align = Info.Align;
2358
2359 if (!Width) {
2360 // An otherwise zero-sized type should still generate an
2361 // atomic operation.
2362 Width = Target->getCharWidth();
2363 assert(Align);
2364 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2365 // If the size of the type doesn't exceed the platform's max
2366 // atomic promotion width, make the size and alignment more
2367 // favorable to atomic operations:
2368
2369 // Round the size up to a power of 2.
2370 Width = llvm::bit_ceil(Width);
2371
2372 // Set the alignment equal to the size.
2373 Align = static_cast<unsigned>(Width);
2374 }
2375 }
2376 break;
2377
2378 case Type::Pipe:
2379 Width = Target->getPointerWidth(LangAS::opencl_global);
2380 Align = Target->getPointerAlign(LangAS::opencl_global);
2381 break;
2382 }
2383
2384 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2385 return TypeInfo(Width, Align, AlignRequirement);
2386}
2387
2389 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2390 if (I != MemoizedUnadjustedAlign.end())
2391 return I->second;
2392
2393 unsigned UnadjustedAlign;
2394 if (const auto *RT = T->getAs<RecordType>()) {
2395 const RecordDecl *RD = RT->getDecl();
2396 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2397 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2398 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2399 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2400 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2401 } else {
2402 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2403 }
2404
2405 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2406 return UnadjustedAlign;
2407}
2408
2410 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2411 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2412 return SimdAlign;
2413}
2414
2415/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2417 return CharUnits::fromQuantity(BitSize / getCharWidth());
2418}
2419
2420/// toBits - Convert a size in characters to a size in characters.
2421int64_t ASTContext::toBits(CharUnits CharSize) const {
2422 return CharSize.getQuantity() * getCharWidth();
2423}
2424
2425/// getTypeSizeInChars - Return the size of the specified type, in characters.
2426/// This method does not work on incomplete types.
2428 return getTypeInfoInChars(T).Width;
2429}
2431 return getTypeInfoInChars(T).Width;
2432}
2433
2434/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2435/// characters. This method does not work on incomplete types.
2438}
2441}
2442
2443/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2444/// type, in characters, before alignment adjustments. This method does
2445/// not work on incomplete types.
2448}
2451}
2452
2453/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2454/// type for the current target in bits. This can be different than the ABI
2455/// alignment in cases where it is beneficial for performance or backwards
2456/// compatibility preserving to overalign a data type. (Note: despite the name,
2457/// the preferred alignment is ABI-impacting, and not an optimization.)
2459 TypeInfo TI = getTypeInfo(T);
2460 unsigned ABIAlign = TI.Align;
2461
2463
2464 // The preferred alignment of member pointers is that of a pointer.
2465 if (T->isMemberPointerType())
2466 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2467
2468 if (!Target->allowsLargerPreferedTypeAlignment())
2469 return ABIAlign;
2470
2471 if (const auto *RT = T->getAs<RecordType>()) {
2472 const RecordDecl *RD = RT->getDecl();
2473
2474 // When used as part of a typedef, or together with a 'packed' attribute,
2475 // the 'aligned' attribute can be used to decrease alignment. Note that the
2476 // 'packed' case is already taken into consideration when computing the
2477 // alignment, we only need to handle the typedef case here.
2479 RD->isInvalidDecl())
2480 return ABIAlign;
2481
2482 unsigned PreferredAlign = static_cast<unsigned>(
2483 toBits(getASTRecordLayout(RD).PreferredAlignment));
2484 assert(PreferredAlign >= ABIAlign &&
2485 "PreferredAlign should be at least as large as ABIAlign.");
2486 return PreferredAlign;
2487 }
2488
2489 // Double (and, for targets supporting AIX `power` alignment, long double) and
2490 // long long should be naturally aligned (despite requiring less alignment) if
2491 // possible.
2492 if (const auto *CT = T->getAs<ComplexType>())
2493 T = CT->getElementType().getTypePtr();
2494 if (const auto *ET = T->getAs<EnumType>())
2495 T = ET->getDecl()->getIntegerType().getTypePtr();
2496 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2497 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2498 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2499 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2500 Target->defaultsToAIXPowerAlignment()))
2501 // Don't increase the alignment if an alignment attribute was specified on a
2502 // typedef declaration.
2503 if (!TI.isAlignRequired())
2504 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2505
2506 return ABIAlign;
2507}
2508
2509/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2510/// for __attribute__((aligned)) on this target, to be used if no alignment
2511/// value is specified.
2514}
2515
2516/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2517/// to a global variable of the specified type.
2519 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2520 return std::max(getPreferredTypeAlign(T),
2521 getMinGlobalAlignOfVar(TypeSize, VD));
2522}
2523
2524/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2525/// should be given to a global variable of the specified type.
2527 const VarDecl *VD) const {
2529}
2530
2532 const VarDecl *VD) const {
2533 // Make the default handling as that of a non-weak definition in the
2534 // current translation unit.
2535 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2536 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2537}
2538
2540 CharUnits Offset = CharUnits::Zero();
2541 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2542 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2543 Offset += Layout->getBaseClassOffset(Base);
2544 Layout = &getASTRecordLayout(Base);
2545 }
2546 return Offset;
2547}
2548
2550 const ValueDecl *MPD = MP.getMemberPointerDecl();
2553 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2554 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2555 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2556 const CXXRecordDecl *Base = RD;
2557 const CXXRecordDecl *Derived = Path[I];
2558 if (DerivedMember)
2559 std::swap(Base, Derived);
2561 RD = Path[I];
2562 }
2563 if (DerivedMember)
2565 return ThisAdjustment;
2566}
2567
2568/// DeepCollectObjCIvars -
2569/// This routine first collects all declared, but not synthesized, ivars in
2570/// super class and then collects all ivars, including those synthesized for
2571/// current class. This routine is used for implementation of current class
2572/// when all ivars, declared and synthesized are known.
2574 bool leafClass,
2576 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2577 DeepCollectObjCIvars(SuperClass, false, Ivars);
2578 if (!leafClass) {
2579 llvm::append_range(Ivars, OI->ivars());
2580 } else {
2581 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2582 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2583 Iv= Iv->getNextIvar())
2584 Ivars.push_back(Iv);
2585 }
2586}
2587
2588/// CollectInheritedProtocols - Collect all protocols in current class and
2589/// those inherited by it.
2592 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2593 // We can use protocol_iterator here instead of
2594 // all_referenced_protocol_iterator since we are walking all categories.
2595 for (auto *Proto : OI->all_referenced_protocols()) {
2596 CollectInheritedProtocols(Proto, Protocols);
2597 }
2598
2599 // Categories of this Interface.
2600 for (const auto *Cat : OI->visible_categories())
2601 CollectInheritedProtocols(Cat, Protocols);
2602
2603 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2604 while (SD) {
2605 CollectInheritedProtocols(SD, Protocols);
2606 SD = SD->getSuperClass();
2607 }
2608 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2609 for (auto *Proto : OC->protocols()) {
2610 CollectInheritedProtocols(Proto, Protocols);
2611 }
2612 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2613 // Insert the protocol.
2614 if (!Protocols.insert(
2615 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2616 return;
2617
2618 for (auto *Proto : OP->protocols())
2619 CollectInheritedProtocols(Proto, Protocols);
2620 }
2621}
2622
2624 const RecordDecl *RD,
2625 bool CheckIfTriviallyCopyable) {
2626 assert(RD->isUnion() && "Must be union type");
2627 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2628
2629 for (const auto *Field : RD->fields()) {
2630 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2631 CheckIfTriviallyCopyable))
2632 return false;
2633 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2634 if (FieldSize != UnionSize)
2635 return false;
2636 }
2637 return !RD->field_empty();
2638}
2639
2640static int64_t getSubobjectOffset(const FieldDecl *Field,
2641 const ASTContext &Context,
2642 const clang::ASTRecordLayout & /*Layout*/) {
2643 return Context.getFieldOffset(Field);
2644}
2645
2646static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2647 const ASTContext &Context,
2648 const clang::ASTRecordLayout &Layout) {
2649 return Context.toBits(Layout.getBaseClassOffset(RD));
2650}
2651
2652static std::optional<int64_t>
2654 const RecordDecl *RD,
2655 bool CheckIfTriviallyCopyable);
2656
2657static std::optional<int64_t>
2658getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2659 bool CheckIfTriviallyCopyable) {
2660 if (Field->getType()->isRecordType()) {
2661 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2662 if (!RD->isUnion())
2663 return structHasUniqueObjectRepresentations(Context, RD,
2664 CheckIfTriviallyCopyable);
2665 }
2666
2667 // A _BitInt type may not be unique if it has padding bits
2668 // but if it is a bitfield the padding bits are not used.
2669 bool IsBitIntType = Field->getType()->isBitIntType();
2670 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2671 !Context.hasUniqueObjectRepresentations(Field->getType(),
2672 CheckIfTriviallyCopyable))
2673 return std::nullopt;
2674
2675 int64_t FieldSizeInBits =
2676 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2677 if (Field->isBitField()) {
2678 // If we have explicit padding bits, they don't contribute bits
2679 // to the actual object representation, so return 0.
2680 if (Field->isUnnamedBitField())
2681 return 0;
2682
2683 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2684 if (IsBitIntType) {
2685 if ((unsigned)BitfieldSize >
2686 cast<BitIntType>(Field->getType())->getNumBits())
2687 return std::nullopt;
2688 } else if (BitfieldSize > FieldSizeInBits) {
2689 return std::nullopt;
2690 }
2691 FieldSizeInBits = BitfieldSize;
2692 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2693 Field->getType(), CheckIfTriviallyCopyable)) {
2694 return std::nullopt;
2695 }
2696 return FieldSizeInBits;
2697}
2698
2699static std::optional<int64_t>
2701 bool CheckIfTriviallyCopyable) {
2702 return structHasUniqueObjectRepresentations(Context, RD,
2703 CheckIfTriviallyCopyable);
2704}
2705
2706template <typename RangeT>
2708 const RangeT &Subobjects, int64_t CurOffsetInBits,
2709 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2710 bool CheckIfTriviallyCopyable) {
2711 for (const auto *Subobject : Subobjects) {
2712 std::optional<int64_t> SizeInBits =
2713 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2714 if (!SizeInBits)
2715 return std::nullopt;
2716 if (*SizeInBits != 0) {
2717 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2718 if (Offset != CurOffsetInBits)
2719 return std::nullopt;
2720 CurOffsetInBits += *SizeInBits;
2721 }
2722 }
2723 return CurOffsetInBits;
2724}
2725
2726static std::optional<int64_t>
2728 const RecordDecl *RD,
2729 bool CheckIfTriviallyCopyable) {
2730 assert(!RD->isUnion() && "Must be struct/class type");
2731 const auto &Layout = Context.getASTRecordLayout(RD);
2732
2733 int64_t CurOffsetInBits = 0;
2734 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2735 if (ClassDecl->isDynamicClass())
2736 return std::nullopt;
2737
2739 for (const auto &Base : ClassDecl->bases()) {
2740 // Empty types can be inherited from, and non-empty types can potentially
2741 // have tail padding, so just make sure there isn't an error.
2742 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2743 }
2744
2745 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2746 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2747 });
2748
2749 std::optional<int64_t> OffsetAfterBases =
2751 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2752 if (!OffsetAfterBases)
2753 return std::nullopt;
2754 CurOffsetInBits = *OffsetAfterBases;
2755 }
2756
2757 std::optional<int64_t> OffsetAfterFields =
2759 RD->fields(), CurOffsetInBits, Context, Layout,
2760 CheckIfTriviallyCopyable);
2761 if (!OffsetAfterFields)
2762 return std::nullopt;
2763 CurOffsetInBits = *OffsetAfterFields;
2764
2765 return CurOffsetInBits;
2766}
2767
2769 QualType Ty, bool CheckIfTriviallyCopyable) const {
2770 // C++17 [meta.unary.prop]:
2771 // The predicate condition for a template specialization
2772 // has_unique_object_representations<T> shall be satisfied if and only if:
2773 // (9.1) - T is trivially copyable, and
2774 // (9.2) - any two objects of type T with the same value have the same
2775 // object representation, where:
2776 // - two objects of array or non-union class type are considered to have
2777 // the same value if their respective sequences of direct subobjects
2778 // have the same values, and
2779 // - two objects of union type are considered to have the same value if
2780 // they have the same active member and the corresponding members have
2781 // the same value.
2782 // The set of scalar types for which this condition holds is
2783 // implementation-defined. [ Note: If a type has padding bits, the condition
2784 // does not hold; otherwise, the condition holds true for unsigned integral
2785 // types. -- end note ]
2786 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2787
2788 // Arrays are unique only if their element type is unique.
2789 if (Ty->isArrayType())
2791 CheckIfTriviallyCopyable);
2792
2793 // (9.1) - T is trivially copyable...
2794 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2795 return false;
2796
2797 // All integrals and enums are unique.
2798 if (Ty->isIntegralOrEnumerationType()) {
2799 // Except _BitInt types that have padding bits.
2800 if (const auto *BIT = Ty->getAs<BitIntType>())
2801 return getTypeSize(BIT) == BIT->getNumBits();
2802
2803 return true;
2804 }
2805
2806 // All other pointers are unique.
2807 if (Ty->isPointerType())
2808 return true;
2809
2810 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2811 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2812
2813 if (Ty->isRecordType()) {
2814 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2815
2816 if (Record->isInvalidDecl())
2817 return false;
2818
2819 if (Record->isUnion())
2821 CheckIfTriviallyCopyable);
2822
2823 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2824 *this, Record, CheckIfTriviallyCopyable);
2825
2826 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2827 }
2828
2829 // FIXME: More cases to handle here (list by rsmith):
2830 // vectors (careful about, eg, vector of 3 foo)
2831 // _Complex int and friends
2832 // _Atomic T
2833 // Obj-C block pointers
2834 // Obj-C object pointers
2835 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2836 // clk_event_t, queue_t, reserve_id_t)
2837 // There're also Obj-C class types and the Obj-C selector type, but I think it
2838 // makes sense for those to return false here.
2839
2840 return false;
2841}
2842
2844 unsigned count = 0;
2845 // Count ivars declared in class extension.
2846 for (const auto *Ext : OI->known_extensions())
2847 count += Ext->ivar_size();
2848
2849 // Count ivar defined in this class's implementation. This
2850 // includes synthesized ivars.
2851 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2852 count += ImplDecl->ivar_size();
2853
2854 return count;
2855}
2856
2858 if (!E)
2859 return false;
2860
2861 // nullptr_t is always treated as null.
2862 if (E->getType()->isNullPtrType()) return true;
2863
2864 if (E->getType()->isAnyPointerType() &&
2867 return true;
2868
2869 // Unfortunately, __null has type 'int'.
2870 if (isa<GNUNullExpr>(E)) return true;
2871
2872 return false;
2873}
2874
2875/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2876/// exists.
2878 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2879 I = ObjCImpls.find(D);
2880 if (I != ObjCImpls.end())
2881 return cast<ObjCImplementationDecl>(I->second);
2882 return nullptr;
2883}
2884
2885/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2886/// exists.
2888 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2889 I = ObjCImpls.find(D);
2890 if (I != ObjCImpls.end())
2891 return cast<ObjCCategoryImplDecl>(I->second);
2892 return nullptr;
2893}
2894
2895/// Set the implementation of ObjCInterfaceDecl.
2897 ObjCImplementationDecl *ImplD) {
2898 assert(IFaceD && ImplD && "Passed null params");
2899 ObjCImpls[IFaceD] = ImplD;
2900}
2901
2902/// Set the implementation of ObjCCategoryDecl.
2904 ObjCCategoryImplDecl *ImplD) {
2905 assert(CatD && ImplD && "Passed null params");
2906 ObjCImpls[CatD] = ImplD;
2907}
2908
2909const ObjCMethodDecl *
2911 return ObjCMethodRedecls.lookup(MD);
2912}
2913
2915 const ObjCMethodDecl *Redecl) {
2916 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2917 ObjCMethodRedecls[MD] = Redecl;
2918}
2919
2921 const NamedDecl *ND) const {
2922 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2923 return ID;
2924 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2925 return CD->getClassInterface();
2926 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2927 return IMD->getClassInterface();
2928
2929 return nullptr;
2930}
2931
2932/// Get the copy initialization expression of VarDecl, or nullptr if
2933/// none exists.
2935 assert(VD && "Passed null params");
2936 assert(VD->hasAttr<BlocksAttr>() &&
2937 "getBlockVarCopyInits - not __block var");
2938 auto I = BlockVarCopyInits.find(VD);
2939 if (I != BlockVarCopyInits.end())
2940 return I->second;
2941 return {nullptr, false};
2942}
2943
2944/// Set the copy initialization expression of a block var decl.
2946 bool CanThrow) {
2947 assert(VD && CopyExpr && "Passed null params");
2948 assert(VD->hasAttr<BlocksAttr>() &&
2949 "setBlockVarCopyInits - not __block var");
2950 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2951}
2952
2954 unsigned DataSize) const {
2955 if (!DataSize)
2957 else
2958 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2959 "incorrect data size provided to CreateTypeSourceInfo!");
2960
2961 auto *TInfo =
2962 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2963 new (TInfo) TypeSourceInfo(T, DataSize);
2964 return TInfo;
2965}
2966
2968 SourceLocation L) const {
2970 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2971 return DI;
2972}
2973
2974const ASTRecordLayout &
2976 return getObjCLayout(D, nullptr);
2977}
2978
2979const ASTRecordLayout &
2981 const ObjCImplementationDecl *D) const {
2982 return getObjCLayout(D->getClassInterface(), D);
2983}
2984
2987 bool &AnyNonCanonArgs) {
2988 SmallVector<TemplateArgument, 16> CanonArgs(Args);
2989 for (auto &Arg : CanonArgs) {
2990 TemplateArgument OrigArg = Arg;
2991 Arg = C.getCanonicalTemplateArgument(Arg);
2992 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
2993 }
2994 return CanonArgs;
2995}
2996
2997//===----------------------------------------------------------------------===//
2998// Type creation/memoization methods
2999//===----------------------------------------------------------------------===//
3000
3002ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3003 unsigned fastQuals = quals.getFastQualifiers();
3004 quals.removeFastQualifiers();
3005
3006 // Check if we've already instantiated this type.
3007 llvm::FoldingSetNodeID ID;
3008 ExtQuals::Profile(ID, baseType, quals);
3009 void *insertPos = nullptr;
3010 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3011 assert(eq->getQualifiers() == quals);
3012 return QualType(eq, fastQuals);
3013 }
3014
3015 // If the base type is not canonical, make the appropriate canonical type.
3016 QualType canon;
3017 if (!baseType->isCanonicalUnqualified()) {
3018 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3019 canonSplit.Quals.addConsistentQualifiers(quals);
3020 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3021
3022 // Re-find the insert position.
3023 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3024 }
3025
3026 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3027 ExtQualNodes.InsertNode(eq, insertPos);
3028 return QualType(eq, fastQuals);
3029}
3030
3032 LangAS AddressSpace) const {
3033 QualType CanT = getCanonicalType(T);
3034 if (CanT.getAddressSpace() == AddressSpace)
3035 return T;
3036
3037 // If we are composing extended qualifiers together, merge together
3038 // into one ExtQuals node.
3039 QualifierCollector Quals;
3040 const Type *TypeNode = Quals.strip(T);
3041
3042 // If this type already has an address space specified, it cannot get
3043 // another one.
3044 assert(!Quals.hasAddressSpace() &&
3045 "Type cannot be in multiple addr spaces!");
3046 Quals.addAddressSpace(AddressSpace);
3047
3048 return getExtQualType(TypeNode, Quals);
3049}
3050
3052 // If the type is not qualified with an address space, just return it
3053 // immediately.
3054 if (!T.hasAddressSpace())
3055 return T;
3056
3057 // If we are composing extended qualifiers together, merge together
3058 // into one ExtQuals node.
3059 QualifierCollector Quals;
3060 const Type *TypeNode;
3061
3062 while (T.hasAddressSpace()) {
3063 TypeNode = Quals.strip(T);
3064
3065 // If the type no longer has an address space after stripping qualifiers,
3066 // jump out.
3067 if (!QualType(TypeNode, 0).hasAddressSpace())
3068 break;
3069
3070 // There might be sugar in the way. Strip it and try again.
3071 T = T.getSingleStepDesugaredType(*this);
3072 }
3073
3074 Quals.removeAddressSpace();
3075
3076 // Removal of the address space can mean there are no longer any
3077 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3078 // or required.
3079 if (Quals.hasNonFastQualifiers())
3080 return getExtQualType(TypeNode, Quals);
3081 else
3082 return QualType(TypeNode, Quals.getFastQualifiers());
3083}
3084
3086 Qualifiers::GC GCAttr) const {
3087 QualType CanT = getCanonicalType(T);
3088 if (CanT.getObjCGCAttr() == GCAttr)
3089 return T;
3090
3091 if (const auto *ptr = T->getAs<PointerType>()) {
3092 QualType Pointee = ptr->getPointeeType();
3093 if (Pointee->isAnyPointerType()) {
3094 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3095 return getPointerType(ResultType);
3096 }
3097 }
3098
3099 // If we are composing extended qualifiers together, merge together
3100 // into one ExtQuals node.
3101 QualifierCollector Quals;
3102 const Type *TypeNode = Quals.strip(T);
3103
3104 // If this type already has an ObjCGC specified, it cannot get
3105 // another one.
3106 assert(!Quals.hasObjCGCAttr() &&
3107 "Type cannot have multiple ObjCGCs!");
3108 Quals.addObjCGCAttr(GCAttr);
3109
3110 return getExtQualType(TypeNode, Quals);
3111}
3112
3114 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3115 QualType Pointee = Ptr->getPointeeType();
3116 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3117 return getPointerType(removeAddrSpaceQualType(Pointee));
3118 }
3119 }
3120 return T;
3121}
3122
3124 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3125 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3126 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3127
3128 llvm::FoldingSetNodeID ID;
3129 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3130
3131 void *InsertPos = nullptr;
3132 CountAttributedType *CATy =
3133 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3134 if (CATy)
3135 return QualType(CATy, 0);
3136
3137 QualType CanonTy = getCanonicalType(WrappedTy);
3138 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3139 DependentDecls.size());
3141 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3142 OrNull, DependentDecls);
3143 Types.push_back(CATy);
3144 CountAttributedTypes.InsertNode(CATy, InsertPos);
3145
3146 return QualType(CATy, 0);
3147}
3148
3150 FunctionType::ExtInfo Info) {
3151 if (T->getExtInfo() == Info)
3152 return T;
3153
3155 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3156 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3157 } else {
3158 const auto *FPT = cast<FunctionProtoType>(T);
3159 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3160 EPI.ExtInfo = Info;
3161 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3162 }
3163
3164 return cast<FunctionType>(Result.getTypePtr());
3165}
3166
3168 QualType ResultType) {
3169 FD = FD->getMostRecentDecl();
3170 while (true) {
3171 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3172 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3173 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3174 if (FunctionDecl *Next = FD->getPreviousDecl())
3175 FD = Next;
3176 else
3177 break;
3178 }
3180 L->DeducedReturnType(FD, ResultType);
3181}
3182
3183/// Get a function type and produce the equivalent function type with the
3184/// specified exception specification. Type sugar that can be present on a
3185/// declaration of a function with an exception specification is permitted
3186/// and preserved. Other type sugar (for instance, typedefs) is not.
3188 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3189 // Might have some parens.
3190 if (const auto *PT = dyn_cast<ParenType>(Orig))
3191 return getParenType(
3192 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3193
3194 // Might be wrapped in a macro qualified type.
3195 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3196 return getMacroQualifiedType(
3197 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3198 MQT->getMacroIdentifier());
3199
3200 // Might have a calling-convention attribute.
3201 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3202 return getAttributedType(
3203 AT->getAttrKind(),
3204 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3205 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3206
3207 // Anything else must be a function type. Rebuild it with the new exception
3208 // specification.
3209 const auto *Proto = Orig->castAs<FunctionProtoType>();
3210 return getFunctionType(
3211 Proto->getReturnType(), Proto->getParamTypes(),
3212 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3213}
3214
3216 QualType U) const {
3217 return hasSameType(T, U) ||
3218 (getLangOpts().CPlusPlus17 &&
3221}
3222
3224 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3225 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3226 SmallVector<QualType, 16> Args(Proto->param_types().size());
3227 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3228 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3229 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3230 }
3231
3232 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3233 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3234 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3235 }
3236
3237 return T;
3238}
3239
3241 return hasSameType(T, U) ||
3244}
3245
3248 bool AsWritten) {
3249 // Update the type.
3250 QualType Updated =
3252 FD->setType(Updated);
3253
3254 if (!AsWritten)
3255 return;
3256
3257 // Update the type in the type source information too.
3258 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3259 // If the type and the type-as-written differ, we may need to update
3260 // the type-as-written too.
3261 if (TSInfo->getType() != FD->getType())
3262 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3263
3264 // FIXME: When we get proper type location information for exceptions,
3265 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3266 // up the TypeSourceInfo;
3267 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3268 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3269 "TypeLoc size mismatch from updating exception specification");
3270 TSInfo->overrideType(Updated);
3271 }
3272}
3273
3274/// getComplexType - Return the uniqued reference to the type for a complex
3275/// number with the specified element type.
3277 // Unique pointers, to guarantee there is only one pointer of a particular
3278 // structure.
3279 llvm::FoldingSetNodeID ID;
3281
3282 void *InsertPos = nullptr;
3283 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3284 return QualType(CT, 0);
3285
3286 // If the pointee type isn't canonical, this won't be a canonical type either,
3287 // so fill in the canonical type field.
3288 QualType Canonical;
3289 if (!T.isCanonical()) {
3290 Canonical = getComplexType(getCanonicalType(T));
3291
3292 // Get the new insert position for the node we care about.
3293 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3295 }
3296 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3297 Types.push_back(New);
3298 ComplexTypes.InsertNode(New, InsertPos);
3299 return QualType(New, 0);
3300}
3301
3302/// getPointerType - Return the uniqued reference to the type for a pointer to
3303/// the specified type.
3305 // Unique pointers, to guarantee there is only one pointer of a particular
3306 // structure.
3307 llvm::FoldingSetNodeID ID;
3309
3310 void *InsertPos = nullptr;
3311 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3312 return QualType(PT, 0);
3313
3314 // If the pointee type isn't canonical, this won't be a canonical type either,
3315 // so fill in the canonical type field.
3316 QualType Canonical;
3317 if (!T.isCanonical()) {
3318 Canonical = getPointerType(getCanonicalType(T));
3319
3320 // Get the new insert position for the node we care about.
3321 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3322 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3323 }
3324 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3325 Types.push_back(New);
3326 PointerTypes.InsertNode(New, InsertPos);
3327 return QualType(New, 0);
3328}
3329
3331 llvm::FoldingSetNodeID ID;
3332 AdjustedType::Profile(ID, Orig, New);
3333 void *InsertPos = nullptr;
3334 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3335 if (AT)
3336 return QualType(AT, 0);
3337
3338 QualType Canonical = getCanonicalType(New);
3339
3340 // Get the new insert position for the node we care about.
3341 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3342 assert(!AT && "Shouldn't be in the map!");
3343
3344 AT = new (*this, alignof(AdjustedType))
3345 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3346 Types.push_back(AT);
3347 AdjustedTypes.InsertNode(AT, InsertPos);
3348 return QualType(AT, 0);
3349}
3350
3352 llvm::FoldingSetNodeID ID;
3353 AdjustedType::Profile(ID, Orig, Decayed);
3354 void *InsertPos = nullptr;
3355 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3356 if (AT)
3357 return QualType(AT, 0);
3358
3359 QualType Canonical = getCanonicalType(Decayed);
3360
3361 // Get the new insert position for the node we care about.
3362 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3363 assert(!AT && "Shouldn't be in the map!");
3364
3365 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3366 Types.push_back(AT);
3367 AdjustedTypes.InsertNode(AT, InsertPos);
3368 return QualType(AT, 0);
3369}
3370
3372 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3373
3374 QualType Decayed;
3375
3376 // C99 6.7.5.3p7:
3377 // A declaration of a parameter as "array of type" shall be
3378 // adjusted to "qualified pointer to type", where the type
3379 // qualifiers (if any) are those specified within the [ and ] of
3380 // the array type derivation.
3381 if (T->isArrayType())
3382 Decayed = getArrayDecayedType(T);
3383
3384 // C99 6.7.5.3p8:
3385 // A declaration of a parameter as "function returning type"
3386 // shall be adjusted to "pointer to function returning type", as
3387 // in 6.3.2.1.
3388 if (T->isFunctionType())
3389 Decayed = getPointerType(T);
3390
3391 return getDecayedType(T, Decayed);
3392}
3393
3395 if (Ty->isArrayParameterType())
3396 return Ty;
3397 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3398 const auto *ATy = cast<ConstantArrayType>(Ty);
3399 llvm::FoldingSetNodeID ID;
3400 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3401 ATy->getSizeExpr(), ATy->getSizeModifier(),
3402 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3403 void *InsertPos = nullptr;
3404 ArrayParameterType *AT =
3405 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3406 if (AT)
3407 return QualType(AT, 0);
3408
3409 QualType Canonical;
3410 if (!Ty.isCanonical()) {
3411 Canonical = getArrayParameterType(getCanonicalType(Ty));
3412
3413 // Get the new insert position for the node we care about.
3414 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 assert(!AT && "Shouldn't be in the map!");
3416 }
3417
3418 AT = new (*this, alignof(ArrayParameterType))
3419 ArrayParameterType(ATy, Canonical);
3420 Types.push_back(AT);
3421 ArrayParameterTypes.InsertNode(AT, InsertPos);
3422 return QualType(AT, 0);
3423}
3424
3425/// getBlockPointerType - Return the uniqued reference to the type for
3426/// a pointer to the specified block.
3428 assert(T->isFunctionType() && "block of function types only");
3429 // Unique pointers, to guarantee there is only one block of a particular
3430 // structure.
3431 llvm::FoldingSetNodeID ID;
3433
3434 void *InsertPos = nullptr;
3435 if (BlockPointerType *PT =
3436 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3437 return QualType(PT, 0);
3438
3439 // If the block pointee type isn't canonical, this won't be a canonical
3440 // type either so fill in the canonical type field.
3441 QualType Canonical;
3442 if (!T.isCanonical()) {
3444
3445 // Get the new insert position for the node we care about.
3446 BlockPointerType *NewIP =
3447 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3448 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3449 }
3450 auto *New =
3451 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3452 Types.push_back(New);
3453 BlockPointerTypes.InsertNode(New, InsertPos);
3454 return QualType(New, 0);
3455}
3456
3457/// getLValueReferenceType - Return the uniqued reference to the type for an
3458/// lvalue reference to the specified type.
3460ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3461 assert((!T->isPlaceholderType() ||
3462 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3463 "Unresolved placeholder type");
3464
3465 // Unique pointers, to guarantee there is only one pointer of a particular
3466 // structure.
3467 llvm::FoldingSetNodeID ID;
3468 ReferenceType::Profile(ID, T, SpelledAsLValue);
3469
3470 void *InsertPos = nullptr;
3471 if (LValueReferenceType *RT =
3472 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3473 return QualType(RT, 0);
3474
3475 const auto *InnerRef = T->getAs<ReferenceType>();
3476
3477 // If the referencee type isn't canonical, this won't be a canonical type
3478 // either, so fill in the canonical type field.
3479 QualType Canonical;
3480 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3481 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3482 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3483
3484 // Get the new insert position for the node we care about.
3485 LValueReferenceType *NewIP =
3486 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3487 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3488 }
3489
3490 auto *New = new (*this, alignof(LValueReferenceType))
3491 LValueReferenceType(T, Canonical, SpelledAsLValue);
3492 Types.push_back(New);
3493 LValueReferenceTypes.InsertNode(New, InsertPos);
3494
3495 return QualType(New, 0);
3496}
3497
3498/// getRValueReferenceType - Return the uniqued reference to the type for an
3499/// rvalue reference to the specified type.
3501 assert((!T->isPlaceholderType() ||
3502 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3503 "Unresolved placeholder type");
3504
3505 // Unique pointers, to guarantee there is only one pointer of a particular
3506 // structure.
3507 llvm::FoldingSetNodeID ID;
3508 ReferenceType::Profile(ID, T, false);
3509
3510 void *InsertPos = nullptr;
3511 if (RValueReferenceType *RT =
3512 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3513 return QualType(RT, 0);
3514
3515 const auto *InnerRef = T->getAs<ReferenceType>();
3516
3517 // If the referencee type isn't canonical, this won't be a canonical type
3518 // either, so fill in the canonical type field.
3519 QualType Canonical;
3520 if (InnerRef || !T.isCanonical()) {
3521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3522 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3523
3524 // Get the new insert position for the node we care about.
3525 RValueReferenceType *NewIP =
3526 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3527 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3528 }
3529
3530 auto *New = new (*this, alignof(RValueReferenceType))
3531 RValueReferenceType(T, Canonical);
3532 Types.push_back(New);
3533 RValueReferenceTypes.InsertNode(New, InsertPos);
3534 return QualType(New, 0);
3535}
3536
3537/// getMemberPointerType - Return the uniqued reference to the type for a
3538/// member pointer to the specified type, in the specified class.
3540 // Unique pointers, to guarantee there is only one pointer of a particular
3541 // structure.
3542 llvm::FoldingSetNodeID ID;
3543 MemberPointerType::Profile(ID, T, Cls);
3544
3545 void *InsertPos = nullptr;
3546 if (MemberPointerType *PT =
3547 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3548 return QualType(PT, 0);
3549
3550 // If the pointee or class type isn't canonical, this won't be a canonical
3551 // type either, so fill in the canonical type field.
3552 QualType Canonical;
3553 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3555
3556 // Get the new insert position for the node we care about.
3557 MemberPointerType *NewIP =
3558 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3559 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3560 }
3561 auto *New = new (*this, alignof(MemberPointerType))
3562 MemberPointerType(T, Cls, Canonical);
3563 Types.push_back(New);
3564 MemberPointerTypes.InsertNode(New, InsertPos);
3565 return QualType(New, 0);
3566}
3567
3568/// getConstantArrayType - Return the unique reference to the type for an
3569/// array of the specified element type.
3571 const llvm::APInt &ArySizeIn,
3572 const Expr *SizeExpr,
3574 unsigned IndexTypeQuals) const {
3575 assert((EltTy->isDependentType() ||
3576 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3577 "Constant array of VLAs is illegal!");
3578
3579 // We only need the size as part of the type if it's instantiation-dependent.
3580 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3581 SizeExpr = nullptr;
3582
3583 // Convert the array size into a canonical width matching the pointer size for
3584 // the target.
3585 llvm::APInt ArySize(ArySizeIn);
3586 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3587
3588 llvm::FoldingSetNodeID ID;
3589 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
3590 ASM, IndexTypeQuals);
3591
3592 void *InsertPos = nullptr;
3593 if (ConstantArrayType *ATP =
3594 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3595 return QualType(ATP, 0);
3596
3597 // If the element type isn't canonical or has qualifiers, or the array bound
3598 // is instantiation-dependent, this won't be a canonical type either, so fill
3599 // in the canonical type field.
3600 QualType Canon;
3601 // FIXME: Check below should look for qualifiers behind sugar.
3602 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3603 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3604 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3605 ASM, IndexTypeQuals);
3606 Canon = getQualifiedType(Canon, canonSplit.Quals);
3607
3608 // Get the new insert position for the node we care about.
3609 ConstantArrayType *NewIP =
3610 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3611 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3612 }
3613
3614 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
3615 ASM, IndexTypeQuals);
3616 ConstantArrayTypes.InsertNode(New, InsertPos);
3617 Types.push_back(New);
3618 return QualType(New, 0);
3619}
3620
3621/// getVariableArrayDecayedType - Turns the given type, which may be
3622/// variably-modified, into the corresponding type with all the known
3623/// sizes replaced with [*].
3625 // Vastly most common case.
3626 if (!type->isVariablyModifiedType()) return type;
3627
3628 QualType result;
3629
3630 SplitQualType split = type.getSplitDesugaredType();
3631 const Type *ty = split.Ty;
3632 switch (ty->getTypeClass()) {
3633#define TYPE(Class, Base)
3634#define ABSTRACT_TYPE(Class, Base)
3635#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3636#include "clang/AST/TypeNodes.inc"
3637 llvm_unreachable("didn't desugar past all non-canonical types?");
3638
3639 // These types should never be variably-modified.
3640 case Type::Builtin:
3641 case Type::Complex:
3642 case Type::Vector:
3643 case Type::DependentVector:
3644 case Type::ExtVector:
3645 case Type::DependentSizedExtVector:
3646 case Type::ConstantMatrix:
3647 case Type::DependentSizedMatrix:
3648 case Type::DependentAddressSpace:
3649 case Type::ObjCObject:
3650 case Type::ObjCInterface:
3651 case Type::ObjCObjectPointer:
3652 case Type::Record:
3653 case Type::Enum:
3654 case Type::UnresolvedUsing:
3655 case Type::TypeOfExpr:
3656 case Type::TypeOf:
3657 case Type::Decltype:
3658 case Type::UnaryTransform:
3659 case Type::DependentName:
3660 case Type::InjectedClassName:
3661 case Type::TemplateSpecialization:
3662 case Type::DependentTemplateSpecialization:
3663 case Type::TemplateTypeParm:
3664 case Type::SubstTemplateTypeParmPack:
3665 case Type::Auto:
3666 case Type::DeducedTemplateSpecialization:
3667 case Type::PackExpansion:
3668 case Type::PackIndexing:
3669 case Type::BitInt:
3670 case Type::DependentBitInt:
3671 case Type::ArrayParameter:
3672 llvm_unreachable("type should never be variably-modified");
3673
3674 // These types can be variably-modified but should never need to
3675 // further decay.
3676 case Type::FunctionNoProto:
3677 case Type::FunctionProto:
3678 case Type::BlockPointer:
3679 case Type::MemberPointer:
3680 case Type::Pipe:
3681 return type;
3682
3683 // These types can be variably-modified. All these modifications
3684 // preserve structure except as noted by comments.
3685 // TODO: if we ever care about optimizing VLAs, there are no-op
3686 // optimizations available here.
3687 case Type::Pointer:
3689 cast<PointerType>(ty)->getPointeeType()));
3690 break;
3691
3692 case Type::LValueReference: {
3693 const auto *lv = cast<LValueReferenceType>(ty);
3694 result = getLValueReferenceType(
3695 getVariableArrayDecayedType(lv->getPointeeType()),
3696 lv->isSpelledAsLValue());
3697 break;
3698 }
3699
3700 case Type::RValueReference: {
3701 const auto *lv = cast<RValueReferenceType>(ty);
3702 result = getRValueReferenceType(
3703 getVariableArrayDecayedType(lv->getPointeeType()));
3704 break;
3705 }
3706
3707 case Type::Atomic: {
3708 const auto *at = cast<AtomicType>(ty);
3709 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3710 break;
3711 }
3712
3713 case Type::ConstantArray: {
3714 const auto *cat = cast<ConstantArrayType>(ty);
3715 result = getConstantArrayType(
3716 getVariableArrayDecayedType(cat->getElementType()),
3717 cat->getSize(),
3718 cat->getSizeExpr(),
3719 cat->getSizeModifier(),
3720 cat->getIndexTypeCVRQualifiers());
3721 break;
3722 }
3723
3724 case Type::DependentSizedArray: {
3725 const auto *dat = cast<DependentSizedArrayType>(ty);
3727 getVariableArrayDecayedType(dat->getElementType()),
3728 dat->getSizeExpr(),
3729 dat->getSizeModifier(),
3730 dat->getIndexTypeCVRQualifiers(),
3731 dat->getBracketsRange());
3732 break;
3733 }
3734
3735 // Turn incomplete types into [*] types.
3736 case Type::IncompleteArray: {
3737 const auto *iat = cast<IncompleteArrayType>(ty);
3738 result =
3740 /*size*/ nullptr, ArraySizeModifier::Normal,
3741 iat->getIndexTypeCVRQualifiers(), SourceRange());
3742 break;
3743 }
3744
3745 // Turn VLA types into [*] types.
3746 case Type::VariableArray: {
3747 const auto *vat = cast<VariableArrayType>(ty);
3748 result = getVariableArrayType(
3749 getVariableArrayDecayedType(vat->getElementType()),
3750 /*size*/ nullptr, ArraySizeModifier::Star,
3751 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
3752 break;
3753 }
3754 }
3755
3756 // Apply the top-level qualifiers from the original.
3757 return getQualifiedType(result, split.Quals);
3758}
3759
3760/// getVariableArrayType - Returns a non-unique reference to the type for a
3761/// variable array of the specified element type.
3764 unsigned IndexTypeQuals,
3765 SourceRange Brackets) const {
3766 // Since we don't unique expressions, it isn't possible to unique VLA's
3767 // that have an expression provided for their size.
3768 QualType Canon;
3769
3770 // Be sure to pull qualifiers off the element type.
3771 // FIXME: Check below should look for qualifiers behind sugar.
3772 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3773 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3774 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3775 IndexTypeQuals, Brackets);
3776 Canon = getQualifiedType(Canon, canonSplit.Quals);
3777 }
3778
3779 auto *New = new (*this, alignof(VariableArrayType))
3780 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3781
3782 VariableArrayTypes.push_back(New);
3783 Types.push_back(New);
3784 return QualType(New, 0);
3785}
3786
3787/// getDependentSizedArrayType - Returns a non-unique reference to
3788/// the type for a dependently-sized array of the specified element
3789/// type.
3791 Expr *numElements,
3793 unsigned elementTypeQuals,
3794 SourceRange brackets) const {
3795 assert((!numElements || numElements->isTypeDependent() ||
3796 numElements->isValueDependent()) &&
3797 "Size must be type- or value-dependent!");
3798
3799 SplitQualType canonElementType = getCanonicalType(elementType).split();
3800
3801 void *insertPos = nullptr;
3802 llvm::FoldingSetNodeID ID;
3804 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
3805 ASM, elementTypeQuals, numElements);
3806
3807 // Look for an existing type with these properties.
3808 DependentSizedArrayType *canonTy =
3809 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3810
3811 // Dependently-sized array types that do not have a specified number
3812 // of elements will have their sizes deduced from a dependent
3813 // initializer.
3814 if (!numElements) {
3815 if (canonTy)
3816 return QualType(canonTy, 0);
3817
3818 auto *newType = new (*this, alignof(DependentSizedArrayType))
3819 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
3820 elementTypeQuals, brackets);
3821 DependentSizedArrayTypes.InsertNode(newType, insertPos);
3822 Types.push_back(newType);
3823 return QualType(newType, 0);
3824 }
3825
3826 // If we don't have one, build one.
3827 if (!canonTy) {
3828 canonTy = new (*this, alignof(DependentSizedArrayType))
3829 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
3830 numElements, ASM, elementTypeQuals, brackets);
3831 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3832 Types.push_back(canonTy);
3833 }
3834
3835 // Apply qualifiers from the element type to the array.
3836 QualType canon = getQualifiedType(QualType(canonTy,0),
3837 canonElementType.Quals);
3838
3839 // If we didn't need extra canonicalization for the element type or the size
3840 // expression, then just use that as our result.
3841 if (QualType(canonElementType.Ty, 0) == elementType &&
3842 canonTy->getSizeExpr() == numElements)
3843 return canon;
3844
3845 // Otherwise, we need to build a type which follows the spelling
3846 // of the element type.
3847 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
3848 DependentSizedArrayType(elementType, canon, numElements, ASM,
3849 elementTypeQuals, brackets);
3850 Types.push_back(sugaredType);
3851 return QualType(sugaredType, 0);
3852}
3853
3856 unsigned elementTypeQuals) const {
3857 llvm::FoldingSetNodeID ID;
3858 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3859
3860 void *insertPos = nullptr;
3861 if (IncompleteArrayType *iat =
3862 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3863 return QualType(iat, 0);
3864
3865 // If the element type isn't canonical, this won't be a canonical type
3866 // either, so fill in the canonical type field. We also have to pull
3867 // qualifiers off the element type.
3868 QualType canon;
3869
3870 // FIXME: Check below should look for qualifiers behind sugar.
3871 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3872 SplitQualType canonSplit = getCanonicalType(elementType).split();
3873 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3874 ASM, elementTypeQuals);
3875 canon = getQualifiedType(canon, canonSplit.Quals);
3876
3877 // Get the new insert position for the node we care about.
3878 IncompleteArrayType *existing =
3879 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3880 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3881 }
3882
3883 auto *newType = new (*this, alignof(IncompleteArrayType))
3884 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3885
3886 IncompleteArrayTypes.InsertNode(newType, insertPos);
3887 Types.push_back(newType);
3888 return QualType(newType, 0);
3889}
3890
3893#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
3894 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3895 NUMVECTORS};
3896
3897#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
3898 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3899
3900 switch (Ty->getKind()) {
3901 default:
3902 llvm_unreachable("Unsupported builtin vector type");
3903 case BuiltinType::SveInt8:
3904 return SVE_INT_ELTTY(8, 16, true, 1);
3905 case BuiltinType::SveUint8:
3906 return SVE_INT_ELTTY(8, 16, false, 1);
3907 case BuiltinType::SveInt8x2:
3908 return SVE_INT_ELTTY(8, 16, true, 2);
3909 case BuiltinType::SveUint8x2:
3910 return SVE_INT_ELTTY(8, 16, false, 2);
3911 case BuiltinType::SveInt8x3:
3912 return SVE_INT_ELTTY(8, 16, true, 3);
3913 case BuiltinType::SveUint8x3:
3914 return SVE_INT_ELTTY(8, 16, false, 3);
3915 case BuiltinType::SveInt8x4:
3916 return SVE_INT_ELTTY(8, 16, true, 4);
3917 case BuiltinType::SveUint8x4:
3918 return SVE_INT_ELTTY(8, 16, false, 4);
3919 case BuiltinType::SveInt16:
3920 return SVE_INT_ELTTY(16, 8, true, 1);
3921 case BuiltinType::SveUint16:
3922 return SVE_INT_ELTTY(16, 8, false, 1);
3923 case BuiltinType::SveInt16x2:
3924 return SVE_INT_ELTTY(16, 8, true, 2);
3925 case BuiltinType::SveUint16x2:
3926 return SVE_INT_ELTTY(16, 8, false, 2);
3927 case BuiltinType::SveInt16x3:
3928 return SVE_INT_ELTTY(16, 8, true, 3);
3929 case BuiltinType::SveUint16x3:
3930 return SVE_INT_ELTTY(16, 8, false, 3);
3931 case BuiltinType::SveInt16x4:
3932 return SVE_INT_ELTTY(16, 8, true, 4);
3933 case BuiltinType::SveUint16x4:
3934 return SVE_INT_ELTTY(16, 8, false, 4);
3935 case BuiltinType::SveInt32:
3936 return SVE_INT_ELTTY(32, 4, true, 1);
3937 case BuiltinType::SveUint32:
3938 return SVE_INT_ELTTY(32, 4, false, 1);
3939 case BuiltinType::SveInt32x2:
3940 return SVE_INT_ELTTY(32, 4, true, 2);
3941 case BuiltinType::SveUint32x2:
3942 return SVE_INT_ELTTY(32, 4, false, 2);
3943 case BuiltinType::SveInt32x3:
3944 return SVE_INT_ELTTY(32, 4, true, 3);
3945 case BuiltinType::SveUint32x3:
3946 return SVE_INT_ELTTY(32, 4, false, 3);
3947 case BuiltinType::SveInt32x4:
3948 return SVE_INT_ELTTY(32, 4, true, 4);
3949 case BuiltinType::SveUint32x4:
3950 return SVE_INT_ELTTY(32, 4, false, 4);
3951 case BuiltinType::SveInt64:
3952 return SVE_INT_ELTTY(64, 2, true, 1);
3953 case BuiltinType::SveUint64:
3954 return SVE_INT_ELTTY(64, 2, false, 1);
3955 case BuiltinType::SveInt64x2:
3956 return SVE_INT_ELTTY(64, 2, true, 2);
3957 case BuiltinType::SveUint64x2:
3958 return SVE_INT_ELTTY(64, 2, false, 2);
3959 case BuiltinType::SveInt64x3:
3960 return SVE_INT_ELTTY(64, 2, true, 3);
3961 case BuiltinType::SveUint64x3:
3962 return SVE_INT_ELTTY(64, 2, false, 3);
3963 case BuiltinType::SveInt64x4:
3964 return SVE_INT_ELTTY(64, 2, true, 4);
3965 case BuiltinType::SveUint64x4:
3966 return SVE_INT_ELTTY(64, 2, false, 4);
3967 case BuiltinType::SveBool:
3968 return SVE_ELTTY(BoolTy, 16, 1);
3969 case BuiltinType::SveBoolx2:
3970 return SVE_ELTTY(BoolTy, 16, 2);
3971 case BuiltinType::SveBoolx4:
3972 return SVE_ELTTY(BoolTy, 16, 4);
3973 case BuiltinType::SveFloat16:
3974 return SVE_ELTTY(HalfTy, 8, 1);
3975 case BuiltinType::SveFloat16x2:
3976 return SVE_ELTTY(HalfTy, 8, 2);
3977 case BuiltinType::SveFloat16x3:
3978 return SVE_ELTTY(HalfTy, 8, 3);
3979 case BuiltinType::SveFloat16x4:
3980 return SVE_ELTTY(HalfTy, 8, 4);
3981 case BuiltinType::SveFloat32:
3982 return SVE_ELTTY(FloatTy, 4, 1);
3983 case BuiltinType::SveFloat32x2:
3984 return SVE_ELTTY(FloatTy, 4, 2);
3985 case BuiltinType::SveFloat32x3:
3986 return SVE_ELTTY(FloatTy, 4, 3);
3987 case BuiltinType::SveFloat32x4:
3988 return SVE_ELTTY(FloatTy, 4, 4);
3989 case BuiltinType::SveFloat64:
3990 return SVE_ELTTY(DoubleTy, 2, 1);
3991 case BuiltinType::SveFloat64x2:
3992 return SVE_ELTTY(DoubleTy, 2, 2);
3993 case BuiltinType::SveFloat64x3:
3994 return SVE_ELTTY(DoubleTy, 2, 3);
3995 case BuiltinType::SveFloat64x4:
3996 return SVE_ELTTY(DoubleTy, 2, 4);
3997 case BuiltinType::SveBFloat16:
3998 return SVE_ELTTY(BFloat16Ty, 8, 1);
3999 case BuiltinType::SveBFloat16x2:
4000 return SVE_ELTTY(BFloat16Ty, 8, 2);
4001 case BuiltinType::SveBFloat16x3:
4002 return SVE_ELTTY(BFloat16Ty, 8, 3);
4003 case BuiltinType::SveBFloat16x4:
4004 return SVE_ELTTY(BFloat16Ty, 8, 4);
4005#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4006 IsSigned) \
4007 case BuiltinType::Id: \
4008 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4009 llvm::ElementCount::getScalable(NumEls), NF};
4010#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4011 case BuiltinType::Id: \
4012 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4013 llvm::ElementCount::getScalable(NumEls), NF};
4014#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4015 case BuiltinType::Id: \
4016 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4017#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4018 case BuiltinType::Id: \
4019 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4020#include "clang/Basic/RISCVVTypes.def"
4021 }
4022}
4023
4024/// getExternrefType - Return a WebAssembly externref type, which represents an
4025/// opaque reference to a host value.
4027 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4028#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4029 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4030 return SingletonId;
4031#include "clang/Basic/WebAssemblyReferenceTypes.def"
4032 }
4033 llvm_unreachable(
4034 "shouldn't try to generate type externref outside WebAssembly target");
4035}
4036
4037/// getScalableVectorType - Return the unique reference to a scalable vector
4038/// type of the specified element type and size. VectorType must be a built-in
4039/// type.
4041 unsigned NumFields) const {
4042 if (Target->hasAArch64SVETypes()) {
4043 uint64_t EltTySize = getTypeSize(EltTy);
4044#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4045 IsSigned, IsFP, IsBF) \
4046 if (!EltTy->isBooleanType() && \
4047 ((EltTy->hasIntegerRepresentation() && \
4048 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4049 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4050 IsFP && !IsBF) || \
4051 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4052 IsBF && !IsFP)) && \
4053 EltTySize == ElBits && NumElts == NumEls) { \
4054 return SingletonId; \
4055 }
4056#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4057 if (EltTy->isBooleanType() && NumElts == NumEls) \
4058 return SingletonId;
4059#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4060#include "clang/Basic/AArch64SVEACLETypes.def"
4061 } else if (Target->hasRISCVVTypes()) {
4062 uint64_t EltTySize = getTypeSize(EltTy);
4063#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4064 IsFP, IsBF) \
4065 if (!EltTy->isBooleanType() && \
4066 ((EltTy->hasIntegerRepresentation() && \
4067 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4068 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4069 IsFP && !IsBF) || \
4070 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4071 IsBF && !IsFP)) && \
4072 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4073 return SingletonId;
4074#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4075 if (EltTy->isBooleanType() && NumElts == NumEls) \
4076 return SingletonId;
4077#include "clang/Basic/RISCVVTypes.def"
4078 }
4079 return QualType();
4080}
4081
4082/// getVectorType - Return the unique reference to a vector type of
4083/// the specified element type and size. VectorType must be a built-in type.
4085 VectorKind VecKind) const {
4086 assert(vecType->isBuiltinType() ||
4087 (vecType->isBitIntType() &&
4088 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4089 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4090 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4091
4092 // Check if we've already instantiated a vector of this type.
4093 llvm::FoldingSetNodeID ID;
4094 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4095
4096 void *InsertPos = nullptr;
4097 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4098 return QualType(VTP, 0);
4099
4100 // If the element type isn't canonical, this won't be a canonical type either,
4101 // so fill in the canonical type field.
4102 QualType Canonical;
4103 if (!vecType.isCanonical()) {
4104 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4105
4106 // Get the new insert position for the node we care about.
4107 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4108 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4109 }
4110 auto *New = new (*this, alignof(VectorType))
4111 VectorType(vecType, NumElts, Canonical, VecKind);
4112 VectorTypes.InsertNode(New, InsertPos);
4113 Types.push_back(New);
4114 return QualType(New, 0);
4115}
4116
4118 SourceLocation AttrLoc,
4119 VectorKind VecKind) const {
4120 llvm::FoldingSetNodeID ID;
4121 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4122 VecKind);
4123 void *InsertPos = nullptr;
4124 DependentVectorType *Canon =
4125 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4127
4128 if (Canon) {
4129 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4130 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4131 } else {
4132 QualType CanonVecTy = getCanonicalType(VecType);
4133 if (CanonVecTy == VecType) {
4134 New = new (*this, alignof(DependentVectorType))
4135 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4136
4137 DependentVectorType *CanonCheck =
4138 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4139 assert(!CanonCheck &&
4140 "Dependent-sized vector_size canonical type broken");
4141 (void)CanonCheck;
4142 DependentVectorTypes.InsertNode(New, InsertPos);
4143 } else {
4144 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4145 SourceLocation(), VecKind);
4146 New = new (*this, alignof(DependentVectorType))
4147 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4148 }
4149 }
4150
4151 Types.push_back(New);
4152 return QualType(New, 0);
4153}
4154
4155/// getExtVectorType - Return the unique reference to an extended vector type of
4156/// the specified element type and size. VectorType must be a built-in type.
4158 unsigned NumElts) const {
4159 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4160 (vecType->isBitIntType() &&
4161 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4162 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4163 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4164
4165 // Check if we've already instantiated a vector of this type.
4166 llvm::FoldingSetNodeID ID;
4167 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4169 void *InsertPos = nullptr;
4170 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4171 return QualType(VTP, 0);
4172
4173 // If the element type isn't canonical, this won't be a canonical type either,
4174 // so fill in the canonical type field.
4175 QualType Canonical;
4176 if (!vecType.isCanonical()) {
4177 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4178
4179 // Get the new insert position for the node we care about.
4180 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4181 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4182 }
4183 auto *New = new (*this, alignof(ExtVectorType))
4184 ExtVectorType(vecType, NumElts, Canonical);
4185 VectorTypes.InsertNode(New, InsertPos);
4186 Types.push_back(New);
4187 return QualType(New, 0);
4188}
4189
4192 Expr *SizeExpr,
4193 SourceLocation AttrLoc) const {
4194 llvm::FoldingSetNodeID ID;
4196 SizeExpr);
4197
4198 void *InsertPos = nullptr;
4200 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4202 if (Canon) {
4203 // We already have a canonical version of this array type; use it as
4204 // the canonical type for a newly-built type.
4205 New = new (*this, alignof(DependentSizedExtVectorType))
4206 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4207 AttrLoc);
4208 } else {
4209 QualType CanonVecTy = getCanonicalType(vecType);
4210 if (CanonVecTy == vecType) {
4211 New = new (*this, alignof(DependentSizedExtVectorType))
4212 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4213
4214 DependentSizedExtVectorType *CanonCheck
4215 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4216 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4217 (void)CanonCheck;
4218 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4219 } else {
4220 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4221 SourceLocation());
4222 New = new (*this, alignof(DependentSizedExtVectorType))
4223 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4224 }
4225 }
4226
4227 Types.push_back(New);
4228 return QualType(New, 0);
4229}
4230
4232 unsigned NumColumns) const {
4233 llvm::FoldingSetNodeID ID;
4234 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4235 Type::ConstantMatrix);
4236
4237 assert(MatrixType::isValidElementType(ElementTy) &&
4238 "need a valid element type");
4239 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4241 "need valid matrix dimensions");
4242 void *InsertPos = nullptr;
4243 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4244 return QualType(MTP, 0);
4245
4246 QualType Canonical;
4247 if (!ElementTy.isCanonical()) {
4248 Canonical =
4249 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4250
4251 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4252 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4253 (void)NewIP;
4254 }
4255
4256 auto *New = new (*this, alignof(ConstantMatrixType))
4257 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4258 MatrixTypes.InsertNode(New, InsertPos);
4259 Types.push_back(New);
4260 return QualType(New, 0);
4261}
4262
4264 Expr *RowExpr,
4265 Expr *ColumnExpr,
4266 SourceLocation AttrLoc) const {
4267 QualType CanonElementTy = getCanonicalType(ElementTy);
4268 llvm::FoldingSetNodeID ID;
4269 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4270 ColumnExpr);
4271
4272 void *InsertPos = nullptr;
4274 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4275
4276 if (!Canon) {
4277 Canon = new (*this, alignof(DependentSizedMatrixType))
4278 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4279 ColumnExpr, AttrLoc);
4280#ifndef NDEBUG
4281 DependentSizedMatrixType *CanonCheck =
4282 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4283 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4284#endif
4285 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4286 Types.push_back(Canon);
4287 }
4288
4289 // Already have a canonical version of the matrix type
4290 //
4291 // If it exactly matches the requested type, use it directly.
4292 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4293 Canon->getRowExpr() == ColumnExpr)
4294 return QualType(Canon, 0);
4295
4296 // Use Canon as the canonical type for newly-built type.
4297 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4298 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4299 ColumnExpr, AttrLoc);
4300 Types.push_back(New);
4301 return QualType(New, 0);
4302}
4303
4305 Expr *AddrSpaceExpr,
4306 SourceLocation AttrLoc) const {
4307 assert(AddrSpaceExpr->isInstantiationDependent());
4308
4309 QualType canonPointeeType = getCanonicalType(PointeeType);
4310
4311 void *insertPos = nullptr;
4312 llvm::FoldingSetNodeID ID;
4313 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4314 AddrSpaceExpr);
4315
4316 DependentAddressSpaceType *canonTy =
4317 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4318
4319 if (!canonTy) {
4320 canonTy = new (*this, alignof(DependentAddressSpaceType))
4321 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4322 AttrLoc);
4323 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4324 Types.push_back(canonTy);
4325 }
4326
4327 if (canonPointeeType == PointeeType &&
4328 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4329 return QualType(canonTy, 0);
4330
4331 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4332 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4333 AddrSpaceExpr, AttrLoc);
4334 Types.push_back(sugaredType);
4335 return QualType(sugaredType, 0);
4336}
4337
4338/// Determine whether \p T is canonical as the result type of a function.
4340 return T.isCanonical() &&
4341 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4342 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4343}
4344
4345/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4348 const FunctionType::ExtInfo &Info) const {
4349 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4350 // functionality creates a function without a prototype regardless of
4351 // language mode (so it makes them even in C++). Once the rewriter has been
4352 // fixed, this assertion can be enabled again.
4353 //assert(!LangOpts.requiresStrictPrototypes() &&
4354 // "strict prototypes are disabled");
4355
4356 // Unique functions, to guarantee there is only one function of a particular
4357 // structure.
4358 llvm::FoldingSetNodeID ID;
4359 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4360
4361 void *InsertPos = nullptr;
4362 if (FunctionNoProtoType *FT =
4363 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4364 return QualType(FT, 0);
4365
4366 QualType Canonical;
4367 if (!isCanonicalResultType(ResultTy)) {
4368 Canonical =
4370
4371 // Get the new insert position for the node we care about.
4372 FunctionNoProtoType *NewIP =
4373 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4374 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4375 }
4376
4377 auto *New = new (*this, alignof(FunctionNoProtoType))
4378 FunctionNoProtoType(ResultTy, Canonical, Info);
4379 Types.push_back(New);
4380 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4381 return QualType(New, 0);
4382}
4383
4386 CanQualType CanResultType = getCanonicalType(ResultType);
4387
4388 // Canonical result types do not have ARC lifetime qualifiers.
4389 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4390 Qualifiers Qs = CanResultType.getQualifiers();
4391 Qs.removeObjCLifetime();
4393 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4394 }
4395
4396 return CanResultType;
4397}
4398
4400 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4401 if (ESI.Type == EST_None)
4402 return true;
4403 if (!NoexceptInType)
4404 return false;
4405
4406 // C++17 onwards: exception specification is part of the type, as a simple
4407 // boolean "can this function type throw".
4408 if (ESI.Type == EST_BasicNoexcept)
4409 return true;
4410
4411 // A noexcept(expr) specification is (possibly) canonical if expr is
4412 // value-dependent.
4413 if (ESI.Type == EST_DependentNoexcept)
4414 return true;
4415
4416 // A dynamic exception specification is canonical if it only contains pack
4417 // expansions (so we can't tell whether it's non-throwing) and all its
4418 // contained types are canonical.
4419 if (ESI.Type == EST_Dynamic) {
4420 bool AnyPackExpansions = false;
4421 for (QualType ET : ESI.Exceptions) {
4422 if (!ET.isCanonical())
4423 return false;
4424 if (ET->getAs<PackExpansionType>())
4425 AnyPackExpansions = true;
4426 }
4427 return AnyPackExpansions;
4428 }
4429
4430 return false;
4431}
4432
4433QualType ASTContext::getFunctionTypeInternal(
4434 QualType ResultTy, ArrayRef<QualType> ArgArray,
4435 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4436 size_t NumArgs = ArgArray.size();
4437
4438 // Unique functions, to guarantee there is only one function of a particular
4439 // structure.
4440 llvm::FoldingSetNodeID ID;
4441 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4442 *this, true);
4443
4444 QualType Canonical;
4445 bool Unique = false;
4446
4447 void *InsertPos = nullptr;
4448 if (FunctionProtoType *FPT =
4449 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4450 QualType Existing = QualType(FPT, 0);
4451
4452 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4453 // it so long as our exception specification doesn't contain a dependent
4454 // noexcept expression, or we're just looking for a canonical type.
4455 // Otherwise, we're going to need to create a type
4456 // sugar node to hold the concrete expression.
4457 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4458 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4459 return Existing;
4460
4461 // We need a new type sugar node for this one, to hold the new noexcept
4462 // expression. We do no canonicalization here, but that's OK since we don't
4463 // expect to see the same noexcept expression much more than once.
4464 Canonical = getCanonicalType(Existing);
4465 Unique = true;
4466 }
4467
4468 bool NoexceptInType = getLangOpts().CPlusPlus17;
4469 bool IsCanonicalExceptionSpec =
4471
4472 // Determine whether the type being created is already canonical or not.
4473 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4474 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4475 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4476 if (!ArgArray[i].isCanonicalAsParam())
4477 isCanonical = false;
4478
4479 if (OnlyWantCanonical)
4480 assert(isCanonical &&
4481 "given non-canonical parameters constructing canonical type");
4482
4483 // If this type isn't canonical, get the canonical version of it if we don't
4484 // already have it. The exception spec is only partially part of the
4485 // canonical type, and only in C++17 onwards.
4486 if (!isCanonical && Canonical.isNull()) {
4487 SmallVector<QualType, 16> CanonicalArgs;
4488 CanonicalArgs.reserve(NumArgs);
4489 for (unsigned i = 0; i != NumArgs; ++i)
4490 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4491
4492 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4493 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4494 CanonicalEPI.HasTrailingReturn = false;
4495
4496 if (IsCanonicalExceptionSpec) {
4497 // Exception spec is already OK.
4498 } else if (NoexceptInType) {
4499 switch (EPI.ExceptionSpec.Type) {
4501 // We don't know yet. It shouldn't matter what we pick here; no-one
4502 // should ever look at this.
4503 [[fallthrough]];
4504 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4505 CanonicalEPI.ExceptionSpec.Type = EST_None;
4506 break;
4507
4508 // A dynamic exception specification is almost always "not noexcept",
4509 // with the exception that a pack expansion might expand to no types.
4510 case EST_Dynamic: {
4511 bool AnyPacks = false;
4512 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4513 if (ET->getAs<PackExpansionType>())
4514 AnyPacks = true;
4515 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4516 }
4517 if (!AnyPacks)
4518 CanonicalEPI.ExceptionSpec.Type = EST_None;
4519 else {
4520 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4521 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4522 }
4523 break;
4524 }
4525
4526 case EST_DynamicNone:
4527 case EST_BasicNoexcept:
4528 case EST_NoexceptTrue:
4529 case EST_NoThrow:
4530 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4531 break;
4532
4534 llvm_unreachable("dependent noexcept is already canonical");
4535 }
4536 } else {
4538 }
4539
4540 // Adjust the canonical function result type.
4541 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4542 Canonical =
4543 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4544
4545 // Get the new insert position for the node we care about.
4546 FunctionProtoType *NewIP =
4547 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4548 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4549 }
4550
4551 // Compute the needed size to hold this FunctionProtoType and the
4552 // various trailing objects.
4553 auto ESH = FunctionProtoType::getExceptionSpecSize(
4554 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4555 size_t Size = FunctionProtoType::totalSizeToAlloc<
4560 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4561 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4562 EPI.ExtParameterInfos ? NumArgs : 0,
4563 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4564
4565 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4567 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4568 Types.push_back(FTP);
4569 if (!Unique)
4570 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4571 return QualType(FTP, 0);
4572}
4573
4574QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4575 llvm::FoldingSetNodeID ID;
4576 PipeType::Profile(ID, T, ReadOnly);
4577
4578 void *InsertPos = nullptr;
4579 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4580 return QualType(PT, 0);
4581
4582 // If the pipe element type isn't canonical, this won't be a canonical type
4583 // either, so fill in the canonical type field.
4584 QualType Canonical;
4585 if (!T.isCanonical()) {
4586 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4587
4588 // Get the new insert position for the node we care about.
4589 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4590 assert(!NewIP && "Shouldn't be in the map!");
4591 (void)NewIP;
4592 }
4593 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4594 Types.push_back(New);
4595 PipeTypes.InsertNode(New, InsertPos);
4596 return QualType(New, 0);
4597}
4598
4600 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4601 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4602 : Ty;
4603}
4604
4606 return getPipeType(T, true);
4607}
4608
4610 return getPipeType(T, false);
4611}
4612
4613QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4614 llvm::FoldingSetNodeID ID;
4615 BitIntType::Profile(ID, IsUnsigned, NumBits);
4616
4617 void *InsertPos = nullptr;
4618 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4619 return QualType(EIT, 0);
4620
4621 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4622 BitIntTypes.InsertNode(New, InsertPos);
4623 Types.push_back(New);
4624 return QualType(New, 0);
4625}
4626
4628 Expr *NumBitsExpr) const {
4629 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4630 llvm::FoldingSetNodeID ID;
4631 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4632
4633 void *InsertPos = nullptr;
4634 if (DependentBitIntType *Existing =
4635 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4636 return QualType(Existing, 0);
4637
4638 auto *New = new (*this, alignof(DependentBitIntType))
4639 DependentBitIntType(IsUnsigned, NumBitsExpr);
4640 DependentBitIntTypes.InsertNode(New, InsertPos);
4641
4642 Types.push_back(New);
4643 return QualType(New, 0);
4644}
4645
4646#ifndef NDEBUG
4648 if (!isa<CXXRecordDecl>(D)) return false;
4649 const auto *RD = cast<CXXRecordDecl>(D);
4650 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4651 return true;
4652 if (RD->getDescribedClassTemplate() &&
4653 !isa<ClassTemplateSpecializationDecl>(RD))
4654 return true;
4655 return false;
4656}
4657#endif
4658
4659/// getInjectedClassNameType - Return the unique reference to the
4660/// injected class name type for the specified templated declaration.
4662 QualType TST) const {
4664 if (Decl->TypeForDecl) {
4665 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4666 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4667 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4668 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4669 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4670 } else {
4671 Type *newType = new (*this, alignof(InjectedClassNameType))
4673 Decl->TypeForDecl = newType;
4674 Types.push_back(newType);
4675 }
4676 return QualType(Decl->TypeForDecl, 0);
4677}
4678
4679/// getTypeDeclType - Return the unique reference to the type for the
4680/// specified type declaration.
4681QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4682 assert(Decl && "Passed null for Decl param");
4683 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4684
4685 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4686 return getTypedefType(Typedef);
4687
4688 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4689 "Template type parameter types are always available.");
4690
4691 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4692 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4694 return getRecordType(Record);
4695 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4696 assert(Enum->isFirstDecl() && "enum has previous declaration");
4697 return getEnumType(Enum);
4698 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4699 return getUnresolvedUsingType(Using);
4700 } else
4701 llvm_unreachable("TypeDecl without a type?");
4702
4703 return QualType(Decl->TypeForDecl, 0);
4704}
4705
4706/// getTypedefType - Return the unique reference to the type for the
4707/// specified typedef name decl.
4709 QualType Underlying) const {
4710 if (!Decl->TypeForDecl) {
4711 if (Underlying.isNull())
4712 Underlying = Decl->getUnderlyingType();
4713 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
4714 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4715 Decl->TypeForDecl = NewType;
4716 Types.push_back(NewType);
4717 return QualType(NewType, 0);
4718 }
4719 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4720 return QualType(Decl->TypeForDecl, 0);
4721 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
4722
4723 llvm::FoldingSetNodeID ID;
4724 TypedefType::Profile(ID, Decl, Underlying);
4725
4726 void *InsertPos = nullptr;
4727 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4728 assert(!T->typeMatchesDecl() &&
4729 "non-divergent case should be handled with TypeDecl");
4730 return QualType(T, 0);
4731 }
4732
4733 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
4734 alignof(TypedefType));
4735 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4736 getCanonicalType(Underlying));
4737 TypedefTypes.InsertNode(NewType, InsertPos);
4738 Types.push_back(NewType);
4739 return QualType(NewType, 0);
4740}
4741
4743 QualType Underlying) const {
4744 llvm::FoldingSetNodeID ID;
4745 UsingType::Profile(ID, Found, Underlying);
4746
4747 void *InsertPos = nullptr;
4748 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4749 return QualType(T, 0);
4750
4751 const Type *TypeForDecl =
4752 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4753
4754 assert(!Underlying.hasLocalQualifiers());
4755 QualType Canon = Underlying->getCanonicalTypeInternal();
4756 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
4757
4758 if (Underlying.getTypePtr() == TypeForDecl)
4759 Underlying = QualType();
4760 void *Mem =
4761 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4762 alignof(UsingType));
4763 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4764 Types.push_back(NewType);
4765 UsingTypes.InsertNode(NewType, InsertPos);
4766 return QualType(NewType, 0);
4767}
4768
4770 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4771
4772 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4773 if (PrevDecl->TypeForDecl)
4774 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4775
4776 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
4777 Decl->TypeForDecl = newType;
4778 Types.push_back(newType);
4779 return QualType(newType, 0);
4780}
4781
4783 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4784
4785 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4786 if (PrevDecl->TypeForDecl)
4787 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4788
4789 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
4790 Decl->TypeForDecl = newType;
4791 Types.push_back(newType);
4792 return QualType(newType, 0);
4793}
4794
4796 const UnresolvedUsingTypenameDecl *Decl) const {
4797 if (Decl->TypeForDecl)
4798 return QualType(Decl->TypeForDecl, 0);
4799
4800 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4802 if (CanonicalDecl->TypeForDecl)
4803 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4804
4805 Type *newType =
4806 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
4807 Decl->TypeForDecl = newType;
4808 Types.push_back(newType);
4809 return QualType(newType, 0);
4810}
4811
4813 QualType modifiedType,
4814 QualType equivalentType) const {
4815 llvm::FoldingSetNodeID id;
4816 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4817
4818 void *insertPos = nullptr;
4819 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4820 if (type) return QualType(type, 0);
4821
4822 QualType canon = getCanonicalType(equivalentType);
4823 type = new (*this, alignof(AttributedType))
4824 AttributedType(canon, attrKind, modifiedType, equivalentType);
4825
4826 Types.push_back(type);
4827 AttributedTypes.InsertNode(type, insertPos);
4828
4829 return QualType(type, 0);
4830}
4831
4832QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4833 QualType Wrapped) {
4834 llvm::FoldingSetNodeID ID;
4835 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4836
4837 void *InsertPos = nullptr;
4839 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4840 if (Ty)
4841 return QualType(Ty, 0);
4842
4843 QualType Canon = getCanonicalType(Wrapped);
4844 Ty = new (*this, alignof(BTFTagAttributedType))
4845 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4846
4847 Types.push_back(Ty);
4848 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4849
4850 return QualType(Ty, 0);
4851}
4852
4853/// Retrieve a substitution-result type.
4855 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
4856 std::optional<unsigned> PackIndex) const {
4857 llvm::FoldingSetNodeID ID;
4858 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4859 PackIndex);
4860 void *InsertPos = nullptr;
4861 SubstTemplateTypeParmType *SubstParm =
4862 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4863
4864 if (!SubstParm) {
4865 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4866 !Replacement.isCanonical()),
4867 alignof(SubstTemplateTypeParmType));
4868 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4869 Index, PackIndex);
4870 Types.push_back(SubstParm);
4871 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4872 }
4873
4874 return QualType(SubstParm, 0);
4875}
4876
4877/// Retrieve a
4880 unsigned Index, bool Final,
4881 const TemplateArgument &ArgPack) {
4882#ifndef NDEBUG
4883 for (const auto &P : ArgPack.pack_elements())
4884 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
4885#endif
4886
4887 llvm::FoldingSetNodeID ID;
4888 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4889 ArgPack);
4890 void *InsertPos = nullptr;
4891 if (SubstTemplateTypeParmPackType *SubstParm =
4892 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4893 return QualType(SubstParm, 0);
4894
4895 QualType Canon;
4896 {
4897 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4898 if (!AssociatedDecl->isCanonicalDecl() ||
4899 !CanonArgPack.structurallyEquals(ArgPack)) {
4901 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4902 [[maybe_unused]] const auto *Nothing =
4903 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4904 assert(!Nothing);
4905 }
4906 }
4907
4908 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
4909 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
4910 ArgPack);
4911 Types.push_back(SubstParm);
4912 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4913 return QualType(SubstParm, 0);
4914}
4915
4916/// Retrieve the template type parameter type for a template
4917/// parameter or parameter pack with the given depth, index, and (optionally)
4918/// name.
4919QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4920 bool ParameterPack,
4921 TemplateTypeParmDecl *TTPDecl) const {
4922 llvm::FoldingSetNodeID ID;
4923 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4924 void *InsertPos = nullptr;
4925 TemplateTypeParmType *TypeParm
4926 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4927
4928 if (TypeParm)
4929 return QualType(TypeParm, 0);
4930
4931 if (TTPDecl) {
4932 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4933 TypeParm = new (*this, alignof(TemplateTypeParmType))
4934 TemplateTypeParmType(TTPDecl, Canon);
4935
4936 TemplateTypeParmType *TypeCheck
4937 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4938 assert(!TypeCheck && "Template type parameter canonical type broken");
4939 (void)TypeCheck;
4940 } else
4941 TypeParm = new (*this, alignof(TemplateTypeParmType))
4942 TemplateTypeParmType(Depth, Index, ParameterPack);
4943
4944 Types.push_back(TypeParm);
4945 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4946
4947 return QualType(TypeParm, 0);
4948}
4949
4952 SourceLocation NameLoc,
4953 const TemplateArgumentListInfo &Args,
4954 QualType Underlying) const {
4955 assert(!Name.getAsDependentTemplateName() &&
4956 "No dependent template names here!");
4957 QualType TST =
4958 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4959
4964 TL.setTemplateNameLoc(NameLoc);
4965 TL.setLAngleLoc(Args.getLAngleLoc());
4966 TL.setRAngleLoc(Args.getRAngleLoc());
4967 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4968 TL.setArgLocInfo(i, Args[i].getLocInfo());
4969 return DI;
4970}
4971
4975 QualType Underlying) const {
4976 assert(!Template.getAsDependentTemplateName() &&
4977 "No dependent template names here!");
4978
4980 ArgVec.reserve(Args.size());
4981 for (const TemplateArgumentLoc &Arg : Args)
4982 ArgVec.push_back(Arg.getArgument());
4983
4984 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4985}
4986
4987#ifndef NDEBUG
4989 for (const TemplateArgument &Arg : Args)
4990 if (Arg.isPackExpansion())
4991 return true;
4992
4993 return true;
4994}
4995#endif
4996
5000 QualType Underlying) const {
5001 assert(!Template.getAsDependentTemplateName() &&
5002 "No dependent template names here!");
5003 // Look through qualified template names.
5005 Template = QTN->getUnderlyingTemplate();
5006
5007 const auto *TD = Template.getAsTemplateDecl();
5008 bool IsTypeAlias = TD && TD->isTypeAlias();
5009 QualType CanonType;
5010 if (!Underlying.isNull())
5011 CanonType = getCanonicalType(Underlying);
5012 else {
5013 // We can get here with an alias template when the specialization contains
5014 // a pack expansion that does not match up with a parameter pack.
5015 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5016 "Caller must compute aliased type");
5017 IsTypeAlias = false;
5018 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5019 }
5020
5021 // Allocate the (non-canonical) template specialization type, but don't
5022 // try to unique it: these types typically have location information that
5023 // we don't unique and don't want to lose.
5024 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5025 sizeof(TemplateArgument) * Args.size() +
5026 (IsTypeAlias ? sizeof(QualType) : 0),
5028 auto *Spec
5029 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5030 IsTypeAlias ? Underlying : QualType());
5031
5032 Types.push_back(Spec);
5033 return QualType(Spec, 0);
5034}
5035
5037 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5038 assert(!Template.getAsDependentTemplateName() &&
5039 "No dependent template names here!");
5040
5041 // Look through qualified template names.
5043 Template = TemplateName(QTN->getUnderlyingTemplate());
5044
5045 // Build the canonical template specialization type.
5046 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5047 bool AnyNonCanonArgs = false;
5048 auto CanonArgs =
5049 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5050
5051 // Determine whether this canonical template specialization type already
5052 // exists.
5053 llvm::FoldingSetNodeID ID;
5054 TemplateSpecializationType::Profile(ID, CanonTemplate,
5055 CanonArgs, *this);
5056
5057 void *InsertPos = nullptr;
5059 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5060
5061 if (!Spec) {
5062 // Allocate a new canonical template specialization type.
5063 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5064 sizeof(TemplateArgument) * CanonArgs.size()),
5066 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5067 CanonArgs,
5068 QualType(), QualType());
5069 Types.push_back(Spec);
5070 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5071 }
5072
5073 assert(Spec->isDependentType() &&
5074 "Non-dependent template-id type must have a canonical type");
5075 return QualType(Spec, 0);
5076}
5077
5080 QualType NamedType,
5081 TagDecl *OwnedTagDecl) const {
5082 llvm::FoldingSetNodeID ID;
5083 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5084
5085 void *InsertPos = nullptr;
5086 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5087 if (T)
5088 return QualType(T, 0);
5089
5090 QualType Canon = NamedType;
5091 if (!Canon.isCanonical()) {
5092 Canon = getCanonicalType(NamedType);
5093 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5094 assert(!CheckT && "Elaborated canonical type broken");
5095 (void)CheckT;
5096 }
5097
5098 void *Mem =
5099 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5100 alignof(ElaboratedType));
5101 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5102
5103 Types.push_back(T);
5104 ElaboratedTypes.InsertNode(T, InsertPos);
5105 return QualType(T, 0);
5106}
5107
5110 llvm::FoldingSetNodeID ID;
5111 ParenType::Profile(ID, InnerType);
5112
5113 void *InsertPos = nullptr;
5114 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5115 if (T)
5116 return QualType(T, 0);
5117
5118 QualType Canon = InnerType;
5119 if (!Canon.isCanonical()) {
5120 Canon = getCanonicalType(InnerType);
5121 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5122 assert(!CheckT && "Paren canonical type broken");
5123 (void)CheckT;
5124 }
5125
5126 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5127 Types.push_back(T);
5128 ParenTypes.InsertNode(T, InsertPos);
5129 return QualType(T, 0);
5130}
5131
5134 const IdentifierInfo *MacroII) const {
5135 QualType Canon = UnderlyingTy;
5136 if (!Canon.isCanonical())
5137 Canon = getCanonicalType(UnderlyingTy);
5138
5139 auto *newType = new (*this, alignof(MacroQualifiedType))
5140 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5141 Types.push_back(newType);
5142 return QualType(newType, 0);
5143}
5144
5147 const IdentifierInfo *Name,
5148 QualType Canon) const {
5149 if (Canon.isNull()) {
5151 if (CanonNNS != NNS)
5152 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5153 }
5154
5155 llvm::FoldingSetNodeID ID;
5156 DependentNameType::Profile(ID, Keyword, NNS, Name);
5157
5158 void *InsertPos = nullptr;
5160 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5161 if (T)
5162 return QualType(T, 0);
5163
5164 T = new (*this, alignof(DependentNameType))
5165 DependentNameType(Keyword, NNS, Name, Canon);
5166 Types.push_back(T);
5167 DependentNameTypes.InsertNode(T, InsertPos);
5168 return QualType(T, 0);
5169}
5170
5173 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5174 // TODO: avoid this copy
5176 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5177 ArgCopy.push_back(Args[I].getArgument());
5178 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5179}
5180
5183 ElaboratedTypeKeyword Keyword,
5185 const IdentifierInfo *Name,
5186 ArrayRef<TemplateArgument> Args) const {
5187 assert((!NNS || NNS->isDependent()) &&
5188 "nested-name-specifier must be dependent");
5189
5190 llvm::FoldingSetNodeID ID;
5191 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5192 Name, Args);
5193
5194 void *InsertPos = nullptr;
5196 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5197 if (T)
5198 return QualType(T, 0);
5199
5201
5202 ElaboratedTypeKeyword CanonKeyword = Keyword;
5203 if (Keyword == ElaboratedTypeKeyword::None)
5204 CanonKeyword = ElaboratedTypeKeyword::Typename;
5205
5206 bool AnyNonCanonArgs = false;
5207 auto CanonArgs =
5208 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5209
5210 QualType Canon;
5211 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5212 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5213 Name,
5214 CanonArgs);
5215
5216 // Find the insert position again.
5217 [[maybe_unused]] auto *Nothing =
5218 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5219 assert(!Nothing && "canonical type broken");
5220 }
5221
5222 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5223 sizeof(TemplateArgument) * Args.size()),
5225 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5226 Name, Args, Canon);
5227 Types.push_back(T);
5228 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5229 return QualType(T, 0);
5230}
5231
5233 TemplateArgument Arg;
5234 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5235 QualType ArgType = getTypeDeclType(TTP);
5236 if (TTP->isParameterPack())
5237 ArgType = getPackExpansionType(ArgType, std::nullopt);
5238
5239 Arg = TemplateArgument(ArgType);
5240 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5241 QualType T =
5242 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5243 // For class NTTPs, ensure we include the 'const' so the type matches that
5244 // of a real template argument.
5245 // FIXME: It would be more faithful to model this as something like an
5246 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5247 if (T->isRecordType())
5248 T.addConst();
5249 Expr *E = new (*this) DeclRefExpr(
5250 *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5251 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5252
5253 if (NTTP->isParameterPack())
5254 E = new (*this)
5255 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5256 Arg = TemplateArgument(E);
5257 } else {
5258 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5259 if (TTP->isParameterPack())
5260 Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>());
5261 else
5262 Arg = TemplateArgument(TemplateName(TTP));
5263 }
5264
5265 if (Param->isTemplateParameterPack())
5266 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5267
5268 return Arg;
5269}
5270
5271void
5274 Args.reserve(Args.size() + Params->size());
5275
5276 for (NamedDecl *Param : *Params)
5277 Args.push_back(getInjectedTemplateArg(Param));
5278}
5279
5281 std::optional<unsigned> NumExpansions,
5282 bool ExpectPackInType) {
5283 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5284 "Pack expansions must expand one or more parameter packs");
5285
5286 llvm::FoldingSetNodeID ID;
5287 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5288
5289 void *InsertPos = nullptr;
5290 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5291 if (T)
5292 return QualType(T, 0);
5293
5294 QualType Canon;
5295 if (!Pattern.isCanonical()) {
5296 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5297 /*ExpectPackInType=*/false);
5298
5299 // Find the insert position again, in case we inserted an element into
5300 // PackExpansionTypes and invalidated our insert position.
5301 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5302 }
5303
5304 T = new (*this, alignof(PackExpansionType))
5305 PackExpansionType(Pattern, Canon, NumExpansions);
5306 Types.push_back(T);
5307 PackExpansionTypes.InsertNode(T, InsertPos);
5308 return QualType(T, 0);
5309}
5310
5311/// CmpProtocolNames - Comparison predicate for sorting protocols
5312/// alphabetically.
5313static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5314 ObjCProtocolDecl *const *RHS) {
5315 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5316}
5317
5319 if (Protocols.empty()) return true;
5320
5321 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5322 return false;
5323
5324 for (unsigned i = 1; i != Protocols.size(); ++i)
5325 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5326 Protocols[i]->getCanonicalDecl() != Protocols[i])
5327 return false;
5328 return true;
5329}
5330
5331static void
5333 // Sort protocols, keyed by name.
5334 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5335
5336 // Canonicalize.
5337 for (ObjCProtocolDecl *&P : Protocols)
5338 P = P->getCanonicalDecl();
5339
5340 // Remove duplicates.
5341 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5342 Protocols.erase(ProtocolsEnd, Protocols.end());
5343}
5344
5346 ObjCProtocolDecl * const *Protocols,
5347 unsigned NumProtocols) const {
5348 return getObjCObjectType(BaseType, {},
5349 llvm::ArrayRef(Protocols, NumProtocols),
5350 /*isKindOf=*/false);
5351}
5352
5354 QualType baseType,
5355 ArrayRef<QualType> typeArgs,
5357 bool isKindOf) const {
5358 // If the base type is an interface and there aren't any protocols or
5359 // type arguments to add, then the interface type will do just fine.
5360 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5361 isa<ObjCInterfaceType>(baseType))
5362 return baseType;
5363
5364 // Look in the folding set for an existing type.
5365 llvm::FoldingSetNodeID ID;
5366 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5367 void *InsertPos = nullptr;
5368 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5369 return QualType(QT, 0);
5370
5371 // Determine the type arguments to be used for canonicalization,
5372 // which may be explicitly specified here or written on the base
5373 // type.
5374 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5375 if (effectiveTypeArgs.empty()) {
5376 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5377 effectiveTypeArgs = baseObject->getTypeArgs();
5378 }
5379
5380 // Build the canonical type, which has the canonical base type and a
5381 // sorted-and-uniqued list of protocols and the type arguments
5382 // canonicalized.
5383 QualType canonical;
5384 bool typeArgsAreCanonical = llvm::all_of(
5385 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5386 bool protocolsSorted = areSortedAndUniqued(protocols);
5387 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5388 // Determine the canonical type arguments.
5389 ArrayRef<QualType> canonTypeArgs;
5390 SmallVector<QualType, 4> canonTypeArgsVec;
5391 if (!typeArgsAreCanonical) {
5392 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5393 for (auto typeArg : effectiveTypeArgs)
5394 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5395 canonTypeArgs = canonTypeArgsVec;
5396 } else {
5397 canonTypeArgs = effectiveTypeArgs;
5398 }
5399
5400 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5401 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5402 if (!protocolsSorted) {
5403 canonProtocolsVec.append(protocols.begin(), protocols.end());
5404 SortAndUniqueProtocols(canonProtocolsVec);
5405 canonProtocols = canonProtocolsVec;
5406 } else {
5407 canonProtocols = protocols;
5408 }
5409
5410 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5411 canonProtocols, isKindOf);
5412
5413 // Regenerate InsertPos.
5414 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5415 }
5416
5417 unsigned size = sizeof(ObjCObjectTypeImpl);
5418 size += typeArgs.size() * sizeof(QualType);
5419 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5420 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5421 auto *T =
5422 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5423 isKindOf);
5424
5425 Types.push_back(T);
5426 ObjCObjectTypes.InsertNode(T, InsertPos);
5427 return QualType(T, 0);
5428}
5429
5430/// Apply Objective-C protocol qualifiers to the given type.
5431/// If this is for the canonical type of a type parameter, we can apply
5432/// protocol qualifiers on the ObjCObjectPointerType.
5435 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5436 bool allowOnPointerType) const {
5437 hasError = false;
5438
5439 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5440 return getObjCTypeParamType(objT->getDecl(), protocols);
5441 }
5442
5443 // Apply protocol qualifiers to ObjCObjectPointerType.
5444 if (allowOnPointerType) {
5445 if (const auto *objPtr =
5446 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5447 const ObjCObjectType *objT = objPtr->getObjectType();
5448 // Merge protocol lists and construct ObjCObjectType.
5450 protocolsVec.append(objT->qual_begin(),
5451 objT->qual_end());
5452 protocolsVec.append(protocols.begin(), protocols.end());
5453 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5455 objT->getBaseType(),
5456 objT->getTypeArgsAsWritten(),
5457 protocols,
5458 objT->isKindOfTypeAsWritten());
5460 }
5461 }
5462
5463 // Apply protocol qualifiers to ObjCObjectType.
5464 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5465 // FIXME: Check for protocols to which the class type is already
5466 // known to conform.
5467
5468 return getObjCObjectType(objT->getBaseType(),
5469 objT->getTypeArgsAsWritten(),
5470 protocols,
5471 objT->isKindOfTypeAsWritten());
5472 }
5473
5474 // If the canonical type is ObjCObjectType, ...
5475 if (type->isObjCObjectType()) {
5476 // Silently overwrite any existing protocol qualifiers.
5477 // TODO: determine whether that's the right thing to do.
5478
5479 // FIXME: Check for protocols to which the class type is already
5480 // known to conform.
5481 return getObjCObjectType(type, {}, protocols, false);
5482 }
5483
5484 // id<protocol-list>
5485 if (type->isObjCIdType()) {
5486 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5487 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5488 objPtr->isKindOfType());
5490 }
5491
5492 // Class<protocol-list>
5493 if (type->isObjCClassType()) {
5494 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5495 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5496 objPtr->isKindOfType());
5498 }
5499
5500 hasError = true;
5501 return type;
5502}
5503
5506 ArrayRef<ObjCProtocolDecl *> protocols) const {
5507 // Look in the folding set for an existing type.
5508 llvm::FoldingSetNodeID ID;
5509 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5510 void *InsertPos = nullptr;
5511 if (ObjCTypeParamType *TypeParam =
5512 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5513 return QualType(TypeParam, 0);
5514
5515 // We canonicalize to the underlying type.
5516 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5517 if (!protocols.empty()) {
5518 // Apply the protocol qualifers.
5519 bool hasError;
5521 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5522 assert(!hasError && "Error when apply protocol qualifier to bound type");
5523 }
5524
5525 unsigned size = sizeof(ObjCTypeParamType);
5526 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5527 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5528 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5529
5530 Types.push_back(newType);
5531 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5532 return QualType(newType, 0);
5533}
5534
5536 ObjCTypeParamDecl *New) const {
5538 // Update TypeForDecl after updating TypeSourceInfo.
5539 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5541 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5542 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5543 New->setTypeForDecl(UpdatedTy.getTypePtr());
5544}
5545
5546/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5547/// protocol list adopt all protocols in QT's qualified-id protocol
5548/// list.
5550 ObjCInterfaceDecl *IC) {
5551 if (!QT->isObjCQualifiedIdType())
5552 return false;
5553
5554 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5555 // If both the right and left sides have qualifiers.
5556 for (auto *Proto : OPT->quals()) {
5557 if (!IC->ClassImplementsProtocol(Proto, false))
5558 return false;
5559 }
5560 return true;
5561 }
5562 return false;
5563}
5564
5565/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5566/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5567/// of protocols.
5569 ObjCInterfaceDecl *IDecl) {
5570 if (!QT->isObjCQualifiedIdType())
5571 return false;
5572 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5573 if (!OPT)
5574 return false;
5575 if (!IDecl->hasDefinition())
5576 return false;
5578 CollectInheritedProtocols(IDecl, InheritedProtocols);
5579 if (InheritedProtocols.empty())
5580 return false;
5581 // Check that if every protocol in list of id<plist> conforms to a protocol
5582 // of IDecl's, then bridge casting is ok.
5583 bool Conforms = false;
5584 for (auto *Proto : OPT->quals()) {
5585 Conforms = false;
5586 for (auto *PI : InheritedProtocols) {
5587 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5588 Conforms = true;
5589 break;
5590 }
5591 }
5592 if (!Conforms)
5593 break;
5594 }
5595 if (Conforms)
5596 return true;
5597
5598 for (auto *PI : InheritedProtocols) {
5599 // If both the right and left sides have qualifiers.
5600 bool Adopts = false;
5601 for (auto *Proto : OPT->quals()) {
5602 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5603 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5604 break;
5605 }
5606 if (!Adopts)
5607 return false;
5608 }
5609 return true;
5610}
5611
5612/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5613/// the given object type.
5615 llvm::FoldingSetNodeID ID;
5616 ObjCObjectPointerType::Profile(ID, ObjectT);
5617
5618 void *InsertPos = nullptr;
5619 if (ObjCObjectPointerType *QT =
5620 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5621 return QualType(QT, 0);
5622
5623 // Find the canonical object type.
5624 QualType Canonical;
5625 if (!ObjectT.isCanonical()) {
5626 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5627
5628 // Regenerate InsertPos.
5629 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5630 }
5631
5632 // No match.
5633 void *Mem =
5635 auto *QType =
5636 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5637
5638 Types.push_back(QType);
5639 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5640 return QualType(QType, 0);
5641}
5642
5643/// getObjCInterfaceType - Return the unique reference to the type for the
5644/// specified ObjC interface decl. The list of protocols is optional.
5646 ObjCInterfaceDecl *PrevDecl) const {
5647 if (Decl->TypeForDecl)
5648 return QualType(Decl->TypeForDecl, 0);
5649
5650 if (PrevDecl) {
5651 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5652 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5653 return QualType(PrevDecl->TypeForDecl, 0);
5654 }
5655
5656 // Prefer the definition, if there is one.
5657 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5658 Decl = Def;
5659
5660 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
5661 auto *T = new (Mem) ObjCInterfaceType(Decl);
5662 Decl->TypeForDecl = T;
5663 Types.push_back(T);
5664 return QualType(T, 0);
5665}
5666
5667/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5668/// TypeOfExprType AST's (since expression's are never shared). For example,
5669/// multiple declarations that refer to "typeof(x)" all contain different
5670/// DeclRefExpr's. This doesn't effect the type checker, since it operates
5671/// on canonical type's (which are always unique).
5673 TypeOfExprType *toe;
5674 if (tofExpr->isTypeDependent()) {
5675 llvm::FoldingSetNodeID ID;
5676 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
5677 Kind == TypeOfKind::Unqualified);
5678
5679 void *InsertPos = nullptr;
5681 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5682 if (Canon) {
5683 // We already have a "canonical" version of an identical, dependent
5684 // typeof(expr) type. Use that as our canonical type.
5685 toe = new (*this, alignof(TypeOfExprType))
5686 TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
5687 } else {
5688 // Build a new, canonical typeof(expr) type.
5689 Canon = new (*this, alignof(DependentTypeOfExprType))
5690 DependentTypeOfExprType(tofExpr, Kind);
5691 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5692 toe = Canon;
5693 }
5694 } else {
5695 QualType Canonical = getCanonicalType(tofExpr->getType());
5696 toe = new (*this, alignof(TypeOfExprType))
5697 TypeOfExprType(tofExpr, Kind, Canonical);
5698 }
5699 Types.push_back(toe);
5700 return QualType(toe, 0);
5701}
5702
5703/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5704/// TypeOfType nodes. The only motivation to unique these nodes would be
5705/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5706/// an issue. This doesn't affect the type checker, since it operates
5707/// on canonical types (which are always unique).
5709 QualType Canonical = getCanonicalType(tofType);
5710 auto *tot =
5711 new (*this, alignof(TypeOfType)) TypeOfType(tofType, Canonical, Kind);
5712 Types.push_back(tot);
5713 return QualType(tot, 0);
5714}
5715
5716/// getReferenceQualifiedType - Given an expr, will return the type for
5717/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5718/// and class member access into account.
5720 // C++11 [dcl.type.simple]p4:
5721 // [...]
5722 QualType T = E->getType();
5723 switch (E->getValueKind()) {
5724 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5725 // type of e;
5726 case VK_XValue:
5727 return getRValueReferenceType(T);
5728 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5729 // type of e;
5730 case VK_LValue:
5731 return getLValueReferenceType(T);
5732 // - otherwise, decltype(e) is the type of e.
5733 case VK_PRValue:
5734 return T;
5735 }
5736 llvm_unreachable("Unknown value kind");
5737}
5738
5739/// Unlike many "get<Type>" functions, we don't unique DecltypeType
5740/// nodes. This would never be helpful, since each such type has its own
5741/// expression, and would not give a significant memory saving, since there
5742/// is an Expr tree under each such type.
5744 DecltypeType *dt;
5745
5746 // C++11 [temp.type]p2:
5747 // If an expression e involves a template parameter, decltype(e) denotes a
5748 // unique dependent type. Two such decltype-specifiers refer to the same
5749 // type only if their expressions are equivalent (14.5.6.1).
5750 if (e->isInstantiationDependent()) {
5751 llvm::FoldingSetNodeID ID;
5752 DependentDecltypeType::Profile(ID, *this, e);
5753
5754 void *InsertPos = nullptr;
5756 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5757 if (!Canon) {
5758 // Build a new, canonical decltype(expr) type.
5759 Canon = new (*this, alignof(DependentDecltypeType))
5761 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5762 }
5763 dt = new (*this, alignof(DecltypeType))
5764 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5765 } else {
5766 dt = new (*this, alignof(DecltypeType))
5767 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5768 }
5769 Types.push_back(dt);
5770 return QualType(dt, 0);
5771}
5772
5774 bool FullySubstituted,
5775 ArrayRef<QualType> Expansions,
5776 int Index) const {
5777 QualType Canonical;
5778 if (FullySubstituted && Index != -1) {
5779 Canonical = getCanonicalType(Expansions[Index]);
5780 } else {
5781 llvm::FoldingSetNodeID ID;
5782 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr);
5783 void *InsertPos = nullptr;
5784 PackIndexingType *Canon =
5785 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
5786 if (!Canon) {
5787 void *Mem = Allocate(
5788 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5790 Canon = new (Mem)
5791 PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions);
5792 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
5793 }
5794 Canonical = QualType(Canon, 0);
5795 }
5796
5797 void *Mem =
5798 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
5800 auto *T = new (Mem)
5801 PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions);
5802 Types.push_back(T);
5803 return QualType(T, 0);
5804}
5805
5806/// getUnaryTransformationType - We don't unique these, since the memory
5807/// savings are minimal and these are rare.
5809 QualType UnderlyingType,
5811 const {
5812 UnaryTransformType *ut = nullptr;
5813
5814 if (BaseType->isDependentType()) {
5815 // Look in the folding set for an existing type.
5816 llvm::FoldingSetNodeID ID;
5818
5819 void *InsertPos = nullptr;
5821 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5822
5823 if (!Canon) {
5824 // Build a new, canonical __underlying_type(type) type.
5825 Canon = new (*this, alignof(DependentUnaryTransformType))
5826 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
5827 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5828 }
5829 ut = new (*this, alignof(UnaryTransformType))
5830 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
5831 } else {
5832 QualType CanonType = getCanonicalType(UnderlyingType);
5833 ut = new (*this, alignof(UnaryTransformType))
5834 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
5835 }
5836 Types.push_back(ut);
5837 return QualType(ut, 0);
5838}
5839
5840QualType ASTContext::getAutoTypeInternal(
5841 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5842 bool IsPack, ConceptDecl *TypeConstraintConcept,
5843 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5844 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5845 !TypeConstraintConcept && !IsDependent)
5846 return getAutoDeductType();
5847
5848 // Look in the folding set for an existing type.
5849 void *InsertPos = nullptr;
5850 llvm::FoldingSetNodeID ID;
5851 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5852 TypeConstraintConcept, TypeConstraintArgs);
5853 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5854 return QualType(AT, 0);
5855
5856 QualType Canon;
5857 if (!IsCanon) {
5858 if (!DeducedType.isNull()) {
5859 Canon = DeducedType.getCanonicalType();
5860 } else if (TypeConstraintConcept) {
5861 bool AnyNonCanonArgs = false;
5862 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
5863 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
5864 *this, TypeConstraintArgs, AnyNonCanonArgs);
5865 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
5866 Canon =
5867 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5868 CanonicalConcept, CanonicalConceptArgs, true);
5869 // Find the insert position again.
5870 [[maybe_unused]] auto *Nothing =
5871 AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5872 assert(!Nothing && "canonical type broken");
5873 }
5874 }
5875 }
5876
5877 void *Mem = Allocate(sizeof(AutoType) +
5878 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5879 alignof(AutoType));
5880 auto *AT = new (Mem) AutoType(
5881 DeducedType, Keyword,
5882 (IsDependent ? TypeDependence::DependentInstantiation
5883 : TypeDependence::None) |
5884 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5885 Canon, TypeConstraintConcept, TypeConstraintArgs);
5886 Types.push_back(AT);
5887 AutoTypes.InsertNode(AT, InsertPos);
5888 return QualType(AT, 0);
5889}
5890
5891/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5892/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5893/// canonical deduced-but-dependent 'auto' type.
5896 bool IsDependent, bool IsPack,
5897 ConceptDecl *TypeConstraintConcept,
5898 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5899 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5900 assert((!IsDependent || DeducedType.isNull()) &&
5901 "A dependent auto should be undeduced");
5902 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5903 TypeConstraintConcept, TypeConstraintArgs);
5904}
5905
5907 QualType CanonT = T.getCanonicalType();
5908
5909 // Remove a type-constraint from a top-level auto or decltype(auto).
5910 if (auto *AT = CanonT->getAs<AutoType>()) {
5911 if (!AT->isConstrained())
5912 return T;
5913 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
5914 AT->isDependentType(),
5915 AT->containsUnexpandedParameterPack()),
5916 T.getQualifiers());
5917 }
5918
5919 // FIXME: We only support constrained auto at the top level in the type of a
5920 // non-type template parameter at the moment. Once we lift that restriction,
5921 // we'll need to recursively build types containing auto here.
5922 assert(!CanonT->getContainedAutoType() ||
5923 !CanonT->getContainedAutoType()->isConstrained());
5924 return T;
5925}
5926
5927/// Return the uniqued reference to the deduced template specialization type
5928/// which has been deduced to the given type, or to the canonical undeduced
5929/// such type, or the canonical deduced-but-dependent such type.
5931 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5932 // Look in the folding set for an existing type.
5933 void *InsertPos = nullptr;
5934 llvm::FoldingSetNodeID ID;
5936 IsDependent);
5938 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5939 return QualType(DTST, 0);
5940
5941 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
5942 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5943 llvm::FoldingSetNodeID TempID;
5944 DTST->Profile(TempID);
5945 assert(ID == TempID && "ID does not match");
5946 Types.push_back(DTST);
5947 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5948 return QualType(DTST, 0);
5949}
5950
5951/// getAtomicType - Return the uniqued reference to the atomic type for
5952/// the given value type.
5954 // Unique pointers, to guarantee there is only one pointer of a particular
5955 // structure.
5956 llvm::FoldingSetNodeID ID;
5958
5959 void *InsertPos = nullptr;
5960 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5961 return QualType(AT, 0);
5962
5963 // If the atomic value type isn't canonical, this won't be a canonical type
5964 // either, so fill in the canonical type field.
5965 QualType Canonical;
5966 if (!T.isCanonical()) {
5967 Canonical = getAtomicType(getCanonicalType(T));
5968
5969 // Get the new insert position for the node we care about.
5970 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5971 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5972 }
5973 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
5974 Types.push_back(New);
5975 AtomicTypes.InsertNode(New, InsertPos);
5976 return QualType(New, 0);
5977}
5978
5979/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5981 if (AutoDeductTy.isNull())
5982 AutoDeductTy = QualType(new (*this, alignof(AutoType))
5984 TypeDependence::None, QualType(),
5985 /*concept*/ nullptr, /*args*/ {}),
5986 0);
5987 return AutoDeductTy;
5988}
5989
5990/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5994 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5995 return AutoRRefDeductTy;
5996}
5997
5998/// getTagDeclType - Return the unique reference to the type for the
5999/// specified TagDecl (struct/union/class/enum) decl.
6001 assert(Decl);
6002 // FIXME: What is the design on getTagDeclType when it requires casting
6003 // away const? mutable?
6004 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6005}
6006
6007/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6008/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6009/// needs to agree with the definition in <stddef.h>.
6011 return getFromTargetType(Target->getSizeType());
6012}
6013
6014/// Return the unique signed counterpart of the integer type
6015/// corresponding to size_t.
6017 return getFromTargetType(Target->getSignedSizeType());
6018}
6019
6020/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6022 return getFromTargetType(Target->getIntMaxType());
6023}
6024
6025/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6027 return getFromTargetType(Target->getUIntMaxType());
6028}
6029
6030/// getSignedWCharType - Return the type of "signed wchar_t".
6031/// Used when in C++, as a GCC extension.
6033 // FIXME: derive from "Target" ?
6034 return WCharTy;
6035}
6036
6037/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6038/// Used when in C++, as a GCC extension.
6040 // FIXME: derive from "Target" ?
6041 return UnsignedIntTy;
6042}
6043
6045 return getFromTargetType(Target->getIntPtrType());
6046}
6047
6050}
6051
6052/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6053/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6055 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6056}
6057
6058/// Return the unique unsigned counterpart of "ptrdiff_t"
6059/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6060/// in the definition of %tu format specifier.
6062 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6063}
6064
6065/// Return the unique type for "pid_t" defined in
6066/// <sys/types.h>. We need this to compute the correct type for vfork().
6068 return getFromTargetType(Target->getProcessIDType());
6069}
6070
6071//===----------------------------------------------------------------------===//
6072// Type Operators
6073//===----------------------------------------------------------------------===//
6074
6076 // Push qualifiers into arrays, and then discard any remaining
6077 // qualifiers.
6078 T = getCanonicalType(T);
6080 const Type *Ty = T.getTypePtr();
6082 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6084 } else if (isa<ArrayType>(Ty)) {
6086 } else if (isa<FunctionType>(Ty)) {
6087 Result = getPointerType(QualType(Ty, 0));
6088 } else {
6089 Result = QualType(Ty, 0);
6090 }
6091
6093}
6094
6096 Qualifiers &quals) {
6097 SplitQualType splitType = type.getSplitUnqualifiedType();
6098
6099 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6100 // the unqualified desugared type and then drops it on the floor.
6101 // We then have to strip that sugar back off with
6102 // getUnqualifiedDesugaredType(), which is silly.
6103 const auto *AT =
6104 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6105
6106 // If we don't have an array, just use the results in splitType.
6107 if (!AT) {
6108 quals = splitType.Quals;
6109 return QualType(splitType.Ty, 0);
6110 }
6111
6112 // Otherwise, recurse on the array's element type.
6113 QualType elementType = AT->getElementType();
6114 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6115
6116 // If that didn't change the element type, AT has no qualifiers, so we
6117 // can just use the results in splitType.
6118 if (elementType == unqualElementType) {
6119 assert(quals.empty()); // from the recursive call
6120 quals = splitType.Quals;
6121 return QualType(splitType.Ty, 0);
6122 }
6123
6124 // Otherwise, add in the qualifiers from the outermost type, then
6125 // build the type back up.
6126 quals.addConsistentQualifiers(splitType.Quals);
6127
6128 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6129 return getConstantArrayType(unqualElementType, CAT->getSize(),
6130 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6131 }
6132
6133 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6134 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6135 }
6136
6137 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6138 return getVariableArrayType(unqualElementType,
6139 VAT->getSizeExpr(),
6140 VAT->getSizeModifier(),
6141 VAT->getIndexTypeCVRQualifiers(),
6142 VAT->getBracketsRange());
6143 }
6144
6145 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6146 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6147 DSAT->getSizeModifier(), 0,
6148 SourceRange());
6149}
6150
6151/// Attempt to unwrap two types that may both be array types with the same bound
6152/// (or both be array types of unknown bound) for the purpose of comparing the
6153/// cv-decomposition of two types per C++ [conv.qual].
6154///
6155/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6156/// C++20 [conv.qual], if permitted by the current language mode.
6158 bool AllowPiMismatch) {
6159 while (true) {
6160 auto *AT1 = getAsArrayType(T1);
6161 if (!AT1)
6162 return;
6163
6164 auto *AT2 = getAsArrayType(T2);
6165 if (!AT2)
6166 return;
6167
6168 // If we don't have two array types with the same constant bound nor two
6169 // incomplete array types, we've unwrapped everything we can.
6170 // C++20 also permits one type to be a constant array type and the other
6171 // to be an incomplete array type.
6172 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6173 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6174 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6175 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6176 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6177 isa<IncompleteArrayType>(AT2))))
6178 return;
6179 } else if (isa<IncompleteArrayType>(AT1)) {
6180 if (!(isa<IncompleteArrayType>(AT2) ||
6181 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6182 isa<ConstantArrayType>(AT2))))
6183 return;
6184 } else {
6185 return;
6186 }
6187
6188 T1 = AT1->getElementType();
6189 T2 = AT2->getElementType();
6190 }
6191}
6192
6193/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6194///
6195/// If T1 and T2 are both pointer types of the same kind, or both array types
6196/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6197/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6198///
6199/// This function will typically be called in a loop that successively
6200/// "unwraps" pointer and pointer-to-member types to compare them at each
6201/// level.
6202///
6203/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6204/// C++20 [conv.qual], if permitted by the current language mode.
6205///
6206/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6207/// pair of types that can't be unwrapped further.
6209 bool AllowPiMismatch) {
6210 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6211
6212 const auto *T1PtrType = T1->getAs<PointerType>();
6213 const auto *T2PtrType = T2->getAs<PointerType>();
6214 if (T1PtrType && T2PtrType) {
6215 T1 = T1PtrType->getPointeeType();
6216 T2 = T2PtrType->getPointeeType();
6217 return true;
6218 }
6219
6220 const auto *T1MPType = T1->getAs<MemberPointerType>();
6221 const auto *T2MPType = T2->getAs<MemberPointerType>();
6222 if (T1MPType && T2MPType &&
6223 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6224 QualType(T2MPType->getClass(), 0))) {
6225 T1 = T1MPType->getPointeeType();
6226 T2 = T2MPType->getPointeeType();
6227 return true;
6228 }
6229
6230 if (getLangOpts().ObjC) {
6231 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6232 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6233 if (T1OPType && T2OPType) {
6234 T1 = T1OPType->getPointeeType();
6235 T2 = T2OPType->getPointeeType();
6236 return true;
6237 }
6238 }
6239
6240 // FIXME: Block pointers, too?
6241
6242 return false;
6243}
6244
6246 while (true) {
6247 Qualifiers Quals;
6248 T1 = getUnqualifiedArrayType(T1, Quals);
6249 T2 = getUnqualifiedArrayType(T2, Quals);
6250 if (hasSameType(T1, T2))
6251 return true;
6252 if (!UnwrapSimilarTypes(T1, T2))
6253 return false;
6254 }
6255}
6256
6258 while (true) {
6259 Qualifiers Quals1, Quals2;
6260 T1 = getUnqualifiedArrayType(T1, Quals1);
6261 T2 = getUnqualifiedArrayType(T2, Quals2);
6262
6263 Quals1.removeCVRQualifiers();
6264 Quals2.removeCVRQualifiers();
6265 if (Quals1 != Quals2)
6266 return false;
6267
6268 if (hasSameType(T1, T2))
6269 return true;
6270
6271 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6272 return false;
6273 }
6274}
6275
6278 SourceLocation NameLoc) const {
6279 switch (Name.getKind()) {
6282 // DNInfo work in progress: CHECKME: what about DNLoc?
6283 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6284 NameLoc);
6285
6287 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6288 // DNInfo work in progress: CHECKME: what about DNLoc?
6289 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6290 }
6291
6293 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6294 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6295 }
6296
6298 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6299 DeclarationName DName;
6300 if (DTN->isIdentifier()) {
6302 return DeclarationNameInfo(DName, NameLoc);
6303 } else {
6305 // DNInfo work in progress: FIXME: source locations?
6306 DeclarationNameLoc DNLoc =
6308 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6309 }
6310 }
6311
6314 = Name.getAsSubstTemplateTemplateParm();
6315 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6316 NameLoc);
6317 }
6318
6321 = Name.getAsSubstTemplateTemplateParmPack();
6323 NameLoc);
6324 }
6326 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6327 NameLoc);
6328 }
6329
6330 llvm_unreachable("bad template name kind!");
6331}
6332
6335 switch (Name.getKind()) {
6339 TemplateDecl *Template = Name.getAsTemplateDecl();
6340 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6341 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6342
6343 // The canonical template name is the canonical template declaration.
6344 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6345 }
6346
6349 llvm_unreachable("cannot canonicalize unresolved template");
6350
6352 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6353 assert(DTN && "Non-dependent template names must refer to template decls.");
6354 return DTN->CanonicalTemplateName;
6355 }
6356
6359 = Name.getAsSubstTemplateTemplateParm();
6361 }
6362
6365 Name.getAsSubstTemplateTemplateParmPack();
6366 TemplateArgument canonArgPack =
6369 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6370 subst->getFinal(), subst->getIndex());
6371 }
6372 }
6373
6374 llvm_unreachable("bad template name!");
6375}
6376
6378 const TemplateName &Y) const {
6381}
6382
6383bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6384 if (!XCE != !YCE)
6385 return false;
6386
6387 if (!XCE)
6388 return true;
6389
6390 llvm::FoldingSetNodeID XCEID, YCEID;
6391 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6392 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6393 return XCEID == YCEID;
6394}
6395
6397 const TypeConstraint *YTC) const {
6398 if (!XTC != !YTC)
6399 return false;
6400
6401 if (!XTC)
6402 return true;
6403
6404 auto *NCX = XTC->getNamedConcept();
6405 auto *NCY = YTC->getNamedConcept();
6406 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6407 return false;
6410 return false;
6412 if (XTC->getConceptReference()
6414 ->NumTemplateArgs !=
6416 return false;
6417
6418 // Compare slowly by profiling.
6419 //
6420 // We couldn't compare the profiling result for the template
6421 // args here. Consider the following example in different modules:
6422 //
6423 // template <__integer_like _Tp, C<_Tp> Sentinel>
6424 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6425 // return __t;
6426 // }
6427 //
6428 // When we compare the profiling result for `C<_Tp>` in different
6429 // modules, it will compare the type of `_Tp` in different modules.
6430 // However, the type of `_Tp` in different modules refer to different
6431 // types here naturally. So we couldn't compare the profiling result
6432 // for the template args directly.
6435}
6436
6438 const NamedDecl *Y) const {
6439 if (X->getKind() != Y->getKind())
6440 return false;
6441
6442 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6443 auto *TY = cast<TemplateTypeParmDecl>(Y);
6444 if (TX->isParameterPack() != TY->isParameterPack())
6445 return false;
6446 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6447 return false;
6448 return isSameTypeConstraint(TX->getTypeConstraint(),
6449 TY->getTypeConstraint());
6450 }
6451
6452 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6453 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6454 return TX->isParameterPack() == TY->isParameterPack() &&
6455 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6456 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6457 TY->getPlaceholderTypeConstraint());
6458 }
6459
6460 auto *TX = cast<TemplateTemplateParmDecl>(X);
6461 auto *TY = cast<TemplateTemplateParmDecl>(Y);
6462 return TX->isParameterPack() == TY->isParameterPack() &&
6463 isSameTemplateParameterList(TX->getTemplateParameters(),
6464 TY->getTemplateParameters());
6465}
6466
6468 const TemplateParameterList *X, const TemplateParameterList *Y) const {
6469 if (X->size() != Y->size())
6470 return false;
6471
6472 for (unsigned I = 0, N = X->size(); I != N; ++I)
6473 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6474 return false;
6475
6476 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6477}
6478
6480 const NamedDecl *Y) const {
6481 // If the type parameter isn't the same already, we don't need to check the
6482 // default argument further.
6483 if (!isSameTemplateParameter(X, Y))
6484 return false;
6485
6486 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6487 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6488 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6489 return false;
6490
6491 return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
6492 }
6493
6494 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6495 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6496 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6497 return false;
6498
6499 Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
6500 Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
6501 llvm::FoldingSetNodeID XID, YID;
6502 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6503 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6504 return XID == YID;
6505 }
6506
6507 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6508 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6509
6510 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6511 return false;
6512
6513 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6514 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6515 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6516}
6517
6519 if (auto *NS = X->getAsNamespace())
6520 return NS;
6521 if (auto *NAS = X->getAsNamespaceAlias())
6522 return NAS->getNamespace();
6523 return nullptr;
6524}
6525
6527 const NestedNameSpecifier *Y) {
6528 if (auto *NSX = getNamespace(X)) {
6529 auto *NSY = getNamespace(Y);
6530 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6531 return false;
6532 } else if (X->getKind() != Y->getKind())
6533 return false;
6534
6535 // FIXME: For namespaces and types, we're permitted to check that the entity
6536 // is named via the same tokens. We should probably do so.
6537 switch (X->getKind()) {
6539 if (X->getAsIdentifier() != Y->getAsIdentifier())
6540 return false;
6541 break;
6544 // We've already checked that we named the same namespace.
6545 break;
6548 if (X->getAsType()->getCanonicalTypeInternal() !=
6550 return false;
6551 break;
6554 return true;
6555 }
6556
6557 // Recurse into earlier portion of NNS, if any.
6558 auto *PX = X->getPrefix();
6559 auto *PY = Y->getPrefix();
6560 if (PX && PY)
6561 return isSameQualifier(PX, PY);
6562 return !PX && !PY;
6563}
6564
6565/// Determine whether the attributes we can overload on are identical for A and
6566/// B. Will ignore any overloadable attrs represented in the type of A and B.
6568 const FunctionDecl *B) {
6569 // Note that pass_object_size attributes are represented in the function's
6570 // ExtParameterInfo, so we don't need to check them here.
6571
6572 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6573 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6574 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6575
6576 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6577 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6578 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6579
6580 // Return false if the number of enable_if attributes is different.
6581 if (!Cand1A || !Cand2A)
6582 return false;
6583
6584 Cand1ID.clear();
6585 Cand2ID.clear();
6586
6587 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6588 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6589
6590 // Return false if any of the enable_if expressions of A and B are
6591 // different.
6592 if (Cand1ID != Cand2ID)
6593 return false;
6594 }
6595 return true;
6596}
6597
6598bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6599 // Caution: this function is called by the AST reader during deserialization,
6600 // so it cannot rely on AST invariants being met. Non-trivial accessors
6601 // should be avoided, along with any traversal of redeclaration chains.
6602
6603 if (X == Y)
6604 return true;
6605
6606 if (X->getDeclName() != Y->getDeclName())
6607 return false;
6608
6609 // Must be in the same context.
6610 //
6611 // Note that we can't use DeclContext::Equals here, because the DeclContexts
6612 // could be two different declarations of the same function. (We will fix the
6613 // semantic DC to refer to the primary definition after merging.)
6614 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6615 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6616 return false;
6617
6618 // Two typedefs refer to the same entity if they have the same underlying
6619 // type.
6620 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6621 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6622 return hasSameType(TypedefX->getUnderlyingType(),
6623 TypedefY->getUnderlyingType());
6624
6625 // Must have the same kind.
6626 if (X->getKind() != Y->getKind())
6627 return false;
6628
6629 // Objective-C classes and protocols with the same name always match.
6630 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6631 return true;
6632
6633 if (isa<ClassTemplateSpecializationDecl>(X)) {
6634 // No need to handle these here: we merge them when adding them to the
6635 // template.
6636 return false;
6637 }
6638
6639 // Compatible tags match.
6640 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6641 const auto *TagY = cast<TagDecl>(Y);
6642 return (TagX->getTagKind() == TagY->getTagKind()) ||
6643 ((TagX->getTagKind() == TagTypeKind::Struct ||
6644 TagX->getTagKind() == TagTypeKind::Class ||
6645 TagX->getTagKind() == TagTypeKind::Interface) &&
6646 (TagY->getTagKind() == TagTypeKind::Struct ||
6647 TagY->getTagKind() == TagTypeKind::Class ||
6648 TagY->getTagKind() == TagTypeKind::Interface));
6649 }
6650
6651 // Functions with the same type and linkage match.
6652 // FIXME: This needs to cope with merging of prototyped/non-prototyped
6653 // functions, etc.
6654 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6655 const auto *FuncY = cast<FunctionDecl>(Y);
6656 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6657 const auto *CtorY = cast<CXXConstructorDecl>(Y);
6658 if (CtorX->getInheritedConstructor() &&
6659 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6660 CtorY->getInheritedConstructor().getConstructor()))
6661 return false;
6662 }
6663
6664 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6665 return false;
6666
6667 // Multiversioned functions with different feature strings are represented
6668 // as separate declarations.
6669 if (FuncX->isMultiVersion()) {
6670 const auto *TAX = FuncX->getAttr<TargetAttr>();
6671 const auto *TAY = FuncY->getAttr<TargetAttr>();
6672 assert(TAX && TAY && "Multiversion Function without target attribute");
6673
6674 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6675 return false;
6676 }
6677
6678 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
6679 // not the same entity if they are constrained.
6680 if ((FuncX->isMemberLikeConstrainedFriend() ||
6681 FuncY->isMemberLikeConstrainedFriend()) &&
6682 !FuncX->getLexicalDeclContext()->Equals(
6683 FuncY->getLexicalDeclContext())) {
6684 return false;
6685 }
6686
6687 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
6688 FuncY->getTrailingRequiresClause()))
6689 return false;
6690
6691 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6692 // Map to the first declaration that we've already merged into this one.
6693 // The TSI of redeclarations might not match (due to calling conventions
6694 // being inherited onto the type but not the TSI), but the TSI type of
6695 // the first declaration of the function should match across modules.
6696 FD = FD->getCanonicalDecl();
6697 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6698 : FD->getType();
6699 };
6700 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6701 if (!hasSameType(XT, YT)) {
6702 // We can get functions with different types on the redecl chain in C++17
6703 // if they have differing exception specifications and at least one of
6704 // the excpetion specs is unresolved.
6705 auto *XFPT = XT->getAs<FunctionProtoType>();
6706 auto *YFPT = YT->getAs<FunctionProtoType>();
6707 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6708 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6711 return true;
6712 return false;
6713 }
6714
6715 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6716 hasSameOverloadableAttrs(FuncX, FuncY);
6717 }
6718
6719 // Variables with the same type and linkage match.
6720 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6721 const auto *VarY = cast<VarDecl>(Y);
6722 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6723 // During deserialization, we might compare variables before we load
6724 // their types. Assume the types will end up being the same.
6725 if (VarX->getType().isNull() || VarY->getType().isNull())
6726 return true;
6727
6728 if (hasSameType(VarX->getType(), VarY->getType()))
6729 return true;
6730
6731 // We can get decls with different types on the redecl chain. Eg.
6732 // template <typename T> struct S { static T Var[]; }; // #1
6733 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6734 // Only? happens when completing an incomplete array type. In this case
6735 // when comparing #1 and #2 we should go through their element type.
6736 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6737 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6738 if (!VarXTy || !VarYTy)
6739 return false;
6740 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6741 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6742 }
6743 return false;
6744 }
6745
6746 // Namespaces with the same name and inlinedness match.
6747 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6748 const auto *NamespaceY = cast<NamespaceDecl>(Y);
6749 return NamespaceX->isInline() == NamespaceY->isInline();
6750 }
6751
6752 // Identical template names and kinds match if their template parameter lists
6753 // and patterns match.
6754 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6755 const auto *TemplateY = cast<TemplateDecl>(Y);
6756
6757 // ConceptDecl wouldn't be the same if their constraint expression differs.
6758 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
6759 const auto *ConceptY = cast<ConceptDecl>(Y);
6760 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
6761 ConceptY->getConstraintExpr()))
6762 return false;
6763 }
6764
6765 return isSameEntity(TemplateX->getTemplatedDecl(),
6766 TemplateY->getTemplatedDecl()) &&
6767 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6768 TemplateY->getTemplateParameters());
6769 }
6770
6771 // Fields with the same name and the same type match.
6772 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6773 const auto *FDY = cast<FieldDecl>(Y);
6774 // FIXME: Also check the bitwidth is odr-equivalent, if any.
6775 return hasSameType(FDX->getType(), FDY->getType());
6776 }
6777
6778 // Indirect fields with the same target field match.
6779 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6780 const auto *IFDY = cast<IndirectFieldDecl>(Y);
6781 return IFDX->getAnonField()->getCanonicalDecl() ==
6782 IFDY->getAnonField()->getCanonicalDecl();
6783 }
6784
6785 // Enumerators with the same name match.
6786 if (isa<EnumConstantDecl>(X))
6787 // FIXME: Also check the value is odr-equivalent.
6788 return true;
6789
6790 // Using shadow declarations with the same target match.
6791 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6792 const auto *USY = cast<UsingShadowDecl>(Y);
6793 return USX->getTargetDecl() == USY->getTargetDecl();
6794 }
6795
6796 // Using declarations with the same qualifier match. (We already know that
6797 // the name matches.)
6798 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6799 const auto *UY = cast<UsingDecl>(Y);
6800 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6801 UX->hasTypename() == UY->hasTypename() &&
6802 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6803 }
6804 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6805 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6806 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6807 UX->isAccessDeclaration() == UY->isAccessDeclaration();
6808 }
6809 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6810 return isSameQualifier(
6811 UX->getQualifier(),
6812 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6813 }
6814
6815 // Using-pack declarations are only created by instantiation, and match if
6816 // they're instantiated from matching UnresolvedUsing...Decls.
6817 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6818 return declaresSameEntity(
6819 UX->getInstantiatedFromUsingDecl(),
6820 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6821 }
6822
6823 // Namespace alias definitions with the same target match.
6824 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6825 const auto *NAY = cast<NamespaceAliasDecl>(Y);
6826 return NAX->getNamespace()->Equals(NAY->getNamespace());
6827 }
6828
6829 return false;
6830}
6831
6834 switch (Arg.getKind()) {
6836 return Arg;
6837
6839 return Arg;
6840
6842 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6844 Arg.getIsDefaulted());
6845 }
6846
6849 /*isNullPtr*/ true, Arg.getIsDefaulted());
6850
6853 Arg.getIsDefaulted());
6854
6856 return TemplateArgument(
6859
6862
6864 return TemplateArgument(*this,
6866 Arg.getAsStructuralValue());
6867
6870 /*isNullPtr*/ false, Arg.getIsDefaulted());
6871
6873 bool AnyNonCanonArgs = false;
6874 auto CanonArgs = ::getCanonicalTemplateArguments(
6875 *this, Arg.pack_elements(), AnyNonCanonArgs);
6876 if (!AnyNonCanonArgs)
6877 return Arg;
6878 return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
6879 CanonArgs);
6880 }
6881 }
6882
6883 // Silence GCC warning
6884 llvm_unreachable("Unhandled template argument kind");
6885}
6886
6889 if (!NNS)
6890 return nullptr;
6891
6892 switch (NNS->getKind()) {
6894 // Canonicalize the prefix but keep the identifier the same.
6895 return NestedNameSpecifier::Create(*this,
6897 NNS->getAsIdentifier());
6898
6900 // A namespace is canonical; build a nested-name-specifier with
6901 // this namespace and no prefix.
6902 return NestedNameSpecifier::Create(*this, nullptr,
6904
6906 // A namespace is canonical; build a nested-name-specifier with
6907 // this namespace and no prefix.
6908 return NestedNameSpecifier::Create(*this, nullptr,
6911
6912 // The difference between TypeSpec and TypeSpecWithTemplate is that the
6913 // latter will have the 'template' keyword when printed.
6916 const Type *T = getCanonicalType(NNS->getAsType());
6917
6918 // If we have some kind of dependent-named type (e.g., "typename T::type"),
6919 // break it apart into its prefix and identifier, then reconsititute those
6920 // as the canonical nested-name-specifier. This is required to canonicalize
6921 // a dependent nested-name-specifier involving typedefs of dependent-name
6922 // types, e.g.,
6923 // typedef typename T::type T1;
6924 // typedef typename T1::type T2;
6925 if (const auto *DNT = T->getAs<DependentNameType>())
6926 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
6927 DNT->getIdentifier());
6928 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6929 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
6930
6931 // TODO: Set 'Template' parameter to true for other template types.
6932 return NestedNameSpecifier::Create(*this, nullptr, false, T);
6933 }
6934
6937 // The global specifier and __super specifer are canonical and unique.
6938 return NNS;
6939 }
6940
6941 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6942}
6943
6945 // Handle the non-qualified case efficiently.
6946 if (!T.hasLocalQualifiers()) {
6947 // Handle the common positive case fast.
6948 if (const auto *AT = dyn_cast<ArrayType>(T))
6949 return AT;
6950 }
6951
6952 // Handle the common negative case fast.
6953 if (!isa<ArrayType>(T.getCanonicalType()))
6954 return nullptr;
6955
6956 // Apply any qualifiers from the array type to the element type. This
6957 // implements C99 6.7.3p8: "If the specification of an array type includes
6958 // any type qualifiers, the element type is so qualified, not the array type."
6959
6960 // If we get here, we either have type qualifiers on the type, or we have
6961 // sugar such as a typedef in the way. If we have type qualifiers on the type
6962 // we must propagate them down into the element type.
6963
6964 SplitQualType split = T.getSplitDesugaredType();
6965 Qualifiers qs = split.Quals;
6966
6967 // If we have a simple case, just return now.
6968 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6969 if (!ATy || qs.empty())
6970 return ATy;
6971
6972 // Otherwise, we have an array and we have qualifiers on it. Push the
6973 // qualifiers into the array element type and return a new array type.
6974 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6975
6976 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6977 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6978 CAT->getSizeExpr(),
6979 CAT->getSizeModifier(),
6980 CAT->getIndexTypeCVRQualifiers()));
6981 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6982 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6983 IAT->getSizeModifier(),
6984 IAT->getIndexTypeCVRQualifiers()));
6985
6986 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6987 return cast<ArrayType>(
6989 DSAT->getSizeExpr(),
6990 DSAT->getSizeModifier(),
6991 DSAT->getIndexTypeCVRQualifiers(),
6992 DSAT->getBracketsRange()));
6993
6994 const auto *VAT = cast<VariableArrayType>(ATy);
6995 return cast<ArrayType>(getVariableArrayType(NewEltTy,
6996 VAT->getSizeExpr(),
6997 VAT->getSizeModifier(),
6998 VAT->getIndexTypeCVRQualifiers(),
6999 VAT->getBracketsRange()));
7000}
7001
7004 return getArrayParameterType(T);
7005 if (T->isArrayType() || T->isFunctionType())
7006 return getDecayedType(T);
7007 return T;
7008}
7009
7013 return T.getUnqualifiedType();
7014}
7015
7017 // C++ [except.throw]p3:
7018 // A throw-expression initializes a temporary object, called the exception
7019 // object, the type of which is determined by removing any top-level
7020 // cv-qualifiers from the static type of the operand of throw and adjusting
7021 // the type from "array of T" or "function returning T" to "pointer to T"
7022 // or "pointer to function returning T", [...]
7024 if (T->isArrayType() || T->isFunctionType())
7025 T = getDecayedType(T);
7026 return T.getUnqualifiedType();
7027}
7028
7029/// getArrayDecayedType - Return the properly qualified result of decaying the
7030/// specified array type to a pointer. This operation is non-trivial when
7031/// handling typedefs etc. The canonical type of "T" must be an array type,
7032/// this returns a pointer to a properly qualified element of the array.
7033///
7034/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7036 // Get the element type with 'getAsArrayType' so that we don't lose any
7037 // typedefs in the element type of the array. This also handles propagation
7038 // of type qualifiers from the array type into the element type if present
7039 // (C99 6.7.3p8).
7040 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7041 assert(PrettyArrayType && "Not an array type!");
7042
7043 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7044
7045 // int x[restrict 4] -> int *restrict
7047 PrettyArrayType->getIndexTypeQualifiers());
7048
7049 // int x[_Nullable] -> int * _Nullable
7050 if (auto Nullability = Ty->getNullability()) {
7051 Result = const_cast<ASTContext *>(this)->getAttributedType(
7053 }
7054 return Result;
7055}
7056
7058 return getBaseElementType(array->getElementType());
7059}
7060
7062 Qualifiers qs;
7063 while (true) {
7064 SplitQualType split = type.getSplitDesugaredType();
7065 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7066 if (!array) break;
7067
7068 type = array->getElementType();
7070 }
7071
7072 return getQualifiedType(type, qs);
7073}
7074
7075/// getConstantArrayElementCount - Returns number of constant array elements.
7076uint64_t
7078 uint64_t ElementCount = 1;
7079 do {
7080 ElementCount *= CA->getZExtSize();
7081 CA = dyn_cast_or_null<ConstantArrayType>(
7083 } while (CA);
7084 return ElementCount;
7085}
7086
7088 const ArrayInitLoopExpr *AILE) const {
7089 if (!AILE)
7090 return 0;
7091
7092 uint64_t ElementCount = 1;
7093
7094 do {
7095 ElementCount *= AILE->getArraySize().getZExtValue();
7096 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7097 } while (AILE);
7098
7099 return ElementCount;
7100}
7101
7102/// getFloatingRank - Return a relative rank for floating point types.
7103/// This routine will assert if passed a built-in type that isn't a float.
7105 if (const auto *CT = T->getAs<ComplexType>())
7106 return getFloatingRank(CT->getElementType());
7107
7108 switch (T->castAs<BuiltinType>()->getKind()) {
7109 default: llvm_unreachable("getFloatingRank(): not a floating type");
7110 case BuiltinType::Float16: return Float16Rank;
7111 case BuiltinType::Half: return HalfRank;
7112 case BuiltinType::Float: return FloatRank;
7113 case BuiltinType::Double: return DoubleRank;
7114 case BuiltinType::LongDouble: return LongDoubleRank;
7115 case BuiltinType::Float128: return Float128Rank;
7116 case BuiltinType::BFloat16: return BFloat16Rank;
7117 case BuiltinType::Ibm128: return Ibm128Rank;
7118 }
7119}
7120
7121/// getFloatingTypeOrder - Compare the rank of the two specified floating
7122/// point types, ignoring the domain of the type (i.e. 'double' ==
7123/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7124/// LHS < RHS, return -1.
7126 FloatingRank LHSR = getFloatingRank(LHS);
7127 FloatingRank RHSR = getFloatingRank(RHS);
7128
7129 if (LHSR == RHSR)
7130 return 0;
7131 if (LHSR > RHSR)
7132 return 1;
7133 return -1;
7134}
7135
7138 return 0;
7139 return getFloatingTypeOrder(LHS, RHS);
7140}
7141
7142/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7143/// routine will assert if passed a built-in type that isn't an integer or enum,
7144/// or if it is not canonicalized.
7145unsigned ASTContext::getIntegerRank(const Type *T) const {
7146 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7147
7148 // Results in this 'losing' to any type of the same size, but winning if
7149 // larger.
7150 if (const auto *EIT = dyn_cast<BitIntType>(T))
7151 return 0 + (EIT->getNumBits() << 3);
7152
7153 switch (cast<BuiltinType>(T)->getKind()) {
7154 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7155 case BuiltinType::Bool:
7156 return 1 + (getIntWidth(BoolTy) << 3);
7157 case BuiltinType::Char_S:
7158 case BuiltinType::Char_U:
7159 case BuiltinType::SChar:
7160 case BuiltinType::UChar:
7161 return 2 + (getIntWidth(CharTy) << 3);
7162 case BuiltinType::Short:
7163 case BuiltinType::UShort:
7164 return 3 + (getIntWidth(ShortTy) << 3);
7165 case BuiltinType::Int:
7166 case BuiltinType::UInt:
7167 return 4 + (getIntWidth(IntTy) << 3);
7168 case BuiltinType::Long:
7169 case BuiltinType::ULong:
7170 return 5 + (getIntWidth(LongTy) << 3);
7171 case BuiltinType::LongLong:
7172 case BuiltinType::ULongLong:
7173 return 6 + (getIntWidth(LongLongTy) << 3);
7174 case BuiltinType::Int128:
7175 case BuiltinType::UInt128:
7176 return 7 + (getIntWidth(Int128Ty) << 3);
7177
7178 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7179 // their underlying types" [c++20 conv.rank]
7180 case BuiltinType::Char8:
7181 return getIntegerRank(UnsignedCharTy.getTypePtr());
7182 case BuiltinType::Char16:
7183 return getIntegerRank(
7184 getFromTargetType(Target->getChar16Type()).getTypePtr());
7185 case BuiltinType::Char32:
7186 return getIntegerRank(
7187 getFromTargetType(Target->getChar32Type()).getTypePtr());
7188 case BuiltinType::WChar_S:
7189 case BuiltinType::WChar_U:
7190 return getIntegerRank(
7191 getFromTargetType(Target->getWCharType()).getTypePtr());
7192 }
7193}
7194
7195/// Whether this is a promotable bitfield reference according
7196/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7197///
7198/// \returns the type this bit-field will promote to, or NULL if no
7199/// promotion occurs.
7201 if (E->isTypeDependent() || E->isValueDependent())
7202 return {};
7203
7204 // C++ [conv.prom]p5:
7205 // If the bit-field has an enumerated type, it is treated as any other
7206 // value of that type for promotion purposes.
7208 return {};
7209
7210 // FIXME: We should not do this unless E->refersToBitField() is true. This
7211 // matters in C where getSourceBitField() will find bit-fields for various
7212 // cases where the source expression is not a bit-field designator.
7213
7214 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7215 if (!Field)
7216 return {};
7217
7218 QualType FT = Field->getType();
7219
7220 uint64_t BitWidth = Field->getBitWidthValue(*this);
7221 uint64_t IntSize = getTypeSize(IntTy);
7222 // C++ [conv.prom]p5:
7223 // A prvalue for an integral bit-field can be converted to a prvalue of type
7224 // int if int can represent all the values of the bit-field; otherwise, it
7225 // can be converted to unsigned int if unsigned int can represent all the
7226 // values of the bit-field. If the bit-field is larger yet, no integral
7227 // promotion applies to it.
7228 // C11 6.3.1.1/2:
7229 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7230 // If an int can represent all values of the original type (as restricted by
7231 // the width, for a bit-field), the value is converted to an int; otherwise,
7232 // it is converted to an unsigned int.
7233 //
7234 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7235 // We perform that promotion here to match GCC and C++.
7236 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7237 // greater than that of 'int'. We perform that promotion to match GCC.
7238 //
7239 // C23 6.3.1.1p2:
7240 // The value from a bit-field of a bit-precise integer type is converted to
7241 // the corresponding bit-precise integer type. (The rest is the same as in
7242 // C11.)
7243 if (QualType QT = Field->getType(); QT->isBitIntType())
7244 return QT;
7245
7246 if (BitWidth < IntSize)
7247 return IntTy;
7248
7249 if (BitWidth == IntSize)
7250 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7251
7252 // Bit-fields wider than int are not subject to promotions, and therefore act
7253 // like the base type. GCC has some weird bugs in this area that we
7254 // deliberately do not follow (GCC follows a pre-standard resolution to
7255 // C's DR315 which treats bit-width as being part of the type, and this leaks
7256 // into their semantics in some cases).
7257 return {};
7258}
7259
7260/// getPromotedIntegerType - Returns the type that Promotable will
7261/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7262/// integer type.
7264 assert(!Promotable.isNull());
7265 assert(isPromotableIntegerType(Promotable));
7266 if (const auto *ET = Promotable->getAs<EnumType>())
7267 return ET->getDecl()->getPromotionType();
7268
7269 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7270 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7271 // (3.9.1) can be converted to a prvalue of the first of the following
7272 // types that can represent all the values of its underlying type:
7273 // int, unsigned int, long int, unsigned long int, long long int, or
7274 // unsigned long long int [...]
7275 // FIXME: Is there some better way to compute this?
7276 if (BT->getKind() == BuiltinType::WChar_S ||
7277 BT->getKind() == BuiltinType::WChar_U ||
7278 BT->getKind() == BuiltinType::Char8 ||
7279 BT->getKind() == BuiltinType::Char16 ||
7280 BT->getKind() == BuiltinType::Char32) {
7281 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7282 uint64_t FromSize = getTypeSize(BT);
7283 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7285 for (const auto &PT : PromoteTypes) {
7286 uint64_t ToSize = getTypeSize(PT);
7287 if (FromSize < ToSize ||
7288 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7289 return PT;
7290 }
7291 llvm_unreachable("char type should fit into long long");
7292 }
7293 }
7294
7295 // At this point, we should have a signed or unsigned integer type.
7296 if (Promotable->isSignedIntegerType())
7297 return IntTy;
7298 uint64_t PromotableSize = getIntWidth(Promotable);
7299 uint64_t IntSize = getIntWidth(IntTy);
7300 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7301 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7302}
7303
7304/// Recurses in pointer/array types until it finds an objc retainable
7305/// type and returns its ownership.
7307 while (!T.isNull()) {
7308 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7309 return T.getObjCLifetime();
7310 if (T->isArrayType())
7312 else if (const auto *PT = T->getAs<PointerType>())
7313 T = PT->getPointeeType();
7314 else if (const auto *RT = T->getAs<ReferenceType>())
7315 T = RT->getPointeeType();
7316 else
7317 break;
7318 }
7319
7320 return Qualifiers::OCL_None;
7321}
7322
7323static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7324 // Incomplete enum types are not treated as integer types.
7325 // FIXME: In C++, enum types are never integer types.
7326 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7327 return ET->getDecl()->getIntegerType().getTypePtr();
7328 return nullptr;
7329}
7330
7331/// getIntegerTypeOrder - Returns the highest ranked integer type:
7332/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7333/// LHS < RHS, return -1.
7335 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7336 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7337
7338 // Unwrap enums to their underlying type.
7339 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7340 LHSC = getIntegerTypeForEnum(ET);
7341 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7342 RHSC = getIntegerTypeForEnum(ET);
7343
7344 if (LHSC == RHSC) return 0;
7345
7346 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7347 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7348
7349 unsigned LHSRank = getIntegerRank(LHSC);
7350 unsigned RHSRank = getIntegerRank(RHSC);
7351
7352 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7353 if (LHSRank == RHSRank) return 0;
7354 return LHSRank > RHSRank ? 1 : -1;
7355 }
7356
7357 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7358 if (LHSUnsigned) {
7359 // If the unsigned [LHS] type is larger, return it.
7360 if (LHSRank >= RHSRank)
7361 return 1;
7362
7363 // If the signed type can represent all values of the unsigned type, it
7364 // wins. Because we are dealing with 2's complement and types that are
7365 // powers of two larger than each other, this is always safe.
7366 return -1;
7367 }
7368
7369 // If the unsigned [RHS] type is larger, return it.
7370 if (RHSRank >= LHSRank)
7371 return -1;
7372
7373 // If the signed type can represent all values of the unsigned type, it
7374 // wins. Because we are dealing with 2's complement and types that are
7375 // powers of two larger than each other, this is always safe.
7376 return 1;
7377}
7378
7380 if (CFConstantStringTypeDecl)
7381 return CFConstantStringTypeDecl;
7382
7383 assert(!CFConstantStringTagDecl &&
7384 "tag and typedef should be initialized together");
7385 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7386 CFConstantStringTagDecl->startDefinition();
7387
7388 struct {
7389 QualType Type;
7390 const char *Name;
7391 } Fields[5];
7392 unsigned Count = 0;
7393
7394 /// Objective-C ABI
7395 ///
7396 /// typedef struct __NSConstantString_tag {
7397 /// const int *isa;
7398 /// int flags;
7399 /// const char *str;
7400 /// long length;
7401 /// } __NSConstantString;
7402 ///
7403 /// Swift ABI (4.1, 4.2)
7404 ///
7405 /// typedef struct __NSConstantString_tag {
7406 /// uintptr_t _cfisa;
7407 /// uintptr_t _swift_rc;
7408 /// _Atomic(uint64_t) _cfinfoa;
7409 /// const char *_ptr;
7410 /// uint32_t _length;
7411 /// } __NSConstantString;
7412 ///
7413 /// Swift ABI (5.0)
7414 ///
7415 /// typedef struct __NSConstantString_tag {
7416 /// uintptr_t _cfisa;
7417 /// uintptr_t _swift_rc;
7418 /// _Atomic(uint64_t) _cfinfoa;
7419 /// const char *_ptr;
7420 /// uintptr_t _length;
7421 /// } __NSConstantString;
7422
7423 const auto CFRuntime = getLangOpts().CFRuntime;
7424 if (static_cast<unsigned>(CFRuntime) <
7425 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7426 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7427 Fields[Count++] = { IntTy, "flags" };
7428 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7429 Fields[Count++] = { LongTy, "length" };
7430 } else {
7431 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7432 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7433 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7434 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7437 Fields[Count++] = { IntTy, "_ptr" };
7438 else
7439 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7440 }
7441
7442 // Create fields
7443 for (unsigned i = 0; i < Count; ++i) {
7444 FieldDecl *Field =
7445 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7446 SourceLocation(), &Idents.get(Fields[i].Name),
7447 Fields[i].Type, /*TInfo=*/nullptr,
7448 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7449 Field->setAccess(AS_public);
7450 CFConstantStringTagDecl->addDecl(Field);
7451 }
7452
7453 CFConstantStringTagDecl->completeDefinition();
7454 // This type is designed to be compatible with NSConstantString, but cannot
7455 // use the same name, since NSConstantString is an interface.
7456 auto tagType = getTagDeclType(CFConstantStringTagDecl);
7457 CFConstantStringTypeDecl =
7458 buildImplicitTypedef(tagType, "__NSConstantString");
7459
7460 return CFConstantStringTypeDecl;
7461}
7462
7464 if (!CFConstantStringTagDecl)
7465 getCFConstantStringDecl(); // Build the tag and the typedef.
7466 return CFConstantStringTagDecl;
7467}
7468
7469// getCFConstantStringType - Return the type used for constant CFStrings.
7472}
7473
7475 if (ObjCSuperType.isNull()) {
7476 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7477 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7478 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7479 }
7480 return ObjCSuperType;
7481}
7482
7484 const auto *TD = T->castAs<TypedefType>();
7485 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7486 const auto *TagType =
7487 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7488 CFConstantStringTagDecl = TagType->getDecl();
7489}
7490
7492 if (BlockDescriptorType)
7493 return getTagDeclType(BlockDescriptorType);
7494
7495 RecordDecl *RD;
7496 // FIXME: Needs the FlagAppleBlock bit.
7497 RD = buildImplicitRecord("__block_descriptor");
7498 RD->startDefinition();
7499
7500 QualType FieldTypes[] = {
7503 };
7504
7505 static const char *const FieldNames[] = {
7506 "reserved",
7507 "Size"
7508 };
7509
7510 for (size_t i = 0; i < 2; ++i) {
7512 *this, RD, SourceLocation(), SourceLocation(),
7513 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7514 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7515 Field->setAccess(AS_public);
7516 RD->addDecl(Field);
7517 }
7518
7519 RD->completeDefinition();
7520
7521 BlockDescriptorType = RD;
7522
7523 return getTagDeclType(BlockDescriptorType);
7524}
7525
7527 if (BlockDescriptorExtendedType)
7528 return getTagDeclType(BlockDescriptorExtendedType);
7529
7530 RecordDecl *RD;
7531 // FIXME: Needs the FlagAppleBlock bit.
7532 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7533 RD->startDefinition();
7534
7535 QualType FieldTypes[] = {
7540 };
7541
7542 static const char *const FieldNames[] = {
7543 "reserved",
7544 "Size",
7545 "CopyFuncPtr",
7546 "DestroyFuncPtr"
7547 };
7548
7549 for (size_t i = 0; i < 4; ++i) {
7551 *this, RD, SourceLocation(), SourceLocation(),
7552 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7553 /*BitWidth=*/nullptr,
7554 /*Mutable=*/false, ICIS_NoInit);
7555 Field->setAccess(AS_public);
7556 RD->addDecl(Field);
7557 }
7558
7559 RD->completeDefinition();
7560
7561 BlockDescriptorExtendedType = RD;
7562 return getTagDeclType(BlockDescriptorExtendedType);
7563}
7564
7566 const auto *BT = dyn_cast<BuiltinType>(T);
7567
7568 if (!BT) {
7569 if (isa<PipeType>(T))
7570 return OCLTK_Pipe;
7571
7572 return OCLTK_Default;
7573 }
7574
7575 switch (BT->getKind()) {
7576#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7577 case BuiltinType::Id: \
7578 return OCLTK_Image;
7579#include "clang/Basic/OpenCLImageTypes.def"
7580
7581 case BuiltinType::OCLClkEvent:
7582 return OCLTK_ClkEvent;
7583
7584 case BuiltinType::OCLEvent:
7585 return OCLTK_Event;
7586
7587 case BuiltinType::OCLQueue:
7588 return OCLTK_Queue;
7589
7590 case BuiltinType::OCLReserveID:
7591 return OCLTK_ReserveID;
7592
7593 case BuiltinType::OCLSampler:
7594 return OCLTK_Sampler;
7595
7596 default:
7597 return OCLTK_Default;
7598 }
7599}
7600
7602 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7603}
7604
7605/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7606/// requires copy/dispose. Note that this must match the logic
7607/// in buildByrefHelpers.
7609 const VarDecl *D) {
7610 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7611 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7612 if (!copyExpr && record->hasTrivialDestructor()) return false;
7613
7614 return true;
7615 }
7616
7617 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7618 // move or destroy.
7620 return true;
7621
7622 if (!Ty->isObjCRetainableType()) return false;
7623
7624 Qualifiers qs = Ty.getQualifiers();
7625
7626 // If we have lifetime, that dominates.
7627 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7628 switch (lifetime) {
7629 case Qualifiers::OCL_None: llvm_unreachable("impossible");
7630
7631 // These are just bits as far as the runtime is concerned.
7634 return false;
7635
7636 // These cases should have been taken care of when checking the type's
7637 // non-triviality.
7640 llvm_unreachable("impossible");
7641 }
7642 llvm_unreachable("fell out of lifetime switch!");
7643 }
7644 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7646}
7647
7649 Qualifiers::ObjCLifetime &LifeTime,
7650 bool &HasByrefExtendedLayout) const {
7651 if (!getLangOpts().ObjC ||
7652 getLangOpts().getGC() != LangOptions::NonGC)
7653 return false;
7654
7655 HasByrefExtendedLayout = false;
7656 if (Ty->isRecordType()) {
7657 HasByrefExtendedLayout = true;
7658 LifeTime = Qualifiers::OCL_None;
7659 } else if ((LifeTime = Ty.getObjCLifetime())) {
7660 // Honor the ARC qualifiers.
7661 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7662 // The MRR rule.
7664 } else {
7665 LifeTime = Qualifiers::OCL_None;
7666 }
7667 return true;
7668}
7669
7671 assert(Target && "Expected target to be initialized");
7672 const llvm::Triple &T = Target->getTriple();
7673 // Windows is LLP64 rather than LP64
7674 if (T.isOSWindows() && T.isArch64Bit())
7675 return UnsignedLongLongTy;
7676 return UnsignedLongTy;
7677}
7678
7680 assert(Target && "Expected target to be initialized");
7681 const llvm::Triple &T = Target->getTriple();
7682 // Windows is LLP64 rather than LP64
7683 if (T.isOSWindows() && T.isArch64Bit())
7684 return LongLongTy;
7685 return LongTy;
7686}
7687
7689 if (!ObjCInstanceTypeDecl)
7690 ObjCInstanceTypeDecl =
7691 buildImplicitTypedef(getObjCIdType(), "instancetype");
7692 return ObjCInstanceTypeDecl;
7693}
7694
7695// This returns true if a type has been typedefed to BOOL:
7696// typedef <type> BOOL;
7698 if (const auto *TT = dyn_cast<TypedefType>(T))
7699 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7700 return II->isStr("BOOL");
7701
7702 return false;
7703}
7704
7705/// getObjCEncodingTypeSize returns size of type for objective-c encoding
7706/// purpose.
7708 if (!type->isIncompleteArrayType() && type->isIncompleteType())
7709 return CharUnits::Zero();
7710
7712
7713 // Make all integer and enum types at least as large as an int
7714 if (sz.isPositive() && type->isIntegralOrEnumerationType())
7715 sz = std::max(sz, getTypeSizeInChars(IntTy));
7716 // Treat arrays as pointers, since that's how they're passed in.
7717 else if (type->isArrayType())
7719 return sz;
7720}
7721
7723 return getTargetInfo().getCXXABI().isMicrosoft() &&
7724 VD->isStaticDataMember() &&
7726 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7727}
7728
7731 if (!VD->isInline())
7733
7734 // In almost all cases, it's a weak definition.
7735 auto *First = VD->getFirstDecl();
7736 if (First->isInlineSpecified() || !First->isStaticDataMember())
7738
7739 // If there's a file-context declaration in this translation unit, it's a
7740 // non-discardable definition.
7741 for (auto *D : VD->redecls())
7742 if (D->getLexicalDeclContext()->isFileContext() &&
7743 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7745
7746 // If we've not seen one yet, we don't know.
7748}
7749
7750static std::string charUnitsToString(const CharUnits &CU) {
7751 return llvm::itostr(CU.getQuantity());
7752}
7753
7754/// getObjCEncodingForBlock - Return the encoded type for this block
7755/// declaration.
7757 std::string S;
7758
7759 const BlockDecl *Decl = Expr->getBlockDecl();
7760 QualType BlockTy =
7761 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7762 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7763 // Encode result type.
7764 if (getLangOpts().EncodeExtendedBlockSig)
7766 true /*Extended*/);
7767 else
7768 getObjCEncodingForType(BlockReturnTy, S);
7769 // Compute size of all parameters.
7770 // Start with computing size of a pointer in number of bytes.
7771 // FIXME: There might(should) be a better way of doing this computation!
7773 CharUnits ParmOffset = PtrSize;
7774 for (auto *PI : Decl->parameters()) {
7775 QualType PType = PI->getType();
7777 if (sz.isZero())
7778 continue;
7779 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7780 ParmOffset += sz;
7781 }
7782 // Size of the argument frame
7783 S += charUnitsToString(ParmOffset);
7784 // Block pointer and offset.
7785 S += "@?0";
7786
7787 // Argument types.
7788 ParmOffset = PtrSize;
7789 for (auto *PVDecl : Decl->parameters()) {
7790 QualType PType = PVDecl->getOriginalType();
7791 if (const auto *AT =
7792 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7793 // Use array's original type only if it has known number of
7794 // elements.
7795 if (!isa<ConstantArrayType>(AT))
7796 PType = PVDecl->getType();
7797 } else if (PType->isFunctionType())
7798 PType = PVDecl->getType();
7799 if (getLangOpts().EncodeExtendedBlockSig)
7801 S, true /*Extended*/);
7802 else
7803 getObjCEncodingForType(PType, S);
7804 S += charUnitsToString(ParmOffset);
7805 ParmOffset += getObjCEncodingTypeSize(PType);
7806 }
7807
7808 return S;
7809}
7810
7811std::string
7813 std::string S;
7814 // Encode result type.
7815 getObjCEncodingForType(Decl->getReturnType(), S);
7816 CharUnits ParmOffset;
7817 // Compute size of all parameters.
7818 for (auto *PI : Decl->parameters()) {
7819 QualType PType = PI->getType();
7821 if (sz.isZero())
7822 continue;
7823
7824 assert(sz.isPositive() &&
7825 "getObjCEncodingForFunctionDecl - Incomplete param type");
7826 ParmOffset += sz;
7827 }
7828 S += charUnitsToString(ParmOffset);
7829 ParmOffset = CharUnits::Zero();
7830
7831 // Argument types.
7832 for (auto *PVDecl : Decl->parameters()) {
7833 QualType PType = PVDecl->getOriginalType();
7834 if (const auto *AT =
7835 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7836 // Use array's original type only if it has known number of
7837 // elements.
7838 if (!isa<ConstantArrayType>(AT))
7839 PType = PVDecl->getType();
7840 } else if (PType->isFunctionType())
7841 PType = PVDecl->getType();
7842 getObjCEncodingForType(PType, S);
7843 S += charUnitsToString(ParmOffset);
7844 ParmOffset += getObjCEncodingTypeSize(PType);
7845 }
7846
7847 return S;
7848}
7849
7850/// getObjCEncodingForMethodParameter - Return the encoded type for a single
7851/// method parameter or return type. If Extended, include class names and
7852/// block object types.
7854 QualType T, std::string& S,
7855 bool Extended) const {
7856 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7858 // Encode parameter type.
7859 ObjCEncOptions Options = ObjCEncOptions()
7860 .setExpandPointedToStructures()
7861 .setExpandStructures()
7862 .setIsOutermostType();
7863 if (Extended)
7864 Options.setEncodeBlockParameters().setEncodeClassNames();
7865 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7866}
7867
7868/// getObjCEncodingForMethodDecl - Return the encoded type for this method
7869/// declaration.
7871 bool Extended) const {
7872 // FIXME: This is not very efficient.
7873 // Encode return type.
7874 std::string S;
7875 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7876 Decl->getReturnType(), S, Extended);
7877 // Compute size of all parameters.
7878 // Start with computing size of a pointer in number of bytes.
7879 // FIXME: There might(should) be a better way of doing this computation!
7881 // The first two arguments (self and _cmd) are pointers; account for
7882 // their size.
7883 CharUnits ParmOffset = 2 * PtrSize;
7884 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7885 E = Decl->sel_param_end(); PI != E; ++PI) {
7886 QualType PType = (*PI)->getType();
7888 if (sz.isZero())
7889 continue;
7890
7891 assert(sz.isPositive() &&
7892 "getObjCEncodingForMethodDecl - Incomplete param type");
7893 ParmOffset += sz;
7894 }
7895 S += charUnitsToString(ParmOffset);
7896 S += "@0:";
7897 S += charUnitsToString(PtrSize);
7898
7899 // Argument types.
7900 ParmOffset = 2 * PtrSize;
7901 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7902 E = Decl->sel_param_end(); PI != E; ++PI) {
7903 const ParmVarDecl *PVDecl = *PI;
7904 QualType PType = PVDecl->getOriginalType();
7905 if (const auto *AT =
7906 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7907 // Use array's original type only if it has known number of
7908 // elements.
7909 if (!isa<ConstantArrayType>(AT))
7910 PType = PVDecl->getType();
7911 } else if (PType->isFunctionType())
7912 PType = PVDecl->getType();
7914 PType, S, Extended);
7915 S += charUnitsToString(ParmOffset);
7916 ParmOffset += getObjCEncodingTypeSize(PType);
7917 }
7918
7919 return S;
7920}
7921
7924 const ObjCPropertyDecl *PD,
7925 const Decl *Container) const {
7926 if (!Container)
7927 return nullptr;
7928 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7929 for (auto *PID : CID->property_impls())
7930 if (PID->getPropertyDecl() == PD)
7931 return PID;
7932 } else {
7933 const auto *OID = cast<ObjCImplementationDecl>(Container);
7934 for (auto *PID : OID->property_impls())
7935 if (PID->getPropertyDecl() == PD)
7936 return PID;
7937 }
7938 return nullptr;
7939}
7940
7941/// getObjCEncodingForPropertyDecl - Return the encoded type for this
7942/// property declaration. If non-NULL, Container must be either an
7943/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7944/// NULL when getting encodings for protocol properties.
7945/// Property attributes are stored as a comma-delimited C string. The simple
7946/// attributes readonly and bycopy are encoded as single characters. The
7947/// parametrized attributes, getter=name, setter=name, and ivar=name, are
7948/// encoded as single characters, followed by an identifier. Property types
7949/// are also encoded as a parametrized attribute. The characters used to encode
7950/// these attributes are defined by the following enumeration:
7951/// @code
7952/// enum PropertyAttributes {
7953/// kPropertyReadOnly = 'R', // property is read-only.
7954/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
7955/// kPropertyByref = '&', // property is a reference to the value last assigned
7956/// kPropertyDynamic = 'D', // property is dynamic
7957/// kPropertyGetter = 'G', // followed by getter selector name
7958/// kPropertySetter = 'S', // followed by setter selector name
7959/// kPropertyInstanceVariable = 'V' // followed by instance variable name
7960/// kPropertyType = 'T' // followed by old-style type encoding.
7961/// kPropertyWeak = 'W' // 'weak' property
7962/// kPropertyStrong = 'P' // property GC'able
7963/// kPropertyNonAtomic = 'N' // property non-atomic
7964/// kPropertyOptional = '?' // property optional
7965/// };
7966/// @endcode
7967std::string
7969 const Decl *Container) const {
7970 // Collect information from the property implementation decl(s).
7971 bool Dynamic = false;
7972 ObjCPropertyImplDecl *SynthesizePID = nullptr;
7973
7974 if (ObjCPropertyImplDecl *PropertyImpDecl =
7976 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7977 Dynamic = true;
7978 else
7979 SynthesizePID = PropertyImpDecl;
7980 }
7981
7982 // FIXME: This is not very efficient.
7983 std::string S = "T";
7984
7985 // Encode result type.
7986 // GCC has some special rules regarding encoding of properties which
7987 // closely resembles encoding of ivars.
7989
7990 if (PD->isOptional())
7991 S += ",?";
7992
7993 if (PD->isReadOnly()) {
7994 S += ",R";
7996 S += ",C";
7998 S += ",&";
8000 S += ",W";
8001 } else {
8002 switch (PD->getSetterKind()) {
8003 case ObjCPropertyDecl::Assign: break;
8004 case ObjCPropertyDecl::Copy: S += ",C"; break;
8005 case ObjCPropertyDecl::Retain: S += ",&"; break;
8006 case ObjCPropertyDecl::Weak: S += ",W"; break;
8007 }
8008 }
8009
8010 // It really isn't clear at all what this means, since properties
8011 // are "dynamic by default".
8012 if (Dynamic)
8013 S += ",D";
8014
8016 S += ",N";
8017
8019 S += ",G";
8020 S += PD->getGetterName().getAsString();
8021 }
8022
8024 S += ",S";
8025 S += PD->getSetterName().getAsString();
8026 }
8027
8028 if (SynthesizePID) {
8029 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8030 S += ",V";
8031 S += OID->getNameAsString();
8032 }
8033
8034 // FIXME: OBJCGC: weak & strong
8035 return S;
8036}
8037
8038/// getLegacyIntegralTypeEncoding -
8039/// Another legacy compatibility encoding: 32-bit longs are encoded as
8040/// 'l' or 'L' , but not always. For typedefs, we need to use
8041/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8043 if (PointeeTy->getAs<TypedefType>()) {
8044 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8045 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8046 PointeeTy = UnsignedIntTy;
8047 else
8048 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8049 PointeeTy = IntTy;
8050 }
8051 }
8052}
8053
8055 const FieldDecl *Field,
8056 QualType *NotEncodedT) const {
8057 // We follow the behavior of gcc, expanding structures which are
8058 // directly pointed to, and expanding embedded structures. Note that
8059 // these rules are sufficient to prevent recursive encoding of the
8060 // same type.
8061 getObjCEncodingForTypeImpl(T, S,
8062 ObjCEncOptions()
8063 .setExpandPointedToStructures()
8064 .setExpandStructures()
8065 .setIsOutermostType(),
8066 Field, NotEncodedT);
8067}
8068
8070 std::string& S) const {
8071 // Encode result type.
8072 // GCC has some special rules regarding encoding of properties which
8073 // closely resembles encoding of ivars.
8074 getObjCEncodingForTypeImpl(T, S,
8075 ObjCEncOptions()
8076 .setExpandPointedToStructures()
8077 .setExpandStructures()
8078 .setIsOutermostType()
8079 .setEncodingProperty(),
8080 /*Field=*/nullptr);
8081}
8082
8084 const BuiltinType *BT) {
8085 BuiltinType::Kind kind = BT->getKind();
8086 switch (kind) {
8087 case BuiltinType::Void: return 'v';
8088 case BuiltinType::Bool: return 'B';
8089 case BuiltinType::Char8:
8090 case BuiltinType::Char_U:
8091 case BuiltinType::UChar: return 'C';
8092 case BuiltinType::Char16:
8093 case BuiltinType::UShort: return 'S';
8094 case BuiltinType::Char32:
8095 case BuiltinType::UInt: return 'I';
8096 case BuiltinType::ULong:
8097 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8098 case BuiltinType::UInt128: return 'T';
8099 case BuiltinType::ULongLong: return 'Q';
8100 case BuiltinType::Char_S:
8101 case BuiltinType::SChar: return 'c';
8102 case BuiltinType::Short: return 's';
8103 case BuiltinType::WChar_S:
8104 case BuiltinType::WChar_U:
8105 case BuiltinType::Int: return 'i';
8106 case BuiltinType::Long:
8107 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8108 case BuiltinType::LongLong: return 'q';
8109 case BuiltinType::Int128: return 't';
8110 case BuiltinType::Float: return 'f';
8111 case BuiltinType::Double: return 'd';
8112 case BuiltinType::LongDouble: return 'D';
8113 case BuiltinType::NullPtr: return '*'; // like char*
8114
8115 case BuiltinType::BFloat16:
8116 case BuiltinType::Float16:
8117 case BuiltinType::Float128:
8118 case BuiltinType::Ibm128:
8119 case BuiltinType::Half:
8120 case BuiltinType::ShortAccum:
8121 case BuiltinType::Accum:
8122 case BuiltinType::LongAccum:
8123 case BuiltinType::UShortAccum:
8124 case BuiltinType::UAccum:
8125 case BuiltinType::ULongAccum:
8126 case BuiltinType::ShortFract:
8127 case BuiltinType::Fract:
8128 case BuiltinType::LongFract:
8129 case BuiltinType::UShortFract:
8130 case BuiltinType::UFract:
8131 case BuiltinType::ULongFract:
8132 case BuiltinType::SatShortAccum:
8133 case BuiltinType::SatAccum:
8134 case BuiltinType::SatLongAccum:
8135 case BuiltinType::SatUShortAccum:
8136 case BuiltinType::SatUAccum:
8137 case BuiltinType::SatULongAccum:
8138 case BuiltinType::SatShortFract:
8139 case BuiltinType::SatFract:
8140 case BuiltinType::SatLongFract:
8141 case BuiltinType::SatUShortFract:
8142 case BuiltinType::SatUFract:
8143 case BuiltinType::SatULongFract:
8144 // FIXME: potentially need @encodes for these!
8145 return ' ';
8146
8147#define SVE_TYPE(Name, Id, SingletonId) \
8148 case BuiltinType::Id:
8149#include "clang/Basic/AArch64SVEACLETypes.def"
8150#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8151#include "clang/Basic/RISCVVTypes.def"
8152#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8153#include "clang/Basic/WebAssemblyReferenceTypes.def"
8154 {
8155 DiagnosticsEngine &Diags = C->getDiagnostics();
8156 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8157 "cannot yet @encode type %0");
8158 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8159 return ' ';
8160 }
8161
8162 case BuiltinType::ObjCId:
8163 case BuiltinType::ObjCClass:
8164 case BuiltinType::ObjCSel:
8165 llvm_unreachable("@encoding ObjC primitive type");
8166
8167 // OpenCL and placeholder types don't need @encodings.
8168#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8169 case BuiltinType::Id:
8170#include "clang/Basic/OpenCLImageTypes.def"
8171#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8172 case BuiltinType::Id:
8173#include "clang/Basic/OpenCLExtensionTypes.def"
8174 case BuiltinType::OCLEvent:
8175 case BuiltinType::OCLClkEvent:
8176 case BuiltinType::OCLQueue:
8177 case BuiltinType::OCLReserveID:
8178 case BuiltinType::OCLSampler:
8179 case BuiltinType::Dependent:
8180#define PPC_VECTOR_TYPE(Name, Id, Size) \
8181 case BuiltinType::Id:
8182#include "clang/Basic/PPCTypes.def"
8183#define BUILTIN_TYPE(KIND, ID)
8184#define PLACEHOLDER_TYPE(KIND, ID) \
8185 case BuiltinType::KIND:
8186#include "clang/AST/BuiltinTypes.def"
8187 llvm_unreachable("invalid builtin type for @encode");
8188 }
8189 llvm_unreachable("invalid BuiltinType::Kind value");
8190}
8191
8192static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8193 EnumDecl *Enum = ET->getDecl();
8194
8195 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8196 if (!Enum->isFixed())
8197 return 'i';
8198
8199 // The encoding of a fixed enum type matches its fixed underlying type.
8200 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8202}
8203
8204static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8205 QualType T, const FieldDecl *FD) {
8206 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8207 S += 'b';
8208 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8209 // The GNU runtime requires more information; bitfields are encoded as b,
8210 // then the offset (in bits) of the first element, then the type of the
8211 // bitfield, then the size in bits. For example, in this structure:
8212 //
8213 // struct
8214 // {
8215 // int integer;
8216 // int flags:2;
8217 // };
8218 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8219 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8220 // information is not especially sensible, but we're stuck with it for
8221 // compatibility with GCC, although providing it breaks anything that
8222 // actually uses runtime introspection and wants to work on both runtimes...
8223 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8224 uint64_t Offset;
8225
8226 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8227 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8228 IVD);
8229 } else {
8230 const RecordDecl *RD = FD->getParent();
8231 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8232 Offset = RL.getFieldOffset(FD->getFieldIndex());
8233 }
8234
8235 S += llvm::utostr(Offset);
8236
8237 if (const auto *ET = T->getAs<EnumType>())
8238 S += ObjCEncodingForEnumType(Ctx, ET);
8239 else {
8240 const auto *BT = T->castAs<BuiltinType>();
8241 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8242 }
8243 }
8244 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8245}
8246
8247// Helper function for determining whether the encoded type string would include
8248// a template specialization type.
8250 bool VisitBasesAndFields) {
8252
8253 if (auto *PT = T->getAs<PointerType>())
8255 PT->getPointeeType().getTypePtr(), false);
8256
8257 auto *CXXRD = T->getAsCXXRecordDecl();
8258
8259 if (!CXXRD)
8260 return false;
8261
8262 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8263 return true;
8264
8265 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8266 return false;
8267
8268 for (const auto &B : CXXRD->bases())
8269 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8270 true))
8271 return true;
8272
8273 for (auto *FD : CXXRD->fields())
8274 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8275 true))
8276 return true;
8277
8278 return false;
8279}
8280
8281// FIXME: Use SmallString for accumulating string.
8282void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8283 const ObjCEncOptions Options,
8284 const FieldDecl *FD,
8285 QualType *NotEncodedT) const {
8287 switch (CT->getTypeClass()) {
8288 case Type::Builtin:
8289 case Type::Enum:
8290 if (FD && FD->isBitField())
8291 return EncodeBitField(this, S, T, FD);
8292 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8293 S += getObjCEncodingForPrimitiveType(this, BT);
8294 else
8295 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8296 return;
8297
8298 case Type::Complex:
8299 S += 'j';
8300 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8301 ObjCEncOptions(),
8302 /*Field=*/nullptr);
8303 return;
8304
8305 case Type::Atomic:
8306 S += 'A';
8307 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8308 ObjCEncOptions(),
8309 /*Field=*/nullptr);
8310 return;
8311
8312 // encoding for pointer or reference types.
8313 case Type::Pointer:
8314 case Type::LValueReference:
8315 case Type::RValueReference: {
8316 QualType PointeeTy;
8317 if (isa<PointerType>(CT)) {
8318 const auto *PT = T->castAs<PointerType>();
8319 if (PT->isObjCSelType()) {
8320 S += ':';
8321 return;
8322 }
8323 PointeeTy = PT->getPointeeType();
8324 } else {
8325 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8326 }
8327
8328 bool isReadOnly = false;
8329 // For historical/compatibility reasons, the read-only qualifier of the
8330 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8331 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8332 // Also, do not emit the 'r' for anything but the outermost type!
8333 if (T->getAs<TypedefType>()) {
8334 if (Options.IsOutermostType() && T.isConstQualified()) {
8335 isReadOnly = true;
8336 S += 'r';
8337 }
8338 } else if (Options.IsOutermostType()) {
8339 QualType P = PointeeTy;
8340 while (auto PT = P->getAs<PointerType>())
8341 P = PT->getPointeeType();
8342 if (P.isConstQualified()) {
8343 isReadOnly = true;
8344 S += 'r';
8345 }
8346 }
8347 if (isReadOnly) {
8348 // Another legacy compatibility encoding. Some ObjC qualifier and type
8349 // combinations need to be rearranged.
8350 // Rewrite "in const" from "nr" to "rn"
8351 if (StringRef(S).ends_with("nr"))
8352 S.replace(S.end()-2, S.end(), "rn");
8353 }
8354
8355 if (PointeeTy->isCharType()) {
8356 // char pointer types should be encoded as '*' unless it is a
8357 // type that has been typedef'd to 'BOOL'.
8358 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8359 S += '*';
8360 return;
8361 }
8362 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8363 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8364 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8365 S += '#';
8366 return;
8367 }
8368 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8369 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8370 S += '@';
8371 return;
8372 }
8373 // If the encoded string for the class includes template names, just emit
8374 // "^v" for pointers to the class.
8375 if (getLangOpts().CPlusPlus &&
8376 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8378 RTy, Options.ExpandPointedToStructures()))) {
8379 S += "^v";
8380 return;
8381 }
8382 // fall through...
8383 }
8384 S += '^';
8386
8387 ObjCEncOptions NewOptions;
8388 if (Options.ExpandPointedToStructures())
8389 NewOptions.setExpandStructures();
8390 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8391 /*Field=*/nullptr, NotEncodedT);
8392 return;
8393 }
8394
8395 case Type::ConstantArray:
8396 case Type::IncompleteArray:
8397 case Type::VariableArray: {
8398 const auto *AT = cast<ArrayType>(CT);
8399
8400 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8401 // Incomplete arrays are encoded as a pointer to the array element.
8402 S += '^';
8403
8404 getObjCEncodingForTypeImpl(
8405 AT->getElementType(), S,
8406 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8407 } else {
8408 S += '[';
8409
8410 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8411 S += llvm::utostr(CAT->getZExtSize());
8412 else {
8413 //Variable length arrays are encoded as a regular array with 0 elements.
8414 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8415 "Unknown array type!");
8416 S += '0';
8417 }
8418
8419 getObjCEncodingForTypeImpl(
8420 AT->getElementType(), S,
8421 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8422 NotEncodedT);
8423 S += ']';
8424 }
8425 return;
8426 }
8427
8428 case Type::FunctionNoProto:
8429 case Type::FunctionProto:
8430 S += '?';
8431 return;
8432
8433 case Type::Record: {
8434 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8435 S += RDecl->isUnion() ? '(' : '{';
8436 // Anonymous structures print as '?'
8437 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8438 S += II->getName();
8439 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8440 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8441 llvm::raw_string_ostream OS(S);
8442 printTemplateArgumentList(OS, TemplateArgs.asArray(),
8444 }
8445 } else {
8446 S += '?';
8447 }
8448 if (Options.ExpandStructures()) {
8449 S += '=';
8450 if (!RDecl->isUnion()) {
8451 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8452 } else {
8453 for (const auto *Field : RDecl->fields()) {
8454 if (FD) {
8455 S += '"';
8456 S += Field->getNameAsString();
8457 S += '"';
8458 }
8459
8460 // Special case bit-fields.
8461 if (Field->isBitField()) {
8462 getObjCEncodingForTypeImpl(Field->getType(), S,
8463 ObjCEncOptions().setExpandStructures(),
8464 Field);
8465 } else {
8466 QualType qt = Field->getType();
8468 getObjCEncodingForTypeImpl(
8469 qt, S,
8470 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8471 NotEncodedT);
8472 }
8473 }
8474 }
8475 }
8476 S += RDecl->isUnion() ? ')' : '}';
8477 return;
8478 }
8479
8480 case Type::BlockPointer: {
8481 const auto *BT = T->castAs<BlockPointerType>();
8482 S += "@?"; // Unlike a pointer-to-function, which is "^?".
8483 if (Options.EncodeBlockParameters()) {
8484 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8485
8486 S += '<';
8487 // Block return type
8488 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8489 Options.forComponentType(), FD, NotEncodedT);
8490 // Block self
8491 S += "@?";
8492 // Block parameters
8493 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8494 for (const auto &I : FPT->param_types())
8495 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8496 NotEncodedT);
8497 }
8498 S += '>';
8499 }
8500 return;
8501 }
8502
8503 case Type::ObjCObject: {
8504 // hack to match legacy encoding of *id and *Class
8506 if (Ty->isObjCIdType()) {
8507 S += "{objc_object=}";
8508 return;
8509 }
8510 else if (Ty->isObjCClassType()) {
8511 S += "{objc_class=}";
8512 return;
8513 }
8514 // TODO: Double check to make sure this intentionally falls through.
8515 [[fallthrough]];
8516 }
8517
8518 case Type::ObjCInterface: {
8519 // Ignore protocol qualifiers when mangling at this level.
8520 // @encode(class_name)
8521 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8522 S += '{';
8523 S += OI->getObjCRuntimeNameAsString();
8524 if (Options.ExpandStructures()) {
8525 S += '=';
8527 DeepCollectObjCIvars(OI, true, Ivars);
8528 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8529 const FieldDecl *Field = Ivars[i];
8530 if (Field->isBitField())
8531 getObjCEncodingForTypeImpl(Field->getType(), S,
8532 ObjCEncOptions().setExpandStructures(),
8533 Field);
8534 else
8535 getObjCEncodingForTypeImpl(Field->getType(), S,
8536 ObjCEncOptions().setExpandStructures(), FD,
8537 NotEncodedT);
8538 }
8539 }
8540 S += '}';
8541 return;
8542 }
8543
8544 case Type::ObjCObjectPointer: {
8545 const auto *OPT = T->castAs<ObjCObjectPointerType>();
8546 if (OPT->isObjCIdType()) {
8547 S += '@';
8548 return;
8549 }
8550
8551 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8552 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8553 // Since this is a binary compatibility issue, need to consult with
8554 // runtime folks. Fortunately, this is a *very* obscure construct.
8555 S += '#';
8556 return;
8557 }
8558
8559 if (OPT->isObjCQualifiedIdType()) {
8560 getObjCEncodingForTypeImpl(
8561 getObjCIdType(), S,
8562 Options.keepingOnly(ObjCEncOptions()
8563 .setExpandPointedToStructures()
8564 .setExpandStructures()),
8565 FD);
8566 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8567 // Note that we do extended encoding of protocol qualifier list
8568 // Only when doing ivar or property encoding.
8569 S += '"';
8570 for (const auto *I : OPT->quals()) {
8571 S += '<';
8572 S += I->getObjCRuntimeNameAsString();
8573 S += '>';
8574 }
8575 S += '"';
8576 }
8577 return;
8578 }
8579
8580 S += '@';
8581 if (OPT->getInterfaceDecl() &&
8582 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8583 S += '"';
8584 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8585 for (const auto *I : OPT->quals()) {
8586 S += '<';
8587 S += I->getObjCRuntimeNameAsString();
8588 S += '>';
8589 }
8590 S += '"';
8591 }
8592 return;
8593 }
8594
8595 // gcc just blithely ignores member pointers.
8596 // FIXME: we should do better than that. 'M' is available.
8597 case Type::MemberPointer:
8598 // This matches gcc's encoding, even though technically it is insufficient.
8599 //FIXME. We should do a better job than gcc.
8600 case Type::Vector:
8601 case Type::ExtVector:
8602 // Until we have a coherent encoding of these three types, issue warning.
8603 if (NotEncodedT)
8604 *NotEncodedT = T;
8605 return;
8606
8607 case Type::ConstantMatrix:
8608 if (NotEncodedT)
8609 *NotEncodedT = T;
8610 return;
8611
8612 case Type::BitInt:
8613 if (NotEncodedT)
8614 *NotEncodedT = T;
8615 return;
8616
8617 // We could see an undeduced auto type here during error recovery.
8618 // Just ignore it.
8619 case Type::Auto:
8620 case Type::DeducedTemplateSpecialization:
8621 return;
8622
8623 case Type::ArrayParameter:
8624 case Type::Pipe:
8625#define ABSTRACT_TYPE(KIND, BASE)
8626#define TYPE(KIND, BASE)
8627#define DEPENDENT_TYPE(KIND, BASE) \
8628 case Type::KIND:
8629#define NON_CANONICAL_TYPE(KIND, BASE) \
8630 case Type::KIND:
8631#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8632 case Type::KIND:
8633#include "clang/AST/TypeNodes.inc"
8634 llvm_unreachable("@encode for dependent type!");
8635 }
8636 llvm_unreachable("bad type kind!");
8637}
8638
8639void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8640 std::string &S,
8641 const FieldDecl *FD,
8642 bool includeVBases,
8643 QualType *NotEncodedT) const {
8644 assert(RDecl && "Expected non-null RecordDecl");
8645 assert(!RDecl->isUnion() && "Should not be called for unions");
8646 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8647 return;
8648
8649 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8650 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8651 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8652
8653 if (CXXRec) {
8654 for (const auto &BI : CXXRec->bases()) {
8655 if (!BI.isVirtual()) {
8656 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8657 if (base->isEmpty())
8658 continue;
8659 uint64_t offs = toBits(layout.getBaseClassOffset(base));
8660 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8661 std::make_pair(offs, base));
8662 }
8663 }
8664 }
8665
8666 for (FieldDecl *Field : RDecl->fields()) {
8667 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8668 continue;
8669 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
8670 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8671 std::make_pair(offs, Field));
8672 }
8673
8674 if (CXXRec && includeVBases) {
8675 for (const auto &BI : CXXRec->vbases()) {
8676 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8677 if (base->isEmpty())
8678 continue;
8679 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8680 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8681 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8682 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8683 std::make_pair(offs, base));
8684 }
8685 }
8686
8687 CharUnits size;
8688 if (CXXRec) {
8689 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8690 } else {
8691 size = layout.getSize();
8692 }
8693
8694#ifndef NDEBUG
8695 uint64_t CurOffs = 0;
8696#endif
8697 std::multimap<uint64_t, NamedDecl *>::iterator
8698 CurLayObj = FieldOrBaseOffsets.begin();
8699
8700 if (CXXRec && CXXRec->isDynamicClass() &&
8701 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8702 if (FD) {
8703 S += "\"_vptr$";
8704 std::string recname = CXXRec->getNameAsString();
8705 if (recname.empty()) recname = "?";
8706 S += recname;
8707 S += '"';
8708 }
8709 S += "^^?";
8710#ifndef NDEBUG
8711 CurOffs += getTypeSize(VoidPtrTy);
8712#endif
8713 }
8714
8715 if (!RDecl->hasFlexibleArrayMember()) {
8716 // Mark the end of the structure.
8717 uint64_t offs = toBits(size);
8718 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8719 std::make_pair(offs, nullptr));
8720 }
8721
8722 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8723#ifndef NDEBUG
8724 assert(CurOffs <= CurLayObj->first);
8725 if (CurOffs < CurLayObj->first) {
8726 uint64_t padding = CurLayObj->first - CurOffs;
8727 // FIXME: There doesn't seem to be a way to indicate in the encoding that
8728 // packing/alignment of members is different that normal, in which case
8729 // the encoding will be out-of-sync with the real layout.
8730 // If the runtime switches to just consider the size of types without
8731 // taking into account alignment, we could make padding explicit in the
8732 // encoding (e.g. using arrays of chars). The encoding strings would be
8733 // longer then though.
8734 CurOffs += padding;
8735 }
8736#endif
8737
8738 NamedDecl *dcl = CurLayObj->second;
8739 if (!dcl)
8740 break; // reached end of structure.
8741
8742 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8743 // We expand the bases without their virtual bases since those are going
8744 // in the initial structure. Note that this differs from gcc which
8745 // expands virtual bases each time one is encountered in the hierarchy,
8746 // making the encoding type bigger than it really is.
8747 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8748 NotEncodedT);
8749 assert(!base->isEmpty());
8750#ifndef NDEBUG
8751 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8752#endif
8753 } else {
8754 const auto *field = cast<FieldDecl>(dcl);
8755 if (FD) {
8756 S += '"';
8757 S += field->getNameAsString();
8758 S += '"';
8759 }
8760
8761 if (field->isBitField()) {
8762 EncodeBitField(this, S, field->getType(), field);
8763#ifndef NDEBUG
8764 CurOffs += field->getBitWidthValue(*this);
8765#endif
8766 } else {
8767 QualType qt = field->getType();
8769 getObjCEncodingForTypeImpl(
8770 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8771 FD, NotEncodedT);
8772#ifndef NDEBUG
8773 CurOffs += getTypeSize(field->getType());
8774#endif
8775 }
8776 }
8777 }
8778}
8779
8781 std::string& S) const {
8782 if (QT & Decl::OBJC_TQ_In)
8783 S += 'n';
8784 if (QT & Decl::OBJC_TQ_Inout)
8785 S += 'N';
8786 if (QT & Decl::OBJC_TQ_Out)
8787 S += 'o';
8788 if (QT & Decl::OBJC_TQ_Bycopy)
8789 S += 'O';
8790 if (QT & Decl::OBJC_TQ_Byref)
8791 S += 'R';
8792 if (QT & Decl::OBJC_TQ_Oneway)
8793 S += 'V';
8794}
8795
8797 if (!ObjCIdDecl) {
8800 ObjCIdDecl = buildImplicitTypedef(T, "id");
8801 }
8802 return ObjCIdDecl;
8803}
8804
8806 if (!ObjCSelDecl) {
8808 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8809 }
8810 return ObjCSelDecl;
8811}
8812
8814 if (!ObjCClassDecl) {
8817 ObjCClassDecl = buildImplicitTypedef(T, "Class");
8818 }
8819 return ObjCClassDecl;
8820}
8821
8823 if (!ObjCProtocolClassDecl) {
8824 ObjCProtocolClassDecl
8827 &Idents.get("Protocol"),
8828 /*typeParamList=*/nullptr,
8829 /*PrevDecl=*/nullptr,
8830 SourceLocation(), true);
8831 }
8832
8833 return ObjCProtocolClassDecl;
8834}
8835
8836//===----------------------------------------------------------------------===//
8837// __builtin_va_list Construction Functions
8838//===----------------------------------------------------------------------===//
8839
8841 StringRef Name) {
8842 // typedef char* __builtin[_ms]_va_list;
8843 QualType T = Context->getPointerType(Context->CharTy);
8844 return Context->buildImplicitTypedef(T, Name);
8845}
8846
8848 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8849}
8850
8852 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8853}
8854
8856 // typedef void* __builtin_va_list;
8857 QualType T = Context->getPointerType(Context->VoidTy);
8858 return Context->buildImplicitTypedef(T, "__builtin_va_list");
8859}
8860
8861static TypedefDecl *
8863 // struct __va_list
8864 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8865 if (Context->getLangOpts().CPlusPlus) {
8866 // namespace std { struct __va_list {
8867 auto *NS = NamespaceDecl::Create(
8868 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8869 /*Inline=*/false, SourceLocation(), SourceLocation(),
8870 &Context->Idents.get("std"),
8871 /*PrevDecl=*/nullptr, /*Nested=*/false);
8872 NS->setImplicit();
8873 VaListTagDecl->setDeclContext(NS);
8874 }
8875
8876 VaListTagDecl->startDefinition();
8877
8878 const size_t NumFields = 5;
8879 QualType FieldTypes[NumFields];
8880 const char *FieldNames[NumFields];
8881
8882 // void *__stack;
8883 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8884 FieldNames[0] = "__stack";
8885
8886 // void *__gr_top;
8887 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8888 FieldNames[1] = "__gr_top";
8889
8890 // void *__vr_top;
8891 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8892 FieldNames[2] = "__vr_top";
8893
8894 // int __gr_offs;
8895 FieldTypes[3] = Context->IntTy;
8896 FieldNames[3] = "__gr_offs";
8897
8898 // int __vr_offs;
8899 FieldTypes[4] = Context->IntTy;
8900 FieldNames[4] = "__vr_offs";
8901
8902 // Create fields
8903 for (unsigned i = 0; i < NumFields; ++i) {
8904 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8905 VaListTagDecl,
8908 &Context->Idents.get(FieldNames[i]),
8909 FieldTypes[i], /*TInfo=*/nullptr,
8910 /*BitWidth=*/nullptr,
8911 /*Mutable=*/false,
8912 ICIS_NoInit);
8913 Field->setAccess(AS_public);
8914 VaListTagDecl->addDecl(Field);
8915 }
8916 VaListTagDecl->completeDefinition();
8917 Context->VaListTagDecl = VaListTagDecl;
8918 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8919
8920 // } __builtin_va_list;
8921 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8922}
8923
8925 // typedef struct __va_list_tag {
8926 RecordDecl *VaListTagDecl;
8927
8928 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8929 VaListTagDecl->startDefinition();
8930
8931 const size_t NumFields = 5;
8932 QualType FieldTypes[NumFields];
8933 const char *FieldNames[NumFields];
8934
8935 // unsigned char gpr;
8936 FieldTypes[0] = Context->UnsignedCharTy;
8937 FieldNames[0] = "gpr";
8938
8939 // unsigned char fpr;
8940 FieldTypes[1] = Context->UnsignedCharTy;
8941 FieldNames[1] = "fpr";
8942
8943 // unsigned short reserved;
8944 FieldTypes[2] = Context->UnsignedShortTy;
8945 FieldNames[2] = "reserved";
8946
8947 // void* overflow_arg_area;
8948 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8949 FieldNames[3] = "overflow_arg_area";
8950
8951 // void* reg_save_area;
8952 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8953 FieldNames[4] = "reg_save_area";
8954
8955 // Create fields
8956 for (unsigned i = 0; i < NumFields; ++i) {
8957 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8960 &Context->Idents.get(FieldNames[i]),
8961 FieldTypes[i], /*TInfo=*/nullptr,
8962 /*BitWidth=*/nullptr,
8963 /*Mutable=*/false,
8964 ICIS_NoInit);
8965 Field->setAccess(AS_public);
8966 VaListTagDecl->addDecl(Field);
8967 }
8968 VaListTagDecl->completeDefinition();
8969 Context->VaListTagDecl = VaListTagDecl;
8970 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8971
8972 // } __va_list_tag;
8973 TypedefDecl *VaListTagTypedefDecl =
8974 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8975
8976 QualType VaListTagTypedefType =
8977 Context->getTypedefType(VaListTagTypedefDecl);
8978
8979 // typedef __va_list_tag __builtin_va_list[1];
8980 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8981 QualType VaListTagArrayType = Context->getConstantArrayType(
8982 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
8983 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8984}
8985
8986static TypedefDecl *
8988 // struct __va_list_tag {
8989 RecordDecl *VaListTagDecl;
8990 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8991 VaListTagDecl->startDefinition();
8992
8993 const size_t NumFields = 4;
8994 QualType FieldTypes[NumFields];
8995 const char *FieldNames[NumFields];
8996
8997 // unsigned gp_offset;
8998 FieldTypes[0] = Context->UnsignedIntTy;
8999 FieldNames[0] = "gp_offset";
9000
9001 // unsigned fp_offset;
9002 FieldTypes[1] = Context->UnsignedIntTy;
9003 FieldNames[1] = "fp_offset";
9004
9005 // void* overflow_arg_area;
9006 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9007 FieldNames[2] = "overflow_arg_area";
9008
9009 // void* reg_save_area;
9010 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9011 FieldNames[3] = "reg_save_area";
9012
9013 // Create fields
9014 for (unsigned i = 0; i < NumFields; ++i) {
9015 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9016 VaListTagDecl,
9019 &Context->Idents.get(FieldNames[i]),
9020 FieldTypes[i], /*TInfo=*/nullptr,
9021 /*BitWidth=*/nullptr,
9022 /*Mutable=*/false,
9023 ICIS_NoInit);
9024 Field->setAccess(AS_public);
9025 VaListTagDecl->addDecl(Field);
9026 }
9027 VaListTagDecl->completeDefinition();
9028 Context->VaListTagDecl = VaListTagDecl;
9029 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9030
9031 // };
9032
9033 // typedef struct __va_list_tag __builtin_va_list[1];
9034 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9035 QualType VaListTagArrayType = Context->getConstantArrayType(
9036 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9037 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9038}
9039
9041 // typedef int __builtin_va_list[4];
9042 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9043 QualType IntArrayType = Context->getConstantArrayType(
9044 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9045 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9046}
9047
9048static TypedefDecl *
9050 // struct __va_list
9051 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9052 if (Context->getLangOpts().CPlusPlus) {
9053 // namespace std { struct __va_list {
9054 NamespaceDecl *NS;
9055 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9056 Context->getTranslationUnitDecl(),
9057 /*Inline=*/false, SourceLocation(),
9058 SourceLocation(), &Context->Idents.get("std"),
9059 /*PrevDecl=*/nullptr, /*Nested=*/false);
9060 NS->setImplicit();
9061 VaListDecl->setDeclContext(NS);
9062 }
9063
9064 VaListDecl->startDefinition();
9065
9066 // void * __ap;
9067 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9068 VaListDecl,
9071 &Context->Idents.get("__ap"),
9072 Context->getPointerType(Context->VoidTy),
9073 /*TInfo=*/nullptr,
9074 /*BitWidth=*/nullptr,
9075 /*Mutable=*/false,
9076 ICIS_NoInit);
9077 Field->setAccess(AS_public);
9078 VaListDecl->addDecl(Field);
9079
9080 // };
9081 VaListDecl->completeDefinition();
9082 Context->VaListTagDecl = VaListDecl;
9083
9084 // typedef struct __va_list __builtin_va_list;
9085 QualType T = Context->getRecordType(VaListDecl);
9086 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9087}
9088
9089static TypedefDecl *
9091 // struct __va_list_tag {
9092 RecordDecl *VaListTagDecl;
9093 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9094 VaListTagDecl->startDefinition();
9095
9096 const size_t NumFields = 4;
9097 QualType FieldTypes[NumFields];
9098 const char *FieldNames[NumFields];
9099
9100 // long __gpr;
9101 FieldTypes[0] = Context->LongTy;
9102 FieldNames[0] = "__gpr";
9103
9104 // long __fpr;
9105 FieldTypes[1] = Context->LongTy;
9106 FieldNames[1] = "__fpr";
9107
9108 // void *__overflow_arg_area;
9109 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9110 FieldNames[2] = "__overflow_arg_area";
9111
9112 // void *__reg_save_area;
9113 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9114 FieldNames[3] = "__reg_save_area";
9115
9116 // Create fields
9117 for (unsigned i = 0; i < NumFields; ++i) {
9118 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9119 VaListTagDecl,
9122 &Context->Idents.get(FieldNames[i]),
9123 FieldTypes[i], /*TInfo=*/nullptr,
9124 /*BitWidth=*/nullptr,
9125 /*Mutable=*/false,
9126 ICIS_NoInit);
9127 Field->setAccess(AS_public);
9128 VaListTagDecl->addDecl(Field);
9129 }
9130 VaListTagDecl->completeDefinition();
9131 Context->VaListTagDecl = VaListTagDecl;
9132 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9133
9134 // };
9135
9136 // typedef __va_list_tag __builtin_va_list[1];
9137 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9138 QualType VaListTagArrayType = Context->getConstantArrayType(
9139 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9140
9141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9142}
9143
9145 // typedef struct __va_list_tag {
9146 RecordDecl *VaListTagDecl;
9147 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9148 VaListTagDecl->startDefinition();
9149
9150 const size_t NumFields = 3;
9151 QualType FieldTypes[NumFields];
9152 const char *FieldNames[NumFields];
9153
9154 // void *CurrentSavedRegisterArea;
9155 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9156 FieldNames[0] = "__current_saved_reg_area_pointer";
9157
9158 // void *SavedRegAreaEnd;
9159 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9160 FieldNames[1] = "__saved_reg_area_end_pointer";
9161
9162 // void *OverflowArea;
9163 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9164 FieldNames[2] = "__overflow_area_pointer";
9165
9166 // Create fields
9167 for (unsigned i = 0; i < NumFields; ++i) {
9169 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9170 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9171 /*TInfo=*/nullptr,
9172 /*BitWidth=*/nullptr,
9173 /*Mutable=*/false, ICIS_NoInit);
9174 Field->setAccess(AS_public);
9175 VaListTagDecl->addDecl(Field);
9176 }
9177 VaListTagDecl->completeDefinition();
9178 Context->VaListTagDecl = VaListTagDecl;
9179 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9180
9181 // } __va_list_tag;
9182 TypedefDecl *VaListTagTypedefDecl =
9183 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9184
9185 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9186
9187 // typedef __va_list_tag __builtin_va_list[1];
9188 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9189 QualType VaListTagArrayType = Context->getConstantArrayType(
9190 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9191
9192 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9193}
9194
9197 switch (Kind) {
9199 return CreateCharPtrBuiltinVaListDecl(Context);
9201 return CreateVoidPtrBuiltinVaListDecl(Context);
9203 return CreateAArch64ABIBuiltinVaListDecl(Context);
9205 return CreatePowerABIBuiltinVaListDecl(Context);
9207 return CreateX86_64ABIBuiltinVaListDecl(Context);
9209 return CreatePNaClABIBuiltinVaListDecl(Context);
9211 return CreateAAPCSABIBuiltinVaListDecl(Context);
9213 return CreateSystemZBuiltinVaListDecl(Context);
9215 return CreateHexagonBuiltinVaListDecl(Context);
9216 }
9217
9218 llvm_unreachable("Unhandled __builtin_va_list type kind");
9219}
9220
9222 if (!BuiltinVaListDecl) {
9223 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9224 assert(BuiltinVaListDecl->isImplicit());
9225 }
9226
9227 return BuiltinVaListDecl;
9228}
9229
9231 // Force the creation of VaListTagDecl by building the __builtin_va_list
9232 // declaration.
9233 if (!VaListTagDecl)
9234 (void)getBuiltinVaListDecl();
9235
9236 return VaListTagDecl;
9237}
9238
9240 if (!BuiltinMSVaListDecl)
9241 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9242
9243 return BuiltinMSVaListDecl;
9244}
9245
9247 // Allow redecl custom type checking builtin for HLSL.
9248 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9250 return true;
9252}
9253
9255 assert(ObjCConstantStringType.isNull() &&
9256 "'NSConstantString' type already set!");
9257
9258 ObjCConstantStringType = getObjCInterfaceType(Decl);
9259}
9260
9261/// Retrieve the template name that corresponds to a non-empty
9262/// lookup.
9265 UnresolvedSetIterator End) const {
9266 unsigned size = End - Begin;
9267 assert(size > 1 && "set is not overloaded!");
9268
9269 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9270 size * sizeof(FunctionTemplateDecl*));
9271 auto *OT = new (memory) OverloadedTemplateStorage(size);
9272
9273 NamedDecl **Storage = OT->getStorage();
9274 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9275 NamedDecl *D = *I;
9276 assert(isa<FunctionTemplateDecl>(D) ||
9277 isa<UnresolvedUsingValueDecl>(D) ||
9278 (isa<UsingShadowDecl>(D) &&
9279 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9280 *Storage++ = D;
9281 }
9282
9283 return TemplateName(OT);
9284}
9285
9286/// Retrieve a template name representing an unqualified-id that has been
9287/// assumed to name a template for ADL purposes.
9289 auto *OT = new (*this) AssumedTemplateStorage(Name);
9290 return TemplateName(OT);
9291}
9292
9293/// Retrieve the template name that represents a qualified
9294/// template name such as \c std::vector.
9296 bool TemplateKeyword,
9297 TemplateName Template) const {
9298 assert(NNS && "Missing nested-name-specifier in qualified template name");
9299
9300 // FIXME: Canonicalization?
9301 llvm::FoldingSetNodeID ID;
9302 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9303
9304 void *InsertPos = nullptr;
9306 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9307 if (!QTN) {
9308 QTN = new (*this, alignof(QualifiedTemplateName))
9309 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9310 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9311 }
9312
9313 return TemplateName(QTN);
9314}
9315
9316/// Retrieve the template name that represents a dependent
9317/// template name such as \c MetaFun::template apply.
9320 const IdentifierInfo *Name) const {
9321 assert((!NNS || NNS->isDependent()) &&
9322 "Nested name specifier must be dependent");
9323
9324 llvm::FoldingSetNodeID ID;
9325 DependentTemplateName::Profile(ID, NNS, Name);
9326
9327 void *InsertPos = nullptr;
9329 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9330
9331 if (QTN)
9332 return TemplateName(QTN);
9333
9335 if (CanonNNS == NNS) {
9336 QTN = new (*this, alignof(DependentTemplateName))
9337 DependentTemplateName(NNS, Name);
9338 } else {
9339 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9340 QTN = new (*this, alignof(DependentTemplateName))
9341 DependentTemplateName(NNS, Name, Canon);
9342 DependentTemplateName *CheckQTN =
9343 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9344 assert(!CheckQTN && "Dependent type name canonicalization broken");
9345 (void)CheckQTN;
9346 }
9347
9348 DependentTemplateNames.InsertNode(QTN, InsertPos);
9349 return TemplateName(QTN);
9350}
9351
9352/// Retrieve the template name that represents a dependent
9353/// template name such as \c MetaFun::template operator+.
9356 OverloadedOperatorKind Operator) const {
9357 assert((!NNS || NNS->isDependent()) &&
9358 "Nested name specifier must be dependent");
9359
9360 llvm::FoldingSetNodeID ID;
9361 DependentTemplateName::Profile(ID, NNS, Operator);
9362
9363 void *InsertPos = nullptr;
9365 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9366
9367 if (QTN)
9368 return TemplateName(QTN);
9369
9371 if (CanonNNS == NNS) {
9372 QTN = new (*this, alignof(DependentTemplateName))
9373 DependentTemplateName(NNS, Operator);
9374 } else {
9375 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9376 QTN = new (*this, alignof(DependentTemplateName))
9377 DependentTemplateName(NNS, Operator, Canon);
9378
9379 DependentTemplateName *CheckQTN
9380 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9381 assert(!CheckQTN && "Dependent template name canonicalization broken");
9382 (void)CheckQTN;
9383 }
9384
9385 DependentTemplateNames.InsertNode(QTN, InsertPos);
9386 return TemplateName(QTN);
9387}
9388
9390 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9391 std::optional<unsigned> PackIndex) const {
9392 llvm::FoldingSetNodeID ID;
9393 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9394 Index, PackIndex);
9395
9396 void *insertPos = nullptr;
9398 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9399
9400 if (!subst) {
9401 subst = new (*this) SubstTemplateTemplateParmStorage(
9402 Replacement, AssociatedDecl, Index, PackIndex);
9403 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9404 }
9405
9406 return TemplateName(subst);
9407}
9408
9411 Decl *AssociatedDecl,
9412 unsigned Index, bool Final) const {
9413 auto &Self = const_cast<ASTContext &>(*this);
9414 llvm::FoldingSetNodeID ID;
9416 AssociatedDecl, Index, Final);
9417
9418 void *InsertPos = nullptr;
9420 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9421
9422 if (!Subst) {
9423 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9424 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9425 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9426 }
9427
9428 return TemplateName(Subst);
9429}
9430
9431/// getFromTargetType - Given one of the integer types provided by
9432/// TargetInfo, produce the corresponding type. The unsigned @p Type
9433/// is actually a value of type @c TargetInfo::IntType.
9434CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9435 switch (Type) {
9436 case TargetInfo::NoInt: return {};
9439 case TargetInfo::SignedShort: return ShortTy;
9441 case TargetInfo::SignedInt: return IntTy;
9443 case TargetInfo::SignedLong: return LongTy;
9447 }
9448
9449 llvm_unreachable("Unhandled TargetInfo::IntType value");
9450}
9451
9452//===----------------------------------------------------------------------===//
9453// Type Predicates.
9454//===----------------------------------------------------------------------===//
9455
9456/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9457/// garbage collection attribute.
9458///
9460 if (getLangOpts().getGC() == LangOptions::NonGC)
9461 return Qualifiers::GCNone;
9462
9463 assert(getLangOpts().ObjC);
9464 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9465
9466 // Default behaviour under objective-C's gc is for ObjC pointers
9467 // (or pointers to them) be treated as though they were declared
9468 // as __strong.
9469 if (GCAttrs == Qualifiers::GCNone) {
9471 return Qualifiers::Strong;
9472 else if (Ty->isPointerType())
9474 } else {
9475 // It's not valid to set GC attributes on anything that isn't a
9476 // pointer.
9477#ifndef NDEBUG
9479 while (const auto *AT = dyn_cast<ArrayType>(CT))
9480 CT = AT->getElementType();
9481 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9482#endif
9483 }
9484 return GCAttrs;
9485}
9486
9487//===----------------------------------------------------------------------===//
9488// Type Compatibility Testing
9489//===----------------------------------------------------------------------===//
9490
9491/// areCompatVectorTypes - Return true if the two specified vector types are
9492/// compatible.
9493static bool areCompatVectorTypes(const VectorType *LHS,
9494 const VectorType *RHS) {
9495 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9496 return LHS->getElementType() == RHS->getElementType() &&
9497 LHS->getNumElements() == RHS->getNumElements();
9498}
9499
9500/// areCompatMatrixTypes - Return true if the two specified matrix types are
9501/// compatible.
9503 const ConstantMatrixType *RHS) {
9504 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9505 return LHS->getElementType() == RHS->getElementType() &&
9506 LHS->getNumRows() == RHS->getNumRows() &&
9507 LHS->getNumColumns() == RHS->getNumColumns();
9508}
9509
9511 QualType SecondVec) {
9512 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9513 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9514
9515 if (hasSameUnqualifiedType(FirstVec, SecondVec))
9516 return true;
9517
9518 // Treat Neon vector types and most AltiVec vector types as if they are the
9519 // equivalent GCC vector types.
9520 const auto *First = FirstVec->castAs<VectorType>();
9521 const auto *Second = SecondVec->castAs<VectorType>();
9522 if (First->getNumElements() == Second->getNumElements() &&
9523 hasSameType(First->getElementType(), Second->getElementType()) &&
9524 First->getVectorKind() != VectorKind::AltiVecPixel &&
9525 First->getVectorKind() != VectorKind::AltiVecBool &&
9528 First->getVectorKind() != VectorKind::SveFixedLengthData &&
9529 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9532 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9534 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
9536 return true;
9537
9538 return false;
9539}
9540
9541/// getSVETypeSize - Return SVE vector or predicate register size.
9542static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9543 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9544 if (Ty->getKind() == BuiltinType::SveBool ||
9545 Ty->getKind() == BuiltinType::SveCount)
9546 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9547 return Context.getLangOpts().VScaleMin * 128;
9548}
9549
9551 QualType SecondType) {
9552 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9553 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9554 if (const auto *VT = SecondType->getAs<VectorType>()) {
9555 // Predicates have the same representation as uint8 so we also have to
9556 // check the kind to make these types incompatible.
9557 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9558 return BT->getKind() == BuiltinType::SveBool;
9559 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9560 return VT->getElementType().getCanonicalType() ==
9561 FirstType->getSveEltType(*this);
9562 else if (VT->getVectorKind() == VectorKind::Generic)
9563 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9564 hasSameType(VT->getElementType(),
9565 getBuiltinVectorTypeInfo(BT).ElementType);
9566 }
9567 }
9568 return false;
9569 };
9570
9571 return IsValidCast(FirstType, SecondType) ||
9572 IsValidCast(SecondType, FirstType);
9573}
9574
9576 QualType SecondType) {
9577 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9578 const auto *BT = FirstType->getAs<BuiltinType>();
9579 if (!BT)
9580 return false;
9581
9582 const auto *VecTy = SecondType->getAs<VectorType>();
9583 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9584 VecTy->getVectorKind() == VectorKind::Generic)) {
9586 getLangOpts().getLaxVectorConversions();
9587
9588 // Can not convert between sve predicates and sve vectors because of
9589 // different size.
9590 if (BT->getKind() == BuiltinType::SveBool &&
9591 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9592 return false;
9593
9594 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9595 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9596 // converts to VLAT and VLAT implicitly converts to GNUT."
9597 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9598 // predicates.
9599 if (VecTy->getVectorKind() == VectorKind::Generic &&
9600 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9601 return false;
9602
9603 // If -flax-vector-conversions=all is specified, the types are
9604 // certainly compatible.
9606 return true;
9607
9608 // If -flax-vector-conversions=integer is specified, the types are
9609 // compatible if the elements are integer types.
9611 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9612 FirstType->getSveEltType(*this)->isIntegerType();
9613 }
9614
9615 return false;
9616 };
9617
9618 return IsLaxCompatible(FirstType, SecondType) ||
9619 IsLaxCompatible(SecondType, FirstType);
9620}
9621
9622/// getRVVTypeSize - Return RVV vector register size.
9623static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
9624 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
9625 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
9626 if (!VScale)
9627 return 0;
9628
9630
9631 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
9632 if (Info.ElementType == Context.BoolTy)
9633 EltSize = 1;
9634
9635 uint64_t MinElts = Info.EC.getKnownMinValue();
9636 return VScale->first * MinElts * EltSize;
9637}
9638
9640 QualType SecondType) {
9641 assert(
9642 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9643 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9644 "Expected RVV builtin type and vector type!");
9645
9646 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9647 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9648 if (const auto *VT = SecondType->getAs<VectorType>()) {
9649 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
9651 return FirstType->isRVVVLSBuiltinType() &&
9652 Info.ElementType == BoolTy &&
9653 getTypeSize(SecondType) == getRVVTypeSize(*this, BT);
9654 }
9655 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
9656 VT->getVectorKind() == VectorKind::Generic)
9657 return FirstType->isRVVVLSBuiltinType() &&
9658 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
9659 hasSameType(VT->getElementType(),
9660 getBuiltinVectorTypeInfo(BT).ElementType);
9661 }
9662 }
9663 return false;
9664 };
9665
9666 return IsValidCast(FirstType, SecondType) ||
9667 IsValidCast(SecondType, FirstType);
9668}
9669
9671 QualType SecondType) {
9672 assert(
9673 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9674 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9675 "Expected RVV builtin type and vector type!");
9676
9677 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9678 const auto *BT = FirstType->getAs<BuiltinType>();
9679 if (!BT)
9680 return false;
9681
9682 if (!BT->isRVVVLSBuiltinType())
9683 return false;
9684
9685 const auto *VecTy = SecondType->getAs<VectorType>();
9686 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
9688 getLangOpts().getLaxVectorConversions();
9689
9690 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
9691 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
9692 return false;
9693
9694 // If -flax-vector-conversions=all is specified, the types are
9695 // certainly compatible.
9697 return true;
9698
9699 // If -flax-vector-conversions=integer is specified, the types are
9700 // compatible if the elements are integer types.
9702 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9703 FirstType->getRVVEltType(*this)->isIntegerType();
9704 }
9705
9706 return false;
9707 };
9708
9709 return IsLaxCompatible(FirstType, SecondType) ||
9710 IsLaxCompatible(SecondType, FirstType);
9711}
9712
9714 while (true) {
9715 // __strong id
9716 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9717 if (Attr->getAttrKind() == attr::ObjCOwnership)
9718 return true;
9719
9720 Ty = Attr->getModifiedType();
9721
9722 // X *__strong (...)
9723 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9724 Ty = Paren->getInnerType();
9725
9726 // We do not want to look through typedefs, typeof(expr),
9727 // typeof(type), or any other way that the type is somehow
9728 // abstracted.
9729 } else {
9730 return false;
9731 }
9732 }
9733}
9734
9735//===----------------------------------------------------------------------===//
9736// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9737//===----------------------------------------------------------------------===//
9738
9739/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9740/// inheritance hierarchy of 'rProto'.
9741bool
9743 ObjCProtocolDecl *rProto) const {
9744 if (declaresSameEntity(lProto, rProto))
9745 return true;
9746 for (auto *PI : rProto->protocols())
9747 if (ProtocolCompatibleWithProtocol(lProto, PI))
9748 return true;
9749 return false;
9750}
9751
9752/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
9753/// Class<pr1, ...>.
9755 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9756 for (auto *lhsProto : lhs->quals()) {
9757 bool match = false;
9758 for (auto *rhsProto : rhs->quals()) {
9759 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9760 match = true;
9761 break;
9762 }
9763 }
9764 if (!match)
9765 return false;
9766 }
9767 return true;
9768}
9769
9770/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9771/// ObjCQualifiedIDType.
9773 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9774 bool compare) {
9775 // Allow id<P..> and an 'id' in all cases.
9776 if (lhs->isObjCIdType() || rhs->isObjCIdType())
9777 return true;
9778
9779 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9780 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9782 return false;
9783
9784 if (lhs->isObjCQualifiedIdType()) {
9785 if (rhs->qual_empty()) {
9786 // If the RHS is a unqualified interface pointer "NSString*",
9787 // make sure we check the class hierarchy.
9788 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9789 for (auto *I : lhs->quals()) {
9790 // when comparing an id<P> on lhs with a static type on rhs,
9791 // see if static class implements all of id's protocols, directly or
9792 // through its super class and categories.
9793 if (!rhsID->ClassImplementsProtocol(I, true))
9794 return false;
9795 }
9796 }
9797 // If there are no qualifiers and no interface, we have an 'id'.
9798 return true;
9799 }
9800 // Both the right and left sides have qualifiers.
9801 for (auto *lhsProto : lhs->quals()) {
9802 bool match = false;
9803
9804 // when comparing an id<P> on lhs with a static type on rhs,
9805 // see if static class implements all of id's protocols, directly or
9806 // through its super class and categories.
9807 for (auto *rhsProto : rhs->quals()) {
9808 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9809 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9810 match = true;
9811 break;
9812 }
9813 }
9814 // If the RHS is a qualified interface pointer "NSString<P>*",
9815 // make sure we check the class hierarchy.
9816 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9817 for (auto *I : lhs->quals()) {
9818 // when comparing an id<P> on lhs with a static type on rhs,
9819 // see if static class implements all of id's protocols, directly or
9820 // through its super class and categories.
9821 if (rhsID->ClassImplementsProtocol(I, true)) {
9822 match = true;
9823 break;
9824 }
9825 }
9826 }
9827 if (!match)
9828 return false;
9829 }
9830
9831 return true;
9832 }
9833
9834 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9835
9836 if (lhs->getInterfaceType()) {
9837 // If both the right and left sides have qualifiers.
9838 for (auto *lhsProto : lhs->quals()) {
9839 bool match = false;
9840
9841 // when comparing an id<P> on rhs with a static type on lhs,
9842 // see if static class implements all of id's protocols, directly or
9843 // through its super class and categories.
9844 // First, lhs protocols in the qualifier list must be found, direct
9845 // or indirect in rhs's qualifier list or it is a mismatch.
9846 for (auto *rhsProto : rhs->quals()) {
9847 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9848 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9849 match = true;
9850 break;
9851 }
9852 }
9853 if (!match)
9854 return false;
9855 }
9856
9857 // Static class's protocols, or its super class or category protocols
9858 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9859 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9860 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9861 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9862 // This is rather dubious but matches gcc's behavior. If lhs has
9863 // no type qualifier and its class has no static protocol(s)
9864 // assume that it is mismatch.
9865 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9866 return false;
9867 for (auto *lhsProto : LHSInheritedProtocols) {
9868 bool match = false;
9869 for (auto *rhsProto : rhs->quals()) {
9870 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9871 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9872 match = true;
9873 break;
9874 }
9875 }
9876 if (!match)
9877 return false;
9878 }
9879 }
9880 return true;
9881 }
9882 return false;
9883}
9884
9885/// canAssignObjCInterfaces - Return true if the two interface types are
9886/// compatible for assignment from RHS to LHS. This handles validation of any
9887/// protocol qualifiers on the LHS or RHS.
9889 const ObjCObjectPointerType *RHSOPT) {
9890 const ObjCObjectType* LHS = LHSOPT->getObjectType();
9891 const ObjCObjectType* RHS = RHSOPT->getObjectType();
9892
9893 // If either type represents the built-in 'id' type, return true.
9894 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9895 return true;
9896
9897 // Function object that propagates a successful result or handles
9898 // __kindof types.
9899 auto finish = [&](bool succeeded) -> bool {
9900 if (succeeded)
9901 return true;
9902
9903 if (!RHS->isKindOfType())
9904 return false;
9905
9906 // Strip off __kindof and protocol qualifiers, then check whether
9907 // we can assign the other way.
9909 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9910 };
9911
9912 // Casts from or to id<P> are allowed when the other side has compatible
9913 // protocols.
9914 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9915 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9916 }
9917
9918 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9919 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9920 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9921 }
9922
9923 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9924 if (LHS->isObjCClass() && RHS->isObjCClass()) {
9925 return true;
9926 }
9927
9928 // If we have 2 user-defined types, fall into that path.
9929 if (LHS->getInterface() && RHS->getInterface()) {
9930 return finish(canAssignObjCInterfaces(LHS, RHS));
9931 }
9932
9933 return false;
9934}
9935
9936/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9937/// for providing type-safety for objective-c pointers used to pass/return
9938/// arguments in block literals. When passed as arguments, passing 'A*' where
9939/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9940/// not OK. For the return type, the opposite is not OK.
9942 const ObjCObjectPointerType *LHSOPT,
9943 const ObjCObjectPointerType *RHSOPT,
9944 bool BlockReturnType) {
9945
9946 // Function object that propagates a successful result or handles
9947 // __kindof types.
9948 auto finish = [&](bool succeeded) -> bool {
9949 if (succeeded)
9950 return true;
9951
9952 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9953 if (!Expected->isKindOfType())
9954 return false;
9955
9956 // Strip off __kindof and protocol qualifiers, then check whether
9957 // we can assign the other way.
9959 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9960 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9961 BlockReturnType);
9962 };
9963
9964 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9965 return true;
9966
9967 if (LHSOPT->isObjCBuiltinType()) {
9968 return finish(RHSOPT->isObjCBuiltinType() ||
9969 RHSOPT->isObjCQualifiedIdType());
9970 }
9971
9972 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9973 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9974 // Use for block parameters previous type checking for compatibility.
9975 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9976 // Or corrected type checking as in non-compat mode.
9977 (!BlockReturnType &&
9978 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9979 else
9981 (BlockReturnType ? LHSOPT : RHSOPT),
9982 (BlockReturnType ? RHSOPT : LHSOPT), false));
9983 }
9984
9985 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9986 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9987 if (LHS && RHS) { // We have 2 user-defined types.
9988 if (LHS != RHS) {
9989 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9990 return finish(BlockReturnType);
9991 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9992 return finish(!BlockReturnType);
9993 }
9994 else
9995 return true;
9996 }
9997 return false;
9998}
9999
10000/// Comparison routine for Objective-C protocols to be used with
10001/// llvm::array_pod_sort.
10003 ObjCProtocolDecl * const *rhs) {
10004 return (*lhs)->getName().compare((*rhs)->getName());
10005}
10006
10007/// getIntersectionOfProtocols - This routine finds the intersection of set
10008/// of protocols inherited from two distinct objective-c pointer objects with
10009/// the given common base.
10010/// It is used to build composite qualifier list of the composite type of
10011/// the conditional expression involving two objective-c pointer objects.
10012static
10014 const ObjCInterfaceDecl *CommonBase,
10015 const ObjCObjectPointerType *LHSOPT,
10016 const ObjCObjectPointerType *RHSOPT,
10017 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10018
10019 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10020 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10021 assert(LHS->getInterface() && "LHS must have an interface base");
10022 assert(RHS->getInterface() && "RHS must have an interface base");
10023
10024 // Add all of the protocols for the LHS.
10026
10027 // Start with the protocol qualifiers.
10028 for (auto *proto : LHS->quals()) {
10029 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10030 }
10031
10032 // Also add the protocols associated with the LHS interface.
10033 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10034
10035 // Add all of the protocols for the RHS.
10037
10038 // Start with the protocol qualifiers.
10039 for (auto *proto : RHS->quals()) {
10040 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10041 }
10042
10043 // Also add the protocols associated with the RHS interface.
10044 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10045
10046 // Compute the intersection of the collected protocol sets.
10047 for (auto *proto : LHSProtocolSet) {
10048 if (RHSProtocolSet.count(proto))
10049 IntersectionSet.push_back(proto);
10050 }
10051
10052 // Compute the set of protocols that is implied by either the common type or
10053 // the protocols within the intersection.
10055 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10056
10057 // Remove any implied protocols from the list of inherited protocols.
10058 if (!ImpliedProtocols.empty()) {
10059 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10060 return ImpliedProtocols.contains(proto);
10061 });
10062 }
10063
10064 // Sort the remaining protocols by name.
10065 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10067}
10068
10069/// Determine whether the first type is a subtype of the second.
10071 QualType rhs) {
10072 // Common case: two object pointers.
10073 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10074 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10075 if (lhsOPT && rhsOPT)
10076 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10077
10078 // Two block pointers.
10079 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10080 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10081 if (lhsBlock && rhsBlock)
10082 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10083
10084 // If either is an unqualified 'id' and the other is a block, it's
10085 // acceptable.
10086 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10087 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10088 return true;
10089
10090 return false;
10091}
10092
10093// Check that the given Objective-C type argument lists are equivalent.
10095 const ObjCInterfaceDecl *iface,
10096 ArrayRef<QualType> lhsArgs,
10097 ArrayRef<QualType> rhsArgs,
10098 bool stripKindOf) {
10099 if (lhsArgs.size() != rhsArgs.size())
10100 return false;
10101
10102 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10103 if (!typeParams)
10104 return false;
10105
10106 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10107 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10108 continue;
10109
10110 switch (typeParams->begin()[i]->getVariance()) {
10112 if (!stripKindOf ||
10113 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10114 rhsArgs[i].stripObjCKindOfType(ctx))) {
10115 return false;
10116 }
10117 break;
10118
10120 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10121 return false;
10122 break;
10123
10125 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10126 return false;
10127 break;
10128 }
10129 }
10130
10131 return true;
10132}
10133
10135 const ObjCObjectPointerType *Lptr,
10136 const ObjCObjectPointerType *Rptr) {
10137 const ObjCObjectType *LHS = Lptr->getObjectType();
10138 const ObjCObjectType *RHS = Rptr->getObjectType();
10139 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10140 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10141
10142 if (!LDecl || !RDecl)
10143 return {};
10144
10145 // When either LHS or RHS is a kindof type, we should return a kindof type.
10146 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10147 // kindof(A).
10148 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10149
10150 // Follow the left-hand side up the class hierarchy until we either hit a
10151 // root or find the RHS. Record the ancestors in case we don't find it.
10152 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10153 LHSAncestors;
10154 while (true) {
10155 // Record this ancestor. We'll need this if the common type isn't in the
10156 // path from the LHS to the root.
10157 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10158
10159 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10160 // Get the type arguments.
10161 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10162 bool anyChanges = false;
10163 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10164 // Both have type arguments, compare them.
10165 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10166 LHS->getTypeArgs(), RHS->getTypeArgs(),
10167 /*stripKindOf=*/true))
10168 return {};
10169 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10170 // If only one has type arguments, the result will not have type
10171 // arguments.
10172 LHSTypeArgs = {};
10173 anyChanges = true;
10174 }
10175
10176 // Compute the intersection of protocols.
10178 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10179 Protocols);
10180 if (!Protocols.empty())
10181 anyChanges = true;
10182
10183 // If anything in the LHS will have changed, build a new result type.
10184 // If we need to return a kindof type but LHS is not a kindof type, we
10185 // build a new result type.
10186 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10188 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10189 anyKindOf || LHS->isKindOfType());
10191 }
10192
10193 return getObjCObjectPointerType(QualType(LHS, 0));
10194 }
10195
10196 // Find the superclass.
10197 QualType LHSSuperType = LHS->getSuperClassType();
10198 if (LHSSuperType.isNull())
10199 break;
10200
10201 LHS = LHSSuperType->castAs<ObjCObjectType>();
10202 }
10203
10204 // We didn't find anything by following the LHS to its root; now check
10205 // the RHS against the cached set of ancestors.
10206 while (true) {
10207 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10208 if (KnownLHS != LHSAncestors.end()) {
10209 LHS = KnownLHS->second;
10210
10211 // Get the type arguments.
10212 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10213 bool anyChanges = false;
10214 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10215 // Both have type arguments, compare them.
10216 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10217 LHS->getTypeArgs(), RHS->getTypeArgs(),
10218 /*stripKindOf=*/true))
10219 return {};
10220 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10221 // If only one has type arguments, the result will not have type
10222 // arguments.
10223 RHSTypeArgs = {};
10224 anyChanges = true;
10225 }
10226
10227 // Compute the intersection of protocols.
10229 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10230 Protocols);
10231 if (!Protocols.empty())
10232 anyChanges = true;
10233
10234 // If we need to return a kindof type but RHS is not a kindof type, we
10235 // build a new result type.
10236 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10238 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10239 anyKindOf || RHS->isKindOfType());
10241 }
10242
10243 return getObjCObjectPointerType(QualType(RHS, 0));
10244 }
10245
10246 // Find the superclass of the RHS.
10247 QualType RHSSuperType = RHS->getSuperClassType();
10248 if (RHSSuperType.isNull())
10249 break;
10250
10251 RHS = RHSSuperType->castAs<ObjCObjectType>();
10252 }
10253
10254 return {};
10255}
10256
10258 const ObjCObjectType *RHS) {
10259 assert(LHS->getInterface() && "LHS is not an interface type");
10260 assert(RHS->getInterface() && "RHS is not an interface type");
10261
10262 // Verify that the base decls are compatible: the RHS must be a subclass of
10263 // the LHS.
10264 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10265 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10266 if (!IsSuperClass)
10267 return false;
10268
10269 // If the LHS has protocol qualifiers, determine whether all of them are
10270 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10271 // LHS).
10272 if (LHS->getNumProtocols() > 0) {
10273 // OK if conversion of LHS to SuperClass results in narrowing of types
10274 // ; i.e., SuperClass may implement at least one of the protocols
10275 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10276 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10277 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10278 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10279 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10280 // qualifiers.
10281 for (auto *RHSPI : RHS->quals())
10282 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10283 // If there is no protocols associated with RHS, it is not a match.
10284 if (SuperClassInheritedProtocols.empty())
10285 return false;
10286
10287 for (const auto *LHSProto : LHS->quals()) {
10288 bool SuperImplementsProtocol = false;
10289 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10290 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10291 SuperImplementsProtocol = true;
10292 break;
10293 }
10294 if (!SuperImplementsProtocol)
10295 return false;
10296 }
10297 }
10298
10299 // If the LHS is specialized, we may need to check type arguments.
10300 if (LHS->isSpecialized()) {
10301 // Follow the superclass chain until we've matched the LHS class in the
10302 // hierarchy. This substitutes type arguments through.
10303 const ObjCObjectType *RHSSuper = RHS;
10304 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10305 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10306
10307 // If the RHS is specializd, compare type arguments.
10308 if (RHSSuper->isSpecialized() &&
10309 !sameObjCTypeArgs(*this, LHS->getInterface(),
10310 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10311 /*stripKindOf=*/true)) {
10312 return false;
10313 }
10314 }
10315
10316 return true;
10317}
10318
10320 // get the "pointed to" types
10321 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10322 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10323
10324 if (!LHSOPT || !RHSOPT)
10325 return false;
10326
10327 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10328 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10329}
10330
10333 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10334 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10335}
10336
10337/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10338/// both shall have the identically qualified version of a compatible type.
10339/// C99 6.2.7p1: Two types have compatible types if their types are the
10340/// same. See 6.7.[2,3,5] for additional rules.
10342 bool CompareUnqualified) {
10343 if (getLangOpts().CPlusPlus)
10344 return hasSameType(LHS, RHS);
10345
10346 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10347}
10348
10350 return typesAreCompatible(LHS, RHS);
10351}
10352
10354 return !mergeTypes(LHS, RHS, true).isNull();
10355}
10356
10357/// mergeTransparentUnionType - if T is a transparent union type and a member
10358/// of T is compatible with SubType, return the merged type, else return
10359/// QualType()
10361 bool OfBlockPointer,
10362 bool Unqualified) {
10363 if (const RecordType *UT = T->getAsUnionType()) {
10364 RecordDecl *UD = UT->getDecl();
10365 if (UD->hasAttr<TransparentUnionAttr>()) {
10366 for (const auto *I : UD->fields()) {
10367 QualType ET = I->getType().getUnqualifiedType();
10368 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10369 if (!MT.isNull())
10370 return MT;
10371 }
10372 }
10373 }
10374
10375 return {};
10376}
10377
10378/// mergeFunctionParameterTypes - merge two types which appear as function
10379/// parameter types
10381 bool OfBlockPointer,
10382 bool Unqualified) {
10383 // GNU extension: two types are compatible if they appear as a function
10384 // argument, one of the types is a transparent union type and the other
10385 // type is compatible with a union member
10386 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10387 Unqualified);
10388 if (!lmerge.isNull())
10389 return lmerge;
10390
10391 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10392 Unqualified);
10393 if (!rmerge.isNull())
10394 return rmerge;
10395
10396 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10397}
10398
10400 bool OfBlockPointer, bool Unqualified,
10401 bool AllowCXX,
10402 bool IsConditionalOperator) {
10403 const auto *lbase = lhs->castAs<FunctionType>();
10404 const auto *rbase = rhs->castAs<FunctionType>();
10405 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10406 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10407 bool allLTypes = true;
10408 bool allRTypes = true;
10409
10410 // Check return type
10411 QualType retType;
10412 if (OfBlockPointer) {
10413 QualType RHS = rbase->getReturnType();
10414 QualType LHS = lbase->getReturnType();
10415 bool UnqualifiedResult = Unqualified;
10416 if (!UnqualifiedResult)
10417 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10418 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10419 }
10420 else
10421 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10422 Unqualified);
10423 if (retType.isNull())
10424 return {};
10425
10426 if (Unqualified)
10427 retType = retType.getUnqualifiedType();
10428
10429 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10430 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10431 if (Unqualified) {
10432 LRetType = LRetType.getUnqualifiedType();
10433 RRetType = RRetType.getUnqualifiedType();
10434 }
10435
10436 if (getCanonicalType(retType) != LRetType)
10437 allLTypes = false;
10438 if (getCanonicalType(retType) != RRetType)
10439 allRTypes = false;
10440
10441 // FIXME: double check this
10442 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10443 // rbase->getRegParmAttr() != 0 &&
10444 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10445 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10446 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10447
10448 // Compatible functions must have compatible calling conventions
10449 if (lbaseInfo.getCC() != rbaseInfo.getCC())
10450 return {};
10451
10452 // Regparm is part of the calling convention.
10453 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10454 return {};
10455 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10456 return {};
10457
10458 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10459 return {};
10460 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10461 return {};
10462 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10463 return {};
10464
10465 // When merging declarations, it's common for supplemental information like
10466 // attributes to only be present in one of the declarations, and we generally
10467 // want type merging to preserve the union of information. So a merged
10468 // function type should be noreturn if it was noreturn in *either* operand
10469 // type.
10470 //
10471 // But for the conditional operator, this is backwards. The result of the
10472 // operator could be either operand, and its type should conservatively
10473 // reflect that. So a function type in a composite type is noreturn only
10474 // if it's noreturn in *both* operand types.
10475 //
10476 // Arguably, noreturn is a kind of subtype, and the conditional operator
10477 // ought to produce the most specific common supertype of its operand types.
10478 // That would differ from this rule in contravariant positions. However,
10479 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
10480 // as a practical matter, it would only affect C code that does abstraction of
10481 // higher-order functions (taking noreturn callbacks!), which is uncommon to
10482 // say the least. So we use the simpler rule.
10483 bool NoReturn = IsConditionalOperator
10484 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10485 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10486 if (lbaseInfo.getNoReturn() != NoReturn)
10487 allLTypes = false;
10488 if (rbaseInfo.getNoReturn() != NoReturn)
10489 allRTypes = false;
10490
10491 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10492
10493 if (lproto && rproto) { // two C99 style function prototypes
10494 assert((AllowCXX ||
10495 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10496 "C++ shouldn't be here");
10497 // Compatible functions must have the same number of parameters
10498 if (lproto->getNumParams() != rproto->getNumParams())
10499 return {};
10500
10501 // Variadic and non-variadic functions aren't compatible
10502 if (lproto->isVariadic() != rproto->isVariadic())
10503 return {};
10504
10505 if (lproto->getMethodQuals() != rproto->getMethodQuals())
10506 return {};
10507
10509 bool canUseLeft, canUseRight;
10510 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10511 newParamInfos))
10512 return {};
10513
10514 if (!canUseLeft)
10515 allLTypes = false;
10516 if (!canUseRight)
10517 allRTypes = false;
10518
10519 // Check parameter type compatibility
10521 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10522 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10523 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10525 lParamType, rParamType, OfBlockPointer, Unqualified);
10526 if (paramType.isNull())
10527 return {};
10528
10529 if (Unqualified)
10530 paramType = paramType.getUnqualifiedType();
10531
10532 types.push_back(paramType);
10533 if (Unqualified) {
10534 lParamType = lParamType.getUnqualifiedType();
10535 rParamType = rParamType.getUnqualifiedType();
10536 }
10537
10538 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10539 allLTypes = false;
10540 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10541 allRTypes = false;
10542 }
10543
10544 if (allLTypes) return lhs;
10545 if (allRTypes) return rhs;
10546
10547 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10548 EPI.ExtInfo = einfo;
10549 EPI.ExtParameterInfos =
10550 newParamInfos.empty() ? nullptr : newParamInfos.data();
10551 return getFunctionType(retType, types, EPI);
10552 }
10553
10554 if (lproto) allRTypes = false;
10555 if (rproto) allLTypes = false;
10556
10557 const FunctionProtoType *proto = lproto ? lproto : rproto;
10558 if (proto) {
10559 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10560 if (proto->isVariadic())
10561 return {};
10562 // Check that the types are compatible with the types that
10563 // would result from default argument promotions (C99 6.7.5.3p15).
10564 // The only types actually affected are promotable integer
10565 // types and floats, which would be passed as a different
10566 // type depending on whether the prototype is visible.
10567 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10568 QualType paramTy = proto->getParamType(i);
10569
10570 // Look at the converted type of enum types, since that is the type used
10571 // to pass enum values.
10572 if (const auto *Enum = paramTy->getAs<EnumType>()) {
10573 paramTy = Enum->getDecl()->getIntegerType();
10574 if (paramTy.isNull())
10575 return {};
10576 }
10577
10578 if (isPromotableIntegerType(paramTy) ||
10579 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10580 return {};
10581 }
10582
10583 if (allLTypes) return lhs;
10584 if (allRTypes) return rhs;
10585
10587 EPI.ExtInfo = einfo;
10588 return getFunctionType(retType, proto->getParamTypes(), EPI);
10589 }
10590
10591 if (allLTypes) return lhs;
10592 if (allRTypes) return rhs;
10593 return getFunctionNoProtoType(retType, einfo);
10594}
10595
10596/// Given that we have an enum type and a non-enum type, try to merge them.
10598 QualType other, bool isBlockReturnType) {
10599 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10600 // a signed integer type, or an unsigned integer type.
10601 // Compatibility is based on the underlying type, not the promotion
10602 // type.
10603 QualType underlyingType = ET->getDecl()->getIntegerType();
10604 if (underlyingType.isNull())
10605 return {};
10606 if (Context.hasSameType(underlyingType, other))
10607 return other;
10608
10609 // In block return types, we're more permissive and accept any
10610 // integral type of the same size.
10611 if (isBlockReturnType && other->isIntegerType() &&
10612 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10613 return other;
10614
10615 return {};
10616}
10617
10618QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
10619 bool Unqualified, bool BlockReturnType,
10620 bool IsConditionalOperator) {
10621 // For C++ we will not reach this code with reference types (see below),
10622 // for OpenMP variant call overloading we might.
10623 //
10624 // C++ [expr]: If an expression initially has the type "reference to T", the
10625 // type is adjusted to "T" prior to any further analysis, the expression
10626 // designates the object or function denoted by the reference, and the
10627 // expression is an lvalue unless the reference is an rvalue reference and
10628 // the expression is a function call (possibly inside parentheses).
10629 auto *LHSRefTy = LHS->getAs<ReferenceType>();
10630 auto *RHSRefTy = RHS->getAs<ReferenceType>();
10631 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10632 LHS->getTypeClass() == RHS->getTypeClass())
10633 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10634 OfBlockPointer, Unqualified, BlockReturnType);
10635 if (LHSRefTy || RHSRefTy)
10636 return {};
10637
10638 if (Unqualified) {
10639 LHS = LHS.getUnqualifiedType();
10640 RHS = RHS.getUnqualifiedType();
10641 }
10642
10643 QualType LHSCan = getCanonicalType(LHS),
10644 RHSCan = getCanonicalType(RHS);
10645
10646 // If two types are identical, they are compatible.
10647 if (LHSCan == RHSCan)
10648 return LHS;
10649
10650 // If the qualifiers are different, the types aren't compatible... mostly.
10651 Qualifiers LQuals = LHSCan.getLocalQualifiers();
10652 Qualifiers RQuals = RHSCan.getLocalQualifiers();
10653 if (LQuals != RQuals) {
10654 // If any of these qualifiers are different, we have a type
10655 // mismatch.
10656 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10657 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10658 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10659 LQuals.hasUnaligned() != RQuals.hasUnaligned())
10660 return {};
10661
10662 // Exactly one GC qualifier difference is allowed: __strong is
10663 // okay if the other type has no GC qualifier but is an Objective
10664 // C object pointer (i.e. implicitly strong by default). We fix
10665 // this by pretending that the unqualified type was actually
10666 // qualified __strong.
10667 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10668 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10669 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10670
10671 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10672 return {};
10673
10674 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10676 }
10677 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10679 }
10680 return {};
10681 }
10682
10683 // Okay, qualifiers are equal.
10684
10685 Type::TypeClass LHSClass = LHSCan->getTypeClass();
10686 Type::TypeClass RHSClass = RHSCan->getTypeClass();
10687
10688 // We want to consider the two function types to be the same for these
10689 // comparisons, just force one to the other.
10690 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10691 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10692
10693 // Same as above for arrays
10694 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10695 LHSClass = Type::ConstantArray;
10696 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10697 RHSClass = Type::ConstantArray;
10698
10699 // ObjCInterfaces are just specialized ObjCObjects.
10700 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10701 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10702
10703 // Canonicalize ExtVector -> Vector.
10704 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10705 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10706
10707 // If the canonical type classes don't match.
10708 if (LHSClass != RHSClass) {
10709 // Note that we only have special rules for turning block enum
10710 // returns into block int returns, not vice-versa.
10711 if (const auto *ETy = LHS->getAs<EnumType>()) {
10712 return mergeEnumWithInteger(*this, ETy, RHS, false);
10713 }
10714 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10715 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10716 }
10717 // allow block pointer type to match an 'id' type.
10718 if (OfBlockPointer && !BlockReturnType) {
10719 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10720 return LHS;
10721 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10722 return RHS;
10723 }
10724 // Allow __auto_type to match anything; it merges to the type with more
10725 // information.
10726 if (const auto *AT = LHS->getAs<AutoType>()) {
10727 if (!AT->isDeduced() && AT->isGNUAutoType())
10728 return RHS;
10729 }
10730 if (const auto *AT = RHS->getAs<AutoType>()) {
10731 if (!AT->isDeduced() && AT->isGNUAutoType())
10732 return LHS;
10733 }
10734 return {};
10735 }
10736
10737 // The canonical type classes match.
10738 switch (LHSClass) {
10739#define TYPE(Class, Base)
10740#define ABSTRACT_TYPE(Class, Base)
10741#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10742#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10743#define DEPENDENT_TYPE(Class, Base) case Type::Class:
10744#include "clang/AST/TypeNodes.inc"
10745 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10746
10747 case Type::Auto:
10748 case Type::DeducedTemplateSpecialization:
10749 case Type::LValueReference:
10750 case Type::RValueReference:
10751 case Type::MemberPointer:
10752 llvm_unreachable("C++ should never be in mergeTypes");
10753
10754 case Type::ObjCInterface:
10755 case Type::IncompleteArray:
10756 case Type::VariableArray:
10757 case Type::FunctionProto:
10758 case Type::ExtVector:
10759 llvm_unreachable("Types are eliminated above");
10760
10761 case Type::Pointer:
10762 {
10763 // Merge two pointer types, while trying to preserve typedef info
10764 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10765 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10766 if (Unqualified) {
10767 LHSPointee = LHSPointee.getUnqualifiedType();
10768 RHSPointee = RHSPointee.getUnqualifiedType();
10769 }
10770 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10771 Unqualified);
10772 if (ResultType.isNull())
10773 return {};
10774 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10775 return LHS;
10776 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10777 return RHS;
10778 return getPointerType(ResultType);
10779 }
10780 case Type::BlockPointer:
10781 {
10782 // Merge two block pointer types, while trying to preserve typedef info
10783 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10784 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10785 if (Unqualified) {
10786 LHSPointee = LHSPointee.getUnqualifiedType();
10787 RHSPointee = RHSPointee.getUnqualifiedType();
10788 }
10789 if (getLangOpts().OpenCL) {
10790 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10791 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10792 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10793 // 6.12.5) thus the following check is asymmetric.
10794 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10795 return {};
10796 LHSPteeQual.removeAddressSpace();
10797 RHSPteeQual.removeAddressSpace();
10798 LHSPointee =
10799 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10800 RHSPointee =
10801 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10802 }
10803 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10804 Unqualified);
10805 if (ResultType.isNull())
10806 return {};
10807 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10808 return LHS;
10809 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10810 return RHS;
10811 return getBlockPointerType(ResultType);
10812 }
10813 case Type::Atomic:
10814 {
10815 // Merge two pointer types, while trying to preserve typedef info
10816 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10817 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10818 if (Unqualified) {
10819 LHSValue = LHSValue.getUnqualifiedType();
10820 RHSValue = RHSValue.getUnqualifiedType();
10821 }
10822 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10823 Unqualified);
10824 if (ResultType.isNull())
10825 return {};
10826 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10827 return LHS;
10828 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10829 return RHS;
10830 return getAtomicType(ResultType);
10831 }
10832 case Type::ConstantArray:
10833 {
10834 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10835 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10836 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
10837 return {};
10838
10839 QualType LHSElem = getAsArrayType(LHS)->getElementType();
10840 QualType RHSElem = getAsArrayType(RHS)->getElementType();
10841 if (Unqualified) {
10842 LHSElem = LHSElem.getUnqualifiedType();
10843 RHSElem = RHSElem.getUnqualifiedType();
10844 }
10845
10846 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10847 if (ResultType.isNull())
10848 return {};
10849
10850 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10851 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10852
10853 // If either side is a variable array, and both are complete, check whether
10854 // the current dimension is definite.
10855 if (LVAT || RVAT) {
10856 auto SizeFetch = [this](const VariableArrayType* VAT,
10857 const ConstantArrayType* CAT)
10858 -> std::pair<bool,llvm::APInt> {
10859 if (VAT) {
10860 std::optional<llvm::APSInt> TheInt;
10861 Expr *E = VAT->getSizeExpr();
10862 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10863 return std::make_pair(true, *TheInt);
10864 return std::make_pair(false, llvm::APSInt());
10865 }
10866 if (CAT)
10867 return std::make_pair(true, CAT->getSize());
10868 return std::make_pair(false, llvm::APInt());
10869 };
10870
10871 bool HaveLSize, HaveRSize;
10872 llvm::APInt LSize, RSize;
10873 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10874 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10875 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10876 return {}; // Definite, but unequal, array dimension
10877 }
10878
10879 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10880 return LHS;
10881 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10882 return RHS;
10883 if (LCAT)
10884 return getConstantArrayType(ResultType, LCAT->getSize(),
10885 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
10886 if (RCAT)
10887 return getConstantArrayType(ResultType, RCAT->getSize(),
10888 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
10889 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10890 return LHS;
10891 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10892 return RHS;
10893 if (LVAT) {
10894 // FIXME: This isn't correct! But tricky to implement because
10895 // the array's size has to be the size of LHS, but the type
10896 // has to be different.
10897 return LHS;
10898 }
10899 if (RVAT) {
10900 // FIXME: This isn't correct! But tricky to implement because
10901 // the array's size has to be the size of RHS, but the type
10902 // has to be different.
10903 return RHS;
10904 }
10905 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10906 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10907 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
10908 }
10909 case Type::FunctionNoProto:
10910 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
10911 /*AllowCXX=*/false, IsConditionalOperator);
10912 case Type::Record:
10913 case Type::Enum:
10914 return {};
10915 case Type::Builtin:
10916 // Only exactly equal builtin types are compatible, which is tested above.
10917 return {};
10918 case Type::Complex:
10919 // Distinct complex types are incompatible.
10920 return {};
10921 case Type::Vector:
10922 // FIXME: The merged type should be an ExtVector!
10923 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10924 RHSCan->castAs<VectorType>()))
10925 return LHS;
10926 return {};
10927 case Type::ConstantMatrix:
10929 RHSCan->castAs<ConstantMatrixType>()))
10930 return LHS;
10931 return {};
10932 case Type::ObjCObject: {
10933 // Check if the types are assignment compatible.
10934 // FIXME: This should be type compatibility, e.g. whether
10935 // "LHS x; RHS x;" at global scope is legal.
10937 RHS->castAs<ObjCObjectType>()))
10938 return LHS;
10939 return {};
10940 }
10941 case Type::ObjCObjectPointer:
10942 if (OfBlockPointer) {
10945 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10946 return LHS;
10947 return {};
10948 }
10951 return LHS;
10952 return {};
10953 case Type::Pipe:
10954 assert(LHS != RHS &&
10955 "Equivalent pipe types should have already been handled!");
10956 return {};
10957 case Type::ArrayParameter:
10958 assert(LHS != RHS &&
10959 "Equivalent ArrayParameter types should have already been handled!");
10960 return {};
10961 case Type::BitInt: {
10962 // Merge two bit-precise int types, while trying to preserve typedef info.
10963 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10964 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10965 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10966 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10967
10968 // Like unsigned/int, shouldn't have a type if they don't match.
10969 if (LHSUnsigned != RHSUnsigned)
10970 return {};
10971
10972 if (LHSBits != RHSBits)
10973 return {};
10974 return LHS;
10975 }
10976 }
10977
10978 llvm_unreachable("Invalid Type::Class!");
10979}
10980
10982 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10983 bool &CanUseFirst, bool &CanUseSecond,
10985 assert(NewParamInfos.empty() && "param info list not empty");
10986 CanUseFirst = CanUseSecond = true;
10987 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10988 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10989
10990 // Fast path: if the first type doesn't have ext parameter infos,
10991 // we match if and only if the second type also doesn't have them.
10992 if (!FirstHasInfo && !SecondHasInfo)
10993 return true;
10994
10995 bool NeedParamInfo = false;
10996 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10997 : SecondFnType->getExtParameterInfos().size();
10998
10999 for (size_t I = 0; I < E; ++I) {
11000 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11001 if (FirstHasInfo)
11002 FirstParam = FirstFnType->getExtParameterInfo(I);
11003 if (SecondHasInfo)
11004 SecondParam = SecondFnType->getExtParameterInfo(I);
11005
11006 // Cannot merge unless everything except the noescape flag matches.
11007 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11008 return false;
11009
11010 bool FirstNoEscape = FirstParam.isNoEscape();
11011 bool SecondNoEscape = SecondParam.isNoEscape();
11012 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11013 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11014 if (NewParamInfos.back().getOpaqueValue())
11015 NeedParamInfo = true;
11016 if (FirstNoEscape != IsNoEscape)
11017 CanUseFirst = false;
11018 if (SecondNoEscape != IsNoEscape)
11019 CanUseSecond = false;
11020 }
11021
11022 if (!NeedParamInfo)
11023 NewParamInfos.clear();
11024
11025 return true;
11026}
11027
11029 ObjCLayouts[CD] = nullptr;
11030}
11031
11032/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11033/// 'RHS' attributes and returns the merged version; including for function
11034/// return types.
11036 QualType LHSCan = getCanonicalType(LHS),
11037 RHSCan = getCanonicalType(RHS);
11038 // If two types are identical, they are compatible.
11039 if (LHSCan == RHSCan)
11040 return LHS;
11041 if (RHSCan->isFunctionType()) {
11042 if (!LHSCan->isFunctionType())
11043 return {};
11044 QualType OldReturnType =
11045 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11046 QualType NewReturnType =
11047 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11048 QualType ResReturnType =
11049 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11050 if (ResReturnType.isNull())
11051 return {};
11052 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11053 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11054 // In either case, use OldReturnType to build the new function type.
11055 const auto *F = LHS->castAs<FunctionType>();
11056 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11057 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11058 EPI.ExtInfo = getFunctionExtInfo(LHS);
11059 QualType ResultType =
11060 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11061 return ResultType;
11062 }
11063 }
11064 return {};
11065 }
11066
11067 // If the qualifiers are different, the types can still be merged.
11068 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11069 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11070 if (LQuals != RQuals) {
11071 // If any of these qualifiers are different, we have a type mismatch.
11072 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11073 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11074 return {};
11075
11076 // Exactly one GC qualifier difference is allowed: __strong is
11077 // okay if the other type has no GC qualifier but is an Objective
11078 // C object pointer (i.e. implicitly strong by default). We fix
11079 // this by pretending that the unqualified type was actually
11080 // qualified __strong.
11081 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11082 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11083 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11084
11085 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11086 return {};
11087
11088 if (GC_L == Qualifiers::Strong)
11089 return LHS;
11090 if (GC_R == Qualifiers::Strong)
11091 return RHS;
11092 return {};
11093 }
11094
11095 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11096 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11097 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11098 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11099 if (ResQT == LHSBaseQT)
11100 return LHS;
11101 if (ResQT == RHSBaseQT)
11102 return RHS;
11103 }
11104 return {};
11105}
11106
11107//===----------------------------------------------------------------------===//
11108// Integer Predicates
11109//===----------------------------------------------------------------------===//
11110
11112 if (const auto *ET = T->getAs<EnumType>())
11113 T = ET->getDecl()->getIntegerType();
11114 if (T->isBooleanType())
11115 return 1;
11116 if (const auto *EIT = T->getAs<BitIntType>())
11117 return EIT->getNumBits();
11118 // For builtin types, just use the standard type sizing method
11119 return (unsigned)getTypeSize(T);
11120}
11121
11123 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11124 T->isFixedPointType()) &&
11125 "Unexpected type");
11126
11127 // Turn <4 x signed int> -> <4 x unsigned int>
11128 if (const auto *VTy = T->getAs<VectorType>())
11129 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11130 VTy->getNumElements(), VTy->getVectorKind());
11131
11132 // For _BitInt, return an unsigned _BitInt with same width.
11133 if (const auto *EITy = T->getAs<BitIntType>())
11134 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11135
11136 // For enums, get the underlying integer type of the enum, and let the general
11137 // integer type signchanging code handle it.
11138 if (const auto *ETy = T->getAs<EnumType>())
11139 T = ETy->getDecl()->getIntegerType();
11140
11141 switch (T->castAs<BuiltinType>()->getKind()) {
11142 case BuiltinType::Char_U:
11143 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11144 case BuiltinType::Char_S:
11145 case BuiltinType::SChar:
11146 case BuiltinType::Char8:
11147 return UnsignedCharTy;
11148 case BuiltinType::Short:
11149 return UnsignedShortTy;
11150 case BuiltinType::Int:
11151 return UnsignedIntTy;
11152 case BuiltinType::Long:
11153 return UnsignedLongTy;
11154 case BuiltinType::LongLong:
11155 return UnsignedLongLongTy;
11156 case BuiltinType::Int128:
11157 return UnsignedInt128Ty;
11158 // wchar_t is special. It is either signed or not, but when it's signed,
11159 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11160 // version of its underlying type instead.
11161 case BuiltinType::WChar_S:
11162 return getUnsignedWCharType();
11163
11164 case BuiltinType::ShortAccum:
11165 return UnsignedShortAccumTy;
11166 case BuiltinType::Accum:
11167 return UnsignedAccumTy;
11168 case BuiltinType::LongAccum:
11169 return UnsignedLongAccumTy;
11170 case BuiltinType::SatShortAccum:
11172 case BuiltinType::SatAccum:
11173 return SatUnsignedAccumTy;
11174 case BuiltinType::SatLongAccum:
11176 case BuiltinType::ShortFract:
11177 return UnsignedShortFractTy;
11178 case BuiltinType::Fract:
11179 return UnsignedFractTy;
11180 case BuiltinType::LongFract:
11181 return UnsignedLongFractTy;
11182 case BuiltinType::SatShortFract:
11184 case BuiltinType::SatFract:
11185 return SatUnsignedFractTy;
11186 case BuiltinType::SatLongFract:
11188 default:
11191 "Unexpected signed integer or fixed point type");
11192 return T;
11193 }
11194}
11195
11197 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11198 T->isFixedPointType()) &&
11199 "Unexpected type");
11200
11201 // Turn <4 x unsigned int> -> <4 x signed int>
11202 if (const auto *VTy = T->getAs<VectorType>())
11203 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11204 VTy->getNumElements(), VTy->getVectorKind());
11205
11206 // For _BitInt, return a signed _BitInt with same width.
11207 if (const auto *EITy = T->getAs<BitIntType>())
11208 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11209
11210 // For enums, get the underlying integer type of the enum, and let the general
11211 // integer type signchanging code handle it.
11212 if (const auto *ETy = T->getAs<EnumType>())
11213 T = ETy->getDecl()->getIntegerType();
11214
11215 switch (T->castAs<BuiltinType>()->getKind()) {
11216 case BuiltinType::Char_S:
11217 // Plain `char` is mapped to `signed char` even if it's already signed
11218 case BuiltinType::Char_U:
11219 case BuiltinType::UChar:
11220 case BuiltinType::Char8:
11221 return SignedCharTy;
11222 case BuiltinType::UShort:
11223 return ShortTy;
11224 case BuiltinType::UInt:
11225 return IntTy;
11226 case BuiltinType::ULong:
11227 return LongTy;
11228 case BuiltinType::ULongLong:
11229 return LongLongTy;
11230 case BuiltinType::UInt128:
11231 return Int128Ty;
11232 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11233 // there's no matching "signed wchar_t". Therefore we return the signed
11234 // version of its underlying type instead.
11235 case BuiltinType::WChar_U:
11236 return getSignedWCharType();
11237
11238 case BuiltinType::UShortAccum:
11239 return ShortAccumTy;
11240 case BuiltinType::UAccum:
11241 return AccumTy;
11242 case BuiltinType::ULongAccum:
11243 return LongAccumTy;
11244 case BuiltinType::SatUShortAccum:
11245 return SatShortAccumTy;
11246 case BuiltinType::SatUAccum:
11247 return SatAccumTy;
11248 case BuiltinType::SatULongAccum:
11249 return SatLongAccumTy;
11250 case BuiltinType::UShortFract:
11251 return ShortFractTy;
11252 case BuiltinType::UFract:
11253 return FractTy;
11254 case BuiltinType::ULongFract:
11255 return LongFractTy;
11256 case BuiltinType::SatUShortFract:
11257 return SatShortFractTy;
11258 case BuiltinType::SatUFract:
11259 return SatFractTy;
11260 case BuiltinType::SatULongFract:
11261 return SatLongFractTy;
11262 default:
11263 assert(
11265 "Unexpected signed integer or fixed point type");
11266 return T;
11267 }
11268}
11269
11271
11273 QualType ReturnType) {}
11274
11275//===----------------------------------------------------------------------===//
11276// Builtin Type Computation
11277//===----------------------------------------------------------------------===//
11278
11279/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11280/// pointer over the consumed characters. This returns the resultant type. If
11281/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11282/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11283/// a vector of "i*".
11284///
11285/// RequiresICE is filled in on return to indicate whether the value is required
11286/// to be an Integer Constant Expression.
11287static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11289 bool &RequiresICE,
11290 bool AllowTypeModifiers) {
11291 // Modifiers.
11292 int HowLong = 0;
11293 bool Signed = false, Unsigned = false;
11294 RequiresICE = false;
11295
11296 // Read the prefixed modifiers first.
11297 bool Done = false;
11298 #ifndef NDEBUG
11299 bool IsSpecial = false;
11300 #endif
11301 while (!Done) {
11302 switch (*Str++) {
11303 default: Done = true; --Str; break;
11304 case 'I':
11305 RequiresICE = true;
11306 break;
11307 case 'S':
11308 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11309 assert(!Signed && "Can't use 'S' modifier multiple times!");
11310 Signed = true;
11311 break;
11312 case 'U':
11313 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11314 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11315 Unsigned = true;
11316 break;
11317 case 'L':
11318 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11319 assert(HowLong <= 2 && "Can't have LLLL modifier");
11320 ++HowLong;
11321 break;
11322 case 'N':
11323 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11324 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11325 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11326 #ifndef NDEBUG
11327 IsSpecial = true;
11328 #endif
11329 if (Context.getTargetInfo().getLongWidth() == 32)
11330 ++HowLong;
11331 break;
11332 case 'W':
11333 // This modifier represents int64 type.
11334 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11335 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11336 #ifndef NDEBUG
11337 IsSpecial = true;
11338 #endif
11339 switch (Context.getTargetInfo().getInt64Type()) {
11340 default:
11341 llvm_unreachable("Unexpected integer type");
11343 HowLong = 1;
11344 break;
11346 HowLong = 2;
11347 break;
11348 }
11349 break;
11350 case 'Z':
11351 // This modifier represents int32 type.
11352 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11353 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11354 #ifndef NDEBUG
11355 IsSpecial = true;
11356 #endif
11357 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11358 default:
11359 llvm_unreachable("Unexpected integer type");
11361 HowLong = 0;
11362 break;
11364 HowLong = 1;
11365 break;
11367 HowLong = 2;
11368 break;
11369 }
11370 break;
11371 case 'O':
11372 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11373 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11374 #ifndef NDEBUG
11375 IsSpecial = true;
11376 #endif
11377 if (Context.getLangOpts().OpenCL)
11378 HowLong = 1;
11379 else
11380 HowLong = 2;
11381 break;
11382 }
11383 }
11384
11385 QualType Type;
11386
11387 // Read the base type.
11388 switch (*Str++) {
11389 default: llvm_unreachable("Unknown builtin type letter!");
11390 case 'x':
11391 assert(HowLong == 0 && !Signed && !Unsigned &&
11392 "Bad modifiers used with 'x'!");
11393 Type = Context.Float16Ty;
11394 break;
11395 case 'y':
11396 assert(HowLong == 0 && !Signed && !Unsigned &&
11397 "Bad modifiers used with 'y'!");
11398 Type = Context.BFloat16Ty;
11399 break;
11400 case 'v':
11401 assert(HowLong == 0 && !Signed && !Unsigned &&
11402 "Bad modifiers used with 'v'!");
11403 Type = Context.VoidTy;
11404 break;
11405 case 'h':
11406 assert(HowLong == 0 && !Signed && !Unsigned &&
11407 "Bad modifiers used with 'h'!");
11408 Type = Context.HalfTy;
11409 break;
11410 case 'f':
11411 assert(HowLong == 0 && !Signed && !Unsigned &&
11412 "Bad modifiers used with 'f'!");
11413 Type = Context.FloatTy;
11414 break;
11415 case 'd':
11416 assert(HowLong < 3 && !Signed && !Unsigned &&
11417 "Bad modifiers used with 'd'!");
11418 if (HowLong == 1)
11419 Type = Context.LongDoubleTy;
11420 else if (HowLong == 2)
11421 Type = Context.Float128Ty;
11422 else
11423 Type = Context.DoubleTy;
11424 break;
11425 case 's':
11426 assert(HowLong == 0 && "Bad modifiers used with 's'!");
11427 if (Unsigned)
11428 Type = Context.UnsignedShortTy;
11429 else
11430 Type = Context.ShortTy;
11431 break;
11432 case 'i':
11433 if (HowLong == 3)
11434 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11435 else if (HowLong == 2)
11436 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11437 else if (HowLong == 1)
11438 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11439 else
11440 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11441 break;
11442 case 'c':
11443 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11444 if (Signed)
11445 Type = Context.SignedCharTy;
11446 else if (Unsigned)
11447 Type = Context.UnsignedCharTy;
11448 else
11449 Type = Context.CharTy;
11450 break;
11451 case 'b': // boolean
11452 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11453 Type = Context.BoolTy;
11454 break;
11455 case 'z': // size_t.
11456 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11457 Type = Context.getSizeType();
11458 break;
11459 case 'w': // wchar_t.
11460 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11461 Type = Context.getWideCharType();
11462 break;
11463 case 'F':
11464 Type = Context.getCFConstantStringType();
11465 break;
11466 case 'G':
11467 Type = Context.getObjCIdType();
11468 break;
11469 case 'H':
11470 Type = Context.getObjCSelType();
11471 break;
11472 case 'M':
11473 Type = Context.getObjCSuperType();
11474 break;
11475 case 'a':
11476 Type = Context.getBuiltinVaListType();
11477 assert(!Type.isNull() && "builtin va list type not initialized!");
11478 break;
11479 case 'A':
11480 // This is a "reference" to a va_list; however, what exactly
11481 // this means depends on how va_list is defined. There are two
11482 // different kinds of va_list: ones passed by value, and ones
11483 // passed by reference. An example of a by-value va_list is
11484 // x86, where va_list is a char*. An example of by-ref va_list
11485 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11486 // we want this argument to be a char*&; for x86-64, we want
11487 // it to be a __va_list_tag*.
11488 Type = Context.getBuiltinVaListType();
11489 assert(!Type.isNull() && "builtin va list type not initialized!");
11490 if (Type->isArrayType())
11491 Type = Context.getArrayDecayedType(Type);
11492 else
11493 Type = Context.getLValueReferenceType(Type);
11494 break;
11495 case 'q': {
11496 char *End;
11497 unsigned NumElements = strtoul(Str, &End, 10);
11498 assert(End != Str && "Missing vector size");
11499 Str = End;
11500
11501 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11502 RequiresICE, false);
11503 assert(!RequiresICE && "Can't require vector ICE");
11504
11505 Type = Context.getScalableVectorType(ElementType, NumElements);
11506 break;
11507 }
11508 case 'Q': {
11509 switch (*Str++) {
11510 case 'a': {
11511 Type = Context.SveCountTy;
11512 break;
11513 }
11514 default:
11515 llvm_unreachable("Unexpected target builtin type");
11516 }
11517 break;
11518 }
11519 case 'V': {
11520 char *End;
11521 unsigned NumElements = strtoul(Str, &End, 10);
11522 assert(End != Str && "Missing vector size");
11523 Str = End;
11524
11525 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11526 RequiresICE, false);
11527 assert(!RequiresICE && "Can't require vector ICE");
11528
11529 // TODO: No way to make AltiVec vectors in builtins yet.
11530 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11531 break;
11532 }
11533 case 'E': {
11534 char *End;
11535
11536 unsigned NumElements = strtoul(Str, &End, 10);
11537 assert(End != Str && "Missing vector size");
11538
11539 Str = End;
11540
11541 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11542 false);
11543 Type = Context.getExtVectorType(ElementType, NumElements);
11544 break;
11545 }
11546 case 'X': {
11547 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11548 false);
11549 assert(!RequiresICE && "Can't require complex ICE");
11550 Type = Context.getComplexType(ElementType);
11551 break;
11552 }
11553 case 'Y':
11554 Type = Context.getPointerDiffType();
11555 break;
11556 case 'P':
11557 Type = Context.getFILEType();
11558 if (Type.isNull()) {
11560 return {};
11561 }
11562 break;
11563 case 'J':
11564 if (Signed)
11565 Type = Context.getsigjmp_bufType();
11566 else
11567 Type = Context.getjmp_bufType();
11568
11569 if (Type.isNull()) {
11571 return {};
11572 }
11573 break;
11574 case 'K':
11575 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11576 Type = Context.getucontext_tType();
11577
11578 if (Type.isNull()) {
11580 return {};
11581 }
11582 break;
11583 case 'p':
11584 Type = Context.getProcessIDType();
11585 break;
11586 }
11587
11588 // If there are modifiers and if we're allowed to parse them, go for it.
11589 Done = !AllowTypeModifiers;
11590 while (!Done) {
11591 switch (char c = *Str++) {
11592 default: Done = true; --Str; break;
11593 case '*':
11594 case '&': {
11595 // Both pointers and references can have their pointee types
11596 // qualified with an address space.
11597 char *End;
11598 unsigned AddrSpace = strtoul(Str, &End, 10);
11599 if (End != Str) {
11600 // Note AddrSpace == 0 is not the same as an unspecified address space.
11601 Type = Context.getAddrSpaceQualType(
11602 Type,
11603 Context.getLangASForBuiltinAddressSpace(AddrSpace));
11604 Str = End;
11605 }
11606 if (c == '*')
11607 Type = Context.getPointerType(Type);
11608 else
11609 Type = Context.getLValueReferenceType(Type);
11610 break;
11611 }
11612 // FIXME: There's no way to have a built-in with an rvalue ref arg.
11613 case 'C':
11614 Type = Type.withConst();
11615 break;
11616 case 'D':
11617 Type = Context.getVolatileType(Type);
11618 break;
11619 case 'R':
11620 Type = Type.withRestrict();
11621 break;
11622 }
11623 }
11624
11625 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11626 "Integer constant 'I' type must be an integer");
11627
11628 return Type;
11629}
11630
11631// On some targets such as PowerPC, some of the builtins are defined with custom
11632// type descriptors for target-dependent types. These descriptors are decoded in
11633// other functions, but it may be useful to be able to fall back to default
11634// descriptor decoding to define builtins mixing target-dependent and target-
11635// independent types. This function allows decoding one type descriptor with
11636// default decoding.
11637QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11638 GetBuiltinTypeError &Error, bool &RequireICE,
11639 bool AllowTypeModifiers) const {
11640 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11641}
11642
11643/// GetBuiltinType - Return the type for the specified builtin.
11645 GetBuiltinTypeError &Error,
11646 unsigned *IntegerConstantArgs) const {
11647 const char *TypeStr = BuiltinInfo.getTypeString(Id);
11648 if (TypeStr[0] == '\0') {
11649 Error = GE_Missing_type;
11650 return {};
11651 }
11652
11653 SmallVector<QualType, 8> ArgTypes;
11654
11655 bool RequiresICE = false;
11656 Error = GE_None;
11657 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11658 RequiresICE, true);
11659 if (Error != GE_None)
11660 return {};
11661
11662 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11663
11664 while (TypeStr[0] && TypeStr[0] != '.') {
11665 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11666 if (Error != GE_None)
11667 return {};
11668
11669 // If this argument is required to be an IntegerConstantExpression and the
11670 // caller cares, fill in the bitmask we return.
11671 if (RequiresICE && IntegerConstantArgs)
11672 *IntegerConstantArgs |= 1 << ArgTypes.size();
11673
11674 // Do array -> pointer decay. The builtin should use the decayed type.
11675 if (Ty->isArrayType())
11676 Ty = getArrayDecayedType(Ty);
11677
11678 ArgTypes.push_back(Ty);
11679 }
11680
11681 if (Id == Builtin::BI__GetExceptionInfo)
11682 return {};
11683
11684 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11685 "'.' should only occur at end of builtin type list!");
11686
11687 bool Variadic = (TypeStr[0] == '.');
11688
11690 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11691 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11692
11693
11694 // We really shouldn't be making a no-proto type here.
11695 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
11696 return getFunctionNoProtoType(ResType, EI);
11697
11699 EPI.ExtInfo = EI;
11700 EPI.Variadic = Variadic;
11702 EPI.ExceptionSpec.Type =
11704
11705 return getFunctionType(ResType, ArgTypes, EPI);
11706}
11707
11709 const FunctionDecl *FD) {
11710 if (!FD->isExternallyVisible())
11711 return GVA_Internal;
11712
11713 // Non-user-provided functions get emitted as weak definitions with every
11714 // use, no matter whether they've been explicitly instantiated etc.
11715 if (!FD->isUserProvided())
11716 return GVA_DiscardableODR;
11717
11719 switch (FD->getTemplateSpecializationKind()) {
11720 case TSK_Undeclared:
11723 break;
11724
11726 return GVA_StrongODR;
11727
11728 // C++11 [temp.explicit]p10:
11729 // [ Note: The intent is that an inline function that is the subject of
11730 // an explicit instantiation declaration will still be implicitly
11731 // instantiated when used so that the body can be considered for
11732 // inlining, but that no out-of-line copy of the inline function would be
11733 // generated in the translation unit. -- end note ]
11736
11739 break;
11740 }
11741
11742 if (!FD->isInlined())
11743 return External;
11744
11745 if ((!Context.getLangOpts().CPlusPlus &&
11746 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11747 !FD->hasAttr<DLLExportAttr>()) ||
11748 FD->hasAttr<GNUInlineAttr>()) {
11749 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11750
11751 // GNU or C99 inline semantics. Determine whether this symbol should be
11752 // externally visible.
11754 return External;
11755
11756 // C99 inline semantics, where the symbol is not externally visible.
11758 }
11759
11760 // Functions specified with extern and inline in -fms-compatibility mode
11761 // forcibly get emitted. While the body of the function cannot be later
11762 // replaced, the function definition cannot be discarded.
11763 if (FD->isMSExternInline())
11764 return GVA_StrongODR;
11765
11766 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11767 isa<CXXConstructorDecl>(FD) &&
11768 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
11769 // Our approach to inheriting constructors is fundamentally different from
11770 // that used by the MS ABI, so keep our inheriting constructor thunks
11771 // internal rather than trying to pick an unambiguous mangling for them.
11772 return GVA_Internal;
11773
11774 return GVA_DiscardableODR;
11775}
11776
11778 const Decl *D, GVALinkage L) {
11779 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11780 // dllexport/dllimport on inline functions.
11781 if (D->hasAttr<DLLImportAttr>()) {
11782 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11784 } else if (D->hasAttr<DLLExportAttr>()) {
11785 if (L == GVA_DiscardableODR)
11786 return GVA_StrongODR;
11787 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11788 // Device-side functions with __global__ attribute must always be
11789 // visible externally so they can be launched from host.
11790 if (D->hasAttr<CUDAGlobalAttr>() &&
11791 (L == GVA_DiscardableODR || L == GVA_Internal))
11792 return GVA_StrongODR;
11793 // Single source offloading languages like CUDA/HIP need to be able to
11794 // access static device variables from host code of the same compilation
11795 // unit. This is done by externalizing the static variable with a shared
11796 // name between the host and device compilation which is the same for the
11797 // same compilation unit whereas different among different compilation
11798 // units.
11799 if (Context.shouldExternalize(D))
11800 return GVA_StrongExternal;
11801 }
11802 return L;
11803}
11804
11805/// Adjust the GVALinkage for a declaration based on what an external AST source
11806/// knows about whether there can be other definitions of this declaration.
11807static GVALinkage
11809 GVALinkage L) {
11810 ExternalASTSource *Source = Ctx.getExternalSource();
11811 if (!Source)
11812 return L;
11813
11814 switch (Source->hasExternalDefinitions(D)) {
11816 // Other translation units rely on us to provide the definition.
11817 if (L == GVA_DiscardableODR)
11818 return GVA_StrongODR;
11819 break;
11820
11823
11825 break;
11826 }
11827 return L;
11828}
11829
11833 basicGVALinkageForFunction(*this, FD)));
11834}
11835
11837 const VarDecl *VD) {
11838 // As an extension for interactive REPLs, make sure constant variables are
11839 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
11840 // marking them as internal.
11841 if (Context.getLangOpts().CPlusPlus &&
11842 Context.getLangOpts().IncrementalExtensions &&
11843 VD->getType().isConstQualified() &&
11844 !VD->getType().isVolatileQualified() && !VD->isInline() &&
11845 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
11846 return GVA_DiscardableODR;
11847
11848 if (!VD->isExternallyVisible())
11849 return GVA_Internal;
11850
11851 if (VD->isStaticLocal()) {
11852 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11853 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11854 LexicalContext = LexicalContext->getLexicalParent();
11855
11856 // ObjC Blocks can create local variables that don't have a FunctionDecl
11857 // LexicalContext.
11858 if (!LexicalContext)
11859 return GVA_DiscardableODR;
11860
11861 // Otherwise, let the static local variable inherit its linkage from the
11862 // nearest enclosing function.
11863 auto StaticLocalLinkage =
11864 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11865
11866 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11867 // be emitted in any object with references to the symbol for the object it
11868 // contains, whether inline or out-of-line."
11869 // Similar behavior is observed with MSVC. An alternative ABI could use
11870 // StrongODR/AvailableExternally to match the function, but none are
11871 // known/supported currently.
11872 if (StaticLocalLinkage == GVA_StrongODR ||
11873 StaticLocalLinkage == GVA_AvailableExternally)
11874 return GVA_DiscardableODR;
11875 return StaticLocalLinkage;
11876 }
11877
11878 // MSVC treats in-class initialized static data members as definitions.
11879 // By giving them non-strong linkage, out-of-line definitions won't
11880 // cause link errors.
11882 return GVA_DiscardableODR;
11883
11884 // Most non-template variables have strong linkage; inline variables are
11885 // linkonce_odr or (occasionally, for compatibility) weak_odr.
11886 GVALinkage StrongLinkage;
11887 switch (Context.getInlineVariableDefinitionKind(VD)) {
11889 StrongLinkage = GVA_StrongExternal;
11890 break;
11893 StrongLinkage = GVA_DiscardableODR;
11894 break;
11896 StrongLinkage = GVA_StrongODR;
11897 break;
11898 }
11899
11900 switch (VD->getTemplateSpecializationKind()) {
11901 case TSK_Undeclared:
11902 return StrongLinkage;
11903
11905 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11906 VD->isStaticDataMember()
11908 : StrongLinkage;
11909
11911 return GVA_StrongODR;
11912
11915
11917 return GVA_DiscardableODR;
11918 }
11919
11920 llvm_unreachable("Invalid Linkage!");
11921}
11922
11926 basicGVALinkageForVariable(*this, VD)));
11927}
11928
11930 if (const auto *VD = dyn_cast<VarDecl>(D)) {
11931 if (!VD->isFileVarDecl())
11932 return false;
11933 // Global named register variables (GNU extension) are never emitted.
11934 if (VD->getStorageClass() == SC_Register)
11935 return false;
11936 if (VD->getDescribedVarTemplate() ||
11937 isa<VarTemplatePartialSpecializationDecl>(VD))
11938 return false;
11939 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11940 // We never need to emit an uninstantiated function template.
11941 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11942 return false;
11943 } else if (isa<PragmaCommentDecl>(D))
11944 return true;
11945 else if (isa<PragmaDetectMismatchDecl>(D))
11946 return true;
11947 else if (isa<OMPRequiresDecl>(D))
11948 return true;
11949 else if (isa<OMPThreadPrivateDecl>(D))
11950 return !D->getDeclContext()->isDependentContext();
11951 else if (isa<OMPAllocateDecl>(D))
11952 return !D->getDeclContext()->isDependentContext();
11953 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11954 return !D->getDeclContext()->isDependentContext();
11955 else if (isa<ImportDecl>(D))
11956 return true;
11957 else
11958 return false;
11959
11960 // If this is a member of a class template, we do not need to emit it.
11962 return false;
11963
11964 // Weak references don't produce any output by themselves.
11965 if (D->hasAttr<WeakRefAttr>())
11966 return false;
11967
11968 // Aliases and used decls are required.
11969 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11970 return true;
11971
11972 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11973 // Forward declarations aren't required.
11974 if (!FD->doesThisDeclarationHaveABody())
11975 return FD->doesDeclarationForceExternallyVisibleDefinition();
11976
11977 // Constructors and destructors are required.
11978 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11979 return true;
11980
11981 // The key function for a class is required. This rule only comes
11982 // into play when inline functions can be key functions, though.
11983 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11984 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11985 const CXXRecordDecl *RD = MD->getParent();
11986 if (MD->isOutOfLine() && RD->isDynamicClass()) {
11987 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11988 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11989 return true;
11990 }
11991 }
11992 }
11993
11995
11996 // static, static inline, always_inline, and extern inline functions can
11997 // always be deferred. Normal inline functions can be deferred in C99/C++.
11998 // Implicit template instantiations can also be deferred in C++.
12000 }
12001
12002 const auto *VD = cast<VarDecl>(D);
12003 assert(VD->isFileVarDecl() && "Expected file scoped var");
12004
12005 // If the decl is marked as `declare target to`, it should be emitted for the
12006 // host and for the device.
12007 if (LangOpts.OpenMP &&
12008 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12009 return true;
12010
12011 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12013 return false;
12014
12015 // Variables in other module units shouldn't be forced to be emitted.
12016 if (VD->isInAnotherModuleUnit())
12017 return false;
12018
12019 // Variables that can be needed in other TUs are required.
12022 return true;
12023
12024 // We never need to emit a variable that is available in another TU.
12026 return false;
12027
12028 // Variables that have destruction with side-effects are required.
12029 if (VD->needsDestruction(*this))
12030 return true;
12031
12032 // Variables that have initialization with side-effects are required.
12033 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12034 // We can get a value-dependent initializer during error recovery.
12035 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12036 return true;
12037
12038 // Likewise, variables with tuple-like bindings are required if their
12039 // bindings have side-effects.
12040 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12041 for (const auto *BD : DD->bindings())
12042 if (const auto *BindingVD = BD->getHoldingVar())
12043 if (DeclMustBeEmitted(BindingVD))
12044 return true;
12045
12046 return false;
12047}
12048
12050 const FunctionDecl *FD,
12051 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12052 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12053 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12054 FD = FD->getMostRecentDecl();
12055 // FIXME: The order of traversal here matters and depends on the order of
12056 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12057 // shouldn't rely on that.
12058 for (auto *CurDecl :
12060 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12061 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12062 !SeenDecls.contains(CurFD)) {
12063 SeenDecls.insert(CurFD);
12064 Pred(CurFD);
12065 }
12066 }
12067}
12068
12070 bool IsCXXMethod,
12071 bool IsBuiltin) const {
12072 // Pass through to the C++ ABI object
12073 if (IsCXXMethod)
12074 return ABI->getDefaultMethodCallConv(IsVariadic);
12075
12076 // Builtins ignore user-specified default calling convention and remain the
12077 // Target's default calling convention.
12078 if (!IsBuiltin) {
12079 switch (LangOpts.getDefaultCallingConv()) {
12081 break;
12083 return CC_C;
12085 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12086 return CC_X86FastCall;
12087 break;
12089 if (!IsVariadic)
12090 return CC_X86StdCall;
12091 break;
12093 // __vectorcall cannot be applied to variadic functions.
12094 if (!IsVariadic)
12095 return CC_X86VectorCall;
12096 break;
12098 // __regcall cannot be applied to variadic functions.
12099 if (!IsVariadic)
12100 return CC_X86RegCall;
12101 break;
12103 if (!IsVariadic)
12104 return CC_M68kRTD;
12105 break;
12106 }
12107 }
12108 return Target->getDefaultCallingConv();
12109}
12110
12112 // Pass through to the C++ ABI object
12113 return ABI->isNearlyEmpty(RD);
12114}
12115
12117 if (!VTContext.get()) {
12118 auto ABI = Target->getCXXABI();
12119 if (ABI.isMicrosoft())
12120 VTContext.reset(new MicrosoftVTableContext(*this));
12121 else {
12122 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12125 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12126 }
12127 }
12128 return VTContext.get();
12129}
12130
12132 if (!T)
12133 T = Target;
12134 switch (T->getCXXABI().getKind()) {
12135 case TargetCXXABI::AppleARM64:
12136 case TargetCXXABI::Fuchsia:
12137 case TargetCXXABI::GenericAArch64:
12138 case TargetCXXABI::GenericItanium:
12139 case TargetCXXABI::GenericARM:
12140 case TargetCXXABI::GenericMIPS:
12141 case TargetCXXABI::iOS:
12142 case TargetCXXABI::WebAssembly:
12143 case TargetCXXABI::WatchOS:
12144 case TargetCXXABI::XL:
12146 case TargetCXXABI::Microsoft:
12148 }
12149 llvm_unreachable("Unsupported ABI");
12150}
12151
12153 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12154 "Device mangle context does not support Microsoft mangling.");
12155 switch (T.getCXXABI().getKind()) {
12156 case TargetCXXABI::AppleARM64:
12157 case TargetCXXABI::Fuchsia:
12158 case TargetCXXABI::GenericAArch64:
12159 case TargetCXXABI::GenericItanium:
12160 case TargetCXXABI::GenericARM:
12161 case TargetCXXABI::GenericMIPS:
12162 case TargetCXXABI::iOS:
12163 case TargetCXXABI::WebAssembly:
12164 case TargetCXXABI::WatchOS:
12165 case TargetCXXABI::XL:
12167 *this, getDiagnostics(),
12168 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12169 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12170 return RD->getDeviceLambdaManglingNumber();
12171 return std::nullopt;
12172 },
12173 /*IsAux=*/true);
12174 case TargetCXXABI::Microsoft:
12176 /*IsAux=*/true);
12177 }
12178 llvm_unreachable("Unsupported ABI");
12179}
12180
12181CXXABI::~CXXABI() = default;
12182
12184 return ASTRecordLayouts.getMemorySize() +
12185 llvm::capacity_in_bytes(ObjCLayouts) +
12186 llvm::capacity_in_bytes(KeyFunctions) +
12187 llvm::capacity_in_bytes(ObjCImpls) +
12188 llvm::capacity_in_bytes(BlockVarCopyInits) +
12189 llvm::capacity_in_bytes(DeclAttrs) +
12190 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12191 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12192 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12193 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12194 llvm::capacity_in_bytes(OverriddenMethods) +
12195 llvm::capacity_in_bytes(Types) +
12196 llvm::capacity_in_bytes(VariableArrayTypes);
12197}
12198
12199/// getIntTypeForBitwidth -
12200/// sets integer QualTy according to specified details:
12201/// bitwidth, signed/unsigned.
12202/// Returns empty type if there is no appropriate target types.
12204 unsigned Signed) const {
12206 CanQualType QualTy = getFromTargetType(Ty);
12207 if (!QualTy && DestWidth == 128)
12208 return Signed ? Int128Ty : UnsignedInt128Ty;
12209 return QualTy;
12210}
12211
12212/// getRealTypeForBitwidth -
12213/// sets floating point QualTy according to specified bitwidth.
12214/// Returns empty type if there is no appropriate target types.
12216 FloatModeKind ExplicitType) const {
12217 FloatModeKind Ty =
12218 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12219 switch (Ty) {
12221 return HalfTy;
12223 return FloatTy;
12225 return DoubleTy;
12227 return LongDoubleTy;
12229 return Float128Ty;
12231 return Ibm128Ty;
12233 return {};
12234 }
12235
12236 llvm_unreachable("Unhandled TargetInfo::RealType value");
12237}
12238
12239void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12240 if (Number <= 1)
12241 return;
12242
12243 MangleNumbers[ND] = Number;
12244
12245 if (Listener)
12246 Listener->AddedManglingNumber(ND, Number);
12247}
12248
12250 bool ForAuxTarget) const {
12251 auto I = MangleNumbers.find(ND);
12252 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12253 // CUDA/HIP host compilation encodes host and device mangling numbers
12254 // as lower and upper half of 32 bit integer.
12255 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12256 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12257 } else {
12258 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12259 "number for aux target");
12260 }
12261 return Res > 1 ? Res : 1;
12262}
12263
12264void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12265 if (Number <= 1)
12266 return;
12267
12268 StaticLocalNumbers[VD] = Number;
12269
12270 if (Listener)
12271 Listener->AddedStaticLocalNumbers(VD, Number);
12272}
12273
12275 auto I = StaticLocalNumbers.find(VD);
12276 return I != StaticLocalNumbers.end() ? I->second : 1;
12277}
12278
12281 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12282 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12283 if (!MCtx)
12285 return *MCtx;
12286}
12287
12290 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12291 std::unique_ptr<MangleNumberingContext> &MCtx =
12292 ExtraMangleNumberingContexts[D];
12293 if (!MCtx)
12295 return *MCtx;
12296}
12297
12298std::unique_ptr<MangleNumberingContext>
12300 return ABI->createMangleNumberingContext();
12301}
12302
12303const CXXConstructorDecl *
12305 return ABI->getCopyConstructorForExceptionObject(
12306 cast<CXXRecordDecl>(RD->getFirstDecl()));
12307}
12308
12310 CXXConstructorDecl *CD) {
12311 return ABI->addCopyConstructorForExceptionObject(
12312 cast<CXXRecordDecl>(RD->getFirstDecl()),
12313 cast<CXXConstructorDecl>(CD->getFirstDecl()));
12314}
12315
12317 TypedefNameDecl *DD) {
12318 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12319}
12320
12323 return ABI->getTypedefNameForUnnamedTagDecl(TD);
12324}
12325
12327 DeclaratorDecl *DD) {
12328 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12329}
12330
12332 return ABI->getDeclaratorForUnnamedTagDecl(TD);
12333}
12334
12335void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12336 ParamIndices[D] = index;
12337}
12338
12340 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12341 assert(I != ParamIndices.end() &&
12342 "ParmIndices lacks entry set by ParmVarDecl");
12343 return I->second;
12344}
12345
12347 unsigned Length) const {
12348 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12349 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12350 EltTy = EltTy.withConst();
12351
12352 EltTy = adjustStringLiteralBaseType(EltTy);
12353
12354 // Get an array type for the string, according to C99 6.4.5. This includes
12355 // the null terminator character.
12356 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12357 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12358}
12359
12362 StringLiteral *&Result = StringLiteralCache[Key];
12363 if (!Result)
12365 *this, Key, StringLiteralKind::Ordinary,
12366 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12367 SourceLocation());
12368 return Result;
12369}
12370
12371MSGuidDecl *
12373 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12374
12375 llvm::FoldingSetNodeID ID;
12376 MSGuidDecl::Profile(ID, Parts);
12377
12378 void *InsertPos;
12379 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12380 return Existing;
12381
12382 QualType GUIDType = getMSGuidType().withConst();
12383 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12384 MSGuidDecls.InsertNode(New, InsertPos);
12385 return New;
12386}
12387
12390 const APValue &APVal) const {
12391 llvm::FoldingSetNodeID ID;
12393
12394 void *InsertPos;
12395 if (UnnamedGlobalConstantDecl *Existing =
12396 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12397 return Existing;
12398
12400 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12401 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12402 return New;
12403}
12404
12407 assert(T->isRecordType() && "template param object of unexpected type");
12408
12409 // C++ [temp.param]p8:
12410 // [...] a static storage duration object of type 'const T' [...]
12411 T.addConst();
12412
12413 llvm::FoldingSetNodeID ID;
12415
12416 void *InsertPos;
12417 if (TemplateParamObjectDecl *Existing =
12418 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12419 return Existing;
12420
12421 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12422 TemplateParamObjectDecls.InsertNode(New, InsertPos);
12423 return New;
12424}
12425
12427 const llvm::Triple &T = getTargetInfo().getTriple();
12428 if (!T.isOSDarwin())
12429 return false;
12430
12431 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12432 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12433 return false;
12434
12435 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12436 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12437 uint64_t Size = sizeChars.getQuantity();
12438 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12439 unsigned Align = alignChars.getQuantity();
12440 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12441 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12442}
12443
12444bool
12446 const ObjCMethodDecl *MethodImpl) {
12447 // No point trying to match an unavailable/deprecated mothod.
12448 if (MethodDecl->hasAttr<UnavailableAttr>()
12449 || MethodDecl->hasAttr<DeprecatedAttr>())
12450 return false;
12451 if (MethodDecl->getObjCDeclQualifier() !=
12452 MethodImpl->getObjCDeclQualifier())
12453 return false;
12454 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12455 return false;
12456
12457 if (MethodDecl->param_size() != MethodImpl->param_size())
12458 return false;
12459
12460 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12461 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12462 EF = MethodDecl->param_end();
12463 IM != EM && IF != EF; ++IM, ++IF) {
12464 const ParmVarDecl *DeclVar = (*IF);
12465 const ParmVarDecl *ImplVar = (*IM);
12466 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12467 return false;
12468 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12469 return false;
12470 }
12471
12472 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12473}
12474
12476 LangAS AS;
12478 AS = LangAS::Default;
12479 else
12480 AS = QT->getPointeeType().getAddressSpace();
12481
12483}
12484
12487}
12488
12489bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12490 if (X == Y)
12491 return true;
12492 if (!X || !Y)
12493 return false;
12494 llvm::FoldingSetNodeID IDX, IDY;
12495 X->Profile(IDX, *this, /*Canonical=*/true);
12496 Y->Profile(IDY, *this, /*Canonical=*/true);
12497 return IDX == IDY;
12498}
12499
12500// The getCommon* helpers return, for given 'same' X and Y entities given as
12501// inputs, another entity which is also the 'same' as the inputs, but which
12502// is closer to the canonical form of the inputs, each according to a given
12503// criteria.
12504// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12505// the regular ones.
12506
12508 if (!declaresSameEntity(X, Y))
12509 return nullptr;
12510 for (const Decl *DX : X->redecls()) {
12511 // If we reach Y before reaching the first decl, that means X is older.
12512 if (DX == Y)
12513 return X;
12514 // If we reach the first decl, then Y is older.
12515 if (DX->isFirstDecl())
12516 return Y;
12517 }
12518 llvm_unreachable("Corrupt redecls chain");
12519}
12520
12521template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12522static T *getCommonDecl(T *X, T *Y) {
12523 return cast_or_null<T>(
12524 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12525 const_cast<Decl *>(cast_or_null<Decl>(Y))));
12526}
12527
12528template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12529static T *getCommonDeclChecked(T *X, T *Y) {
12530 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12531 const_cast<Decl *>(cast<Decl>(Y))));
12532}
12533
12535 TemplateName Y) {
12536 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12537 return X;
12538 // FIXME: There are cases here where we could find a common template name
12539 // with more sugar. For example one could be a SubstTemplateTemplate*
12540 // replacing the other.
12542 if (CX.getAsVoidPointer() !=
12544 return TemplateName();
12545 return CX;
12546}
12547
12548static TemplateName
12551 assert(R.getAsVoidPointer() != nullptr);
12552 return R;
12553}
12554
12556 ArrayRef<QualType> Ys, bool Unqualified = false) {
12557 assert(Xs.size() == Ys.size());
12558 SmallVector<QualType, 8> Rs(Xs.size());
12559 for (size_t I = 0; I < Rs.size(); ++I)
12560 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
12561 return Rs;
12562}
12563
12564template <class T>
12565static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
12566 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
12567 : SourceLocation();
12568}
12569
12571 const TemplateArgument &X,
12572 const TemplateArgument &Y) {
12573 if (X.getKind() != Y.getKind())
12574 return TemplateArgument();
12575
12576 switch (X.getKind()) {
12578 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
12579 return TemplateArgument();
12580 return TemplateArgument(
12581 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
12583 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
12584 return TemplateArgument();
12585 return TemplateArgument(
12586 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
12587 /*Unqualified=*/true);
12589 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
12590 return TemplateArgument();
12591 // FIXME: Try to keep the common sugar.
12592 return X;
12594 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
12595 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12596 if (!CTN.getAsVoidPointer())
12597 return TemplateArgument();
12598 return TemplateArgument(CTN);
12599 }
12601 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
12603 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12604 if (!CTN.getAsVoidPointer())
12605 return TemplateName();
12606 auto NExpX = X.getNumTemplateExpansions();
12607 assert(NExpX == Y.getNumTemplateExpansions());
12608 return TemplateArgument(CTN, NExpX);
12609 }
12610 default:
12611 // FIXME: Handle the other argument kinds.
12612 return X;
12613 }
12614}
12615
12620 if (Xs.size() != Ys.size())
12621 return true;
12622 R.resize(Xs.size());
12623 for (size_t I = 0; I < R.size(); ++I) {
12624 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
12625 if (R[I].isNull())
12626 return true;
12627 }
12628 return false;
12629}
12630
12635 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
12636 assert(!Different);
12637 (void)Different;
12638 return R;
12639}
12640
12641template <class T>
12643 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
12645}
12646
12647template <class T>
12649 const T *Y) {
12650 // FIXME: Try to keep the common NNS sugar.
12651 return X->getQualifier() == Y->getQualifier()
12652 ? X->getQualifier()
12653 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
12654}
12655
12656template <class T>
12657static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
12658 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
12659}
12660
12661template <class T>
12663 Qualifiers &QX, const T *Y,
12664 Qualifiers &QY) {
12665 QualType EX = X->getElementType(), EY = Y->getElementType();
12666 QualType R = Ctx.getCommonSugaredType(EX, EY,
12667 /*Unqualified=*/true);
12668 Qualifiers RQ = R.getQualifiers();
12669 QX += EX.getQualifiers() - RQ;
12670 QY += EY.getQualifiers() - RQ;
12671 return R;
12672}
12673
12674template <class T>
12675static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
12676 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
12677}
12678
12679template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
12680 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
12681 return X->getSizeExpr();
12682}
12683
12684static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
12685 assert(X->getSizeModifier() == Y->getSizeModifier());
12686 return X->getSizeModifier();
12687}
12688
12690 const ArrayType *Y) {
12691 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
12692 return X->getIndexTypeCVRQualifiers();
12693}
12694
12695// Merges two type lists such that the resulting vector will contain
12696// each type (in a canonical sense) only once, in the order they appear
12697// from X to Y. If they occur in both X and Y, the result will contain
12698// the common sugared type between them.
12701 llvm::DenseMap<QualType, unsigned> Found;
12702 for (auto Ts : {X, Y}) {
12703 for (QualType T : Ts) {
12704 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
12705 if (!Res.second) {
12706 QualType &U = Out[Res.first->second];
12707 U = Ctx.getCommonSugaredType(U, T);
12708 } else {
12709 Out.emplace_back(T);
12710 }
12711 }
12712 }
12713}
12714
12718 SmallVectorImpl<QualType> &ExceptionTypeStorage,
12719 bool AcceptDependent) {
12720 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
12721
12722 // If either of them can throw anything, that is the result.
12723 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
12724 if (EST1 == I)
12725 return ESI1;
12726 if (EST2 == I)
12727 return ESI2;
12728 }
12729
12730 // If either of them is non-throwing, the result is the other.
12731 for (auto I :
12733 if (EST1 == I)
12734 return ESI2;
12735 if (EST2 == I)
12736 return ESI1;
12737 }
12738
12739 // If we're left with value-dependent computed noexcept expressions, we're
12740 // stuck. Before C++17, we can just drop the exception specification entirely,
12741 // since it's not actually part of the canonical type. And this should never
12742 // happen in C++17, because it would mean we were computing the composite
12743 // pointer type of dependent types, which should never happen.
12744 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
12745 assert(AcceptDependent &&
12746 "computing composite pointer type of dependent types");
12748 }
12749
12750 // Switch over the possibilities so that people adding new values know to
12751 // update this function.
12752 switch (EST1) {
12753 case EST_None:
12754 case EST_DynamicNone:
12755 case EST_MSAny:
12756 case EST_BasicNoexcept:
12758 case EST_NoexceptFalse:
12759 case EST_NoexceptTrue:
12760 case EST_NoThrow:
12761 llvm_unreachable("These ESTs should be handled above");
12762
12763 case EST_Dynamic: {
12764 // This is the fun case: both exception specifications are dynamic. Form
12765 // the union of the two lists.
12766 assert(EST2 == EST_Dynamic && "other cases should already be handled");
12767 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
12768 ESI2.Exceptions);
12770 Result.Exceptions = ExceptionTypeStorage;
12771 return Result;
12772 }
12773
12774 case EST_Unevaluated:
12775 case EST_Uninstantiated:
12776 case EST_Unparsed:
12777 llvm_unreachable("shouldn't see unresolved exception specifications here");
12778 }
12779
12780 llvm_unreachable("invalid ExceptionSpecificationType");
12781}
12782
12784 Qualifiers &QX, const Type *Y,
12785 Qualifiers &QY) {
12786 Type::TypeClass TC = X->getTypeClass();
12787 assert(TC == Y->getTypeClass());
12788 switch (TC) {
12789#define UNEXPECTED_TYPE(Class, Kind) \
12790 case Type::Class: \
12791 llvm_unreachable("Unexpected " Kind ": " #Class);
12792
12793#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
12794#define TYPE(Class, Base)
12795#include "clang/AST/TypeNodes.inc"
12796
12797#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
12798 SUGAR_FREE_TYPE(Builtin)
12799 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
12800 SUGAR_FREE_TYPE(DependentBitInt)
12803 SUGAR_FREE_TYPE(ObjCInterface)
12805 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
12806 SUGAR_FREE_TYPE(UnresolvedUsing)
12807#undef SUGAR_FREE_TYPE
12808#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
12809 NON_UNIQUE_TYPE(TypeOfExpr)
12810 NON_UNIQUE_TYPE(VariableArray)
12811#undef NON_UNIQUE_TYPE
12812
12813 UNEXPECTED_TYPE(TypeOf, "sugar")
12814
12815#undef UNEXPECTED_TYPE
12816
12817 case Type::Auto: {
12818 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
12819 assert(AX->getDeducedType().isNull());
12820 assert(AY->getDeducedType().isNull());
12821 assert(AX->getKeyword() == AY->getKeyword());
12822 assert(AX->isInstantiationDependentType() ==
12823 AY->isInstantiationDependentType());
12824 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
12825 AY->getTypeConstraintArguments());
12826 return Ctx.getAutoType(QualType(), AX->getKeyword(),
12828 AX->containsUnexpandedParameterPack(),
12829 getCommonDeclChecked(AX->getTypeConstraintConcept(),
12830 AY->getTypeConstraintConcept()),
12831 As);
12832 }
12833 case Type::IncompleteArray: {
12834 const auto *AX = cast<IncompleteArrayType>(X),
12835 *AY = cast<IncompleteArrayType>(Y);
12836 return Ctx.getIncompleteArrayType(
12837 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12839 }
12840 case Type::DependentSizedArray: {
12841 const auto *AX = cast<DependentSizedArrayType>(X),
12842 *AY = cast<DependentSizedArrayType>(Y);
12843 return Ctx.getDependentSizedArrayType(
12844 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12845 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
12847 AX->getBracketsRange() == AY->getBracketsRange()
12848 ? AX->getBracketsRange()
12849 : SourceRange());
12850 }
12851 case Type::ConstantArray: {
12852 const auto *AX = cast<ConstantArrayType>(X),
12853 *AY = cast<ConstantArrayType>(Y);
12854 assert(AX->getSize() == AY->getSize());
12855 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12856 ? AX->getSizeExpr()
12857 : nullptr;
12858 return Ctx.getConstantArrayType(
12859 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12861 }
12862 case Type::ArrayParameter: {
12863 const auto *AX = cast<ArrayParameterType>(X),
12864 *AY = cast<ArrayParameterType>(Y);
12865 assert(AX->getSize() == AY->getSize());
12866 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12867 ? AX->getSizeExpr()
12868 : nullptr;
12869 auto ArrayTy = Ctx.getConstantArrayType(
12870 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12872 return Ctx.getArrayParameterType(ArrayTy);
12873 }
12874 case Type::Atomic: {
12875 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
12876 return Ctx.getAtomicType(
12877 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
12878 }
12879 case Type::Complex: {
12880 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
12881 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
12882 }
12883 case Type::Pointer: {
12884 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
12885 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
12886 }
12887 case Type::BlockPointer: {
12888 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
12889 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
12890 }
12891 case Type::ObjCObjectPointer: {
12892 const auto *PX = cast<ObjCObjectPointerType>(X),
12893 *PY = cast<ObjCObjectPointerType>(Y);
12894 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
12895 }
12896 case Type::MemberPointer: {
12897 const auto *PX = cast<MemberPointerType>(X),
12898 *PY = cast<MemberPointerType>(Y);
12899 return Ctx.getMemberPointerType(
12900 getCommonPointeeType(Ctx, PX, PY),
12901 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
12902 QualType(PY->getClass(), 0))
12903 .getTypePtr());
12904 }
12905 case Type::LValueReference: {
12906 const auto *PX = cast<LValueReferenceType>(X),
12907 *PY = cast<LValueReferenceType>(Y);
12908 // FIXME: Preserve PointeeTypeAsWritten.
12909 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
12910 PX->isSpelledAsLValue() ||
12911 PY->isSpelledAsLValue());
12912 }
12913 case Type::RValueReference: {
12914 const auto *PX = cast<RValueReferenceType>(X),
12915 *PY = cast<RValueReferenceType>(Y);
12916 // FIXME: Preserve PointeeTypeAsWritten.
12917 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
12918 }
12919 case Type::DependentAddressSpace: {
12920 const auto *PX = cast<DependentAddressSpaceType>(X),
12921 *PY = cast<DependentAddressSpaceType>(Y);
12922 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
12923 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
12924 PX->getAddrSpaceExpr(),
12925 getCommonAttrLoc(PX, PY));
12926 }
12927 case Type::FunctionNoProto: {
12928 const auto *FX = cast<FunctionNoProtoType>(X),
12929 *FY = cast<FunctionNoProtoType>(Y);
12930 assert(FX->getExtInfo() == FY->getExtInfo());
12931 return Ctx.getFunctionNoProtoType(
12932 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
12933 FX->getExtInfo());
12934 }
12935 case Type::FunctionProto: {
12936 const auto *FX = cast<FunctionProtoType>(X),
12937 *FY = cast<FunctionProtoType>(Y);
12938 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
12939 EPIY = FY->getExtProtoInfo();
12940 assert(EPIX.ExtInfo == EPIY.ExtInfo);
12941 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
12942 assert(EPIX.RefQualifier == EPIY.RefQualifier);
12943 assert(EPIX.TypeQuals == EPIY.TypeQuals);
12944 assert(EPIX.Variadic == EPIY.Variadic);
12945
12946 // FIXME: Can we handle an empty EllipsisLoc?
12947 // Use emtpy EllipsisLoc if X and Y differ.
12948
12949 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
12950
12951 QualType R =
12952 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
12953 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
12954 /*Unqualified=*/true);
12955
12956 SmallVector<QualType, 8> Exceptions;
12958 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
12959 return Ctx.getFunctionType(R, P, EPIX);
12960 }
12961 case Type::ObjCObject: {
12962 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
12963 assert(
12964 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
12965 OY->getProtocols().begin(), OY->getProtocols().end(),
12966 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
12967 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
12968 }) &&
12969 "protocol lists must be the same");
12970 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
12971 OY->getTypeArgsAsWritten());
12972 return Ctx.getObjCObjectType(
12973 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
12974 OX->getProtocols(),
12975 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
12976 }
12977 case Type::ConstantMatrix: {
12978 const auto *MX = cast<ConstantMatrixType>(X),
12979 *MY = cast<ConstantMatrixType>(Y);
12980 assert(MX->getNumRows() == MY->getNumRows());
12981 assert(MX->getNumColumns() == MY->getNumColumns());
12982 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
12983 MX->getNumRows(), MX->getNumColumns());
12984 }
12985 case Type::DependentSizedMatrix: {
12986 const auto *MX = cast<DependentSizedMatrixType>(X),
12987 *MY = cast<DependentSizedMatrixType>(Y);
12988 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
12989 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
12990 return Ctx.getDependentSizedMatrixType(
12991 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
12992 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
12993 }
12994 case Type::Vector: {
12995 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
12996 assert(VX->getNumElements() == VY->getNumElements());
12997 assert(VX->getVectorKind() == VY->getVectorKind());
12998 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
12999 VX->getNumElements(), VX->getVectorKind());
13000 }
13001 case Type::ExtVector: {
13002 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13003 assert(VX->getNumElements() == VY->getNumElements());
13004 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13005 VX->getNumElements());
13006 }
13007 case Type::DependentSizedExtVector: {
13008 const auto *VX = cast<DependentSizedExtVectorType>(X),
13009 *VY = cast<DependentSizedExtVectorType>(Y);
13011 getCommonSizeExpr(Ctx, VX, VY),
13012 getCommonAttrLoc(VX, VY));
13013 }
13014 case Type::DependentVector: {
13015 const auto *VX = cast<DependentVectorType>(X),
13016 *VY = cast<DependentVectorType>(Y);
13017 assert(VX->getVectorKind() == VY->getVectorKind());
13018 return Ctx.getDependentVectorType(
13019 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13020 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13021 }
13022 case Type::InjectedClassName: {
13023 const auto *IX = cast<InjectedClassNameType>(X),
13024 *IY = cast<InjectedClassNameType>(Y);
13025 return Ctx.getInjectedClassNameType(
13026 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13027 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13028 IY->getInjectedSpecializationType()));
13029 }
13030 case Type::TemplateSpecialization: {
13031 const auto *TX = cast<TemplateSpecializationType>(X),
13032 *TY = cast<TemplateSpecializationType>(Y);
13033 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13034 TY->template_arguments());
13036 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13037 TY->getTemplateName()),
13038 As, X->getCanonicalTypeInternal());
13039 }
13040 case Type::Decltype: {
13041 const auto *DX = cast<DecltypeType>(X);
13042 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13043 assert(DX->isDependentType());
13044 assert(DY->isDependentType());
13045 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13046 // As Decltype is not uniqued, building a common type would be wasteful.
13047 return QualType(DX, 0);
13048 }
13049 case Type::PackIndexing: {
13050 const auto *DX = cast<PackIndexingType>(X);
13051 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13052 assert(DX->isDependentType());
13053 assert(DY->isDependentType());
13054 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13055 return QualType(DX, 0);
13056 }
13057 case Type::DependentName: {
13058 const auto *NX = cast<DependentNameType>(X),
13059 *NY = cast<DependentNameType>(Y);
13060 assert(NX->getIdentifier() == NY->getIdentifier());
13061 return Ctx.getDependentNameType(
13062 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13063 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13064 }
13065 case Type::DependentTemplateSpecialization: {
13066 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13067 *TY = cast<DependentTemplateSpecializationType>(Y);
13068 assert(TX->getIdentifier() == TY->getIdentifier());
13069 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13070 TY->template_arguments());
13072 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13073 TX->getIdentifier(), As);
13074 }
13075 case Type::UnaryTransform: {
13076 const auto *TX = cast<UnaryTransformType>(X),
13077 *TY = cast<UnaryTransformType>(Y);
13078 assert(TX->getUTTKind() == TY->getUTTKind());
13079 return Ctx.getUnaryTransformType(
13080 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13081 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13082 TY->getUnderlyingType()),
13083 TX->getUTTKind());
13084 }
13085 case Type::PackExpansion: {
13086 const auto *PX = cast<PackExpansionType>(X),
13087 *PY = cast<PackExpansionType>(Y);
13088 assert(PX->getNumExpansions() == PY->getNumExpansions());
13089 return Ctx.getPackExpansionType(
13090 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13091 PX->getNumExpansions(), false);
13092 }
13093 case Type::Pipe: {
13094 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13095 assert(PX->isReadOnly() == PY->isReadOnly());
13096 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13098 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13099 }
13100 case Type::TemplateTypeParm: {
13101 const auto *TX = cast<TemplateTypeParmType>(X),
13102 *TY = cast<TemplateTypeParmType>(Y);
13103 assert(TX->getDepth() == TY->getDepth());
13104 assert(TX->getIndex() == TY->getIndex());
13105 assert(TX->isParameterPack() == TY->isParameterPack());
13106 return Ctx.getTemplateTypeParmType(
13107 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13108 getCommonDecl(TX->getDecl(), TY->getDecl()));
13109 }
13110 }
13111 llvm_unreachable("Unknown Type Class");
13112}
13113
13115 const Type *Y,
13116 SplitQualType Underlying) {
13117 Type::TypeClass TC = X->getTypeClass();
13118 if (TC != Y->getTypeClass())
13119 return QualType();
13120 switch (TC) {
13121#define UNEXPECTED_TYPE(Class, Kind) \
13122 case Type::Class: \
13123 llvm_unreachable("Unexpected " Kind ": " #Class);
13124#define TYPE(Class, Base)
13125#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13126#include "clang/AST/TypeNodes.inc"
13127
13128#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13131 CANONICAL_TYPE(BlockPointer)
13132 CANONICAL_TYPE(Builtin)
13134 CANONICAL_TYPE(ConstantArray)
13135 CANONICAL_TYPE(ArrayParameter)
13136 CANONICAL_TYPE(ConstantMatrix)
13138 CANONICAL_TYPE(ExtVector)
13139 CANONICAL_TYPE(FunctionNoProto)
13140 CANONICAL_TYPE(FunctionProto)
13141 CANONICAL_TYPE(IncompleteArray)
13142 CANONICAL_TYPE(LValueReference)
13143 CANONICAL_TYPE(MemberPointer)
13144 CANONICAL_TYPE(ObjCInterface)
13145 CANONICAL_TYPE(ObjCObject)
13146 CANONICAL_TYPE(ObjCObjectPointer)
13150 CANONICAL_TYPE(RValueReference)
13151 CANONICAL_TYPE(VariableArray)
13153#undef CANONICAL_TYPE
13154
13155#undef UNEXPECTED_TYPE
13156
13157 case Type::Adjusted: {
13158 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13159 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13160 if (!Ctx.hasSameType(OX, OY))
13161 return QualType();
13162 // FIXME: It's inefficient to have to unify the original types.
13163 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13164 Ctx.getQualifiedType(Underlying));
13165 }
13166 case Type::Decayed: {
13167 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13168 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13169 if (!Ctx.hasSameType(OX, OY))
13170 return QualType();
13171 // FIXME: It's inefficient to have to unify the original types.
13172 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13173 Ctx.getQualifiedType(Underlying));
13174 }
13175 case Type::Attributed: {
13176 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13177 AttributedType::Kind Kind = AX->getAttrKind();
13178 if (Kind != AY->getAttrKind())
13179 return QualType();
13180 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13181 if (!Ctx.hasSameType(MX, MY))
13182 return QualType();
13183 // FIXME: It's inefficient to have to unify the modified types.
13184 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13185 Ctx.getQualifiedType(Underlying));
13186 }
13187 case Type::BTFTagAttributed: {
13188 const auto *BX = cast<BTFTagAttributedType>(X);
13189 const BTFTypeTagAttr *AX = BX->getAttr();
13190 // The attribute is not uniqued, so just compare the tag.
13191 if (AX->getBTFTypeTag() !=
13192 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13193 return QualType();
13194 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13195 }
13196 case Type::Auto: {
13197 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13198
13199 AutoTypeKeyword KW = AX->getKeyword();
13200 if (KW != AY->getKeyword())
13201 return QualType();
13202
13203 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13204 AY->getTypeConstraintConcept());
13206 if (CD &&
13207 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13208 AY->getTypeConstraintArguments())) {
13209 CD = nullptr; // The arguments differ, so make it unconstrained.
13210 As.clear();
13211 }
13212
13213 // Both auto types can't be dependent, otherwise they wouldn't have been
13214 // sugar. This implies they can't contain unexpanded packs either.
13215 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13216 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13217 }
13218 case Type::PackIndexing:
13219 case Type::Decltype:
13220 return QualType();
13221 case Type::DeducedTemplateSpecialization:
13222 // FIXME: Try to merge these.
13223 return QualType();
13224
13225 case Type::Elaborated: {
13226 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13227 return Ctx.getElaboratedType(
13228 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13229 Ctx.getQualifiedType(Underlying),
13230 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13231 }
13232 case Type::MacroQualified: {
13233 const auto *MX = cast<MacroQualifiedType>(X),
13234 *MY = cast<MacroQualifiedType>(Y);
13235 const IdentifierInfo *IX = MX->getMacroIdentifier();
13236 if (IX != MY->getMacroIdentifier())
13237 return QualType();
13238 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13239 }
13240 case Type::SubstTemplateTypeParm: {
13241 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13242 *SY = cast<SubstTemplateTypeParmType>(Y);
13243 Decl *CD =
13244 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13245 if (!CD)
13246 return QualType();
13247 unsigned Index = SX->getIndex();
13248 if (Index != SY->getIndex())
13249 return QualType();
13250 auto PackIndex = SX->getPackIndex();
13251 if (PackIndex != SY->getPackIndex())
13252 return QualType();
13253 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13254 CD, Index, PackIndex);
13255 }
13256 case Type::ObjCTypeParam:
13257 // FIXME: Try to merge these.
13258 return QualType();
13259 case Type::Paren:
13260 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13261
13262 case Type::TemplateSpecialization: {
13263 const auto *TX = cast<TemplateSpecializationType>(X),
13264 *TY = cast<TemplateSpecializationType>(Y);
13265 TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13266 TY->getTemplateName());
13267 if (!CTN.getAsVoidPointer())
13268 return QualType();
13270 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13271 TY->template_arguments()))
13272 return QualType();
13273 return Ctx.getTemplateSpecializationType(CTN, Args,
13274 Ctx.getQualifiedType(Underlying));
13275 }
13276 case Type::Typedef: {
13277 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13278 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13279 if (!CD)
13280 return QualType();
13281 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13282 }
13283 case Type::TypeOf: {
13284 // The common sugar between two typeof expressions, where one is
13285 // potentially a typeof_unqual and the other is not, we unify to the
13286 // qualified type as that retains the most information along with the type.
13287 // We only return a typeof_unqual type when both types are unqual types.
13289 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13290 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13292 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13293 }
13294 case Type::TypeOfExpr:
13295 return QualType();
13296
13297 case Type::UnaryTransform: {
13298 const auto *UX = cast<UnaryTransformType>(X),
13299 *UY = cast<UnaryTransformType>(Y);
13300 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13301 if (KX != UY->getUTTKind())
13302 return QualType();
13303 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13304 if (!Ctx.hasSameType(BX, BY))
13305 return QualType();
13306 // FIXME: It's inefficient to have to unify the base types.
13307 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13308 Ctx.getQualifiedType(Underlying), KX);
13309 }
13310 case Type::Using: {
13311 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13312 const UsingShadowDecl *CD =
13313 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13314 if (!CD)
13315 return QualType();
13316 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13317 }
13318 case Type::CountAttributed: {
13319 const auto *DX = cast<CountAttributedType>(X),
13320 *DY = cast<CountAttributedType>(Y);
13321 if (DX->isCountInBytes() != DY->isCountInBytes())
13322 return QualType();
13323 if (DX->isOrNull() != DY->isOrNull())
13324 return QualType();
13325 Expr *CEX = DX->getCountExpr();
13326 Expr *CEY = DY->getCountExpr();
13327 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
13328 if (Ctx.hasSameExpr(CEX, CEY))
13329 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13330 DX->isCountInBytes(), DX->isOrNull(),
13331 CDX);
13332 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
13333 return QualType();
13334 // Two declarations with the same integer constant may still differ in their
13335 // expression pointers, so we need to evaluate them.
13336 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
13337 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
13338 if (VX != VY)
13339 return QualType();
13340 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13341 DX->isCountInBytes(), DX->isOrNull(),
13342 CDX);
13343 }
13344 }
13345 llvm_unreachable("Unhandled Type Class");
13346}
13347
13348static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13350 while (true) {
13351 QTotal.addConsistentQualifiers(T.Quals);
13353 if (NT == QualType(T.Ty, 0))
13354 break;
13355 R.push_back(T);
13356 T = NT.split();
13357 }
13358 return R;
13359}
13360
13362 bool Unqualified) {
13363 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13364 if (X == Y)
13365 return X;
13366 if (!Unqualified) {
13367 if (X.isCanonical())
13368 return X;
13369 if (Y.isCanonical())
13370 return Y;
13371 }
13372
13373 SplitQualType SX = X.split(), SY = Y.split();
13374 Qualifiers QX, QY;
13375 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13376 // until we reach their underlying "canonical nodes". Note these are not
13377 // necessarily canonical types, as they may still have sugared properties.
13378 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13379 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13380 if (SX.Ty != SY.Ty) {
13381 // The canonical nodes differ. Build a common canonical node out of the two,
13382 // unifying their sugar. This may recurse back here.
13383 SX.Ty =
13384 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13385 } else {
13386 // The canonical nodes were identical: We may have desugared too much.
13387 // Add any common sugar back in.
13388 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13389 QX -= SX.Quals;
13390 QY -= SY.Quals;
13391 SX = Xs.pop_back_val();
13392 SY = Ys.pop_back_val();
13393 }
13394 }
13395 if (Unqualified)
13397 else
13398 assert(QX == QY);
13399
13400 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13401 // related. Walk up these nodes, unifying them and adding the result.
13402 while (!Xs.empty() && !Ys.empty()) {
13403 auto Underlying = SplitQualType(
13404 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13405 SX = Xs.pop_back_val();
13406 SY = Ys.pop_back_val();
13407 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13409 // Stop at the first pair which is unrelated.
13410 if (!SX.Ty) {
13411 SX.Ty = Underlying.Ty;
13412 break;
13413 }
13414 QX -= Underlying.Quals;
13415 };
13416
13417 // Add back the missing accumulated qualifiers, which were stripped off
13418 // with the sugar nodes we could not unify.
13419 QualType R = getQualifiedType(SX.Ty, QX);
13420 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13421 return R;
13422}
13423
13425 assert(Ty->isFixedPointType());
13426
13428 return Ty;
13429
13430 switch (Ty->castAs<BuiltinType>()->getKind()) {
13431 default:
13432 llvm_unreachable("Not a saturated fixed point type!");
13433 case BuiltinType::SatShortAccum:
13434 return ShortAccumTy;
13435 case BuiltinType::SatAccum:
13436 return AccumTy;
13437 case BuiltinType::SatLongAccum:
13438 return LongAccumTy;
13439 case BuiltinType::SatUShortAccum:
13440 return UnsignedShortAccumTy;
13441 case BuiltinType::SatUAccum:
13442 return UnsignedAccumTy;
13443 case BuiltinType::SatULongAccum:
13444 return UnsignedLongAccumTy;
13445 case BuiltinType::SatShortFract:
13446 return ShortFractTy;
13447 case BuiltinType::SatFract:
13448 return FractTy;
13449 case BuiltinType::SatLongFract:
13450 return LongFractTy;
13451 case BuiltinType::SatUShortFract:
13452 return UnsignedShortFractTy;
13453 case BuiltinType::SatUFract:
13454 return UnsignedFractTy;
13455 case BuiltinType::SatULongFract:
13456 return UnsignedLongFractTy;
13457 }
13458}
13459
13461 assert(Ty->isFixedPointType());
13462
13463 if (Ty->isSaturatedFixedPointType()) return Ty;
13464
13465 switch (Ty->castAs<BuiltinType>()->getKind()) {
13466 default:
13467 llvm_unreachable("Not a fixed point type!");
13468 case BuiltinType::ShortAccum:
13469 return SatShortAccumTy;
13470 case BuiltinType::Accum:
13471 return SatAccumTy;
13472 case BuiltinType::LongAccum:
13473 return SatLongAccumTy;
13474 case BuiltinType::UShortAccum:
13476 case BuiltinType::UAccum:
13477 return SatUnsignedAccumTy;
13478 case BuiltinType::ULongAccum:
13480 case BuiltinType::ShortFract:
13481 return SatShortFractTy;
13482 case BuiltinType::Fract:
13483 return SatFractTy;
13484 case BuiltinType::LongFract:
13485 return SatLongFractTy;
13486 case BuiltinType::UShortFract:
13488 case BuiltinType::UFract:
13489 return SatUnsignedFractTy;
13490 case BuiltinType::ULongFract:
13492 }
13493}
13494
13496 if (LangOpts.OpenCL)
13498
13499 if (LangOpts.CUDA)
13501
13502 return getLangASFromTargetAS(AS);
13503}
13504
13505// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13506// doesn't include ASTContext.h
13507template
13509 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13511 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13512 const clang::ASTContext &Ctx, Decl *Value);
13513
13515 assert(Ty->isFixedPointType());
13516
13517 const TargetInfo &Target = getTargetInfo();
13518 switch (Ty->castAs<BuiltinType>()->getKind()) {
13519 default:
13520 llvm_unreachable("Not a fixed point type!");
13521 case BuiltinType::ShortAccum:
13522 case BuiltinType::SatShortAccum:
13523 return Target.getShortAccumScale();
13524 case BuiltinType::Accum:
13525 case BuiltinType::SatAccum:
13526 return Target.getAccumScale();
13527 case BuiltinType::LongAccum:
13528 case BuiltinType::SatLongAccum:
13529 return Target.getLongAccumScale();
13530 case BuiltinType::UShortAccum:
13531 case BuiltinType::SatUShortAccum:
13532 return Target.getUnsignedShortAccumScale();
13533 case BuiltinType::UAccum:
13534 case BuiltinType::SatUAccum:
13535 return Target.getUnsignedAccumScale();
13536 case BuiltinType::ULongAccum:
13537 case BuiltinType::SatULongAccum:
13538 return Target.getUnsignedLongAccumScale();
13539 case BuiltinType::ShortFract:
13540 case BuiltinType::SatShortFract:
13541 return Target.getShortFractScale();
13542 case BuiltinType::Fract:
13543 case BuiltinType::SatFract:
13544 return Target.getFractScale();
13545 case BuiltinType::LongFract:
13546 case BuiltinType::SatLongFract:
13547 return Target.getLongFractScale();
13548 case BuiltinType::UShortFract:
13549 case BuiltinType::SatUShortFract:
13550 return Target.getUnsignedShortFractScale();
13551 case BuiltinType::UFract:
13552 case BuiltinType::SatUFract:
13553 return Target.getUnsignedFractScale();
13554 case BuiltinType::ULongFract:
13555 case BuiltinType::SatULongFract:
13556 return Target.getUnsignedLongFractScale();
13557 }
13558}
13559
13561 assert(Ty->isFixedPointType());
13562
13563 const TargetInfo &Target = getTargetInfo();
13564 switch (Ty->castAs<BuiltinType>()->getKind()) {
13565 default:
13566 llvm_unreachable("Not a fixed point type!");
13567 case BuiltinType::ShortAccum:
13568 case BuiltinType::SatShortAccum:
13569 return Target.getShortAccumIBits();
13570 case BuiltinType::Accum:
13571 case BuiltinType::SatAccum:
13572 return Target.getAccumIBits();
13573 case BuiltinType::LongAccum:
13574 case BuiltinType::SatLongAccum:
13575 return Target.getLongAccumIBits();
13576 case BuiltinType::UShortAccum:
13577 case BuiltinType::SatUShortAccum:
13578 return Target.getUnsignedShortAccumIBits();
13579 case BuiltinType::UAccum:
13580 case BuiltinType::SatUAccum:
13581 return Target.getUnsignedAccumIBits();
13582 case BuiltinType::ULongAccum:
13583 case BuiltinType::SatULongAccum:
13584 return Target.getUnsignedLongAccumIBits();
13585 case BuiltinType::ShortFract:
13586 case BuiltinType::SatShortFract:
13587 case BuiltinType::Fract:
13588 case BuiltinType::SatFract:
13589 case BuiltinType::LongFract:
13590 case BuiltinType::SatLongFract:
13591 case BuiltinType::UShortFract:
13592 case BuiltinType::SatUShortFract:
13593 case BuiltinType::UFract:
13594 case BuiltinType::SatUFract:
13595 case BuiltinType::ULongFract:
13596 case BuiltinType::SatULongFract:
13597 return 0;
13598 }
13599}
13600
13601llvm::FixedPointSemantics
13603 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
13604 "Can only get the fixed point semantics for a "
13605 "fixed point or integer type.");
13606 if (Ty->isIntegerType())
13607 return llvm::FixedPointSemantics::GetIntegerSemantics(
13608 getIntWidth(Ty), Ty->isSignedIntegerType());
13609
13610 bool isSigned = Ty->isSignedFixedPointType();
13611 return llvm::FixedPointSemantics(
13612 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
13614 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
13615}
13616
13617llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
13618 assert(Ty->isFixedPointType());
13619 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
13620}
13621
13622llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
13623 assert(Ty->isFixedPointType());
13624 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
13625}
13626
13628 assert(Ty->isUnsignedFixedPointType() &&
13629 "Expected unsigned fixed point type");
13630
13631 switch (Ty->castAs<BuiltinType>()->getKind()) {
13632 case BuiltinType::UShortAccum:
13633 return ShortAccumTy;
13634 case BuiltinType::UAccum:
13635 return AccumTy;
13636 case BuiltinType::ULongAccum:
13637 return LongAccumTy;
13638 case BuiltinType::SatUShortAccum:
13639 return SatShortAccumTy;
13640 case BuiltinType::SatUAccum:
13641 return SatAccumTy;
13642 case BuiltinType::SatULongAccum:
13643 return SatLongAccumTy;
13644 case BuiltinType::UShortFract:
13645 return ShortFractTy;
13646 case BuiltinType::UFract:
13647 return FractTy;
13648 case BuiltinType::ULongFract:
13649 return LongFractTy;
13650 case BuiltinType::SatUShortFract:
13651 return SatShortFractTy;
13652 case BuiltinType::SatUFract:
13653 return SatFractTy;
13654 case BuiltinType::SatULongFract:
13655 return SatLongFractTy;
13656 default:
13657 llvm_unreachable("Unexpected unsigned fixed point type");
13658 }
13659}
13660
13662 const TargetVersionAttr *TV) const {
13663 assert(TV != nullptr);
13665 std::vector<std::string> ResFeats;
13666 TV->getFeatures(Feats);
13667 for (auto &Feature : Feats)
13668 if (Target->validateCpuSupports(Feature.str()))
13669 // Use '?' to mark features that came from TargetVersion.
13670 ResFeats.push_back("?" + Feature.str());
13671 return ResFeats;
13672}
13673
13675ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
13676 assert(TD != nullptr);
13677 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
13678
13679 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
13680 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
13681 });
13682 return ParsedAttr;
13683}
13684
13685void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13686 const FunctionDecl *FD) const {
13687 if (FD)
13688 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
13689 else
13690 Target->initFeatureMap(FeatureMap, getDiagnostics(),
13691 Target->getTargetOpts().CPU,
13692 Target->getTargetOpts().Features);
13693}
13694
13695// Fills in the supplied string map with the set of target features for the
13696// passed in function.
13697void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13698 GlobalDecl GD) const {
13699 StringRef TargetCPU = Target->getTargetOpts().CPU;
13700 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
13701 if (const auto *TD = FD->getAttr<TargetAttr>()) {
13703
13704 // Make a copy of the features as passed on the command line into the
13705 // beginning of the additional features from the function to override.
13706 ParsedAttr.Features.insert(
13707 ParsedAttr.Features.begin(),
13708 Target->getTargetOpts().FeaturesAsWritten.begin(),
13709 Target->getTargetOpts().FeaturesAsWritten.end());
13710
13711 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
13712 TargetCPU = ParsedAttr.CPU;
13713
13714 // Now populate the feature map, first with the TargetCPU which is either
13715 // the default or a new one from the target attribute string. Then we'll use
13716 // the passed in features (FeaturesAsWritten) along with the new ones from
13717 // the attribute.
13718 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
13719 ParsedAttr.Features);
13720 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
13722 Target->getCPUSpecificCPUDispatchFeatures(
13723 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
13724 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
13725 Features.insert(Features.begin(),
13726 Target->getTargetOpts().FeaturesAsWritten.begin(),
13727 Target->getTargetOpts().FeaturesAsWritten.end());
13728 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13729 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
13730 std::vector<std::string> Features;
13731 if (Target->getTriple().isAArch64()) {
13732 // TargetClones for AArch64
13734 TC->getFeatures(Feats, GD.getMultiVersionIndex());
13735 for (StringRef Feat : Feats)
13736 if (Target->validateCpuSupports(Feat.str()))
13737 // Use '?' to mark features that came from AArch64 TargetClones.
13738 Features.push_back("?" + Feat.str());
13739 Features.insert(Features.begin(),
13740 Target->getTargetOpts().FeaturesAsWritten.begin(),
13741 Target->getTargetOpts().FeaturesAsWritten.end());
13742 } else {
13743 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
13744 if (VersionStr.starts_with("arch="))
13745 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
13746 else if (VersionStr != "default")
13747 Features.push_back((StringRef{"+"} + VersionStr).str());
13748 }
13749 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13750 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
13751 std::vector<std::string> Feats = filterFunctionTargetVersionAttrs(TV);
13752 Feats.insert(Feats.begin(),
13753 Target->getTargetOpts().FeaturesAsWritten.begin(),
13754 Target->getTargetOpts().FeaturesAsWritten.end());
13755 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Feats);
13756 } else {
13757 FeatureMap = Target->getTargetOpts().FeatureMap;
13758 }
13759}
13760
13762 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
13763 return *OMPTraitInfoVector.back();
13764}
13765
13768 const ASTContext::SectionInfo &Section) {
13769 if (Section.Decl)
13770 return DB << Section.Decl;
13771 return DB << "a prior #pragma section";
13772}
13773
13774bool ASTContext::mayExternalize(const Decl *D) const {
13775 bool IsInternalVar =
13776 isa<VarDecl>(D) &&
13777 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
13778 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
13779 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
13780 (D->hasAttr<CUDAConstantAttr>() &&
13781 !D->getAttr<CUDAConstantAttr>()->isImplicit());
13782 // CUDA/HIP: managed variables need to be externalized since it is
13783 // a declaration in IR, therefore cannot have internal linkage. Kernels in
13784 // anonymous name space needs to be externalized to avoid duplicate symbols.
13785 return (IsInternalVar &&
13786 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
13787 (D->hasAttr<CUDAGlobalAttr>() &&
13788 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
13789 GVA_Internal);
13790}
13791
13793 return mayExternalize(D) &&
13794 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
13795 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
13796}
13797
13798StringRef ASTContext::getCUIDHash() const {
13799 if (!CUIDHash.empty())
13800 return CUIDHash;
13801 if (LangOpts.CUID.empty())
13802 return StringRef();
13803 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
13804 return CUIDHash;
13805}
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:3285
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:83
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:2976
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:50
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)
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
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:1123
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
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:1122
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:2119
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:1993
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:1204
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3235
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:2380
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:2575
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3249
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:2591
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:1957
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:2432
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:1132
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:2141
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:1931
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:1937
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:1591
CanQualType WideCharTy
Definition: ASTContext.h:1095
CanQualType OMPIteratorTy
Definition: ASTContext.h:1132
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:1131
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1123
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:1149
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:2074
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:1969
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:1981
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:1123
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3214
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1119
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:1150
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:3228
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3221
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:1163
CanQualType PseudoObjectTy
Definition: ASTContext.h:1122
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:3245
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
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:1157
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:1124
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:1128
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:2321
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2064
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:2618
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:2341
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1121
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:3210
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:3242
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:1128
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:3224
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:1288
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:1120
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:1129
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:1569
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:2771
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:1129
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:3217
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1130
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:1189
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:1794
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:3231
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:2243
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2249
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2246
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2255
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2252
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:1128
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:2372
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:2345
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:3238
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:3299
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3318
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:3689
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3519
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3533
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3537
QualType getElementType() const
Definition: Type.h:3531
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3541
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:7190
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7195
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:5605
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5660
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5688
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5982
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5041
bool isConstrained() const
Definition: Type.h:6001
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5723
A fixed int type of a specified bitwidth.
Definition: Type.h:7243
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7260
unsigned getNumBits() const
Definition: Type.h:7255
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4494
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3350
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3367
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:2982
Kind getKind() const
Definition: Type.h:3024
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3294
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:3087
QualType getElementType() const
Definition: Type.h:3097
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3102
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:3557
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3653
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3613
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3672
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3633
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4168
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4189
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4206
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4186
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4197
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3248
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3284
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3333
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:1266
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:1786
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1922
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1700
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:5359
Represents a C++17 deduced template specialization type.
Definition: Type.h:6030
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6052
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5948
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3860
Expr * getAddrSpaceExpr() const
Definition: Type.h:3871
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3882
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7288
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5387
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5391
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6453
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6485
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3802
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3839
Expr * getSizeExpr() const
Definition: Type.h:3822
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3900
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3925
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4227
Expr * getRowExpr() const
Definition: Type.h:4239
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4247
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:6505
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6532
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5308
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5312
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:5510
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5515
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4022
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4047
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:6372
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6425
Represents an enum.
Definition: Decl.h:3867
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4072
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4086
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4027
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4938
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5576
EnumDecl * getDecl() const
Definition: Type.h:5583
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:4084
@ 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:3923
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:4062
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:5332
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:3057
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3148
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4644
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4592
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
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:4545
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:2599
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:2830
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:4266
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2372
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:4612
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4628
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4657
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5102
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4916
unsigned getNumParams() const
Definition: Type.h:4890
QualType getParamType(unsigned i) const
Definition: Type.h:4892
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3785
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4922
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5013
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4901
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4897
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5078
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5074
Declaration of a template function.
Definition: DeclTemplate.h:957
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4368
CallingConv getCC() const
Definition: Type.h:4430
bool getNoCfCheck() const
Definition: Type.h:4420
unsigned getRegParm() const
Definition: Type.h:4423
bool getNoCallerSavedRegs() const
Definition: Type.h:4419
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4442
bool getHasRegParm() const
Definition: Type.h:4421
bool getNoReturn() const
Definition: Type.h:4416
bool getProducesResult() const
Definition: Type.h:4417
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4283
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4323
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4257
ExtInfo getExtInfo() const
Definition: Type.h:4586
QualType getReturnType() const
Definition: Type.h:4574
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:4799
Represents a C array with an unspecified size.
Definition: Type.h:3704
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3721
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6222
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:3425
@ 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:5243
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:4146
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4153
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3461
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3497
QualType getPointeeType() const
Definition: Type.h:3477
const Type * getClass() const
Definition: Type.h:3491
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
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:6953
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
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:7009
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7090
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:910
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7084
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7166
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7046
bool qual_empty() const
Definition: Type.h:7138
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7067
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7021
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7061
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1798
qual_range quals() const
Definition: Type.h:7128
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7073
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:6906
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4327
Represents a class type in Objective C.
Definition: Type.h:6755
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:6870
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:832
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:6865
bool isObjCQualifiedClass() const
Definition: Type.h:6837
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:6817
bool isObjCClass() const
Definition: Type.h:6823
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:868
bool isObjCQualifiedId() const
Definition: Type.h:6836
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:850
bool isObjCUnqualifiedId() const
Definition: Type.h:6827
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6988
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:6881
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:6661
qual_iterator qual_end() const
Definition: Type.h:6655
qual_iterator qual_begin() const
Definition: Type.h:6654
qual_range quals() const
Definition: Type.h:6653
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:6681
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4344
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:4173
Represents a pack expansion of types.
Definition: Type.h:6570
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6604
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5446
Sugar for parentheses used when specifying types.
Definition: Type.h:3114
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3128
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:7209
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7226
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3140
QualType getPointeeType() const
Definition: Type.h:3150
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3155
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:7444
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2739
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:7491
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7449
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:7360
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7486
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7400
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:7454
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7381
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7433
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:7417
const Type * getTypePtrOrNull() const
Definition: Type.h:7364
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:2899
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7392
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:7300
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7307
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:3443
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:4168
bool hasFlexibleArrayMember() const
Definition: Decl.h:4201
field_range fields() const
Definition: Decl.h:4374
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5015
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5081
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4359
bool field_empty() const
Definition: Decl.h:4382
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5550
RecordDecl * getDecl() const
Definition: Type.h:5560
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:3381
QualType getPointeeType() const
Definition: Type.h:3399
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3407
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:5890
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4190
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5820
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5859
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4737
bool isUnion() const
Definition: Decl.h:3790
TagDecl * getDecl() const
Definition: Type.cpp:4018
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:218
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
IntType getInt64Type() const
Definition: TargetInfo.h:405
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:834
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1624
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1618
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:727
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:772
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:319
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:328
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:332
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:337
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:346
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:324
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:341
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:488
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:370
unsigned getHalfAlign() const
Definition: TargetInfo.h:763
unsigned getBFloat16Align() const
Definition: TargetInfo.h:773
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:762
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:947
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:735
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1605
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:791
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:998
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
unsigned getFloat128Align() const
Definition: TargetInfo.h:792
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:699
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:793
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:783
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:784
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1017
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:6090
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4279
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:5792
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:3390
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3415
const Type * getTypeForDecl() const
Definition: Decl.h:3414
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:5275
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5323
A container of type source information.
Definition: Type.h:7331
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:1881
bool isBlockPointerType() const
Definition: Type.h:7621
bool isBooleanType() const
Definition: Type.h:8034
bool isObjCBuiltinType() const
Definition: Type.h:7796
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2567
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:7687
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:7882
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2145
bool isConstantArrayType() const
Definition: Type.h:7683
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:2020
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2351
bool isArrayType() const
Definition: Type.h:7679
bool isCharType() const
Definition: Type.cpp:2088
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:476
bool isPointerType() const
Definition: Type.h:7613
bool isArrayParameterType() const
Definition: Type.h:7695
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7946
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8194
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:7895
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:7987
bool isEnumeralType() const
Definition: Type.h:7711
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2498
bool isObjCQualifiedIdType() const
Definition: Type.h:7766
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8021
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2235
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2536
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2759
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2662
bool isBitIntType() const
Definition: Type.h:7841
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7875
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2654
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7959
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7975
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:2185
QualType getCanonicalTypeInternal() const
Definition: Type.h:2937
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8077
bool isMemberPointerType() const
Definition: Type.h:7661
bool isObjCIdType() const
Definition: Type.h:7778
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7983
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8180
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2361
bool isFunctionType() const
Definition: Type.h:7609
bool isObjCObjectPointerType() const
Definition: Type.h:7745
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:8001
bool isVectorType() const
Definition: Type.h:7719
bool isObjCClassType() const
Definition: Type.h:7784
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2549
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2485
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:2195
bool isAnyPointerType() const
Definition: Type.h:7617
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:8127
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:7939
bool isRecordType() const
Definition: Type.h:7707
bool isObjCRetainableType() const
Definition: Type.cpp:4888
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4635
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3534
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5503
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
QualType getUnderlyingType() const
Definition: Decl.h:3487
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3494
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5228
A unary type transform, which is a type constructed from another.
Definition: Type.h:5467
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:5145
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:5196
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:5365
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:3748
Expr * getSizeExpr() const
Definition: Type.h:3767
Represents a GCC generic vector type.
Definition: Type.h:3970
unsigned getNumElements() const
Definition: Type.h:3985
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3994
VectorKind getVectorKind() const
Definition: Type.h:3990
QualType getElementType() const
Definition: Type.h:3984
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:204
@ OCLTK_ReserveID
Definition: TargetInfo.h:211
@ OCLTK_Sampler
Definition: TargetInfo.h:212
@ OCLTK_Pipe
Definition: TargetInfo.h:209
@ OCLTK_ClkEvent
Definition: TargetInfo.h:206
@ OCLTK_Event
Definition: TargetInfo.h:207
@ OCLTK_Default
Definition: TargetInfo.h:205
@ OCLTK_Queue
Definition: TargetInfo.h:210
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:7513
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:3516
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition: Type.h:6300
@ 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:1033
@ TypeAlignment
Definition: Type.h:73
FloatModeKind
Definition: TargetInfo.h:72
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:3933
@ 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:6275
@ 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:4708
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4710
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4713
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:4716
Extra information about a function prototype.
Definition: Type.h:4736
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4743
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:4766
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4744
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:4761
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4737
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4495
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4551
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4500
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:57
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:142
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