1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTLambda.h"
19#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTStructuralEquivalence.h"
21#include "clang/AST/ASTTypeTraits.h"
22#include "clang/AST/Attr.h"
23#include "clang/AST/AttrIterator.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Comment.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclBase.h"
28#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclContextInternals.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/DeclOpenMP.h"
32#include "clang/AST/DeclTemplate.h"
33#include "clang/AST/DeclarationName.h"
34#include "clang/AST/DependenceFlags.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
37#include "clang/AST/ExternalASTSource.h"
38#include "clang/AST/Mangle.h"
39#include "clang/AST/MangleNumberingContext.h"
40#include "clang/AST/NestedNameSpecifier.h"
41#include "clang/AST/ParentMapContext.h"
42#include "clang/AST/RawCommentList.h"
43#include "clang/AST/RecordLayout.h"
44#include "clang/AST/Stmt.h"
45#include "clang/AST/TemplateBase.h"
46#include "clang/AST/TemplateName.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
49#include "clang/AST/UnresolvedSet.h"
50#include "clang/AST/VTableBuilder.h"
51#include "clang/Basic/AddressSpaces.h"
52#include "clang/Basic/Builtins.h"
53#include "clang/Basic/CommentOptions.h"
54#include "clang/Basic/DiagnosticAST.h"
55#include "clang/Basic/ExceptionSpecificationType.h"
56#include "clang/Basic/IdentifierTable.h"
57#include "clang/Basic/LLVM.h"
58#include "clang/Basic/LangOptions.h"
59#include "clang/Basic/Linkage.h"
60#include "clang/Basic/Module.h"
61#include "clang/Basic/NoSanitizeList.h"
62#include "clang/Basic/ObjCRuntime.h"
63#include "clang/Basic/ProfileList.h"
64#include "clang/Basic/SourceLocation.h"
65#include "clang/Basic/SourceManager.h"
66#include "clang/Basic/Specifiers.h"
67#include "clang/Basic/TargetCXXABI.h"
68#include "clang/Basic/TargetInfo.h"
69#include "clang/Basic/XRayLists.h"
70#include "clang/Lex/MacroInfo.h"
71#include "llvm/ADT/APFixedPoint.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/APSInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/SmallPtrSet.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/ADT/StringRef.h"
84#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
85#include "llvm/Support/Capacity.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/MD5.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/SipHash.h"
92#include "llvm/Support/raw_ostream.h"
93#include "llvm/TargetParser/AArch64TargetParser.h"
94#include "llvm/TargetParser/RISCVTargetParser.h"
95#include "llvm/TargetParser/Triple.h"
96#include <algorithm>
97#include <cassert>
98#include <cstddef>
99#include <cstdint>
100#include <cstdlib>
101#include <map>
102#include <memory>
103#include <optional>
104#include <string>
105#include <tuple>
106#include <utility>
107
108using namespace clang;
109
110enum FloatingRank {
111 BFloat16Rank,
112 Float16Rank,
113 HalfRank,
114 FloatRank,
115 DoubleRank,
116 LongDoubleRank,
117 Float128Rank,
118 Ibm128Rank
119};
120
121/// \returns The locations that are relevant when searching for Doc comments
122/// related to \p Key.
123static SmallVector<SourceLocation, 2>
124getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
125 SourceManager &SourceMgr) {
126 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
127 SourceLocation DefLoc = MI->getDefinitionLoc();
128 if (DefLoc.isInvalid() || !DefLoc.isFileID())
129 return {};
130
131 // The macro's definition location points at its name (e.g. FOO in
132 // `#define FOO 1`). The text between a preceding documentation comment
133 // and the name contains the `#define` directive itself, which would be
134 // rejected by the preprocessor-directive guard in
135 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
136 // the guard only fires when something *else* sits between the comment
137 // and our directive.
138 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
139 bool Invalid = false;
140 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
141 if (Invalid)
142 return {};
143 unsigned Offset = Decomposed.second;
144 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
145 Found != StringRef::npos)
146 Offset = Found;
147 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
148 .getLocWithOffset(Offset)};
149 }
150
151 const auto *D = cast<const Decl *>(Val&: Key);
152 assert(D);
153
154 // User can not attach documentation to implicit declarations.
155 if (D->isImplicit())
156 return {};
157
158 // User can not attach documentation to implicit instantiations.
159 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
160 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
161 return {};
162 }
163
164 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
165 if (VD->isStaticDataMember() &&
166 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
167 return {};
168 }
169
170 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
171 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174
175 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
176 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
177 if (TSK == TSK_ImplicitInstantiation ||
178 TSK == TSK_Undeclared)
179 return {};
180 }
181
182 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
183 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
184 return {};
185 }
186 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
187 // When tag declaration (but not definition!) is part of the
188 // decl-specifier-seq of some other declaration, it doesn't get comment
189 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
190 return {};
191 }
192 // TODO: handle comments for function parameters properly.
193 if (isa<ParmVarDecl>(Val: D))
194 return {};
195
196 // TODO: we could look up template parameter documentation in the template
197 // documentation.
198 if (isa<TemplateTypeParmDecl>(Val: D) ||
199 isa<NonTypeTemplateParmDecl>(Val: D) ||
200 isa<TemplateTemplateParmDecl>(Val: D))
201 return {};
202
203 SmallVector<SourceLocation, 2> Locations;
204 // Find declaration location.
205 // For Objective-C declarations we generally don't expect to have multiple
206 // declarators, thus use declaration starting location as the "declaration
207 // location".
208 // For all other declarations multiple declarators are used quite frequently,
209 // so we use the location of the identifier as the "declaration location".
210 SourceLocation BaseLocation;
211 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
212 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
213 isa<ClassTemplateSpecializationDecl>(Val: D) ||
214 // Allow association with Y across {} in `typedef struct X {} Y`.
215 isa<TypedefDecl>(Val: D))
216 BaseLocation = D->getBeginLoc();
217 else
218 BaseLocation = D->getLocation();
219
220 if (!D->getLocation().isMacroID()) {
221 Locations.emplace_back(Args&: BaseLocation);
222 } else {
223 const auto *DeclCtx = D->getDeclContext();
224
225 // When encountering definitions generated from a macro (that are not
226 // contained by another declaration in the macro) we need to try and find
227 // the comment at the location of the expansion but if there is no comment
228 // there we should retry to see if there is a comment inside the macro as
229 // well. To this end we return first BaseLocation to first look at the
230 // expansion site, the second value is the spelling location of the
231 // beginning of the declaration defined inside the macro.
232 if (!(DeclCtx &&
233 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
234 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
235 }
236
237 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
238 // we don't refer to the macro argument location at the expansion site (this
239 // can happen if the name's spelling is provided via macro argument), and
240 // always to the declaration itself.
241 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
242 }
243
244 return Locations;
245}
246
247RawComment *ASTContext::getRawCommentNoCacheImpl(
248 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
249 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
250 // If the declaration doesn't map directly to a location in a file, we
251 // can't find the comment.
252 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
253 return nullptr;
254
255 // If there are no comments anywhere, we won't find anything.
256 if (CommentsInTheFile.empty())
257 return nullptr;
258
259 const auto *D = dyn_cast<const Decl *>(Val&: Key);
260 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
261
262 // Decompose the location for the declaration and find the beginning of the
263 // file buffer.
264 const FileIDAndOffset LocDecomp =
265 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
266
267 // Slow path.
268 auto OffsetCommentBehindDecl =
269 CommentsInTheFile.lower_bound(x: LocDecomp.second);
270
271 // First check whether we have a trailing comment.
272 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
273 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
274 if ((CommentBehindDecl->isDocumentation() ||
275 LangOpts.CommentOpts.ParseAllComments) &&
276 CommentBehindDecl->isTrailingComment() &&
277 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
278 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
279 isa<ObjCPropertyDecl>(Val: D))))) {
280
281 // Check that Doxygen trailing comment comes after the declaration, starts
282 // on the same line and in the same file as the declaration.
283 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
284 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
285 Offset: OffsetCommentBehindDecl->first)) {
286 return CommentBehindDecl;
287 }
288 }
289 }
290
291 // The comment just after the declaration was not a trailing comment.
292 // Let's look at the previous comment.
293 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
294 return nullptr;
295
296 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
297 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
298
299 // Check that we actually have a non-member Doxygen comment.
300 if (!(CommentBeforeDecl->isDocumentation() ||
301 LangOpts.CommentOpts.ParseAllComments) ||
302 CommentBeforeDecl->isTrailingComment())
303 return nullptr;
304
305 // Decompose the end of the comment.
306 const unsigned CommentEndOffset =
307 Comments.getCommentEndOffset(C: CommentBeforeDecl);
308 if (CommentEndOffset > LocDecomp.second)
309 return nullptr;
310
311 // Get the corresponding buffer.
312 bool Invalid = false;
313 const char *Buffer =
314 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
315 if (Invalid)
316 return nullptr;
317
318 // Extract text between the comment and declaration.
319 StringRef Text(Buffer + CommentEndOffset,
320 LocDecomp.second - CommentEndOffset);
321
322 // There should be no other declarations or preprocessor directives between
323 // comment and declaration.
324 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
325 return nullptr;
326
327 return CommentBeforeDecl;
328}
329
330RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
331 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
332
333 for (const auto Loc : Locs) {
334 // If the declaration or macro doesn't map directly to a location in a file,
335 // we can't find the comment.
336 if (Loc.isInvalid() || !Loc.isFileID())
337 continue;
338
339 if (ExternalSource && !CommentsLoaded) {
340 ExternalSource->ReadComments();
341 CommentsLoaded = true;
342 }
343
344 if (Comments.empty())
345 continue;
346
347 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
348 if (!File.isValid())
349 continue;
350
351 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
352 if (!CommentsInThisFile || CommentsInThisFile->empty())
353 continue;
354
355 if (RawComment *Comment =
356 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
357 return Comment;
358 }
359
360 return nullptr;
361}
362
363void ASTContext::addComment(const RawComment &RC) {
364 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
365 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
366 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
367}
368
369const RawComment *
370ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
371 const Decl **OriginalDecl) const {
372 if (Key.isNull()) {
373 if (OriginalDecl)
374 *OriginalDecl = nullptr;
375 return nullptr;
376 }
377
378 // Macros have no redeclaration chain: look up directly, populate the cache,
379 // and return.
380 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
381 if (OriginalDecl)
382 *OriginalDecl = nullptr;
383 auto Existing = RawComments.find(Val: Key);
384 if (Existing != RawComments.end())
385 return Existing->second;
386 if (const RawComment *RC = getRawCommentNoCache(Key)) {
387 cacheRawComment(Original: MI, Comment: *RC);
388 return RC;
389 }
390 return nullptr;
391 }
392
393 const Decl *D = cast<const Decl *>(Val&: Key);
394 D = &adjustDeclToTemplate(D: *D);
395
396 // Any comment directly attached to D?
397 {
398 auto DeclComment = RawComments.find(Val: D);
399 if (DeclComment != RawComments.end()) {
400 if (OriginalDecl)
401 *OriginalDecl = D;
402 return DeclComment->second;
403 }
404 }
405
406 // Any comment attached to any redeclaration of D?
407 const Decl *CanonicalD = D->getCanonicalDecl();
408 if (!CanonicalD)
409 return nullptr;
410
411 {
412 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
413 if (RedeclComment != RedeclChainComments.end()) {
414 if (OriginalDecl)
415 *OriginalDecl = RedeclComment->second;
416 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
417 assert(CommentAtRedecl != RawComments.end() &&
418 "This decl is supposed to have comment attached.");
419 return CommentAtRedecl->second;
420 }
421 }
422
423 // Any redeclarations of D that we haven't checked for comments yet?
424 const Decl *LastCheckedRedecl = [&]() {
425 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
426 bool CanUseCommentlessCache = false;
427 if (LastChecked) {
428 for (auto *Redecl : CanonicalD->redecls()) {
429 if (Redecl == D) {
430 CanUseCommentlessCache = true;
431 break;
432 }
433 if (Redecl == LastChecked)
434 break;
435 }
436 }
437 // FIXME: This could be improved so that even if CanUseCommentlessCache
438 // is false, once we've traversed past CanonicalD we still skip ahead
439 // LastChecked.
440 return CanUseCommentlessCache ? LastChecked : nullptr;
441 }();
442
443 for (const Decl *Redecl : D->redecls()) {
444 assert(Redecl);
445 // Skip all redeclarations that have been checked previously.
446 if (LastCheckedRedecl) {
447 if (LastCheckedRedecl == Redecl) {
448 LastCheckedRedecl = nullptr;
449 }
450 continue;
451 }
452 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
453 if (RedeclComment) {
454 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
455 if (OriginalDecl)
456 *OriginalDecl = Redecl;
457 return RedeclComment;
458 }
459 CommentlessRedeclChains[CanonicalD] = Redecl;
460 }
461
462 if (OriginalDecl)
463 *OriginalDecl = nullptr;
464 return nullptr;
465}
466
467void ASTContext::cacheRawComment(RawCommentLookupKey Original,
468 const RawComment &Comment) const {
469 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
470 RawComments.try_emplace(Key: Original, Args: &Comment);
471 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
472 const Decl *const CanonicalDecl = D->getCanonicalDecl();
473 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
474 CommentlessRedeclChains.erase(Val: CanonicalDecl);
475 }
476}
477
478static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
479 SmallVectorImpl<const NamedDecl *> &Redeclared) {
480 const DeclContext *DC = ObjCMethod->getDeclContext();
481 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
482 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
483 if (!ID)
484 return;
485 // Add redeclared method here.
486 for (const auto *Ext : ID->known_extensions()) {
487 if (ObjCMethodDecl *RedeclaredMethod =
488 Ext->getMethod(Sel: ObjCMethod->getSelector(),
489 isInstance: ObjCMethod->isInstanceMethod()))
490 Redeclared.push_back(Elt: RedeclaredMethod);
491 }
492 }
493}
494
495void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
496 const Preprocessor *PP) {
497 if (Comments.empty() || Decls.empty())
498 return;
499
500 FileID File;
501 for (const Decl *D : Decls) {
502 if (D->isInvalidDecl())
503 continue;
504
505 D = &adjustDeclToTemplate(D: *D);
506 SourceLocation Loc = D->getLocation();
507 if (Loc.isValid()) {
508 // See if there are any new comments that are not attached to a decl.
509 // The location doesn't have to be precise - we care only about the file.
510 File = SourceMgr.getDecomposedLoc(Loc).first;
511 break;
512 }
513 }
514
515 if (File.isInvalid())
516 return;
517
518 auto CommentsInThisFile = Comments.getCommentsInFile(File);
519 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
520 CommentsInThisFile->rbegin()->second->isAttached())
521 return;
522
523 // There is at least one comment not attached to a decl.
524 // Maybe it should be attached to one of Decls?
525 //
526 // Note that this way we pick up not only comments that precede the
527 // declaration, but also comments that *follow* the declaration -- thanks to
528 // the lookahead in the lexer: we've consumed the semicolon and looked
529 // ahead through comments.
530 for (const Decl *D : Decls) {
531 assert(D);
532 if (D->isInvalidDecl())
533 continue;
534
535 D = &adjustDeclToTemplate(D: *D);
536
537 if (RawComments.count(Val: D) > 0)
538 continue;
539
540 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
541
542 for (const auto DeclLoc : DeclLocs) {
543 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
544 continue;
545
546 const FileID DeclFile = SourceMgr.getDecomposedLoc(Loc: DeclLoc).first;
547 if (!DeclFile.isValid())
548 continue;
549
550 const auto *CommentsInDeclFile =
551 DeclFile == File ? CommentsInThisFile
552 : Comments.getCommentsInFile(File: DeclFile);
553 if (!CommentsInDeclFile || CommentsInDeclFile->empty())
554 continue;
555
556 if (RawComment *const DocComment =
557 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInDeclFile)) {
558 cacheRawComment(Original: D, Comment: *DocComment);
559 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
560 ParsedComments[D->getCanonicalDecl()] = FC;
561 break;
562 }
563 }
564 }
565}
566
567comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
568 const Decl *D) const {
569 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
570 ThisDeclInfo->CommentDecl = D;
571 ThisDeclInfo->IsFilled = false;
572 ThisDeclInfo->fill();
573 ThisDeclInfo->CommentDecl = FC->getDecl();
574 if (!ThisDeclInfo->TemplateParameters)
575 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
576 comments::FullComment *CFC =
577 new (*this) comments::FullComment(FC->getBlocks(),
578 ThisDeclInfo);
579 return CFC;
580}
581
582comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
583 const RawComment *RC = getRawCommentNoCache(Key: D);
584 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
585}
586
587comments::FullComment *ASTContext::getCommentForDecl(
588 const Decl *D,
589 const Preprocessor *PP) const {
590 if (!D || D->isInvalidDecl())
591 return nullptr;
592 D = &adjustDeclToTemplate(D: *D);
593
594 const Decl *Canonical = D->getCanonicalDecl();
595 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
596 ParsedComments.find(Val: Canonical);
597
598 if (Pos != ParsedComments.end()) {
599 if (Canonical != D) {
600 comments::FullComment *FC = Pos->second;
601 comments::FullComment *CFC = cloneFullComment(FC, D);
602 return CFC;
603 }
604 return Pos->second;
605 }
606
607 const Decl *OriginalDecl = nullptr;
608
609 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
610 if (!RC) {
611 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
612 SmallVector<const NamedDecl*, 8> Overridden;
613 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
614 if (OMD && OMD->isPropertyAccessor())
615 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
616 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
617 return cloneFullComment(FC, D);
618 if (OMD)
619 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
620 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
621 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
622 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
623 return cloneFullComment(FC, D);
624 }
625 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
626 // Attach any tag type's documentation to its typedef if latter
627 // does not have one of its own.
628 QualType QT = TD->getUnderlyingType();
629 if (const auto *TT = QT->getAs<TagType>())
630 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
631 return cloneFullComment(FC, D);
632 }
633 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
634 while (IC->getSuperClass()) {
635 IC = IC->getSuperClass();
636 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
637 return cloneFullComment(FC, D);
638 }
639 }
640 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
641 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
642 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
643 return cloneFullComment(FC, D);
644 }
645 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
646 if (!(RD = RD->getDefinition()))
647 return nullptr;
648 // Check non-virtual bases.
649 for (const auto &I : RD->bases()) {
650 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
651 continue;
652 QualType Ty = I.getType();
653 if (Ty.isNull())
654 continue;
655 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
656 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
657 continue;
658
659 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
660 return cloneFullComment(FC, D);
661 }
662 }
663 // Check virtual bases.
664 for (const auto &I : RD->vbases()) {
665 if (I.getAccessSpecifier() != AS_public)
666 continue;
667 QualType Ty = I.getType();
668 if (Ty.isNull())
669 continue;
670 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
671 if (!(VirtualBase= VirtualBase->getDefinition()))
672 continue;
673 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
674 return cloneFullComment(FC, D);
675 }
676 }
677 }
678 return nullptr;
679 }
680
681 // If the RawComment was attached to other redeclaration of this Decl, we
682 // should parse the comment in context of that other Decl. This is important
683 // because comments can contain references to parameter names which can be
684 // different across redeclarations.
685 if (D != OriginalDecl && OriginalDecl)
686 return getCommentForDecl(D: OriginalDecl, PP);
687
688 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
689 ParsedComments[Canonical] = FC;
690 return FC;
691}
692
693void ASTContext::CanonicalTemplateTemplateParm::Profile(
694 llvm::FoldingSetNodeID &ID, const ASTContext &C,
695 TemplateTemplateParmDecl *Parm) {
696 ID.AddInteger(I: Parm->getDepth());
697 ID.AddInteger(I: Parm->getPosition());
698 ID.AddBoolean(B: Parm->isParameterPack());
699 ID.AddInteger(I: Parm->templateParameterKind());
700
701 TemplateParameterList *Params = Parm->getTemplateParameters();
702 ID.AddInteger(I: Params->size());
703 for (TemplateParameterList::const_iterator P = Params->begin(),
704 PEnd = Params->end();
705 P != PEnd; ++P) {
706 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
707 ID.AddInteger(I: 0);
708 ID.AddBoolean(B: TTP->isParameterPack());
709 ID.AddInteger(
710 I: TTP->getNumExpansionParameters().toInternalRepresentation());
711 continue;
712 }
713
714 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
715 ID.AddInteger(I: 1);
716 ID.AddBoolean(B: NTTP->isParameterPack());
717 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
718 .getAsOpaquePtr());
719 if (NTTP->isExpandedParameterPack()) {
720 ID.AddBoolean(B: true);
721 ID.AddInteger(I: NTTP->getNumExpansionTypes());
722 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
723 QualType T = NTTP->getExpansionType(I);
724 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
725 }
726 } else
727 ID.AddBoolean(B: false);
728 continue;
729 }
730
731 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
732 ID.AddInteger(I: 2);
733 Profile(ID, C, Parm: TTP);
734 }
735}
736
737TemplateTemplateParmDecl *
738ASTContext::getCanonicalTemplateTemplateParmDecl(
739 TemplateTemplateParmDecl *TTP) const {
740 // Check if we already have a canonical template template parameter.
741 llvm::FoldingSetNodeID ID;
742 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
743 llvm::FoldingSetInsertToken Token;
744 CanonicalTemplateTemplateParm *Canonical =
745 CanonTemplateTemplateParms.lookup(ID, Token);
746 if (Canonical)
747 return Canonical->getParam();
748
749 // Build a canonical template parameter list.
750 TemplateParameterList *Params = TTP->getTemplateParameters();
751 SmallVector<NamedDecl *, 4> CanonParams;
752 CanonParams.reserve(N: Params->size());
753 for (TemplateParameterList::const_iterator P = Params->begin(),
754 PEnd = Params->end();
755 P != PEnd; ++P) {
756 // Note that, per C++20 [temp.over.link]/6, when determining whether
757 // template-parameters are equivalent, constraints are ignored.
758 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
759 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
760 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
761 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
762 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
763 NumExpanded: TTP->getNumExpansionParameters());
764 CanonParams.push_back(Elt: NewTTP);
765 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
766 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
767 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
768 NonTypeTemplateParmDecl *Param;
769 if (NTTP->isExpandedParameterPack()) {
770 SmallVector<QualType, 2> ExpandedTypes;
771 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
772 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
773 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
774 ExpandedTInfos.push_back(
775 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
776 }
777
778 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
779 StartLoc: SourceLocation(),
780 IdLoc: SourceLocation(),
781 D: NTTP->getDepth(),
782 P: NTTP->getPosition(), Id: nullptr,
783 T,
784 TInfo,
785 ExpandedTypes,
786 ExpandedTInfos);
787 } else {
788 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
789 StartLoc: SourceLocation(),
790 IdLoc: SourceLocation(),
791 D: NTTP->getDepth(),
792 P: NTTP->getPosition(), Id: nullptr,
793 T,
794 ParameterPack: NTTP->isParameterPack(),
795 TInfo);
796 }
797 CanonParams.push_back(Elt: Param);
798 } else
799 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
800 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
801 }
802
803 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
804 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
805 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
806 ParameterKind: TTP->templateParameterKind(),
807 /*Typename=*/false,
808 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
809 Params: CanonParams, RAngleLoc: SourceLocation(),
810 /*RequiresClause=*/nullptr));
811
812 // Get the new insert position for the node we care about.
813 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
814 assert(!Canonical && "Shouldn't be in the map!");
815 (void)Canonical;
816
817 // Create the canonical template template parameter entry.
818 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
819 CanonTemplateTemplateParms.insert(N: Canonical, Token);
820 return CanonTTP;
821}
822
823TemplateTemplateParmDecl *
824ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
825 TemplateTemplateParmDecl *TTP) const {
826 llvm::FoldingSetNodeID ID;
827 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
828 llvm::FoldingSetInsertToken Token;
829 CanonicalTemplateTemplateParm *Canonical =
830 CanonTemplateTemplateParms.lookup(ID, Token);
831 return Canonical ? Canonical->getParam() : nullptr;
832}
833
834TemplateTemplateParmDecl *
835ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
836 TemplateTemplateParmDecl *CanonTTP) const {
837 llvm::FoldingSetNodeID ID;
838 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
839 llvm::FoldingSetInsertToken Token;
840 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
841 return Existing->getParam();
842 CanonTemplateTemplateParms.insert(
843 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
844 return CanonTTP;
845}
846
847/// For the purposes of overflow pattern exclusion, does this match the
848/// while(i--) pattern?
849static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
850 if (UO->getOpcode() != UO_PostDec)
851 return false;
852
853 if (!UO->getType()->isUnsignedIntegerType())
854 return false;
855
856 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
857 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
858 Kind: LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
859 return false;
860
861 // all Parents (usually just one) must be a WhileStmt
862 return llvm::all_of(
863 Range: Ctx.getParentMapContext().getParents(Node: *UO),
864 P: [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
865}
866
867bool ASTContext::isUnaryOverflowPatternExcluded(const UnaryOperator *UO) {
868 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
869 // ... like -1UL;
870 if (UO->getOpcode() == UO_Minus &&
871 getLangOpts().isOverflowPatternExcluded(
872 Kind: LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
873 UO->isIntegerConstantExpr(Ctx: *this)) {
874 return true;
875 }
876
877 if (matchesPostDecrInWhile(UO, Ctx&: *this))
878 return true;
879
880 return false;
881}
882
883/// Check if a type can have its sanitizer instrumentation elided based on its
884/// presence within an ignorelist.
885bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
886 const QualType &Ty) const {
887 std::string TyName = Ty.getUnqualifiedType().getAsString(Policy: getPrintingPolicy());
888 return NoSanitizeL->containsType(Mask, MangledTypeName: TyName);
889}
890
891TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
892 auto Kind = getTargetInfo().getCXXABI().getKind();
893 return getLangOpts().CXXABI.value_or(u&: Kind);
894}
895
896CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
897 if (!LangOpts.CPlusPlus) return nullptr;
898
899 switch (getCXXABIKind()) {
900 case TargetCXXABI::AppleARM64:
901 case TargetCXXABI::Fuchsia:
902 case TargetCXXABI::GenericARM: // Same as Itanium at this level
903 case TargetCXXABI::iOS:
904 case TargetCXXABI::WatchOS:
905 case TargetCXXABI::GenericAArch64:
906 case TargetCXXABI::GenericMIPS:
907 case TargetCXXABI::GenericItanium:
908 case TargetCXXABI::WebAssembly:
909 case TargetCXXABI::XL:
910 return CreateItaniumCXXABI(Ctx&: *this);
911 case TargetCXXABI::Microsoft:
912 return CreateMicrosoftCXXABI(Ctx&: *this);
913 }
914 llvm_unreachable("Invalid CXXABI type!");
915}
916
917interp::Context &ASTContext::getInterpContext() const {
918 if (!InterpContext) {
919 InterpContext.reset(p: new interp::Context(const_cast<ASTContext &>(*this)));
920 }
921 return *InterpContext;
922}
923
924static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
925 const LangOptions &LangOpts) {
926 switch (LangOpts.getAddressSpaceMapMangling()) {
927 case LangOptions::ASMM_Target:
928 return TI.useAddressSpaceMapMangling();
929 case LangOptions::ASMM_On:
930 return true;
931 case LangOptions::ASMM_Off:
932 return false;
933 }
934 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
935}
936
937ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
938 IdentifierTable &idents, SelectorTable &sels,
939 Builtin::Context &builtins, TranslationUnitKind TUKind)
940 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
941 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
942 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
943 DependentSizedMatrixTypes(this_()),
944 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
945 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
946 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
947 AttributedTypes(this_()), DependentBitIntTypes(this_()),
948 HLSLAttributedResourceTypes(this_()),
949 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
950 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
951 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
952 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
953 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
954 LangOpts.XRayNeverInstrumentFiles,
955 LangOpts.XRayAttrListFiles, SM)),
956 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
957 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
958 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
959 DeclarationNames(*this), Comments(SM),
960 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
961 CompCategories(this_()), LastSDM(nullptr, 0) {
962 addTranslationUnitDecl();
963}
964
965void ASTContext::cleanup() {
966 // Release the DenseMaps associated with DeclContext objects.
967 // FIXME: Is this the ideal solution?
968 ReleaseDeclContextMaps();
969
970 // Call all of the deallocation functions on all of their targets.
971 for (auto &Pair : Deallocations)
972 (Pair.first)(Pair.second);
973 Deallocations.clear();
974
975 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
976 // because they can contain DenseMaps.
977 for (llvm::DenseMap<const ObjCInterfaceDecl *,
978 const ASTRecordLayout *>::iterator
979 I = ObjCLayouts.begin(),
980 E = ObjCLayouts.end();
981 I != E;)
982 // Increment in loop to prevent using deallocated memory.
983 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
984 R->Destroy(Ctx&: *this);
985 ObjCLayouts.clear();
986
987 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
988 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
989 // Increment in loop to prevent using deallocated memory.
990 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
991 R->Destroy(Ctx&: *this);
992 }
993 ASTRecordLayouts.clear();
994
995 CtorClosureDefaultArgs.clear();
996
997 for (const auto &Value : ModuleInitializers)
998 Value.second->~PerModuleInitializers();
999 ModuleInitializers.clear();
1000
1001 TUDecl = nullptr;
1002 XRayFilter.reset();
1003 NoSanitizeL.reset();
1004}
1005
1006ASTContext::~ASTContext() { cleanup(); }
1007
1008void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1009 TraversalScope = TopLevelDecls;
1010 getParentMapContext().clear();
1011}
1012
1013void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1014 Deallocations.push_back(Elt: {Callback, Data});
1015}
1016
1017void
1018ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1019 ExternalSource = std::move(Source);
1020}
1021
1022void ASTContext::PrintStats() const {
1023 llvm::errs() << "\n*** AST Context Stats:\n";
1024 llvm::errs() << " " << Types.size() << " types total.\n";
1025
1026 unsigned counts[] = {
1027#define TYPE(Name, Parent) 0,
1028#define ABSTRACT_TYPE(Name, Parent)
1029#include "clang/AST/TypeNodes.inc"
1030 0 // Extra
1031 };
1032
1033 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1034 Type *T = Types[i];
1035 counts[(unsigned)T->getTypeClass()]++;
1036 }
1037
1038 unsigned Idx = 0;
1039 unsigned TotalBytes = 0;
1040#define TYPE(Name, Parent) \
1041 if (counts[Idx]) \
1042 llvm::errs() << " " << counts[Idx] << " " << #Name \
1043 << " types, " << sizeof(Name##Type) << " each " \
1044 << "(" << counts[Idx] * sizeof(Name##Type) \
1045 << " bytes)\n"; \
1046 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1047 ++Idx;
1048#define ABSTRACT_TYPE(Name, Parent)
1049#include "clang/AST/TypeNodes.inc"
1050
1051 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1052
1053 // Implicit special member functions.
1054 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1055 << NumImplicitDefaultConstructors
1056 << " implicit default constructors created\n";
1057 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1058 << NumImplicitCopyConstructors
1059 << " implicit copy constructors created\n";
1060 if (getLangOpts().CPlusPlus)
1061 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1062 << NumImplicitMoveConstructors
1063 << " implicit move constructors created\n";
1064 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1065 << NumImplicitCopyAssignmentOperators
1066 << " implicit copy assignment operators created\n";
1067 if (getLangOpts().CPlusPlus)
1068 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1069 << NumImplicitMoveAssignmentOperators
1070 << " implicit move assignment operators created\n";
1071 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1072 << NumImplicitDestructors
1073 << " implicit destructors created\n";
1074
1075 if (ExternalSource) {
1076 llvm::errs() << "\n";
1077 ExternalSource->PrintStats();
1078 }
1079
1080 BumpAlloc.PrintStats();
1081}
1082
1083void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1084 bool NotifyListeners) {
1085 if (NotifyListeners)
1086 if (auto *Listener = getASTMutationListener();
1087 Listener && !ND->isUnconditionallyVisible())
1088 Listener->RedefinedHiddenDefinition(D: ND, M);
1089
1090 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1091}
1092
1093void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1094 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1095 if (It == MergedDefModules.end())
1096 return;
1097
1098 auto &Merged = It->second;
1099 llvm::DenseSet<Module*> Found;
1100 for (Module *&M : Merged)
1101 if (!Found.insert(V: M).second)
1102 M = nullptr;
1103 llvm::erase(C&: Merged, V: nullptr);
1104}
1105
1106ArrayRef<Module *>
1107ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1108 auto MergedIt =
1109 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1110 if (MergedIt == MergedDefModules.end())
1111 return {};
1112 return MergedIt->second;
1113}
1114
1115void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1116 if (LazyInitializers.empty())
1117 return;
1118
1119 auto *Source = Ctx.getExternalSource();
1120 assert(Source && "lazy initializers but no external source");
1121
1122 auto LazyInits = std::move(LazyInitializers);
1123 LazyInitializers.clear();
1124
1125 for (auto ID : LazyInits)
1126 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1127
1128 assert(LazyInitializers.empty() &&
1129 "GetExternalDecl for lazy module initializer added more inits");
1130}
1131
1132void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1133 // One special case: if we add a module initializer that imports another
1134 // module, and that module's only initializer is an ImportDecl, simplify.
1135 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1136 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1137
1138 // Maybe the ImportDecl does nothing at all. (Common case.)
1139 if (It == ModuleInitializers.end())
1140 return;
1141
1142 // Maybe the ImportDecl only imports another ImportDecl.
1143 auto &Imported = *It->second;
1144 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1145 Imported.resolve(Ctx&: *this);
1146 auto *OnlyDecl = Imported.Initializers.front();
1147 if (isa<ImportDecl>(Val: OnlyDecl))
1148 D = OnlyDecl;
1149 }
1150 }
1151
1152 auto *&Inits = ModuleInitializers[M];
1153 if (!Inits)
1154 Inits = new (*this) PerModuleInitializers;
1155 Inits->Initializers.push_back(Elt: D);
1156}
1157
1158void ASTContext::addLazyModuleInitializers(Module *M,
1159 ArrayRef<GlobalDeclID> IDs) {
1160 auto *&Inits = ModuleInitializers[M];
1161 if (!Inits)
1162 Inits = new (*this) PerModuleInitializers;
1163 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1164 From: IDs.begin(), To: IDs.end());
1165}
1166
1167ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1168 auto It = ModuleInitializers.find(Val: M);
1169 if (It == ModuleInitializers.end())
1170 return {};
1171
1172 auto *Inits = It->second;
1173 Inits->resolve(Ctx&: *this);
1174 return Inits->Initializers;
1175}
1176
1177void ASTContext::setCurrentNamedModule(Module *M) {
1178 assert(M->isNamedModule());
1179 assert(!CurrentCXXNamedModule &&
1180 "We should set named module for ASTContext for only once");
1181 CurrentCXXNamedModule = M;
1182}
1183
1184bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1185 if (!M1 != !M2)
1186 return false;
1187
1188 /// Get the representative module for M. The representative module is the
1189 /// first module unit for a specific primary module name. So that the module
1190 /// units have the same representative module belongs to the same module.
1191 ///
1192 /// The process is helpful to reduce the expensive string operations.
1193 auto GetRepresentativeModule = [this](const Module *M) {
1194 auto Iter = SameModuleLookupSet.find(Val: M);
1195 if (Iter != SameModuleLookupSet.end())
1196 return Iter->second;
1197
1198 const Module *RepresentativeModule =
1199 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1200 .first->second;
1201 SameModuleLookupSet[M] = RepresentativeModule;
1202 return RepresentativeModule;
1203 };
1204
1205 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1206 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1207}
1208
1209ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1210 if (!ExternCContext)
1211 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1212
1213 return ExternCContext;
1214}
1215
1216BuiltinTemplateDecl *
1217ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1218 const IdentifierInfo *II) const {
1219 auto *BuiltinTemplate =
1220 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1221 BuiltinTemplate->setImplicit();
1222 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1223
1224 return BuiltinTemplate;
1225}
1226
1227#define BuiltinTemplate(BTName) \
1228 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1229 if (!Decl##BTName) \
1230 Decl##BTName = \
1231 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1232 return Decl##BTName; \
1233 }
1234#include "clang/Basic/BuiltinTemplates.inc"
1235
1236RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1237 RecordDecl::TagKind TK) const {
1238 SourceLocation Loc;
1239 RecordDecl *NewDecl;
1240 if (getLangOpts().CPlusPlus)
1241 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1242 IdLoc: Loc, Id: &Idents.get(Name));
1243 else
1244 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1245 Id: &Idents.get(Name));
1246 NewDecl->setImplicit();
1247 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1248 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1249 return NewDecl;
1250}
1251
1252TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1253 StringRef Name) const {
1254 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1255 TypedefDecl *NewDecl = TypedefDecl::Create(
1256 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1257 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1258 NewDecl->setImplicit();
1259 return NewDecl;
1260}
1261
1262TypedefDecl *ASTContext::getInt128Decl() const {
1263 if (!Int128Decl)
1264 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1265 return Int128Decl;
1266}
1267
1268TypedefDecl *ASTContext::getUInt128Decl() const {
1269 if (!UInt128Decl)
1270 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1271 return UInt128Decl;
1272}
1273
1274void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1275 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1276 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1277 Types.push_back(Elt: Ty);
1278}
1279
1280void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1281 const TargetInfo *AuxTarget) {
1282 assert((!this->Target || this->Target == &Target) &&
1283 "Incorrect target reinitialization");
1284 assert(VoidTy.isNull() && "Context reinitialized?");
1285
1286 this->Target = &Target;
1287 this->AuxTarget = AuxTarget;
1288
1289 ABI.reset(p: createCXXABI(T: Target));
1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1291
1292 // C99 6.2.5p19.
1293 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1294
1295 // C99 6.2.5p2.
1296 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1297 // C99 6.2.5p3.
1298 if (LangOpts.CharIsSigned)
1299 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1300 else
1301 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1302 // C99 6.2.5p4.
1303 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1304 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1305 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1306 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1307 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1308
1309 // C99 6.2.5p6.
1310 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1311 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1312 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1313 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1314 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1315
1316 // C99 6.2.5p10.
1317 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1318 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1319 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1320
1321 // GNU extension, __float128 for IEEE quadruple precision
1322 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1323
1324 // __ibm128 for IBM extended precision
1325 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1326
1327 // C11 extension ISO/IEC TS 18661-3
1328 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1329
1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1331 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1332 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1333 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1334 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1335 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1336 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1337 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1338 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1339 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1340 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1341 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1342 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1343 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1344 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1345 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1346 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1347 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1348 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1349 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1350 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1351 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1352 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1353 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1354 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1355
1356 // GNU extension, 128-bit integers.
1357 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1358 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1359
1360 // C++ 3.9.1p5
1361 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1362 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1363 else // -fshort-wchar makes wchar_t be unsigned.
1364 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1365 if (LangOpts.CPlusPlus && LangOpts.WChar)
1366 WideCharTy = WCharTy;
1367 else {
1368 // C99 (or C++ using -fno-wchar).
1369 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1370 }
1371
1372 WIntTy = getFromTargetType(Type: Target.getWIntType());
1373
1374 // C++20 (proposed)
1375 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1376
1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1379 else // C99
1380 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1381
1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1383 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1384 else // C99
1385 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1386
1387 // Placeholder type for type-dependent expressions whose type is
1388 // completely unknown. No code should ever check a type against
1389 // DependentTy and users should never see it; however, it is here to
1390 // help diagnose failures to properly check for type-dependent
1391 // expressions.
1392 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1393
1394 // Placeholder type for functions.
1395 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1396
1397 // Placeholder type for bound members.
1398 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1399
1400 // Placeholder type for unresolved templates.
1401 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1402
1403 // Placeholder type for pseudo-objects.
1404 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1405
1406 // "any" type; useful for debugger-like clients.
1407 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1408
1409 // Placeholder type for unbridged ARC casts.
1410 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1411
1412 // Placeholder type for builtin functions.
1413 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1414
1415 // Placeholder type for OMP array sections.
1416 if (LangOpts.OpenMP) {
1417 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1418 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1419 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1420 }
1421 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1422 // don't bother, as we're just using the same type as OMP.
1423 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1424 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1425 }
1426 if (LangOpts.MatrixTypes)
1427 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1428
1429 // Builtin types for 'id', 'Class', and 'SEL'.
1430 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1431 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1432 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1433
1434 if (LangOpts.OpenCL) {
1435#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1436 InitBuiltinType(SingletonId, BuiltinType::Id);
1437#include "clang/Basic/OpenCLImageTypes.def"
1438
1439 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1440 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1441 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1442 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1443 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1444
1445#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1446 InitBuiltinType(Id##Ty, BuiltinType::Id);
1447#include "clang/Basic/OpenCLExtensionTypes.def"
1448 }
1449
1450 if (LangOpts.HLSL) {
1451#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1452 InitBuiltinType(SingletonId, BuiltinType::Id);
1453#include "clang/Basic/HLSLIntangibleTypes.def"
1454
1455#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/HLSLPackedTypes.def"
1458 }
1459
1460 if (Target.hasAArch64ACLETypes() ||
1461 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1462#define SVE_TYPE(Name, Id, SingletonId) \
1463 InitBuiltinType(SingletonId, BuiltinType::Id);
1464#include "clang/Basic/AArch64ACLETypes.def"
1465 }
1466
1467 if (Target.getTriple().isPPC64()) {
1468#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1469 InitBuiltinType(Id##Ty, BuiltinType::Id);
1470#include "clang/Basic/PPCTypes.def"
1471#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1472 InitBuiltinType(Id##Ty, BuiltinType::Id);
1473#include "clang/Basic/PPCTypes.def"
1474 }
1475
1476 if (Target.hasRISCVVTypes()) {
1477#define RVV_TYPE(Name, Id, SingletonId) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/RISCVVTypes.def"
1480 }
1481
1482 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1483#define WASM_TYPE(Name, Id, SingletonId) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/WebAssemblyReferenceTypes.def"
1486 }
1487
1488 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1489#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1490 InitBuiltinType(SingletonId, BuiltinType::Id);
1491#include "clang/Basic/AMDGPUTypes.def"
1492 }
1493
1494 if (Target.getTriple().isSPIRV() ||
1495 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1496#define SPIRV_TYPE(Name, Id, SingletonId) \
1497 InitBuiltinType(SingletonId, BuiltinType::Id);
1498#include "clang/Basic/SPIRVTypes.def"
1499 }
1500
1501 // Builtin type for __objc_yes and __objc_no
1502 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1503 SignedCharTy : BoolTy);
1504
1505 ObjCConstantStringType = QualType();
1506
1507 ObjCSuperType = QualType();
1508
1509 // void * type
1510 if (LangOpts.OpenCLGenericAddressSpace) {
1511 auto Q = VoidTy.getQualifiers();
1512 Q.setAddressSpace(LangAS::opencl_generic);
1513 VoidPtrTy = getPointerType(T: getCanonicalType(
1514 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1515 } else {
1516 VoidPtrTy = getPointerType(T: VoidTy);
1517 }
1518
1519 // nullptr type (C++0x 2.14.7)
1520 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1521
1522 // std::meta::info type (C++26 21.4.1)
1523 InitBuiltinType(R&: MetaInfoTy, K: BuiltinType::MetaInfo);
1524
1525 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1526 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1527
1528 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1529
1530 // Builtin type used to help define __builtin_va_list.
1531 VaListTagDecl = nullptr;
1532
1533 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1534 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1535 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1536 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1537 }
1538}
1539
1540DiagnosticsEngine &ASTContext::getDiagnostics() const {
1541 return SourceMgr.getDiagnostics();
1542}
1543
1544AttrVec *ASTContext::allocateAttrVec() {
1545 return new (DeclAttrAllocator.Allocate()) AttrVec;
1546}
1547
1548ArrayRef<CXXDefaultArgExpr *>
1549ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1550 return CtorClosureDefaultArgs.lookup(Val: CD);
1551}
1552
1553void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1554 ArrayRef<CXXDefaultArgExpr *> Args) {
1555 assert(!CtorClosureDefaultArgs.contains(CD));
1556 CtorClosureDefaultArgs[CD] = Args;
1557}
1558
1559ArrayRef<ExplicitInstantiationDecl *>
1560ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1561 auto It =
1562 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1563 if (It != ExplicitInstantiations.end())
1564 return It->second;
1565 return {};
1566}
1567
1568void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1569 ExplicitInstantiationDecl *EID) {
1570 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1571 NewVal: EID);
1572}
1573
1574ASTContext::TemplateOrSpecializationInfo
1575ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1576 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1577 TemplateOrInstantiation.find(Val: Var);
1578 if (Pos == TemplateOrInstantiation.end())
1579 return {};
1580
1581 return Pos->second;
1582}
1583
1584void
1585ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1586 TemplateSpecializationKind TSK,
1587 SourceLocation PointOfInstantiation) {
1588 assert(Inst->isStaticDataMember() && "Not a static data member");
1589 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1590 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1591 Tmpl, TSK, PointOfInstantiation));
1592}
1593
1594void
1595ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1596 TemplateOrSpecializationInfo TSI) {
1597 assert(!TemplateOrInstantiation[Inst] &&
1598 "Already noted what the variable was instantiated from");
1599 TemplateOrInstantiation[Inst] = TSI;
1600}
1601
1602NamedDecl *
1603ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1604 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1605}
1606
1607void
1608ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1609 assert((isa<UsingDecl>(Pattern) ||
1610 isa<UnresolvedUsingValueDecl>(Pattern) ||
1611 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1612 "pattern decl is not a using decl");
1613 assert((isa<UsingDecl>(Inst) ||
1614 isa<UnresolvedUsingValueDecl>(Inst) ||
1615 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1616 "instantiation did not produce a using decl");
1617 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1618 InstantiatedFromUsingDecl[Inst] = Pattern;
1619}
1620
1621UsingEnumDecl *
1622ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1623 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1624}
1625
1626void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1627 UsingEnumDecl *Pattern) {
1628 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1629 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1630}
1631
1632UsingShadowDecl *
1633ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1634 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1635}
1636
1637void
1638ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1639 UsingShadowDecl *Pattern) {
1640 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1641 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1642}
1643
1644FieldDecl *
1645ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1646 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1647}
1648
1649void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1650 FieldDecl *Tmpl) {
1651 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1652 "Instantiated field decl is not unnamed");
1653 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1654 "Template field decl is not unnamed");
1655 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1656 "Already noted what unnamed field was instantiated from");
1657
1658 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1659}
1660
1661ASTContext::overridden_cxx_method_iterator
1662ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1663 return overridden_methods(Method).begin();
1664}
1665
1666ASTContext::overridden_cxx_method_iterator
1667ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1668 return overridden_methods(Method).end();
1669}
1670
1671unsigned
1672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1673 auto Range = overridden_methods(Method);
1674 return Range.end() - Range.begin();
1675}
1676
1677ASTContext::overridden_method_range
1678ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1679 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1680 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1681 if (Pos == OverriddenMethods.end())
1682 return overridden_method_range(nullptr, nullptr);
1683 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1684}
1685
1686void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1687 const CXXMethodDecl *Overridden) {
1688 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1689 OverriddenMethods[Method].push_back(NewVal: Overridden);
1690}
1691
1692void ASTContext::getOverriddenMethods(
1693 const NamedDecl *D,
1694 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1695 assert(D);
1696
1697 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1698 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1699 in_end: overridden_methods_end(Method: CXXMethod));
1700 return;
1701 }
1702
1703 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1704 if (!Method)
1705 return;
1706
1707 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1708 Method->getOverriddenMethods(Overridden&: OverDecls);
1709 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1710}
1711
1712std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1713ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1714 assert(RD);
1715 CXXRecordDecl *D = RD->getDefinition();
1716 auto it = RelocatableClasses.find(Val: D);
1717 if (it != RelocatableClasses.end())
1718 return it->getSecond();
1719 return std::nullopt;
1720}
1721
1722void ASTContext::setRelocationInfoForCXXRecord(
1723 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1724 assert(RD);
1725 CXXRecordDecl *D = RD->getDefinition();
1726 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1727 RelocatableClasses.insert(KV: {D, Info});
1728}
1729
1730static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1731 const ASTContext &Context, const CXXRecordDecl *Class) {
1732 if (!Class->isPolymorphic())
1733 return false;
1734 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1735 using AuthAttr = VTablePointerAuthenticationAttr;
1736 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1737 if (!ExplicitAuth)
1738 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1739 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1740 ExplicitAuth->getAddressDiscrimination();
1741 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1742 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1743 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1744}
1745
1746ASTContext::PointerAuthContent
1747ASTContext::findPointerAuthContent(QualType T) const {
1748 assert(isPointerAuthenticationAvailable());
1749
1750 T = T.getCanonicalType();
1751 if (T->isDependentType())
1752 return PointerAuthContent::None;
1753
1754 if (T.hasAddressDiscriminatedPointerAuth())
1755 return PointerAuthContent::AddressDiscriminatedData;
1756 const RecordDecl *RD = T->getAsRecordDecl();
1757 if (!RD)
1758 return PointerAuthContent::None;
1759
1760 if (RD->isInvalidDecl())
1761 return PointerAuthContent::None;
1762
1763 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1764 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1765 return Existing->second;
1766
1767 PointerAuthContent Result = PointerAuthContent::None;
1768
1769 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1770 auto [ResultIter, DidAdd] =
1771 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1772 (void)ResultIter;
1773 (void)DidAdd;
1774 assert(DidAdd);
1775 return Result;
1776 };
1777 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1778 static_assert(PointerAuthContent::None <
1779 PointerAuthContent::AddressDiscriminatedVTable);
1780 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1781 PointerAuthContent::AddressDiscriminatedData);
1782 if (NewResult > Result)
1783 Result = NewResult;
1784 return Result != PointerAuthContent::AddressDiscriminatedData;
1785 };
1786 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1787 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1788 !ShouldContinueAfterUpdate(
1789 PointerAuthContent::AddressDiscriminatedVTable))
1790 return SaveResultAndReturn();
1791 for (auto Base : CXXRD->bases()) {
1792 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1793 return SaveResultAndReturn();
1794 }
1795 }
1796 for (auto *FieldDecl : RD->fields()) {
1797 if (!ShouldContinueAfterUpdate(
1798 findPointerAuthContent(T: FieldDecl->getType())))
1799 return SaveResultAndReturn();
1800 }
1801 return SaveResultAndReturn();
1802}
1803
1804void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1805 assert(!Import->getNextLocalImport() &&
1806 "Import declaration already in the chain");
1807 assert(!Import->isFromASTFile() && "Non-local import declaration");
1808 if (!FirstLocalImport) {
1809 FirstLocalImport = Import;
1810 LastLocalImport = Import;
1811 return;
1812 }
1813
1814 LastLocalImport->setNextLocalImport(Import);
1815 LastLocalImport = Import;
1816}
1817
1818//===----------------------------------------------------------------------===//
1819// Type Sizing and Analysis
1820//===----------------------------------------------------------------------===//
1821
1822/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1823/// scalar floating point type.
1824const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1825 switch (T->castAs<BuiltinType>()->getKind()) {
1826 default:
1827 llvm_unreachable("Not a floating point type!");
1828 case BuiltinType::BFloat16:
1829 return Target->getBFloat16Format();
1830 case BuiltinType::Float16:
1831 return Target->getHalfFormat();
1832 case BuiltinType::Half:
1833 return Target->getHalfFormat();
1834 case BuiltinType::Float: return Target->getFloatFormat();
1835 case BuiltinType::Double: return Target->getDoubleFormat();
1836 case BuiltinType::Ibm128:
1837 return Target->getIbm128Format();
1838 case BuiltinType::LongDouble:
1839 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1840 return AuxTarget->getLongDoubleFormat();
1841 return Target->getLongDoubleFormat();
1842 case BuiltinType::Float128:
1843 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1844 return AuxTarget->getFloat128Format();
1845 return Target->getFloat128Format();
1846 }
1847}
1848
1849CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1850 unsigned Align = Target->getCharWidth();
1851
1852 const unsigned AlignFromAttr = D->getMaxAlignment();
1853 if (AlignFromAttr)
1854 Align = AlignFromAttr;
1855
1856 // __attribute__((aligned)) can increase or decrease alignment
1857 // *except* on a struct or struct member, where it only increases
1858 // alignment unless 'packed' is also specified.
1859 //
1860 // It is an error for alignas to decrease alignment, so we can
1861 // ignore that possibility; Sema should diagnose it.
1862 bool UseAlignAttrOnly;
1863 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1864 UseAlignAttrOnly =
1865 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1866 else
1867 UseAlignAttrOnly = AlignFromAttr != 0;
1868 // If we're using the align attribute only, just ignore everything
1869 // else about the declaration and its type.
1870 if (UseAlignAttrOnly) {
1871 // do nothing
1872 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1873 QualType T = VD->getType();
1874 if (const auto *RT = T->getAs<ReferenceType>()) {
1875 if (ForAlignof)
1876 T = RT->getPointeeType();
1877 else
1878 T = getPointerType(T: RT->getPointeeType());
1879 }
1880 QualType BaseT = getBaseElementType(QT: T);
1881 if (T->isFunctionType())
1882 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1883 else if (!BaseT->isIncompleteType()) {
1884 // Adjust alignments of declarations with array type by the
1885 // large-array alignment on the target.
1886 if (const ArrayType *arrayType = getAsArrayType(T)) {
1887 unsigned MinWidth = Target->getLargeArrayMinWidth();
1888 if (!ForAlignof && MinWidth) {
1889 if (isa<VariableArrayType>(Val: arrayType))
1890 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1891 else if (isa<ConstantArrayType>(Val: arrayType) &&
1892 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1893 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1894 }
1895 }
1896 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1897 if (BaseT.getQualifiers().hasUnaligned())
1898 Align = Target->getCharWidth();
1899 }
1900
1901 // Ensure minimum alignment for global variables.
1902 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1903 if (VD->hasGlobalStorage() && !ForAlignof) {
1904 uint64_t TypeSize =
1905 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1906 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1907 }
1908
1909 // Fields can be subject to extra alignment constraints, like if
1910 // the field is packed, the struct is packed, or the struct has a
1911 // a max-field-alignment constraint (#pragma pack). So calculate
1912 // the actual alignment of the field within the struct, and then
1913 // (as we're expected to) constrain that by the alignment of the type.
1914 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1915 const RecordDecl *Parent = Field->getParent();
1916 // We can only produce a sensible answer if the record is valid.
1917 if (!Parent->isInvalidDecl()) {
1918 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1919
1920 // Start with the record's overall alignment.
1921 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1922
1923 // Use the GCD of that and the offset within the record.
1924 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1925 if (Offset > 0) {
1926 // Alignment is always a power of 2, so the GCD will be a power of 2,
1927 // which means we get to do this crazy thing instead of Euclid's.
1928 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1929 if (LowBitOfOffset < FieldAlign)
1930 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1931 }
1932
1933 Align = std::min(a: Align, b: FieldAlign);
1934 }
1935 }
1936 }
1937
1938 // Some targets have hard limitation on the maximum requestable alignment in
1939 // aligned attribute for static variables.
1940 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1941 const auto *VD = dyn_cast<VarDecl>(Val: D);
1942 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1943 Align = std::min(a: Align, b: MaxAlignedAttr);
1944
1945 return toCharUnitsFromBits(BitSize: Align);
1946}
1947
1948CharUnits ASTContext::getExnObjectAlignment() const {
1949 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1950}
1951
1952// getTypeInfoDataSizeInChars - Return the size of a type, in
1953// chars. If the type is a record, its data size is returned. This is
1954// the size of the memcpy that's performed when assigning this type
1955// using a trivial copy/move assignment operator.
1956TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1957 TypeInfoChars Info = getTypeInfoInChars(T);
1958
1959 // In C++, objects can sometimes be allocated into the tail padding
1960 // of a base-class subobject. We decide whether that's possible
1961 // during class layout, so here we can just trust the layout results.
1962 if (getLangOpts().CPlusPlus) {
1963 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1964 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1965 Info.Width = layout.getDataSize();
1966 }
1967 }
1968
1969 return Info;
1970}
1971
1972/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1973/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1974TypeInfoChars
1975static getConstantArrayInfoInChars(const ASTContext &Context,
1976 const ConstantArrayType *CAT) {
1977 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1978 uint64_t Size = CAT->getZExtSize();
1979 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1980 (uint64_t)(-1)/Size) &&
1981 "Overflow in array type char size evaluation");
1982 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1983 unsigned Align = EltInfo.Align.getQuantity();
1984 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1985 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
1986 Width = llvm::alignTo(Value: Width, Align);
1987 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
1988 CharUnits::fromQuantity(Quantity: Align),
1989 EltInfo.AlignRequirement);
1990}
1991
1992TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1993 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
1994 return getConstantArrayInfoInChars(Context: *this, CAT);
1995 TypeInfo Info = getTypeInfo(T);
1996 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
1997 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
1998}
1999
2000TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2001 return getTypeInfoInChars(T: T.getTypePtr());
2002}
2003
2004bool ASTContext::isPromotableIntegerType(QualType T) const {
2005 // HLSL doesn't promote all small integer types to int, it
2006 // just uses the rank-based promotion rules for all types.
2007 if (getLangOpts().HLSL)
2008 return false;
2009
2010 if (const auto *BT = T->getAs<BuiltinType>())
2011 switch (BT->getKind()) {
2012 case BuiltinType::Bool:
2013 case BuiltinType::Char_S:
2014 case BuiltinType::Char_U:
2015 case BuiltinType::SChar:
2016 case BuiltinType::UChar:
2017 case BuiltinType::Short:
2018 case BuiltinType::UShort:
2019 case BuiltinType::WChar_S:
2020 case BuiltinType::WChar_U:
2021 case BuiltinType::Char8:
2022 case BuiltinType::Char16:
2023 case BuiltinType::Char32:
2024 return true;
2025 default:
2026 return false;
2027 }
2028
2029 // Enumerated types are promotable to their compatible integer types
2030 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2031 if (const auto *ED = T->getAsEnumDecl()) {
2032 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2033 ED->isScoped())
2034 return false;
2035
2036 return true;
2037 }
2038
2039 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2040 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2041 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2042 }
2043
2044 return false;
2045}
2046
2047bool ASTContext::isAlignmentRequired(const Type *T) const {
2048 return getTypeInfo(T).isAlignRequired();
2049}
2050
2051bool ASTContext::isAlignmentRequired(QualType T) const {
2052 return isAlignmentRequired(T: T.getTypePtr());
2053}
2054
2055unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2056 bool NeedsPreferredAlignment) const {
2057 // An alignment on a typedef overrides anything else.
2058 if (const auto *TT = T->getAs<TypedefType>())
2059 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2060 return Align;
2061
2062 // If we have an (array of) complete type, we're done.
2063 T = getBaseElementType(QT: T);
2064 if (!T->isIncompleteType())
2065 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2066
2067 // If we had an array type, its element type might be a typedef
2068 // type with an alignment attribute.
2069 if (const auto *TT = T->getAs<TypedefType>())
2070 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2071 return Align;
2072
2073 // Otherwise, see if the declaration of the type had an attribute.
2074 if (const auto *TD = T->getAsTagDecl())
2075 return TD->getMaxAlignment();
2076
2077 return 0;
2078}
2079
2080TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2081 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2082 if (I != MemoizedTypeInfo.end())
2083 return I->second;
2084
2085 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2086 TypeInfo TI = getTypeInfoImpl(T);
2087 MemoizedTypeInfo[T] = TI;
2088 return TI;
2089}
2090
2091/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2092/// method does not work on incomplete types.
2093///
2094/// FIXME: Pointers into different addr spaces could have different sizes and
2095/// alignment requirements: getPointerInfo should take an AddrSpace, this
2096/// should take a QualType, &c.
2097TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2098 uint64_t Width = 0;
2099 unsigned Align = 8;
2100 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2101 LangAS AS = LangAS::Default;
2102 switch (T->getTypeClass()) {
2103#define TYPE(Class, Base)
2104#define ABSTRACT_TYPE(Class, Base)
2105#define NON_CANONICAL_TYPE(Class, Base)
2106#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2107#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2108 case Type::Class: \
2109 assert(!T->isDependentType() && "should not see dependent types here"); \
2110 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2111#include "clang/AST/TypeNodes.inc"
2112 llvm_unreachable("Should not see dependent types");
2113
2114 case Type::FunctionNoProto:
2115 case Type::FunctionProto:
2116 // GCC extension: alignof(function) = 32 bits
2117 Width = 0;
2118 Align = 32;
2119 break;
2120
2121 case Type::IncompleteArray:
2122 case Type::VariableArray:
2123 case Type::ConstantArray:
2124 case Type::ArrayParameter: {
2125 // Model non-constant sized arrays as size zero, but track the alignment.
2126 uint64_t Size = 0;
2127 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2128 Size = CAT->getZExtSize();
2129
2130 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2131 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2132 "Overflow in array type bit size evaluation");
2133 Width = EltInfo.Width * Size;
2134 Align = EltInfo.Align;
2135 AlignRequirement = EltInfo.AlignRequirement;
2136 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2137 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2138 Width = llvm::alignTo(Value: Width, Align);
2139 break;
2140 }
2141
2142 case Type::ExtVector:
2143 case Type::Vector: {
2144 const auto *VT = cast<VectorType>(Val: T);
2145 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2146 Width = VT->isPackedVectorBoolType(ctx: *this)
2147 ? VT->getNumElements()
2148 : EltInfo.Width * VT->getNumElements();
2149 // Enforce at least byte size and alignment.
2150 Width = std::max<unsigned>(a: 8, b: Width);
2151 Align = std::max<unsigned>(
2152 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2153
2154 // If the alignment is not a power of 2, round up to the next power of 2.
2155 // This happens for non-power-of-2 length vectors.
2156 if (Align & (Align-1)) {
2157 Align = llvm::bit_ceil(Value: Align);
2158 Width = llvm::alignTo(Value: Width, Align);
2159 }
2160 // Adjust the alignment based on the target max.
2161 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2162 if (TargetVectorAlign && TargetVectorAlign < Align)
2163 Align = TargetVectorAlign;
2164 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2165 // Adjust the alignment for fixed-length SVE vectors. This is important
2166 // for non-power-of-2 vector lengths.
2167 Align = 128;
2168 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2169 // Adjust the alignment for fixed-length SVE predicates.
2170 Align = 16;
2171 else if (isRVVFixedLengthVectorKind(VK: VT->getVectorKind()))
2172 // Adjust the alignment for fixed-length RVV vectors.
2173 Align = std::min<unsigned>(a: 64, b: Width);
2174 // Vector types have their natural alignment resist reduction by
2175 // #pragma pack in MSVC record layout.
2176 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2177 break;
2178 }
2179
2180 case Type::ConstantMatrix: {
2181 const auto *MT = cast<ConstantMatrixType>(Val: T);
2182 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2183 // The internal layout of a matrix value is implementation defined.
2184 // Initially be ABI compatible with arrays with respect to alignment and
2185 // size.
2186 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2187 Align = ElementInfo.Align;
2188 break;
2189 }
2190
2191 case Type::Builtin:
2192 switch (cast<BuiltinType>(Val: T)->getKind()) {
2193 default: llvm_unreachable("Unknown builtin type!");
2194 case BuiltinType::Void:
2195 // GCC extension: alignof(void) = 8 bits.
2196 Width = 0;
2197 Align = 8;
2198 break;
2199 case BuiltinType::Bool:
2200 Width = Target->getBoolWidth();
2201 Align = Target->getBoolAlign();
2202 break;
2203 case BuiltinType::Char_S:
2204 case BuiltinType::Char_U:
2205 case BuiltinType::UChar:
2206 case BuiltinType::SChar:
2207 case BuiltinType::Char8:
2208 Width = Target->getCharWidth();
2209 Align = Target->getCharAlign();
2210 break;
2211 case BuiltinType::WChar_S:
2212 case BuiltinType::WChar_U:
2213 Width = Target->getWCharWidth();
2214 Align = Target->getWCharAlign();
2215 break;
2216 case BuiltinType::Char16:
2217 Width = Target->getChar16Width();
2218 Align = Target->getChar16Align();
2219 break;
2220 case BuiltinType::Char32:
2221 Width = Target->getChar32Width();
2222 Align = Target->getChar32Align();
2223 break;
2224 case BuiltinType::UShort:
2225 case BuiltinType::Short:
2226 Width = Target->getShortWidth();
2227 Align = Target->getShortAlign();
2228 break;
2229 case BuiltinType::UInt:
2230 case BuiltinType::Int:
2231 Width = Target->getIntWidth();
2232 Align = Target->getIntAlign();
2233 break;
2234 case BuiltinType::ULong:
2235 case BuiltinType::Long:
2236 Width = Target->getLongWidth();
2237 Align = Target->getLongAlign();
2238 break;
2239 case BuiltinType::ULongLong:
2240 case BuiltinType::LongLong:
2241 Width = Target->getLongLongWidth();
2242 Align = Target->getLongLongAlign();
2243 break;
2244 case BuiltinType::Int128:
2245 case BuiltinType::UInt128:
2246 Width = 128;
2247 Align = Target->getInt128Align();
2248 break;
2249 case BuiltinType::ShortAccum:
2250 case BuiltinType::UShortAccum:
2251 case BuiltinType::SatShortAccum:
2252 case BuiltinType::SatUShortAccum:
2253 Width = Target->getShortAccumWidth();
2254 Align = Target->getShortAccumAlign();
2255 break;
2256 case BuiltinType::Accum:
2257 case BuiltinType::UAccum:
2258 case BuiltinType::SatAccum:
2259 case BuiltinType::SatUAccum:
2260 Width = Target->getAccumWidth();
2261 Align = Target->getAccumAlign();
2262 break;
2263 case BuiltinType::LongAccum:
2264 case BuiltinType::ULongAccum:
2265 case BuiltinType::SatLongAccum:
2266 case BuiltinType::SatULongAccum:
2267 Width = Target->getLongAccumWidth();
2268 Align = Target->getLongAccumAlign();
2269 break;
2270 case BuiltinType::ShortFract:
2271 case BuiltinType::UShortFract:
2272 case BuiltinType::SatShortFract:
2273 case BuiltinType::SatUShortFract:
2274 Width = Target->getShortFractWidth();
2275 Align = Target->getShortFractAlign();
2276 break;
2277 case BuiltinType::Fract:
2278 case BuiltinType::UFract:
2279 case BuiltinType::SatFract:
2280 case BuiltinType::SatUFract:
2281 Width = Target->getFractWidth();
2282 Align = Target->getFractAlign();
2283 break;
2284 case BuiltinType::LongFract:
2285 case BuiltinType::ULongFract:
2286 case BuiltinType::SatLongFract:
2287 case BuiltinType::SatULongFract:
2288 Width = Target->getLongFractWidth();
2289 Align = Target->getLongFractAlign();
2290 break;
2291 case BuiltinType::BFloat16:
2292 if (Target->hasBFloat16Type()) {
2293 Width = Target->getBFloat16Width();
2294 Align = Target->getBFloat16Align();
2295 } else if ((getLangOpts().SYCLIsDevice ||
2296 (getLangOpts().OpenMP &&
2297 getLangOpts().OpenMPIsTargetDevice)) &&
2298 AuxTarget->hasBFloat16Type()) {
2299 Width = AuxTarget->getBFloat16Width();
2300 Align = AuxTarget->getBFloat16Align();
2301 }
2302 break;
2303 case BuiltinType::Float16:
2304 case BuiltinType::Half:
2305 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2306 !getLangOpts().OpenMPIsTargetDevice) {
2307 Width = Target->getHalfWidth();
2308 Align = Target->getHalfAlign();
2309 } else {
2310 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2311 "Expected OpenMP device compilation.");
2312 Width = AuxTarget->getHalfWidth();
2313 Align = AuxTarget->getHalfAlign();
2314 }
2315 break;
2316 case BuiltinType::Float:
2317 Width = Target->getFloatWidth();
2318 Align = Target->getFloatAlign();
2319 break;
2320 case BuiltinType::Double:
2321 Width = Target->getDoubleWidth();
2322 Align = Target->getDoubleAlign();
2323 break;
2324 case BuiltinType::Ibm128:
2325 Width = Target->getIbm128Width();
2326 Align = Target->getIbm128Align();
2327 break;
2328 case BuiltinType::LongDouble:
2329 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2330 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2331 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2332 Width = AuxTarget->getLongDoubleWidth();
2333 Align = AuxTarget->getLongDoubleAlign();
2334 } else {
2335 Width = Target->getLongDoubleWidth();
2336 Align = Target->getLongDoubleAlign();
2337 }
2338 // x87 extended precision (fp80) has its natural alignment resist
2339 // reduction by #pragma pack in MSVC record layout.
2340 if (&Target->getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
2341 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2342 break;
2343 case BuiltinType::Float128:
2344 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2345 !getLangOpts().OpenMPIsTargetDevice) {
2346 Width = Target->getFloat128Width();
2347 Align = Target->getFloat128Align();
2348 } else {
2349 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2350 "Expected OpenMP device compilation.");
2351 Width = AuxTarget->getFloat128Width();
2352 Align = AuxTarget->getFloat128Align();
2353 }
2354 break;
2355 case BuiltinType::NullPtr:
2356 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2357 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2358 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2359 break;
2360 case BuiltinType::MetaInfo:
2361 // sizeof(std::meta::info) == sizeof(void*)
2362 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2363 // alignof(std::meta::info) == alignof(void*)
2364 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2365 break;
2366 case BuiltinType::ObjCId:
2367 case BuiltinType::ObjCClass:
2368 case BuiltinType::ObjCSel:
2369 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2370 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2371 break;
2372 case BuiltinType::OCLSampler:
2373 case BuiltinType::OCLEvent:
2374 case BuiltinType::OCLClkEvent:
2375 case BuiltinType::OCLQueue:
2376 case BuiltinType::OCLReserveID:
2377#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2378 case BuiltinType::Id:
2379#include "clang/Basic/OpenCLImageTypes.def"
2380#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2381 case BuiltinType::Id:
2382#include "clang/Basic/OpenCLExtensionTypes.def"
2383 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2384 Width = Target->getPointerWidth(AddrSpace: AS);
2385 Align = Target->getPointerAlign(AddrSpace: AS);
2386 break;
2387 // The SVE types are effectively target-specific. The length of an
2388 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2389 // of 128 bits. There is one predicate bit for each vector byte, so the
2390 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2391 //
2392 // Because the length is only known at runtime, we use a dummy value
2393 // of 0 for the static length. The alignment values are those defined
2394 // by the Procedure Call Standard for the Arm Architecture.
2395#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2396 case BuiltinType::Id: \
2397 Width = 0; \
2398 Align = 128; \
2399 break;
2400#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2401 case BuiltinType::Id: \
2402 Width = 0; \
2403 Align = 16; \
2404 break;
2405#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2406 case BuiltinType::Id: \
2407 Width = 0; \
2408 Align = 16; \
2409 break;
2410#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2411 case BuiltinType::Id: \
2412 Width = Bits; \
2413 Align = Bits; \
2414 break;
2415#include "clang/Basic/AArch64ACLETypes.def"
2416#define PPC_VECTOR_TYPE(Name, Id, Size) \
2417 case BuiltinType::Id: \
2418 Width = Size; \
2419 Align = Size; \
2420 break;
2421#include "clang/Basic/PPCTypes.def"
2422#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2423 IsFP, IsBF) \
2424 case BuiltinType::Id: \
2425 Width = 0; \
2426 Align = ElBits; \
2427 break;
2428#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2429 case BuiltinType::Id: \
2430 Width = 0; \
2431 Align = 8; \
2432 break;
2433#include "clang/Basic/RISCVVTypes.def"
2434#define WASM_TYPE(Name, Id, SingletonId) \
2435 case BuiltinType::Id: \
2436 Width = 0; \
2437 Align = 8; \
2438 break;
2439#include "clang/Basic/WebAssemblyReferenceTypes.def"
2440#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2441 case BuiltinType::ID: \
2442 Width = WIDTH; \
2443 Align = ALIGN; \
2444 break;
2445#include "clang/Basic/AMDGPUTypes.def"
2446#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2447#include "clang/Basic/HLSLIntangibleTypes.def"
2448 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2449 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2450 break;
2451#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2452#include "clang/Basic/HLSLPackedTypes.def"
2453 Width = 32;
2454 Align = 32;
2455 break;
2456#define SPIRV_TYPE(Name, Id, SingletonId) \
2457 case BuiltinType::Id: \
2458 Width = Target->getPointerWidth(LangAS::Default); \
2459 Align = Target->getPointerAlign(LangAS::Default); \
2460 break;
2461#include "clang/Basic/SPIRVTypes.def"
2462 }
2463 break;
2464 case Type::ObjCObjectPointer:
2465 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2466 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2467 break;
2468 case Type::BlockPointer:
2469 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AddrSpace: AS);
2471 Align = Target->getPointerAlign(AddrSpace: AS);
2472 break;
2473 case Type::LValueReference:
2474 case Type::RValueReference:
2475 // alignof and sizeof should never enter this code path here, so we go
2476 // the pointer route.
2477 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2478 Width = Target->getPointerWidth(AddrSpace: AS);
2479 Align = Target->getPointerAlign(AddrSpace: AS);
2480 break;
2481 case Type::Pointer:
2482 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2483 Width = Target->getPointerWidth(AddrSpace: AS);
2484 Align = Target->getPointerAlign(AddrSpace: AS);
2485 break;
2486 case Type::MemberPointer: {
2487 const auto *MPT = cast<MemberPointerType>(Val: T);
2488 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2489 Width = MPI.Width;
2490 Align = MPI.Align;
2491 break;
2492 }
2493 case Type::Complex: {
2494 // Complex types have the same alignment as their elements, but twice the
2495 // size.
2496 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2497 Width = EltInfo.Width * 2;
2498 Align = EltInfo.Align;
2499 break;
2500 }
2501 case Type::ObjCObject:
2502 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2503 case Type::Adjusted:
2504 case Type::Decayed:
2505 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2506 case Type::ObjCInterface: {
2507 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2508 if (ObjCI->getDecl()->isInvalidDecl()) {
2509 Width = 8;
2510 Align = 8;
2511 break;
2512 }
2513 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2514 Width = toBits(CharSize: Layout.getSize());
2515 Align = toBits(CharSize: Layout.getAlignment());
2516 break;
2517 }
2518 case Type::BitInt: {
2519 const auto *EIT = cast<BitIntType>(Val: T);
2520 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2521 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2522 break;
2523 }
2524 case Type::Record:
2525 case Type::Enum: {
2526 const auto *TT = cast<TagType>(Val: T);
2527 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2528
2529 if (TD->isInvalidDecl()) {
2530 Width = 8;
2531 Align = 8;
2532 break;
2533 }
2534
2535 if (isa<EnumType>(Val: TT)) {
2536 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2537 TypeInfo Info =
2538 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2539 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2540 Info.Align = AttrAlign;
2541 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2542 }
2543 return Info;
2544 }
2545
2546 const auto *RD = cast<RecordDecl>(Val: TD);
2547 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2548 Width = toBits(CharSize: Layout.getSize());
2549 Align = toBits(CharSize: Layout.getAlignment());
2550 AlignRequirement = RD->hasAttr<AlignedAttr>()
2551 ? AlignRequirementKind::RequiredByRecord
2552 : AlignRequirementKind::None;
2553 break;
2554 }
2555
2556 case Type::SubstTemplateTypeParm:
2557 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2558 getReplacementType().getTypePtr());
2559
2560 case Type::Auto:
2561 case Type::DeducedTemplateSpecialization: {
2562 const auto *A = cast<DeducedType>(Val: T);
2563 assert(!A->getDeducedType().isNull() &&
2564 "cannot request the size of an undeduced or dependent auto type");
2565 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2566 }
2567
2568 case Type::Paren:
2569 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2570
2571 case Type::MacroQualified:
2572 return getTypeInfo(
2573 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2574
2575 case Type::ObjCTypeParam:
2576 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2577
2578 case Type::Using:
2579 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2580
2581 case Type::Typedef: {
2582 const auto *TT = cast<TypedefType>(Val: T);
2583 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2584 // If the typedef has an aligned attribute on it, it overrides any computed
2585 // alignment we have. This violates the GCC documentation (which says that
2586 // attribute(aligned) can only round up) but matches its implementation.
2587 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2588 Align = AttrAlign;
2589 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2590 } else {
2591 Align = Info.Align;
2592 AlignRequirement = Info.AlignRequirement;
2593 }
2594 Width = Info.Width;
2595 break;
2596 }
2597
2598 case Type::Attributed:
2599 return getTypeInfo(
2600 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2601
2602 case Type::CountAttributed:
2603 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2604
2605 case Type::LateParsedAttr:
2606 return getTypeInfo(T: cast<LateParsedAttrType>(Val: T)->desugar().getTypePtr());
2607
2608 case Type::BTFTagAttributed:
2609 return getTypeInfo(
2610 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2611
2612 case Type::OverflowBehavior:
2613 return getTypeInfo(
2614 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2615
2616 case Type::HLSLAttributedResource:
2617 return getTypeInfo(
2618 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2619
2620 case Type::HLSLInlineSpirv: {
2621 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2622 // Size is specified in bytes, convert to bits
2623 Width = ST->getSize() * 8;
2624 Align = ST->getAlignment();
2625 if (Width == 0 && Align == 0) {
2626 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2627 Width = 32;
2628 Align = 32;
2629 }
2630 break;
2631 }
2632
2633 case Type::Atomic: {
2634 // Start with the base type information.
2635 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2636 Width = Info.Width;
2637 Align = Info.Align;
2638
2639 if (!Width) {
2640 // An otherwise zero-sized type should still generate an
2641 // atomic operation.
2642 Width = Target->getCharWidth();
2643 assert(Align);
2644 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2645 // If the size of the type doesn't exceed the platform's max
2646 // atomic promotion width, make the size and alignment more
2647 // favorable to atomic operations:
2648
2649 // Round the size up to a power of 2.
2650 Width = llvm::bit_ceil(Value: Width);
2651
2652 // Set the alignment equal to the size.
2653 Align = static_cast<unsigned>(Width);
2654 }
2655 }
2656 break;
2657
2658 case Type::PredefinedSugar:
2659 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2660
2661 case Type::Pipe:
2662 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2663 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2664 break;
2665 }
2666
2667 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2668 return TypeInfo(Width, Align, AlignRequirement);
2669}
2670
2671unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2672 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2673 if (I != MemoizedUnadjustedAlign.end())
2674 return I->second;
2675
2676 unsigned UnadjustedAlign;
2677 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2678 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2679 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2680 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2681 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2682 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2683 } else {
2684 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2685 }
2686
2687 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2688 return UnadjustedAlign;
2689}
2690
2691unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2692 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2693 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2694 return SimdAlign;
2695}
2696
2697/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2698CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2699 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2700}
2701
2702/// toBits - Convert a size in characters to a size in characters.
2703int64_t ASTContext::toBits(CharUnits CharSize) const {
2704 return CharSize.getQuantity() * getCharWidth();
2705}
2706
2707/// getTypeSizeInChars - Return the size of the specified type, in characters.
2708/// This method does not work on incomplete types.
2709CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2710 return getTypeInfoInChars(T).Width;
2711}
2712CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2713 return getTypeInfoInChars(T).Width;
2714}
2715
2716/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2717/// characters. This method does not work on incomplete types.
2718CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2719 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2720}
2721CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2722 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2723}
2724
2725/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2726/// type, in characters, before alignment adjustments. This method does
2727/// not work on incomplete types.
2728CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2729 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2730}
2731CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2732 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2733}
2734
2735/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2736/// type for the current target in bits. This can be different than the ABI
2737/// alignment in cases where it is beneficial for performance or backwards
2738/// compatibility preserving to overalign a data type. (Note: despite the name,
2739/// the preferred alignment is ABI-impacting, and not an optimization.)
2740unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2741 TypeInfo TI = getTypeInfo(T);
2742 unsigned ABIAlign = TI.Align;
2743
2744 T = T->getBaseElementTypeUnsafe();
2745
2746 // The preferred alignment of member pointers is that of a pointer.
2747 if (T->isMemberPointerType())
2748 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2749
2750 if (!Target->allowsLargerPreferedTypeAlignment())
2751 return ABIAlign;
2752
2753 if (const auto *RD = T->getAsRecordDecl()) {
2754 // When used as part of a typedef, or together with a 'packed' attribute,
2755 // the 'aligned' attribute can be used to decrease alignment. Note that the
2756 // 'packed' case is already taken into consideration when computing the
2757 // alignment, we only need to handle the typedef case here.
2758 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2759 RD->isInvalidDecl())
2760 return ABIAlign;
2761
2762 unsigned PreferredAlign = static_cast<unsigned>(
2763 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2764 assert(PreferredAlign >= ABIAlign &&
2765 "PreferredAlign should be at least as large as ABIAlign.");
2766 return PreferredAlign;
2767 }
2768
2769 // Double (and, for targets supporting AIX `power` alignment, long double) and
2770 // long long should be naturally aligned (despite requiring less alignment) if
2771 // possible.
2772 if (const auto *CT = T->getAs<ComplexType>())
2773 T = CT->getElementType().getTypePtr();
2774 if (const auto *ED = T->getAsEnumDecl())
2775 T = ED->getIntegerType().getTypePtr();
2776 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2777 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2778 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2779 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2780 Target->defaultsToAIXPowerAlignment()))
2781 // Don't increase the alignment if an alignment attribute was specified on a
2782 // typedef declaration.
2783 if (!TI.isAlignRequired())
2784 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2785
2786 return ABIAlign;
2787}
2788
2789/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2790/// for __attribute__((aligned)) on this target, to be used if no alignment
2791/// value is specified.
2792unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2793 return getTargetInfo().getDefaultAlignForAttributeAligned();
2794}
2795
2796/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2797/// to a global variable of the specified type.
2798unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2799 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2800 return std::max(a: getPreferredTypeAlign(T),
2801 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2802}
2803
2804/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2805/// should be given to a global variable of the specified type.
2806CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2807 const VarDecl *VD) const {
2808 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2809}
2810
2811unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2812 const VarDecl *VD) const {
2813 // Make the default handling as that of a non-weak definition in the
2814 // current translation unit.
2815 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2816 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2817}
2818
2819CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2820 CharUnits Offset = CharUnits::Zero();
2821 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2822 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2823 Offset += Layout->getBaseClassOffset(Base);
2824 Layout = &getASTRecordLayout(D: Base);
2825 }
2826 return Offset;
2827}
2828
2829CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2830 const ValueDecl *MPD = MP.getMemberPointerDecl();
2831 CharUnits ThisAdjustment = CharUnits::Zero();
2832 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2833 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2834 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2835 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2836 const CXXRecordDecl *Base = RD;
2837 const CXXRecordDecl *Derived = Path[I];
2838 if (DerivedMember)
2839 std::swap(a&: Base, b&: Derived);
2840 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2841 RD = Path[I];
2842 }
2843 if (DerivedMember)
2844 ThisAdjustment = -ThisAdjustment;
2845 return ThisAdjustment;
2846}
2847
2848/// DeepCollectObjCIvars -
2849/// This routine first collects all declared, but not synthesized, ivars in
2850/// super class and then collects all ivars, including those synthesized for
2851/// current class. This routine is used for implementation of current class
2852/// when all ivars, declared and synthesized are known.
2853void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2854 bool leafClass,
2855 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2856 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2857 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2858 if (!leafClass) {
2859 llvm::append_range(C&: Ivars, R: OI->ivars());
2860 } else {
2861 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2862 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2863 Iv= Iv->getNextIvar())
2864 Ivars.push_back(Elt: Iv);
2865 }
2866}
2867
2868/// CollectInheritedProtocols - Collect all protocols in current class and
2869/// those inherited by it.
2870void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2871 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2872 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2873 // We can use protocol_iterator here instead of
2874 // all_referenced_protocol_iterator since we are walking all categories.
2875 for (auto *Proto : OI->all_referenced_protocols()) {
2876 CollectInheritedProtocols(CDecl: Proto, Protocols);
2877 }
2878
2879 // Categories of this Interface.
2880 for (const auto *Cat : OI->visible_categories())
2881 CollectInheritedProtocols(CDecl: Cat, Protocols);
2882
2883 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2884 while (SD) {
2885 CollectInheritedProtocols(CDecl: SD, Protocols);
2886 SD = SD->getSuperClass();
2887 }
2888 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2889 for (auto *Proto : OC->protocols()) {
2890 CollectInheritedProtocols(CDecl: Proto, Protocols);
2891 }
2892 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2893 // Insert the protocol.
2894 if (!Protocols.insert(
2895 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2896 return;
2897
2898 for (auto *Proto : OP->protocols())
2899 CollectInheritedProtocols(CDecl: Proto, Protocols);
2900 }
2901}
2902
2903static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2904 const RecordDecl *RD,
2905 bool CheckIfTriviallyCopyable) {
2906 assert(RD->isUnion() && "Must be union type");
2907 CharUnits UnionSize =
2908 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2909
2910 for (const auto *Field : RD->fields()) {
2911 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2912 CheckIfTriviallyCopyable))
2913 return false;
2914 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2915 if (FieldSize != UnionSize)
2916 return false;
2917 }
2918 return !RD->field_empty();
2919}
2920
2921static int64_t getSubobjectOffset(const FieldDecl *Field,
2922 const ASTContext &Context,
2923 const clang::ASTRecordLayout & /*Layout*/) {
2924 return Context.getFieldOffset(FD: Field);
2925}
2926
2927static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2928 const ASTContext &Context,
2929 const clang::ASTRecordLayout &Layout) {
2930 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2931}
2932
2933static std::optional<int64_t>
2934structHasUniqueObjectRepresentations(const ASTContext &Context,
2935 const RecordDecl *RD,
2936 bool CheckIfTriviallyCopyable);
2937
2938static std::optional<int64_t>
2939getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2940 bool CheckIfTriviallyCopyable) {
2941 if (const auto *RD = Field->getType()->getAsRecordDecl();
2942 RD && !RD->isUnion())
2943 return structHasUniqueObjectRepresentations(Context, RD,
2944 CheckIfTriviallyCopyable);
2945
2946 // A _BitInt type may not be unique if it has padding bits
2947 // but if it is a bitfield the padding bits are not used.
2948 bool IsBitIntType = Field->getType()->isBitIntType();
2949 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2950 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2951 CheckIfTriviallyCopyable))
2952 return std::nullopt;
2953
2954 int64_t FieldSizeInBits =
2955 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2956 if (Field->isBitField()) {
2957 // If we have explicit padding bits, they don't contribute bits
2958 // to the actual object representation, so return 0.
2959 if (Field->isUnnamedBitField())
2960 return 0;
2961
2962 int64_t BitfieldSize = Field->getBitWidthValue();
2963 if (IsBitIntType) {
2964 if ((unsigned)BitfieldSize >
2965 cast<BitIntType>(Val: Field->getType())->getNumBits())
2966 return std::nullopt;
2967 } else if (BitfieldSize > FieldSizeInBits) {
2968 return std::nullopt;
2969 }
2970 FieldSizeInBits = BitfieldSize;
2971 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2972 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2973 return std::nullopt;
2974 }
2975 return FieldSizeInBits;
2976}
2977
2978static std::optional<int64_t>
2979getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2980 bool CheckIfTriviallyCopyable) {
2981 return structHasUniqueObjectRepresentations(Context, RD,
2982 CheckIfTriviallyCopyable);
2983}
2984
2985template <typename RangeT>
2986static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2987 const RangeT &Subobjects, int64_t CurOffsetInBits,
2988 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2989 bool CheckIfTriviallyCopyable) {
2990 for (const auto *Subobject : Subobjects) {
2991 std::optional<int64_t> SizeInBits =
2992 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2993 if (!SizeInBits)
2994 return std::nullopt;
2995 if (*SizeInBits != 0) {
2996 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2997 if (Offset != CurOffsetInBits)
2998 return std::nullopt;
2999 CurOffsetInBits += *SizeInBits;
3000 }
3001 }
3002 return CurOffsetInBits;
3003}
3004
3005static std::optional<int64_t>
3006structHasUniqueObjectRepresentations(const ASTContext &Context,
3007 const RecordDecl *RD,
3008 bool CheckIfTriviallyCopyable) {
3009 assert(!RD->isUnion() && "Must be struct/class type");
3010 const auto &Layout = Context.getASTRecordLayout(D: RD);
3011
3012 int64_t CurOffsetInBits = 0;
3013 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3014 if (ClassDecl->isDynamicClass())
3015 return std::nullopt;
3016
3017 SmallVector<CXXRecordDecl *, 4> Bases;
3018 for (const auto &Base : ClassDecl->bases()) {
3019 // Empty types can be inherited from, and non-empty types can potentially
3020 // have tail padding, so just make sure there isn't an error.
3021 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3022 }
3023
3024 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3025 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3026 });
3027
3028 std::optional<int64_t> OffsetAfterBases =
3029 structSubobjectsHaveUniqueObjectRepresentations(
3030 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3031 if (!OffsetAfterBases)
3032 return std::nullopt;
3033 CurOffsetInBits = *OffsetAfterBases;
3034 }
3035
3036 std::optional<int64_t> OffsetAfterFields =
3037 structSubobjectsHaveUniqueObjectRepresentations(
3038 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3039 CheckIfTriviallyCopyable);
3040 if (!OffsetAfterFields)
3041 return std::nullopt;
3042 CurOffsetInBits = *OffsetAfterFields;
3043
3044 return CurOffsetInBits;
3045}
3046
3047bool ASTContext::hasUniqueObjectRepresentations(
3048 QualType Ty, bool CheckIfTriviallyCopyable) const {
3049 // C++17 [meta.unary.prop]:
3050 // The predicate condition for a template specialization
3051 // has_unique_object_representations<T> shall be satisfied if and only if:
3052 // (9.1) - T is trivially copyable, and
3053 // (9.2) - any two objects of type T with the same value have the same
3054 // object representation, where:
3055 // - two objects of array or non-union class type are considered to have
3056 // the same value if their respective sequences of direct subobjects
3057 // have the same values, and
3058 // - two objects of union type are considered to have the same value if
3059 // they have the same active member and the corresponding members have
3060 // the same value.
3061 // The set of scalar types for which this condition holds is
3062 // implementation-defined. [ Note: If a type has padding bits, the condition
3063 // does not hold; otherwise, the condition holds true for unsigned integral
3064 // types. -- end note ]
3065 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3066
3067 // Arrays are unique only if their element type is unique.
3068 if (Ty->isArrayType())
3069 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3070 CheckIfTriviallyCopyable);
3071
3072 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3073 "hasUniqueObjectRepresentations should not be called with an "
3074 "incomplete type");
3075
3076 // _Atomic(T) shares T's object representation unless its size was rounded
3077 // up to a power of two, in which case the extra bytes are padding. Atomic
3078 // types are never trivially copyable, so (9.1) is judged on the value type.
3079 if (const auto *AT = Ty->getAs<AtomicType>())
3080 return getTypeSize(T: AT) == getTypeSize(T: AT->getValueType()) &&
3081 hasUniqueObjectRepresentations(Ty: AT->getValueType(),
3082 CheckIfTriviallyCopyable);
3083
3084 // (9.1) - T is trivially copyable...
3085 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3086 return false;
3087
3088 // All integrals and enums are unique.
3089 if (Ty->isIntegralOrEnumerationType()) {
3090 // Address discriminated integer types are not unique.
3091 if (Ty.hasAddressDiscriminatedPointerAuth())
3092 return false;
3093 // Except _BitInt types that have padding bits.
3094 if (const auto *BIT = Ty->getAs<BitIntType>())
3095 return getTypeSize(T: BIT) == BIT->getNumBits();
3096
3097 return true;
3098 }
3099
3100 // All other pointers are unique.
3101 if (Ty->isPointerType())
3102 return !Ty.hasAddressDiscriminatedPointerAuth();
3103
3104 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3105 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3106
3107 if (const auto *Record = Ty->getAsRecordDecl()) {
3108 if (Record->isInvalidDecl())
3109 return false;
3110
3111 if (Record->isUnion())
3112 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3113 CheckIfTriviallyCopyable);
3114
3115 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3116 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3117
3118 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3119 }
3120
3121 // FIXME: More cases to handle here (list by rsmith):
3122 // vectors (careful about, eg, vector of 3 foo)
3123 // _Complex int and friends
3124 // Obj-C block pointers
3125 // Obj-C object pointers
3126 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3127 // clk_event_t, queue_t, reserve_id_t)
3128 // There're also Obj-C class types and the Obj-C selector type, but I think it
3129 // makes sense for those to return false here.
3130
3131 return false;
3132}
3133
3134unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3135 unsigned count = 0;
3136 // Count ivars declared in class extension.
3137 for (const auto *Ext : OI->known_extensions())
3138 count += Ext->ivar_size();
3139
3140 // Count ivar defined in this class's implementation. This
3141 // includes synthesized ivars.
3142 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3143 count += ImplDecl->ivar_size();
3144
3145 return count;
3146}
3147
3148bool ASTContext::isSentinelNullExpr(const Expr *E) {
3149 if (!E)
3150 return false;
3151
3152 // nullptr_t is always treated as null.
3153 if (E->getType()->isNullPtrType()) return true;
3154
3155 if (E->getType()->isAnyPointerType() &&
3156 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3157 NPC: Expr::NPC_ValueDependentIsNull))
3158 return true;
3159
3160 // Unfortunately, __null has type 'int'.
3161 if (isa<GNUNullExpr>(Val: E)) return true;
3162
3163 return false;
3164}
3165
3166/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3167/// exists.
3168ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3169 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3170 I = ObjCImpls.find(Val: D);
3171 if (I != ObjCImpls.end())
3172 return cast<ObjCImplementationDecl>(Val: I->second);
3173 return nullptr;
3174}
3175
3176/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3177/// exists.
3178ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3179 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3180 I = ObjCImpls.find(Val: D);
3181 if (I != ObjCImpls.end())
3182 return cast<ObjCCategoryImplDecl>(Val: I->second);
3183 return nullptr;
3184}
3185
3186/// Set the implementation of ObjCInterfaceDecl.
3187void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3188 ObjCImplementationDecl *ImplD) {
3189 assert(IFaceD && ImplD && "Passed null params");
3190 ObjCImpls[IFaceD] = ImplD;
3191}
3192
3193/// Set the implementation of ObjCCategoryDecl.
3194void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3195 ObjCCategoryImplDecl *ImplD) {
3196 assert(CatD && ImplD && "Passed null params");
3197 ObjCImpls[CatD] = ImplD;
3198}
3199
3200const ObjCMethodDecl *
3201ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3202 return ObjCMethodRedecls.lookup(Val: MD);
3203}
3204
3205void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3206 const ObjCMethodDecl *Redecl) {
3207 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3208 ObjCMethodRedecls[MD] = Redecl;
3209}
3210
3211const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3212 const NamedDecl *ND) const {
3213 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3214 return ID;
3215 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3216 return CD->getClassInterface();
3217 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3218 return IMD->getClassInterface();
3219
3220 return nullptr;
3221}
3222
3223/// Get the copy initialization expression of VarDecl, or nullptr if
3224/// none exists.
3225BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3226 assert(VD && "Passed null params");
3227 assert(VD->hasAttr<BlocksAttr>() &&
3228 "getBlockVarCopyInits - not __block var");
3229 auto I = BlockVarCopyInits.find(Val: VD);
3230 if (I != BlockVarCopyInits.end())
3231 return I->second;
3232 return {nullptr, false};
3233}
3234
3235/// Set the copy initialization expression of a block var decl.
3236void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3237 bool CanThrow) {
3238 assert(VD && CopyExpr && "Passed null params");
3239 assert(VD->hasAttr<BlocksAttr>() &&
3240 "setBlockVarCopyInits - not __block var");
3241 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3242}
3243
3244TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3245 unsigned DataSize) const {
3246 if (!DataSize)
3247 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3248 else
3249 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3250 "incorrect data size provided to CreateTypeSourceInfo!");
3251
3252 auto *TInfo =
3253 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3254 new (TInfo) TypeSourceInfo(T, DataSize);
3255 return TInfo;
3256}
3257
3258TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3259 SourceLocation L) const {
3260 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3261 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3262 return TSI;
3263}
3264
3265const ASTRecordLayout &
3266ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3267 return getObjCLayout(D);
3268}
3269
3270static auto getCanonicalTemplateArguments(const ASTContext &C,
3271 ArrayRef<TemplateArgument> Args,
3272 bool &AnyNonCanonArgs) {
3273 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3274 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3275 return CanonArgs;
3276}
3277
3278bool ASTContext::canonicalizeTemplateArguments(
3279 MutableArrayRef<TemplateArgument> Args) const {
3280 bool AnyNonCanonArgs = false;
3281 for (auto &Arg : Args) {
3282 TemplateArgument OrigArg = Arg;
3283 Arg = getCanonicalTemplateArgument(Arg);
3284 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3285 }
3286 return AnyNonCanonArgs;
3287}
3288
3289//===----------------------------------------------------------------------===//
3290// Type creation/memoization methods
3291//===----------------------------------------------------------------------===//
3292
3293QualType
3294ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3295 unsigned fastQuals = quals.getFastQualifiers();
3296 quals.removeFastQualifiers();
3297
3298 // Check if we've already instantiated this type.
3299 llvm::FoldingSetNodeID ID;
3300 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3301 llvm::FoldingSetInsertToken Token;
3302 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3303 assert(eq->getQualifiers() == quals);
3304 return QualType(eq, fastQuals);
3305 }
3306
3307 // If the base type is not canonical, make the appropriate canonical type.
3308 QualType canon;
3309 if (!baseType->isCanonicalUnqualified()) {
3310 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3311 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3312 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3313
3314 // Re-find the insert position.
3315 (void)ExtQualNodes.lookup(ID, Token);
3316 }
3317
3318 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3319 ExtQualNodes.insert(N: eq, Token);
3320 return QualType(eq, fastQuals);
3321}
3322
3323QualType ASTContext::getAddrSpaceQualType(QualType T,
3324 LangAS AddressSpace) const {
3325 QualType CanT = getCanonicalType(T);
3326 if (CanT.getAddressSpace() == AddressSpace)
3327 return T;
3328
3329 // If we are composing extended qualifiers together, merge together
3330 // into one ExtQuals node.
3331 QualifierCollector Quals;
3332 const Type *TypeNode = Quals.strip(type: T);
3333
3334 // If this type already has an address space specified, it cannot get
3335 // another one.
3336 assert(!Quals.hasAddressSpace() &&
3337 "Type cannot be in multiple addr spaces!");
3338 Quals.addAddressSpace(space: AddressSpace);
3339
3340 return getExtQualType(baseType: TypeNode, quals: Quals);
3341}
3342
3343QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3344 // If the type is not qualified with an address space, just return it
3345 // immediately.
3346 if (!T.hasAddressSpace())
3347 return T;
3348
3349 QualifierCollector Quals;
3350 const Type *TypeNode;
3351 // For arrays, strip the qualifier off the element type, then reconstruct the
3352 // array type
3353 if (T.getTypePtr()->isArrayType()) {
3354 T = getUnqualifiedArrayType(T, Quals);
3355 TypeNode = T.getTypePtr();
3356 } else {
3357 // If we are composing extended qualifiers together, merge together
3358 // into one ExtQuals node.
3359 while (T.hasAddressSpace()) {
3360 TypeNode = Quals.strip(type: T);
3361
3362 // If the type no longer has an address space after stripping qualifiers,
3363 // jump out.
3364 if (!QualType(TypeNode, 0).hasAddressSpace())
3365 break;
3366
3367 // There might be sugar in the way. Strip it and try again.
3368 T = T.getSingleStepDesugaredType(Context: *this);
3369 }
3370 }
3371
3372 Quals.removeAddressSpace();
3373
3374 // Removal of the address space can mean there are no longer any
3375 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3376 // or required.
3377 if (Quals.hasNonFastQualifiers())
3378 return getExtQualType(baseType: TypeNode, quals: Quals);
3379 else
3380 return QualType(TypeNode, Quals.getFastQualifiers());
3381}
3382
3383uint16_t
3384ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD,
3385 bool IsVTTEntry) {
3386 assert(RD->isPolymorphic() &&
3387 "Attempted to get vtable pointer discriminator on a monomorphic type");
3388
3389 std::unique_ptr<MangleContext> MC(createMangleContext());
3390 SmallString<256> Str;
3391 llvm::raw_svector_ostream Out(Str);
3392 MC->mangleCXXVTable(RD, Out);
3393 if (IsVTTEntry)
3394 Out << VTTVTablePointerDiscriminatorSuffix;
3395 return llvm::getPointerAuthStableSipHash(S: Str);
3396}
3397
3398/// Encode a function type for use in the discriminator of a function pointer
3399/// type. We can't use the itanium scheme for this since C has quite permissive
3400/// rules for type compatibility that we need to be compatible with.
3401///
3402/// Formally, this function associates every function pointer type T with an
3403/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3404/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3405/// compatibility requires equivalent treatment under the ABI, so
3406/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3407/// a subset of ~. Crucially, however, it must be a proper subset because
3408/// CCompatible is not an equivalence relation: for example, int[] is compatible
3409/// with both int[1] and int[2], but the latter are not compatible with each
3410/// other. Therefore this encoding function must be careful to only distinguish
3411/// types if there is no third type with which they are both required to be
3412/// compatible.
3413static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3414 raw_ostream &OS, QualType QT) {
3415 // FIXME: Consider address space qualifiers.
3416 const Type *T = QT.getCanonicalType().getTypePtr();
3417
3418 // FIXME: Consider using the C++ type mangling when we encounter a construct
3419 // that is incompatible with C.
3420
3421 switch (T->getTypeClass()) {
3422 case Type::Atomic:
3423 return encodeTypeForFunctionPointerAuth(
3424 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3425
3426 case Type::LValueReference:
3427 OS << "R";
3428 encodeTypeForFunctionPointerAuth(Ctx, OS,
3429 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3430 return;
3431 case Type::RValueReference:
3432 OS << "O";
3433 encodeTypeForFunctionPointerAuth(Ctx, OS,
3434 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3435 return;
3436
3437 case Type::Pointer:
3438 // C11 6.7.6.1p2:
3439 // For two pointer types to be compatible, both shall be identically
3440 // qualified and both shall be pointers to compatible types.
3441 // FIXME: we should also consider pointee types.
3442 OS << "P";
3443 return;
3444
3445 case Type::ObjCObjectPointer:
3446 case Type::BlockPointer:
3447 OS << "P";
3448 return;
3449
3450 case Type::Complex:
3451 OS << "C";
3452 return encodeTypeForFunctionPointerAuth(
3453 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3454
3455 case Type::VariableArray:
3456 case Type::ConstantArray:
3457 case Type::IncompleteArray:
3458 case Type::ArrayParameter:
3459 // C11 6.7.6.2p6:
3460 // For two array types to be compatible, both shall have compatible
3461 // element types, and if both size specifiers are present, and are integer
3462 // constant expressions, then both size specifiers shall have the same
3463 // constant value [...]
3464 //
3465 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3466 // width of the array.
3467 OS << "A";
3468 return encodeTypeForFunctionPointerAuth(
3469 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3470
3471 case Type::ObjCInterface:
3472 case Type::ObjCObject:
3473 OS << "<objc_object>";
3474 return;
3475
3476 case Type::Enum: {
3477 // C11 6.7.2.2p4:
3478 // Each enumerated type shall be compatible with char, a signed integer
3479 // type, or an unsigned integer type.
3480 //
3481 // So we have to treat enum types as integers.
3482 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3483 return encodeTypeForFunctionPointerAuth(
3484 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3485 }
3486
3487 case Type::FunctionNoProto:
3488 case Type::FunctionProto: {
3489 // C11 6.7.6.3p15:
3490 // For two function types to be compatible, both shall specify compatible
3491 // return types. Moreover, the parameter type lists, if both are present,
3492 // shall agree in the number of parameters and in the use of the ellipsis
3493 // terminator; corresponding parameters shall have compatible types.
3494 //
3495 // That paragraph goes on to describe how unprototyped functions are to be
3496 // handled, which we ignore here. Unprototyped function pointers are hashed
3497 // as though they were prototyped nullary functions since thats probably
3498 // what the user meant. This behavior is non-conforming.
3499 // FIXME: If we add a "custom discriminator" function type attribute we
3500 // should encode functions as their discriminators.
3501 OS << "F";
3502 const auto *FuncType = cast<FunctionType>(Val: T);
3503 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3504 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3505 for (QualType Param : FPT->param_types()) {
3506 Param = Ctx.getSignatureParameterType(T: Param);
3507 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3508 }
3509 if (FPT->isVariadic())
3510 OS << "z";
3511 }
3512 OS << "E";
3513 return;
3514 }
3515
3516 case Type::MemberPointer: {
3517 OS << "M";
3518 const auto *MPT = T->castAs<MemberPointerType>();
3519 encodeTypeForFunctionPointerAuth(
3520 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3521 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3522 return;
3523 }
3524 case Type::ExtVector:
3525 case Type::Vector:
3526 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3527 break;
3528
3529 // Don't bother discriminating based on these types.
3530 case Type::Pipe:
3531 case Type::BitInt:
3532 case Type::ConstantMatrix:
3533 OS << "?";
3534 return;
3535
3536 case Type::Builtin: {
3537 const auto *BTy = T->castAs<BuiltinType>();
3538 switch (BTy->getKind()) {
3539#define SIGNED_TYPE(Id, SingletonId) \
3540 case BuiltinType::Id: \
3541 OS << "i"; \
3542 return;
3543#define UNSIGNED_TYPE(Id, SingletonId) \
3544 case BuiltinType::Id: \
3545 OS << "i"; \
3546 return;
3547#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3548#define BUILTIN_TYPE(Id, SingletonId)
3549#include "clang/AST/BuiltinTypes.def"
3550 llvm_unreachable("placeholder types should not appear here.");
3551
3552 case BuiltinType::Half:
3553 OS << "Dh";
3554 return;
3555 case BuiltinType::Float:
3556 OS << "f";
3557 return;
3558 case BuiltinType::Double:
3559 OS << "d";
3560 return;
3561 case BuiltinType::LongDouble:
3562 OS << "e";
3563 return;
3564 case BuiltinType::Float16:
3565 OS << "DF16_";
3566 return;
3567 case BuiltinType::Float128:
3568 OS << "g";
3569 return;
3570
3571 case BuiltinType::Void:
3572 OS << "v";
3573 return;
3574
3575 case BuiltinType::ObjCId:
3576 case BuiltinType::ObjCClass:
3577 case BuiltinType::ObjCSel:
3578 case BuiltinType::NullPtr:
3579 OS << "P";
3580 return;
3581
3582 // Don't bother discriminating based on OpenCL types.
3583 case BuiltinType::OCLSampler:
3584 case BuiltinType::OCLEvent:
3585 case BuiltinType::OCLClkEvent:
3586 case BuiltinType::OCLQueue:
3587 case BuiltinType::OCLReserveID:
3588 case BuiltinType::BFloat16:
3589 case BuiltinType::VectorQuad:
3590 case BuiltinType::VectorPair:
3591 case BuiltinType::DMR1024:
3592 case BuiltinType::DMR2048:
3593 case BuiltinType::MetaInfo:
3594 OS << "?";
3595 return;
3596
3597 // Don't bother discriminating based on these seldom-used types.
3598 case BuiltinType::Ibm128:
3599 return;
3600#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3601 case BuiltinType::Id: \
3602 return;
3603#include "clang/Basic/OpenCLImageTypes.def"
3604#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3605 case BuiltinType::Id: \
3606 return;
3607#include "clang/Basic/OpenCLExtensionTypes.def"
3608#define SVE_TYPE(Name, Id, SingletonId) \
3609 case BuiltinType::Id: \
3610 return;
3611#include "clang/Basic/AArch64ACLETypes.def"
3612#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3613 case BuiltinType::Id: \
3614 return;
3615#include "clang/Basic/HLSLIntangibleTypes.def"
3616#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3617 case BuiltinType::Id: \
3618 return;
3619#include "clang/Basic/HLSLPackedTypes.def"
3620 case BuiltinType::Dependent:
3621 llvm_unreachable("should never get here");
3622#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3623#include "clang/Basic/AMDGPUTypes.def"
3624 case BuiltinType::WasmExternRef:
3625#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3626#include "clang/Basic/RISCVVTypes.def"
3627#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3628#include "clang/Basic/SPIRVTypes.def"
3629 llvm_unreachable("not yet implemented");
3630 }
3631 llvm_unreachable("should never get here");
3632 }
3633 case Type::Record: {
3634 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3635 const IdentifierInfo *II = RD->getIdentifier();
3636
3637 // In C++, an immediate typedef of an anonymous struct or union
3638 // is considered to name it for ODR purposes, but C's specification
3639 // of type compatibility does not have a similar rule. Using the typedef
3640 // name in function type discriminators anyway, as we do here,
3641 // therefore technically violates the C standard: two function pointer
3642 // types defined in terms of two typedef'd anonymous structs with
3643 // different names are formally still compatible, but we are assigning
3644 // them different discriminators and therefore incompatible ABIs.
3645 //
3646 // This is a relatively minor violation that significantly improves
3647 // discrimination in some cases and has not caused problems in
3648 // practice. Regardless, it is now part of the ABI in places where
3649 // function type discrimination is used, and it can no longer be
3650 // changed except on new platforms.
3651
3652 if (!II)
3653 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3654 II = Typedef->getDeclName().getAsIdentifierInfo();
3655
3656 if (!II) {
3657 OS << "<anonymous_record>";
3658 return;
3659 }
3660 OS << II->getLength() << II->getName();
3661 return;
3662 }
3663 case Type::HLSLAttributedResource:
3664 case Type::HLSLInlineSpirv:
3665 llvm_unreachable("should never get here");
3666 break;
3667 case Type::OverflowBehavior:
3668 llvm_unreachable("should never get here");
3669 break;
3670 case Type::DeducedTemplateSpecialization:
3671 case Type::Auto:
3672#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3673#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3674#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3675#define ABSTRACT_TYPE(Class, Base)
3676#define TYPE(Class, Base)
3677#include "clang/AST/TypeNodes.inc"
3678 llvm_unreachable("unexpected non-canonical or dependent type!");
3679 return;
3680 }
3681}
3682
3683uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3684 assert(!T->isDependentType() &&
3685 "cannot compute type discriminator of a dependent type");
3686 SmallString<256> Str;
3687 llvm::raw_svector_ostream Out(Str);
3688
3689 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3690 T = T->getPointeeType();
3691
3692 if (T->isFunctionType()) {
3693 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3694 } else {
3695 T = T.getUnqualifiedType();
3696 // Calls to member function pointers don't need to worry about
3697 // language interop or the laxness of the C type compatibility rules.
3698 // We just mangle the member pointer type directly, which is
3699 // implicitly much stricter about type matching. However, we do
3700 // strip any top-level exception specification before this mangling.
3701 // C++23 requires calls to work when the function type is convertible
3702 // to the pointer type by a function pointer conversion, which can
3703 // change the exception specification. This does not technically
3704 // require the exception specification to not affect representation,
3705 // because the function pointer conversion is still always a direct
3706 // value conversion and therefore an opportunity to resign the
3707 // pointer. (This is in contrast to e.g. qualification conversions,
3708 // which can be applied in nested pointer positions, effectively
3709 // requiring qualified and unqualified representations to match.)
3710 // However, it is pragmatic to ignore exception specifications
3711 // because it allows a certain amount of `noexcept` mismatching
3712 // to not become a visible ODR problem. This also leaves some
3713 // room for the committee to add laxness to function pointer
3714 // conversions in future standards.
3715 if (auto *MPT = T->getAs<MemberPointerType>())
3716 if (MPT->isMemberFunctionPointer()) {
3717 QualType PointeeType = MPT->getPointeeType();
3718 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3719 EST_None) {
3720 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3721 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3722 Cls: MPT->getMostRecentCXXRecordDecl());
3723 }
3724 }
3725 std::unique_ptr<MangleContext> MC(createMangleContext());
3726 MC->mangleCanonicalTypeName(T, Out);
3727 }
3728
3729 return llvm::getPointerAuthStableSipHash(S: Str);
3730}
3731
3732QualType ASTContext::getObjCGCQualType(QualType T,
3733 Qualifiers::GC GCAttr) const {
3734 QualType CanT = getCanonicalType(T);
3735 if (CanT.getObjCGCAttr() == GCAttr)
3736 return T;
3737
3738 if (const auto *ptr = T->getAs<PointerType>()) {
3739 QualType Pointee = ptr->getPointeeType();
3740 if (Pointee->isAnyPointerType()) {
3741 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3742 return getPointerType(T: ResultType);
3743 }
3744 }
3745
3746 // If we are composing extended qualifiers together, merge together
3747 // into one ExtQuals node.
3748 QualifierCollector Quals;
3749 const Type *TypeNode = Quals.strip(type: T);
3750
3751 // If this type already has an ObjCGC specified, it cannot get
3752 // another one.
3753 assert(!Quals.hasObjCGCAttr() &&
3754 "Type cannot have multiple ObjCGCs!");
3755 Quals.addObjCGCAttr(type: GCAttr);
3756
3757 return getExtQualType(baseType: TypeNode, quals: Quals);
3758}
3759
3760QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3761 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3762 QualType Pointee = Ptr->getPointeeType();
3763 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3764 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3765 }
3766 }
3767 return T;
3768}
3769
3770QualType ASTContext::getCountAttributedType(
3771 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3772 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3773 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3774 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3775
3776 // Complete (non-late-parsed) path: the count expression is known up front.
3777 // This deliberately preserves the pre-existing uniquing behavior -- the
3778 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3779 // getIncompleteCountAttributedType (count filled in later) opts out of
3780 // uniquing.
3781 llvm::FoldingSetNodeID ID;
3782 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3783
3784 llvm::FoldingSetInsertToken Token;
3785 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3786 if (CATy)
3787 return QualType(CATy, 0);
3788
3789 QualType CanonTy = getCanonicalType(T: WrappedTy);
3790 CATy = CountAttributedType::Create(Ctx: *this, Wrapped: WrappedTy, Canon: CanonTy, CountExpr,
3791 CountInBytes, OrNull, CoupledDecls: DependentDecls);
3792 Types.push_back(Elt: CATy);
3793 CountAttributedTypes.insert(N: CATy, Token);
3794
3795 return QualType(CATy, 0);
3796}
3797
3798CountAttributedType *ASTContext::getIncompleteCountAttributedType(
3799 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3800 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3801
3802 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3803 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3804 // null here, so every incomplete node would profile identically as
3805 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3806 // collide. The node stays un-uniqued even after completion; see
3807 // `completeCountAttributedType`.
3808 //
3809 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3810 // without ever being completed (a nested counted_by, or an argument that
3811 // fails to parse), and a null-count node must not be reachable by anything
3812 // that scans `Types`. `completeCountAttributedType` registers it once the
3813 // count is in place.
3814 return CountAttributedType::Create(
3815 Ctx: *this, Wrapped: WrappedTy, Canon: getCanonicalType(T: WrappedTy),
3816 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3817 /*CoupledDecls=*/{});
3818}
3819
3820void ASTContext::completeCountAttributedType(
3821 CountAttributedType *CATy, Expr *CountExpr,
3822 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3823 CATy->complete(Ctx: *this, E: CountExpr, CoupledDecls: DependentDecls);
3824 // Safe for `Types` scanners now that the count is in place; see
3825 // `getIncompleteCountAttributedType` for why it was held back.
3826 //
3827 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3828 // an eagerly built node: this pointer is already embedded in the enclosing
3829 // types and handed out, so an equal node that happens to exist cannot be
3830 // merged into. The only cost is that a completed node is never
3831 // pointer-shared with an equal eager one, which does not affect semantic
3832 // type equality -- `hasSameType` compares canonical types, and this sugar's
3833 // canonical type is the wrapped type's.
3834 Types.push_back(Elt: CATy);
3835}
3836
3837QualType ASTContext::getLateParsedAttrType(
3838 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3839 QualType CanonTy = getCanonicalType(T: WrappedTy);
3840
3841 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3842 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3843
3844 Types.push_back(Elt: LPATy);
3845 return QualType(LPATy, 0);
3846}
3847
3848QualType
3849ASTContext::adjustType(QualType Orig,
3850 llvm::function_ref<QualType(QualType)> Adjust) const {
3851 switch (Orig->getTypeClass()) {
3852 case Type::Attributed: {
3853 const auto *AT = cast<AttributedType>(Val&: Orig);
3854 return getAttributedType(attrKind: AT->getAttrKind(),
3855 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3856 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3857 attr: AT->getAttr());
3858 }
3859
3860 case Type::BTFTagAttributed: {
3861 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3862 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3863 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3864 }
3865
3866 case Type::OverflowBehavior: {
3867 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3868 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3869 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3870 }
3871
3872 case Type::Paren:
3873 return getParenType(
3874 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3875
3876 case Type::Adjusted: {
3877 const auto *AT = cast<AdjustedType>(Val&: Orig);
3878 return getAdjustedType(Orig: AT->getOriginalType(),
3879 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3880 }
3881
3882 case Type::MacroQualified: {
3883 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3884 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3885 MacroII: MQT->getMacroIdentifier());
3886 }
3887
3888 default:
3889 return Adjust(Orig);
3890 }
3891}
3892
3893const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3894 FunctionType::ExtInfo Info) {
3895 if (T->getExtInfo() == Info)
3896 return T;
3897
3898 QualType Result;
3899 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3900 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3901 } else {
3902 const auto *FPT = cast<FunctionProtoType>(Val: T);
3903 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3904 EPI.ExtInfo = Info;
3905 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3906 }
3907
3908 return cast<FunctionType>(Val: Result.getTypePtr());
3909}
3910
3911QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3912 QualType ResultType) {
3913 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3914 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3915 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3916
3917 const auto *FPT = Orig->castAs<FunctionProtoType>();
3918 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3919 EPI: FPT->getExtProtoInfo());
3920 });
3921}
3922
3923void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3924 QualType ResultType) {
3925 FD = FD->getMostRecentDecl();
3926 while (true) {
3927 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3928 if (FunctionDecl *Next = FD->getPreviousDecl())
3929 FD = Next;
3930 else
3931 break;
3932 }
3933 if (ASTMutationListener *L = getASTMutationListener())
3934 L->DeducedReturnType(FD, ReturnType: ResultType);
3935}
3936
3937/// Get a function type and produce the equivalent function type with the
3938/// specified exception specification. Type sugar that can be present on a
3939/// declaration of a function with an exception specification is permitted
3940/// and preserved. Other type sugar (for instance, typedefs) is not.
3941QualType ASTContext::getFunctionTypeWithExceptionSpec(
3942 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3943 return adjustType(Orig, Adjust: [&](QualType Ty) {
3944 const auto *Proto = Ty->castAs<FunctionProtoType>();
3945 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3946 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3947 });
3948}
3949
3950bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3951 QualType U) const {
3952 return hasSameType(T1: T, T2: U) ||
3953 (getLangOpts().CPlusPlus17 &&
3954 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3955 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3956}
3957
3958QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3959 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3960 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3961 SmallVector<QualType, 16> Args(Proto->param_types().size());
3962 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3963 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3964 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3965 }
3966
3967 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3968 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3969 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3970 }
3971
3972 return T;
3973}
3974
3975bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3976 return hasSameType(T1: T, T2: U) ||
3977 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3978 T2: getFunctionTypeWithoutPtrSizes(T: U));
3979}
3980
3981QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3982 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3983 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3984 EPI.ExtParameterInfos = nullptr;
3985 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3986 }
3987 return T;
3988}
3989
3990bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3991 QualType U) const {
3992 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3993 T2: getFunctionTypeWithoutParamABIs(T: U));
3994}
3995
3996void ASTContext::adjustExceptionSpec(
3997 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3998 bool AsWritten) {
3999 // Update the type.
4000 QualType Updated =
4001 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
4002 FD->setType(Updated);
4003
4004 if (!AsWritten)
4005 return;
4006
4007 // Update the type in the type source information too.
4008 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4009 // If the type and the type-as-written differ, we may need to update
4010 // the type-as-written too.
4011 if (TSInfo->getType() != FD->getType())
4012 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
4013
4014 // FIXME: When we get proper type location information for exceptions,
4015 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4016 // up the TypeSourceInfo;
4017 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4018 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4019 "TypeLoc size mismatch from updating exception specification");
4020 TSInfo->overrideType(T: Updated);
4021 }
4022}
4023
4024/// getComplexType - Return the uniqued reference to the type for a complex
4025/// number with the specified element type.
4026QualType ASTContext::getComplexType(QualType T) const {
4027 // Unique pointers, to guarantee there is only one pointer of a particular
4028 // structure.
4029 llvm::FoldingSetInsertToken Token;
4030 if (ComplexType *CT = ComplexTypes.lookup(Key: T, Token))
4031 return QualType(CT, 0);
4032
4033 // If the pointee type isn't canonical, this won't be a canonical type either,
4034 // so fill in the canonical type field.
4035 QualType Canonical;
4036 if (!T.isCanonical()) {
4037 Canonical = getComplexType(T: getCanonicalType(T));
4038
4039 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4040 }
4041 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4042 Types.push_back(Elt: New);
4043 ComplexTypes.insert(N: New, Token);
4044 return QualType(New, 0);
4045}
4046
4047/// getPointerType - Return the uniqued reference to the type for a pointer to
4048/// the specified type.
4049QualType ASTContext::getPointerType(QualType T) const {
4050 // Unique pointers, to guarantee there is only one pointer of a particular
4051 // structure.
4052 llvm::FoldingSetInsertToken Token;
4053 if (PointerType *PT = PointerTypes.lookup(Key: T, Token))
4054 return QualType(PT, 0);
4055
4056 // If the pointee type isn't canonical, this won't be a canonical type either,
4057 // so fill in the canonical type field.
4058 QualType Canonical;
4059 if (!T.isCanonical()) {
4060 Canonical = getPointerType(T: getCanonicalType(T));
4061
4062 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4063 }
4064 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4065 Types.push_back(Elt: New);
4066 PointerTypes.insert(N: New, Token);
4067 return QualType(New, 0);
4068}
4069
4070QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4071 llvm::FoldingSetInsertToken Token;
4072 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, New}, Token);
4073 if (AT)
4074 return QualType(AT, 0);
4075
4076 QualType Canonical = getCanonicalType(T: New);
4077
4078 AT = new (*this, alignof(AdjustedType))
4079 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4080 Types.push_back(Elt: AT);
4081 AdjustedTypes.insert(N: AT, Token);
4082 return QualType(AT, 0);
4083}
4084
4085QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4086 llvm::FoldingSetInsertToken Token;
4087 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, Decayed}, Token);
4088 if (AT)
4089 return QualType(AT, 0);
4090
4091 QualType Canonical = getCanonicalType(T: Decayed);
4092
4093 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4094 Types.push_back(Elt: AT);
4095 AdjustedTypes.insert(N: AT, Token);
4096 return QualType(AT, 0);
4097}
4098
4099QualType ASTContext::getDecayedType(QualType T) const {
4100 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4101
4102 QualType Decayed;
4103
4104 // C99 6.7.5.3p7:
4105 // A declaration of a parameter as "array of type" shall be
4106 // adjusted to "qualified pointer to type", where the type
4107 // qualifiers (if any) are those specified within the [ and ] of
4108 // the array type derivation.
4109 if (T->isArrayType())
4110 Decayed = getArrayDecayedType(T);
4111
4112 // C99 6.7.5.3p8:
4113 // A declaration of a parameter as "function returning type"
4114 // shall be adjusted to "pointer to function returning type", as
4115 // in 6.3.2.1.
4116 if (T->isFunctionType())
4117 Decayed = getPointerType(T);
4118
4119 return getDecayedType(Orig: T, Decayed);
4120}
4121
4122QualType ASTContext::getArrayParameterType(QualType Ty) const {
4123 if (Ty->isArrayParameterType())
4124 return Ty;
4125 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4126 QualType DTy = Ty.getDesugaredType(Context: *this);
4127 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4128 llvm::FoldingSetNodeID ID;
4129 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4130 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4131 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4132 llvm::FoldingSetInsertToken Token;
4133 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4134 if (AT)
4135 return QualType(AT, 0);
4136
4137 QualType Canonical;
4138 if (!DTy.isCanonical()) {
4139 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4140
4141 // Get the new insert position for the node we care about.
4142 AT = ArrayParameterTypes.lookup(ID, Token);
4143 assert(!AT && "Shouldn't be in the map!");
4144 }
4145
4146 AT = new (*this, alignof(ArrayParameterType))
4147 ArrayParameterType(ATy, Canonical);
4148 Types.push_back(Elt: AT);
4149 ArrayParameterTypes.insert(N: AT, Token);
4150 return QualType(AT, 0);
4151}
4152
4153/// getBlockPointerType - Return the uniqued reference to the type for
4154/// a pointer to the specified block.
4155QualType ASTContext::getBlockPointerType(QualType T) const {
4156 assert(T->isFunctionType() && "block of function types only");
4157 // Unique pointers, to guarantee there is only one block of a particular
4158 // structure.
4159 llvm::FoldingSetInsertToken Token;
4160 if (BlockPointerType *PT = BlockPointerTypes.lookup(Key: T, Token))
4161 return QualType(PT, 0);
4162
4163 // If the block pointee type isn't canonical, this won't be a canonical
4164 // type either so fill in the canonical type field.
4165 QualType Canonical;
4166 if (!T.isCanonical()) {
4167 Canonical = getBlockPointerType(T: getCanonicalType(T));
4168
4169 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4170 }
4171 auto *New =
4172 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4173 Types.push_back(Elt: New);
4174 BlockPointerTypes.insert(N: New, Token);
4175 return QualType(New, 0);
4176}
4177
4178/// getLValueReferenceType - Return the uniqued reference to the type for an
4179/// lvalue reference to the specified type.
4180QualType
4181ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4182 assert((!T->isPlaceholderType() ||
4183 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4184 "Unresolved placeholder type");
4185
4186 // Unique pointers, to guarantee there is only one pointer of a particular
4187 // structure.
4188 llvm::FoldingSetInsertToken Token;
4189 if (LValueReferenceType *RT =
4190 LValueReferenceTypes.lookup(Key: {T, SpelledAsLValue}, Token))
4191 return QualType(RT, 0);
4192
4193 const auto *InnerRef = T->getAs<ReferenceType>();
4194
4195 // If the referencee type isn't canonical, this won't be a canonical type
4196 // either, so fill in the canonical type field.
4197 QualType Canonical;
4198 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4199 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4200 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4201
4202 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4203 "Shouldn't be in the map!");
4204 }
4205
4206 auto *New = new (*this, alignof(LValueReferenceType))
4207 LValueReferenceType(T, Canonical, SpelledAsLValue);
4208 Types.push_back(Elt: New);
4209 LValueReferenceTypes.insert(N: New, Token);
4210
4211 return QualType(New, 0);
4212}
4213
4214/// getRValueReferenceType - Return the uniqued reference to the type for an
4215/// rvalue reference to the specified type.
4216QualType ASTContext::getRValueReferenceType(QualType T) const {
4217 assert((!T->isPlaceholderType() ||
4218 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4219 "Unresolved placeholder type");
4220
4221 // Unique pointers, to guarantee there is only one pointer of a particular
4222 // structure.
4223 llvm::FoldingSetInsertToken Token;
4224 if (RValueReferenceType *RT = RValueReferenceTypes.lookup(Key: {T, false}, Token))
4225 return QualType(RT, 0);
4226
4227 const auto *InnerRef = T->getAs<ReferenceType>();
4228
4229 // If the referencee type isn't canonical, this won't be a canonical type
4230 // either, so fill in the canonical type field.
4231 QualType Canonical;
4232 if (InnerRef || !T.isCanonical()) {
4233 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4234 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4235
4236 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4237 "Shouldn't be in the map!");
4238 }
4239
4240 auto *New = new (*this, alignof(RValueReferenceType))
4241 RValueReferenceType(T, Canonical);
4242 Types.push_back(Elt: New);
4243 RValueReferenceTypes.insert(N: New, Token);
4244 return QualType(New, 0);
4245}
4246
4247QualType ASTContext::getMemberPointerType(QualType T,
4248 NestedNameSpecifier Qualifier,
4249 const CXXRecordDecl *Cls) const {
4250 if (!Qualifier) {
4251 assert(Cls && "At least one of Qualifier or Cls must be provided");
4252 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4253 } else if (!Cls) {
4254 Cls = Qualifier.getAsRecordDecl();
4255 }
4256 // Unique pointers, to guarantee there is only one pointer of a particular
4257 // structure.
4258 llvm::FoldingSetNodeID ID;
4259 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4260
4261 llvm::FoldingSetInsertToken Token;
4262 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4263 return QualType(PT, 0);
4264
4265 NestedNameSpecifier CanonicalQualifier = [&] {
4266 if (!Cls)
4267 return Qualifier.getCanonical();
4268 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4269 assert(R.isCanonical());
4270 return R;
4271 }();
4272 // If the pointee or class type isn't canonical, this won't be a canonical
4273 // type either, so fill in the canonical type field.
4274 QualType Canonical;
4275 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4276 Canonical =
4277 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4278 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4279 // Get the new insert position for the node we care about.
4280 [[maybe_unused]] MemberPointerType *NewIP =
4281 MemberPointerTypes.lookup(ID, Token);
4282 assert(!NewIP && "Shouldn't be in the map!");
4283 }
4284 auto *New = new (*this, alignof(MemberPointerType))
4285 MemberPointerType(T, Qualifier, Canonical);
4286 Types.push_back(Elt: New);
4287 MemberPointerTypes.insert(N: New, Token);
4288 return QualType(New, 0);
4289}
4290
4291/// getConstantArrayType - Return the unique reference to the type for an
4292/// array of the specified element type.
4293QualType ASTContext::getConstantArrayType(QualType EltTy,
4294 const llvm::APInt &ArySizeIn,
4295 const Expr *SizeExpr,
4296 ArraySizeModifier ASM,
4297 unsigned IndexTypeQuals) const {
4298 assert((EltTy->isDependentType() ||
4299 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4300 "Constant array of VLAs is illegal!");
4301
4302 // We only need the size as part of the type if it's instantiation-dependent.
4303 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4304 SizeExpr = nullptr;
4305
4306 // Convert the array size into a canonical width matching the pointer size for
4307 // the target.
4308 llvm::APInt ArySize(ArySizeIn);
4309 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4310
4311 llvm::FoldingSetNodeID ID;
4312 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4313 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4314
4315 llvm::FoldingSetInsertToken Token;
4316 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4317 return QualType(ATP, 0);
4318
4319 // If the element type isn't canonical or has qualifiers, or the array bound
4320 // is instantiation-dependent, this won't be a canonical type either, so fill
4321 // in the canonical type field.
4322 QualType Canon;
4323 // FIXME: Check below should look for qualifiers behind sugar.
4324 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4325 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4326 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4327 ASM, IndexTypeQuals);
4328 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4329
4330 // Get the new insert position for the node we care about.
4331 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4332 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4333 }
4334
4335 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4336 SzMod: ASM, Qual: IndexTypeQuals);
4337 ConstantArrayTypes.insert(N: New, Token);
4338 Types.push_back(Elt: New);
4339 return QualType(New, 0);
4340}
4341
4342/// getVariableArrayDecayedType - Turns the given type, which may be
4343/// variably-modified, into the corresponding type with all the known
4344/// sizes replaced with [*].
4345QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4346 // Vastly most common case.
4347 if (!type->isVariablyModifiedType()) return type;
4348
4349 QualType result;
4350
4351 SplitQualType split = type.getSplitDesugaredType();
4352 const Type *ty = split.Ty;
4353 switch (ty->getTypeClass()) {
4354#define TYPE(Class, Base)
4355#define ABSTRACT_TYPE(Class, Base)
4356#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4357#include "clang/AST/TypeNodes.inc"
4358 llvm_unreachable("didn't desugar past all non-canonical types?");
4359
4360 // These types should never be variably-modified.
4361 case Type::Builtin:
4362 case Type::Complex:
4363 case Type::Vector:
4364 case Type::DependentVector:
4365 case Type::ExtVector:
4366 case Type::DependentSizedExtVector:
4367 case Type::ConstantMatrix:
4368 case Type::DependentSizedMatrix:
4369 case Type::DependentAddressSpace:
4370 case Type::ObjCObject:
4371 case Type::ObjCInterface:
4372 case Type::ObjCObjectPointer:
4373 case Type::Record:
4374 case Type::Enum:
4375 case Type::UnresolvedUsing:
4376 case Type::TypeOfExpr:
4377 case Type::TypeOf:
4378 case Type::Decltype:
4379 case Type::UnaryTransform:
4380 case Type::DependentName:
4381 case Type::InjectedClassName:
4382 case Type::TemplateSpecialization:
4383 case Type::TemplateTypeParm:
4384 case Type::SubstTemplateTypeParmPack:
4385 case Type::SubstBuiltinTemplatePack:
4386 case Type::Auto:
4387 case Type::DeducedTemplateSpecialization:
4388 case Type::PackExpansion:
4389 case Type::PackIndexing:
4390 case Type::BitInt:
4391 case Type::DependentBitInt:
4392 case Type::ArrayParameter:
4393 case Type::HLSLAttributedResource:
4394 case Type::HLSLInlineSpirv:
4395 case Type::OverflowBehavior:
4396 llvm_unreachable("type should never be variably-modified");
4397
4398 // These types can be variably-modified but should never need to
4399 // further decay.
4400 case Type::FunctionNoProto:
4401 case Type::FunctionProto:
4402 case Type::BlockPointer:
4403 case Type::MemberPointer:
4404 case Type::Pipe:
4405 return type;
4406
4407 // These types can be variably-modified. All these modifications
4408 // preserve structure except as noted by comments.
4409 // TODO: if we ever care about optimizing VLAs, there are no-op
4410 // optimizations available here.
4411 case Type::Pointer:
4412 result = getPointerType(T: getVariableArrayDecayedType(
4413 type: cast<PointerType>(Val: ty)->getPointeeType()));
4414 break;
4415
4416 case Type::LValueReference: {
4417 const auto *lv = cast<LValueReferenceType>(Val: ty);
4418 result = getLValueReferenceType(
4419 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4420 SpelledAsLValue: lv->isSpelledAsLValue());
4421 break;
4422 }
4423
4424 case Type::RValueReference: {
4425 const auto *lv = cast<RValueReferenceType>(Val: ty);
4426 result = getRValueReferenceType(
4427 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4428 break;
4429 }
4430
4431 case Type::Atomic: {
4432 const auto *at = cast<AtomicType>(Val: ty);
4433 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4434 break;
4435 }
4436
4437 case Type::ConstantArray: {
4438 const auto *cat = cast<ConstantArrayType>(Val: ty);
4439 result = getConstantArrayType(
4440 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4441 ArySizeIn: cat->getSize(),
4442 SizeExpr: cat->getSizeExpr(),
4443 ASM: cat->getSizeModifier(),
4444 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4445 break;
4446 }
4447
4448 case Type::DependentSizedArray: {
4449 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4450 result = getDependentSizedArrayType(
4451 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4452 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4453 break;
4454 }
4455
4456 // Turn incomplete types into [*] types.
4457 case Type::IncompleteArray: {
4458 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4459 result =
4460 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4461 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4462 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4463 break;
4464 }
4465
4466 // Turn VLA types into [*] types.
4467 case Type::VariableArray: {
4468 const auto *vat = cast<VariableArrayType>(Val: ty);
4469 result =
4470 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4471 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4472 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4473 break;
4474 }
4475 }
4476
4477 // Apply the top-level qualifiers from the original.
4478 return getQualifiedType(T: result, Qs: split.Quals);
4479}
4480
4481/// getVariableArrayType - Returns a non-unique reference to the type for a
4482/// variable array of the specified element type.
4483QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4484 ArraySizeModifier ASM,
4485 unsigned IndexTypeQuals) const {
4486 // Since we don't unique expressions, it isn't possible to unique VLA's
4487 // that have an expression provided for their size.
4488 QualType Canon;
4489
4490 // Be sure to pull qualifiers off the element type.
4491 // FIXME: Check below should look for qualifiers behind sugar.
4492 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4493 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4494 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4495 IndexTypeQuals);
4496 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4497 }
4498
4499 auto *New = new (*this, alignof(VariableArrayType))
4500 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4501
4502 VariableArrayTypes.push_back(x: New);
4503 Types.push_back(Elt: New);
4504 return QualType(New, 0);
4505}
4506
4507/// getDependentSizedArrayType - Returns a non-unique reference to
4508/// the type for a dependently-sized array of the specified element
4509/// type.
4510QualType
4511ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4512 ArraySizeModifier ASM,
4513 unsigned elementTypeQuals) const {
4514 assert((!numElements || numElements->isTypeDependent() ||
4515 numElements->isValueDependent()) &&
4516 "Size must be type- or value-dependent!");
4517
4518 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4519
4520 llvm::FoldingSetInsertToken Token;
4521 llvm::FoldingSetNodeID ID;
4522 DependentSizedArrayType::Profile(
4523 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4524 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4525
4526 // Look for an existing type with these properties.
4527 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4528
4529 // Dependently-sized array types that do not have a specified number
4530 // of elements will have their sizes deduced from a dependent
4531 // initializer.
4532 if (!numElements) {
4533 if (canonTy)
4534 return QualType(canonTy, 0);
4535
4536 auto *newType = new (*this, alignof(DependentSizedArrayType))
4537 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4538 elementTypeQuals);
4539 DependentSizedArrayTypes.insert(N: newType, Token);
4540 Types.push_back(Elt: newType);
4541 return QualType(newType, 0);
4542 }
4543
4544 // If we don't have one, build one.
4545 if (!canonTy) {
4546 canonTy = new (*this, alignof(DependentSizedArrayType))
4547 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4548 numElements, ASM, elementTypeQuals);
4549 DependentSizedArrayTypes.insert(N: canonTy, Token);
4550 Types.push_back(Elt: canonTy);
4551 }
4552
4553 // Apply qualifiers from the element type to the array.
4554 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4555 Qs: canonElementType.Quals);
4556
4557 // If we didn't need extra canonicalization for the element type or the size
4558 // expression, then just use that as our result.
4559 if (QualType(canonElementType.Ty, 0) == elementType &&
4560 canonTy->getSizeExpr() == numElements)
4561 return canon;
4562
4563 // Otherwise, we need to build a type which follows the spelling
4564 // of the element type.
4565 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4566 DependentSizedArrayType(elementType, canon, numElements, ASM,
4567 elementTypeQuals);
4568 Types.push_back(Elt: sugaredType);
4569 return QualType(sugaredType, 0);
4570}
4571
4572QualType ASTContext::getIncompleteArrayType(QualType elementType,
4573 ArraySizeModifier ASM,
4574 unsigned elementTypeQuals) const {
4575 llvm::FoldingSetNodeID ID;
4576 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4577
4578 llvm::FoldingSetInsertToken Token;
4579 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4580 return QualType(iat, 0);
4581
4582 // If the element type isn't canonical, this won't be a canonical type
4583 // either, so fill in the canonical type field. We also have to pull
4584 // qualifiers off the element type.
4585 QualType canon;
4586
4587 // FIXME: Check below should look for qualifiers behind sugar.
4588 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4589 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4590 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4591 ASM, elementTypeQuals);
4592 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4593
4594 // Get the new insert position for the node we care about.
4595 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4596 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4597 }
4598
4599 auto *newType = new (*this, alignof(IncompleteArrayType))
4600 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4601
4602 IncompleteArrayTypes.insert(N: newType, Token);
4603 Types.push_back(Elt: newType);
4604 return QualType(newType, 0);
4605}
4606
4607ASTContext::BuiltinVectorTypeInfo
4608ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4609#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4610 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4611 NUMVECTORS};
4612
4613#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4614 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4615
4616 switch (Ty->getKind()) {
4617 default:
4618 llvm_unreachable("Unsupported builtin vector type");
4619
4620#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4621 ElBits, NF, IsSigned) \
4622 case BuiltinType::Id: \
4623 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4624 llvm::ElementCount::getScalable(NumEls), NF};
4625#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4626 ElBits, NF) \
4627 case BuiltinType::Id: \
4628 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4629 llvm::ElementCount::getScalable(NumEls), NF};
4630#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4631 ElBits, NF) \
4632 case BuiltinType::Id: \
4633 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4634#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4635 ElBits, NF) \
4636 case BuiltinType::Id: \
4637 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4638#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4639 case BuiltinType::Id: \
4640 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4641#include "clang/Basic/AArch64ACLETypes.def"
4642
4643#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4644 IsSigned) \
4645 case BuiltinType::Id: \
4646 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4647 llvm::ElementCount::getScalable(NumEls), NF};
4648#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4649 case BuiltinType::Id: \
4650 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4651 llvm::ElementCount::getScalable(NumEls), NF};
4652#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4653 case BuiltinType::Id: \
4654 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4655#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4656 case BuiltinType::Id: \
4657 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4658#include "clang/Basic/RISCVVTypes.def"
4659 }
4660}
4661
4662/// getExternrefType - Return a WebAssembly externref type, which represents an
4663/// opaque reference to a host value.
4664QualType ASTContext::getWebAssemblyExternrefType() const {
4665 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4666#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4667 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4668 return SingletonId;
4669#include "clang/Basic/WebAssemblyReferenceTypes.def"
4670 }
4671 llvm_unreachable(
4672 "shouldn't try to generate type externref outside WebAssembly target");
4673}
4674
4675/// getScalableVectorType - Return the unique reference to a scalable vector
4676/// type of the specified element type and size. VectorType must be a built-in
4677/// type.
4678QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4679 unsigned NumFields) const {
4680 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4681 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4682 return It->second;
4683
4684 if (Target->hasAArch64ACLETypes()) {
4685 uint64_t EltTySize = getTypeSize(T: EltTy);
4686
4687#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4688 ElBits, NF, IsSigned) \
4689 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4690 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4691 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4692 return ScalableVecTyMap[K] = SingletonId; \
4693 }
4694#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4695 ElBits, NF) \
4696 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4697 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4698 return ScalableVecTyMap[K] = SingletonId; \
4699 }
4700#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4701 ElBits, NF) \
4702 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4703 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4704 return ScalableVecTyMap[K] = SingletonId; \
4705 }
4706#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4707 ElBits, NF) \
4708 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4709 NumElts == (NumEls * NF) && NumFields == 1) { \
4710 return ScalableVecTyMap[K] = SingletonId; \
4711 }
4712#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4713 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4714 return ScalableVecTyMap[K] = SingletonId;
4715#include "clang/Basic/AArch64ACLETypes.def"
4716 } else if (Target->hasRISCVVTypes()) {
4717 uint64_t EltTySize = getTypeSize(T: EltTy);
4718#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4719 IsFP, IsBF) \
4720 if (!EltTy->isBooleanType() && \
4721 ((EltTy->hasIntegerRepresentation() && \
4722 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4723 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4724 IsFP && !IsBF) || \
4725 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4726 IsBF && !IsFP)) && \
4727 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4728 return ScalableVecTyMap[K] = SingletonId;
4729#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4730 if (EltTy->isBooleanType() && NumElts == NumEls) \
4731 return ScalableVecTyMap[K] = SingletonId;
4732#include "clang/Basic/RISCVVTypes.def"
4733 }
4734 return QualType();
4735}
4736
4737/// getVectorType - Return the unique reference to a vector type of
4738/// the specified element type and size. VectorType must be a built-in type.
4739QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4740 VectorKind VecKind) const {
4741 assert(vecType->isBuiltinType() ||
4742 (vecType->isBitIntType() &&
4743 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4744 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4745
4746 // Check if we've already instantiated a vector of this type.
4747 llvm::FoldingSetNodeID ID;
4748 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4749
4750 llvm::FoldingSetInsertToken Token;
4751 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4752 return QualType(VTP, 0);
4753
4754 // If the element type isn't canonical, this won't be a canonical type either,
4755 // so fill in the canonical type field.
4756 QualType Canonical;
4757 if (!vecType.isCanonical()) {
4758 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4759
4760 // Get the new insert position for the node we care about.
4761 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4762 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4763 }
4764 auto *New = new (*this, alignof(VectorType))
4765 VectorType(vecType, NumElts, Canonical, VecKind);
4766 VectorTypes.insert(N: New, Token);
4767 Types.push_back(Elt: New);
4768 return QualType(New, 0);
4769}
4770
4771QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4772 SourceLocation AttrLoc,
4773 VectorKind VecKind) const {
4774 llvm::FoldingSetNodeID ID;
4775 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4776 VecKind);
4777 llvm::FoldingSetInsertToken Token;
4778 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4779 DependentVectorType *New;
4780
4781 if (Canon) {
4782 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4783 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4784 } else {
4785 QualType CanonVecTy = getCanonicalType(T: VecType);
4786 if (CanonVecTy == VecType) {
4787 New = new (*this, alignof(DependentVectorType))
4788 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4789
4790 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4791 assert(!CanonCheck &&
4792 "Dependent-sized vector_size canonical type broken");
4793 (void)CanonCheck;
4794 DependentVectorTypes.insert(N: New, Token);
4795 } else {
4796 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4797 AttrLoc: SourceLocation(), VecKind);
4798 New = new (*this, alignof(DependentVectorType))
4799 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4800 }
4801 }
4802
4803 Types.push_back(Elt: New);
4804 return QualType(New, 0);
4805}
4806
4807/// getExtVectorType - Return the unique reference to an extended vector type of
4808/// the specified element type and size. VectorType must be a built-in type.
4809QualType ASTContext::getExtVectorType(QualType vecType,
4810 unsigned NumElts) const {
4811 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4812 (vecType->isBitIntType() &&
4813 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4814 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4815
4816 // Check if we've already instantiated a vector of this type.
4817 llvm::FoldingSetNodeID ID;
4818 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4819 VecKind: VectorKind::Generic);
4820 llvm::FoldingSetInsertToken Token;
4821 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4822 return QualType(VTP, 0);
4823
4824 // If the element type isn't canonical, this won't be a canonical type either,
4825 // so fill in the canonical type field.
4826 QualType Canonical;
4827 if (!vecType.isCanonical()) {
4828 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4829
4830 // Get the new insert position for the node we care about.
4831 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4832 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4833 }
4834 auto *New = new (*this, alignof(ExtVectorType))
4835 ExtVectorType(vecType, NumElts, Canonical);
4836 VectorTypes.insert(N: New, Token);
4837 Types.push_back(Elt: New);
4838 return QualType(New, 0);
4839}
4840
4841QualType
4842ASTContext::getDependentSizedExtVectorType(QualType vecType,
4843 Expr *SizeExpr,
4844 SourceLocation AttrLoc) const {
4845 llvm::FoldingSetNodeID ID;
4846 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4847 SizeExpr);
4848
4849 llvm::FoldingSetInsertToken Token;
4850 DependentSizedExtVectorType *Canon =
4851 DependentSizedExtVectorTypes.lookup(ID, Token);
4852 DependentSizedExtVectorType *New;
4853 if (Canon) {
4854 // We already have a canonical version of this array type; use it as
4855 // the canonical type for a newly-built type.
4856 New = new (*this, alignof(DependentSizedExtVectorType))
4857 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4858 AttrLoc);
4859 } else {
4860 QualType CanonVecTy = getCanonicalType(T: vecType);
4861 if (CanonVecTy == vecType) {
4862 New = new (*this, alignof(DependentSizedExtVectorType))
4863 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4864
4865 DependentSizedExtVectorType *CanonCheck =
4866 DependentSizedExtVectorTypes.lookup(ID, Token);
4867 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4868 (void)CanonCheck;
4869 DependentSizedExtVectorTypes.insert(N: New, Token);
4870 } else {
4871 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4872 AttrLoc: SourceLocation());
4873 New = new (*this, alignof(DependentSizedExtVectorType))
4874 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4875 }
4876 }
4877
4878 Types.push_back(Elt: New);
4879 return QualType(New, 0);
4880}
4881
4882QualType ASTContext::getConstantMatrixType(
4883 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4884 std::optional<MatrixType::LayoutKind> Layout) const {
4885 llvm::FoldingSetNodeID ID;
4886 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns, Layout,
4887 TypeClass: Type::ConstantMatrix);
4888
4889 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4890 "need a valid element type");
4891 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4892 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4893 "need valid matrix dimensions");
4894 llvm::FoldingSetInsertToken Token;
4895 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4896 return QualType(MTP, 0);
4897
4898 QualType Canonical;
4899 if (Layout || !ElementTy.isCanonical()) {
4900 Canonical = getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows,
4901 NumColumns, Layout: std::nullopt);
4902
4903 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4904 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4905 (void)NewIP;
4906 }
4907
4908 auto *New = new (*this, alignof(ConstantMatrixType))
4909 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4910 MatrixTypes.insert(N: New, Token);
4911 Types.push_back(Elt: New);
4912 return QualType(New, 0);
4913}
4914
4915QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4916 Expr *RowExpr,
4917 Expr *ColumnExpr,
4918 SourceLocation AttrLoc) const {
4919 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4920 llvm::FoldingSetNodeID ID;
4921 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4922 ColumnExpr);
4923
4924 llvm::FoldingSetInsertToken Token;
4925 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4926
4927 if (!Canon) {
4928 Canon = new (*this, alignof(DependentSizedMatrixType))
4929 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4930 ColumnExpr, AttrLoc);
4931#ifndef NDEBUG
4932 DependentSizedMatrixType *CanonCheck =
4933 DependentSizedMatrixTypes.lookup(ID, Token);
4934 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4935#endif
4936 DependentSizedMatrixTypes.insert(N: Canon, Token);
4937 Types.push_back(Elt: Canon);
4938 }
4939
4940 // Already have a canonical version of the matrix type
4941 //
4942 // If it exactly matches the requested type, use it directly.
4943 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4944 Canon->getRowExpr() == ColumnExpr)
4945 return QualType(Canon, 0);
4946
4947 // Use Canon as the canonical type for newly-built type.
4948 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4949 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4950 ColumnExpr, AttrLoc);
4951 Types.push_back(Elt: New);
4952 return QualType(New, 0);
4953}
4954
4955QualType
4956ASTContext::getMatrixTypeWithLayout(QualType T,
4957 MatrixType::LayoutKind Layout) const {
4958 Qualifiers Quals = T.getQualifiers();
4959 const Type *Ty = T->getUnqualifiedDesugaredType();
4960
4961 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: Ty))
4962 return getQualifiedType(T: getConstantMatrixType(ElementTy: MT->getElementType(),
4963 NumRows: MT->getNumRows(),
4964 NumColumns: MT->getNumColumns(), Layout),
4965 Qs: Quals);
4966
4967 const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty);
4968 if (!CAT)
4969 return T;
4970
4971 QualType Result = getConstantArrayType(
4972 EltTy: getMatrixTypeWithLayout(T: CAT->getElementType(), Layout), ArySizeIn: CAT->getSize(),
4973 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(),
4974 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers());
4975 if (isa<ArrayParameterType>(Val: CAT))
4976 Result = getArrayParameterType(Ty: Result);
4977
4978 return getQualifiedType(T: Result, Qs: Quals);
4979}
4980
4981QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4982 Expr *AddrSpaceExpr,
4983 SourceLocation AttrLoc) const {
4984 assert(AddrSpaceExpr->isInstantiationDependent());
4985
4986 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4987
4988 llvm::FoldingSetInsertToken Token;
4989 llvm::FoldingSetNodeID ID;
4990 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4991 AddrSpaceExpr);
4992
4993 DependentAddressSpaceType *canonTy =
4994 DependentAddressSpaceTypes.lookup(ID, Token);
4995
4996 if (!canonTy) {
4997 canonTy = new (*this, alignof(DependentAddressSpaceType))
4998 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4999 AttrLoc);
5000 DependentAddressSpaceTypes.insert(N: canonTy, Token);
5001 Types.push_back(Elt: canonTy);
5002 }
5003
5004 if (canonPointeeType == PointeeType &&
5005 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
5006 return QualType(canonTy, 0);
5007
5008 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5009 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5010 AddrSpaceExpr, AttrLoc);
5011 Types.push_back(Elt: sugaredType);
5012 return QualType(sugaredType, 0);
5013}
5014
5015/// Determine whether \p T is canonical as the result type of a function.
5016static bool isCanonicalResultType(QualType T) {
5017 return T.isCanonical() &&
5018 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5019 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5020}
5021
5022/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5023QualType
5024ASTContext::getFunctionNoProtoType(QualType ResultTy,
5025 const FunctionType::ExtInfo &Info) const {
5026 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5027 // functionality creates a function without a prototype regardless of
5028 // language mode (so it makes them even in C++). Once the rewriter has been
5029 // fixed, this assertion can be enabled again.
5030 //assert(!LangOpts.requiresStrictPrototypes() &&
5031 // "strict prototypes are disabled");
5032
5033 // Unique functions, to guarantee there is only one function of a particular
5034 // structure.
5035 llvm::FoldingSetNodeID ID;
5036 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
5037
5038 llvm::FoldingSetInsertToken Token;
5039 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5040 return QualType(FT, 0);
5041
5042 QualType Canonical;
5043 if (!isCanonicalResultType(T: ResultTy)) {
5044 Canonical =
5045 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
5046
5047 // Get the new insert position for the node we care about.
5048 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5049 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5050 }
5051
5052 auto *New = new (*this, alignof(FunctionNoProtoType))
5053 FunctionNoProtoType(ResultTy, Canonical, Info);
5054 Types.push_back(Elt: New);
5055 FunctionNoProtoTypes.insert(N: New, Token);
5056 return QualType(New, 0);
5057}
5058
5059CanQualType
5060ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5061 CanQualType CanResultType = getCanonicalType(T: ResultType);
5062
5063 // Canonical result types do not have ARC lifetime qualifiers.
5064 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5065 Qualifiers Qs = CanResultType.getQualifiers();
5066 Qs.removeObjCLifetime();
5067 return CanQualType::CreateUnsafe(
5068 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5069 }
5070
5071 return CanResultType;
5072}
5073
5074static bool isCanonicalExceptionSpecification(
5075 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5076 if (ESI.Type == EST_None)
5077 return true;
5078 if (!NoexceptInType)
5079 return false;
5080
5081 // C++17 onwards: exception specification is part of the type, as a simple
5082 // boolean "can this function type throw".
5083 if (ESI.Type == EST_BasicNoexcept)
5084 return true;
5085
5086 // A noexcept(expr) specification is (possibly) canonical if expr is
5087 // value-dependent.
5088 if (ESI.Type == EST_DependentNoexcept)
5089 return true;
5090
5091 // A dynamic exception specification is canonical if it only contains pack
5092 // expansions (so we can't tell whether it's non-throwing) and all its
5093 // contained types are canonical.
5094 if (ESI.Type == EST_Dynamic) {
5095 bool AnyPackExpansions = false;
5096 for (QualType ET : ESI.Exceptions) {
5097 if (!ET.isCanonical())
5098 return false;
5099 if (ET->getAs<PackExpansionType>())
5100 AnyPackExpansions = true;
5101 }
5102 return AnyPackExpansions;
5103 }
5104
5105 return false;
5106}
5107
5108QualType ASTContext::getFunctionTypeInternal(
5109 QualType ResultTy, ArrayRef<QualType> ArgArray,
5110 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5111 size_t NumArgs = ArgArray.size();
5112
5113 // Unique functions, to guarantee there is only one function of a particular
5114 // structure.
5115 llvm::FoldingSetNodeID ID;
5116 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5117 Context: *this);
5118
5119 QualType Canonical;
5120 bool Unique = false;
5121
5122 llvm::FoldingSetInsertToken Token;
5123 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5124 QualType Existing = QualType(FPT, 0);
5125
5126 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5127 // it so long as our exception specification doesn't contain a dependent
5128 // noexcept expression, or we're just looking for a canonical type.
5129 // Otherwise, we're going to need to create a type
5130 // sugar node to hold the concrete expression.
5131 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5132 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5133 return Existing;
5134
5135 // We need a new type sugar node for this one, to hold the new noexcept
5136 // expression. We do no canonicalization here, but that's OK since we don't
5137 // expect to see the same noexcept expression much more than once.
5138 Canonical = getCanonicalType(T: Existing);
5139 Unique = true;
5140 }
5141
5142 bool NoexceptInType = getLangOpts().CPlusPlus17;
5143 bool IsCanonicalExceptionSpec =
5144 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5145
5146 // Determine whether the type being created is already canonical or not.
5147 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5148 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5149 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5150 if (!ArgArray[i].isCanonicalAsParam())
5151 isCanonical = false;
5152
5153 if (OnlyWantCanonical)
5154 assert(isCanonical &&
5155 "given non-canonical parameters constructing canonical type");
5156
5157 // If this type isn't canonical, get the canonical version of it if we don't
5158 // already have it. The exception spec is only partially part of the
5159 // canonical type, and only in C++17 onwards.
5160 if (!isCanonical && Canonical.isNull()) {
5161 SmallVector<QualType, 16> CanonicalArgs;
5162 CanonicalArgs.reserve(N: NumArgs);
5163 for (unsigned i = 0; i != NumArgs; ++i)
5164 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5165
5166 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5167 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5168 CanonicalEPI.HasTrailingReturn = false;
5169
5170 if (IsCanonicalExceptionSpec) {
5171 // Exception spec is already OK.
5172 } else if (NoexceptInType) {
5173 switch (EPI.ExceptionSpec.Type) {
5174 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5175 // We don't know yet. It shouldn't matter what we pick here; no-one
5176 // should ever look at this.
5177 [[fallthrough]];
5178 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5179 CanonicalEPI.ExceptionSpec.Type = EST_None;
5180 break;
5181
5182 // A dynamic exception specification is almost always "not noexcept",
5183 // with the exception that a pack expansion might expand to no types.
5184 case EST_Dynamic: {
5185 bool AnyPacks = false;
5186 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5187 if (ET->getAs<PackExpansionType>())
5188 AnyPacks = true;
5189 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5190 }
5191 if (!AnyPacks)
5192 CanonicalEPI.ExceptionSpec.Type = EST_None;
5193 else {
5194 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5195 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5196 }
5197 break;
5198 }
5199
5200 case EST_DynamicNone:
5201 case EST_BasicNoexcept:
5202 case EST_NoexceptTrue:
5203 case EST_NoThrow:
5204 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5205 break;
5206
5207 case EST_DependentNoexcept:
5208 llvm_unreachable("dependent noexcept is already canonical");
5209 }
5210 } else {
5211 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5212 }
5213
5214 // Adjust the canonical function result type.
5215 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5216 Canonical =
5217 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5218
5219 // Get the new insert position for the node we care about.
5220 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5221 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5222 }
5223
5224 // Compute the needed size to hold this FunctionProtoType and the
5225 // various trailing objects.
5226 auto ESH = FunctionProtoType::getExceptionSpecSize(
5227 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5228 size_t Size = FunctionProtoType::totalSizeToAlloc<
5229 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5230 FunctionType::FunctionTypeExtraAttributeInfo,
5231 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5232 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5233 FunctionEffect, EffectConditionExpr>(
5234 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5235 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5236 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5237 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5238 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5239 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5240 Counts: EPI.FunctionEffects.conditions().size());
5241
5242 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5243 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5244 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5245 Types.push_back(Elt: FTP);
5246 if (!Unique)
5247 FunctionProtoTypes.insert(N: FTP, Token);
5248 if (!EPI.FunctionEffects.empty())
5249 AnyFunctionEffects = true;
5250 return QualType(FTP, 0);
5251}
5252
5253QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5254 llvm::FoldingSetInsertToken Token;
5255 if (PipeType *PT = PipeTypes.lookup(Key: {T, ReadOnly}, Token))
5256 return QualType(PT, 0);
5257
5258 // If the pipe element type isn't canonical, this won't be a canonical type
5259 // either, so fill in the canonical type field.
5260 QualType Canonical;
5261 if (!T.isCanonical()) {
5262 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5263
5264 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5265 "Shouldn't be in the map!");
5266 }
5267 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5268 Types.push_back(Elt: New);
5269 PipeTypes.insert(N: New, Token);
5270 return QualType(New, 0);
5271}
5272
5273QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5274 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5275 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5276 : Ty;
5277}
5278
5279QualType ASTContext::getReadPipeType(QualType T) const {
5280 return getPipeType(T, ReadOnly: true);
5281}
5282
5283QualType ASTContext::getWritePipeType(QualType T) const {
5284 return getPipeType(T, ReadOnly: false);
5285}
5286
5287QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5288 auto Key = std::make_pair(x: unsigned(IsUnsigned), y&: NumBits);
5289
5290 llvm::FoldingSetInsertToken Token;
5291 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5292 return QualType(EIT, 0);
5293
5294 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5295 BitIntTypes.insert(N: New, Token);
5296 Types.push_back(Elt: New);
5297 return QualType(New, 0);
5298}
5299
5300QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5301 Expr *NumBitsExpr) const {
5302 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5303 llvm::FoldingSetNodeID ID;
5304 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5305
5306 llvm::FoldingSetInsertToken Token;
5307 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5308 return QualType(Existing, 0);
5309
5310 auto *New = new (*this, alignof(DependentBitIntType))
5311 DependentBitIntType(IsUnsigned, NumBitsExpr);
5312 DependentBitIntTypes.insert(N: New, Token);
5313
5314 Types.push_back(Elt: New);
5315 return QualType(New, 0);
5316}
5317
5318QualType
5319ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5320 using Kind = PredefinedSugarType::Kind;
5321
5322 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5323 Target != nullptr)
5324 return QualType(Target, 0);
5325
5326 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5327 switch (KDI) {
5328 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5329 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5330 // are part of the core language and are widely used. Using
5331 // PredefinedSugarType makes these types as named sugar types rather than
5332 // standard integer types, enabling better hints and diagnostics.
5333 case Kind::SizeT:
5334 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5335 case Kind::SignedSizeT:
5336 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5337 case Kind::PtrdiffT:
5338 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5339 }
5340 llvm_unreachable("unexpected kind");
5341 };
5342 auto *New = new (*this, alignof(PredefinedSugarType))
5343 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5344 getCanonicalType(*this, static_cast<Kind>(KD)));
5345 Types.push_back(Elt: New);
5346 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5347 return QualType(New, 0);
5348}
5349
5350QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5351 NestedNameSpecifier Qualifier,
5352 const TypeDecl *Decl) const {
5353 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5354 return getTagType(Keyword, Qualifier, TD: Tag,
5355 /*OwnsTag=*/false);
5356 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5357 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5358 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5359 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5360
5361 assert(Keyword == ElaboratedTypeKeyword::None);
5362 assert(!Qualifier);
5363 return QualType(Decl->TypeForDecl, 0);
5364}
5365
5366CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5367 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5368 return getCanonicalTagType(TD: Tag);
5369 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5370 return getCanonicalType(T: TN->getUnderlyingType());
5371 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5372 return getCanonicalUnresolvedUsingType(D: UD);
5373 assert(TD->TypeForDecl);
5374 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5375}
5376
5377QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5378 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5379 return getCanonicalTagType(TD);
5380 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5381 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5382 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5383 /*Qualifier=*/std::nullopt, Decl: TD);
5384 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5385 return getCanonicalUnresolvedUsingType(D: Using);
5386
5387 assert(Decl->TypeForDecl);
5388 return QualType(Decl->TypeForDecl, 0);
5389}
5390
5391/// getTypedefType - Return the unique reference to the type for the
5392/// specified typedef name decl.
5393QualType
5394ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5395 NestedNameSpecifier Qualifier,
5396 const TypedefNameDecl *Decl, QualType UnderlyingType,
5397 std::optional<bool> TypeMatchesDeclOrNone) const {
5398 if (!TypeMatchesDeclOrNone) {
5399 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5400 assert(!DeclUnderlyingType.isNull());
5401 if (UnderlyingType.isNull())
5402 UnderlyingType = DeclUnderlyingType;
5403 else
5404 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5405 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5406 } else {
5407 // FIXME: This is a workaround for a serialization cycle: assume the decl
5408 // underlying type is not available; don't touch it.
5409 assert(!UnderlyingType.isNull());
5410 }
5411
5412 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5413 *TypeMatchesDeclOrNone) {
5414 if (Decl->TypeForDecl)
5415 return QualType(Decl->TypeForDecl, 0);
5416
5417 auto *NewType = new (*this, alignof(TypedefType))
5418 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5419 !*TypeMatchesDeclOrNone);
5420
5421 Types.push_back(Elt: NewType);
5422 Decl->TypeForDecl = NewType;
5423 return QualType(NewType, 0);
5424 }
5425
5426 llvm::FoldingSetNodeID ID;
5427 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5428 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5429
5430 llvm::FoldingSetInsertToken Token;
5431 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5432 TypedefTypes.lookup(ID, Token))
5433 return QualType(Placeholder->getType(), 0);
5434
5435 void *Mem =
5436 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5437 NestedNameSpecifier, QualType>(
5438 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5439 Align: alignof(TypedefType));
5440 auto *NewType =
5441 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5442 UnderlyingType, !*TypeMatchesDeclOrNone);
5443 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5444 FoldingSetPlaceholder<TypedefType>();
5445 TypedefTypes.insert(N: Placeholder, Token);
5446 Types.push_back(Elt: NewType);
5447 return QualType(NewType, 0);
5448}
5449
5450QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5451 NestedNameSpecifier Qualifier,
5452 const UsingShadowDecl *D,
5453 QualType UnderlyingType) const {
5454 // FIXME: This is expensive to compute every time!
5455 if (UnderlyingType.isNull()) {
5456 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5457 UnderlyingType =
5458 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5459 : ElaboratedTypeKeyword::None,
5460 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5461 }
5462
5463 llvm::FoldingSetNodeID ID;
5464 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5465
5466 llvm::FoldingSetInsertToken Token;
5467 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5468 return QualType(T, 0);
5469
5470 assert(!UnderlyingType.hasLocalQualifiers());
5471
5472 assert(
5473 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5474 UnderlyingType));
5475
5476 void *Mem =
5477 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5478 Align: alignof(UsingType));
5479 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5480 Types.push_back(Elt: T);
5481 UsingTypes.insert(N: T, Token);
5482 return QualType(T, 0);
5483}
5484
5485TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5486 NestedNameSpecifier Qualifier,
5487 const TagDecl *TD, bool OwnsTag,
5488 bool IsInjected,
5489 const Type *CanonicalType,
5490 bool WithFoldingSetNode) const {
5491 auto [TC, Size] = [&] {
5492 switch (TD->getDeclKind()) {
5493 case Decl::Enum:
5494 static_assert(alignof(EnumType) == alignof(TagType));
5495 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5496 case Decl::ClassTemplatePartialSpecialization:
5497 case Decl::ClassTemplateSpecialization:
5498 case Decl::CXXRecord:
5499 static_assert(alignof(RecordType) == alignof(TagType));
5500 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5501 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5502 return std::make_tuple(args: Type::InjectedClassName,
5503 args: sizeof(InjectedClassNameType));
5504 [[fallthrough]];
5505 case Decl::Record:
5506 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5507 default:
5508 llvm_unreachable("unexpected decl kind");
5509 }
5510 }();
5511
5512 if (Qualifier) {
5513 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5514 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5515 sizeof(NestedNameSpecifier);
5516 }
5517 void *Mem;
5518 if (WithFoldingSetNode) {
5519 // FIXME: It would be more profitable to tail allocate the folding set node
5520 // from the type, instead of the other way around, due to the greater
5521 // alignment requirements of the type. But this makes it harder to deal with
5522 // the different type node sizes. This would require either uniquing from
5523 // different folding sets, or having the folding setaccept a
5524 // contextual parameter which is not fixed at construction.
5525 Mem = Allocate(
5526 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5527 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5528 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5529 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5530 Mem = T->getTagType();
5531 } else {
5532 Mem = Allocate(Size, Align: alignof(TagType));
5533 }
5534
5535 auto *T = [&, TC = TC]() -> TagType * {
5536 switch (TC) {
5537 case Type::Enum: {
5538 assert(isa<EnumDecl>(TD));
5539 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5540 IsInjected, CanonicalType);
5541 assert(reinterpret_cast<void *>(T) ==
5542 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5543 "TagType must be the first base of EnumType");
5544 return T;
5545 }
5546 case Type::Record: {
5547 assert(isa<RecordDecl>(TD));
5548 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5549 IsInjected, CanonicalType);
5550 assert(reinterpret_cast<void *>(T) ==
5551 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5552 "TagType must be the first base of RecordType");
5553 return T;
5554 }
5555 case Type::InjectedClassName: {
5556 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5557 IsInjected, CanonicalType);
5558 assert(reinterpret_cast<void *>(T) ==
5559 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5560 "TagType must be the first base of InjectedClassNameType");
5561 return T;
5562 }
5563 default:
5564 llvm_unreachable("unexpected type class");
5565 }
5566 }();
5567 assert(T->getKeyword() == Keyword);
5568 assert(T->getQualifier() == Qualifier);
5569 assert(T->getDecl() == TD);
5570 assert(T->isInjected() == IsInjected);
5571 assert(T->isTagOwned() == OwnsTag);
5572 assert((T->isCanonicalUnqualified()
5573 ? QualType()
5574 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5575 Types.push_back(Elt: T);
5576 return T;
5577}
5578
5579static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5580 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5581 RD && RD->isInjectedClassName())
5582 return cast<TagDecl>(Val: RD->getDeclContext());
5583 return TD;
5584}
5585
5586CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5587 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5588 if (TD->TypeForDecl)
5589 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5590
5591 const Type *CanonicalType = getTagTypeInternal(
5592 Keyword: ElaboratedTypeKeyword::None,
5593 /*Qualifier=*/std::nullopt, TD,
5594 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5595 /*WithFoldingSetNode=*/false);
5596 TD->TypeForDecl = CanonicalType;
5597 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5598}
5599
5600QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5601 NestedNameSpecifier Qualifier,
5602 const TagDecl *TD, bool OwnsTag) const {
5603
5604 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5605 bool IsInjected = TD != NonInjectedTD;
5606
5607 ElaboratedTypeKeyword PreferredKeyword =
5608 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5609 : KeywordHelpers::getKeywordForTagTypeKind(
5610 Tag: NonInjectedTD->getTagKind());
5611
5612 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5613 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5614 return QualType(T, 0);
5615
5616 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5617 const Type *T =
5618 getTagTypeInternal(Keyword,
5619 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5620 /*OwnsTag=*/false, IsInjected, CanonicalType,
5621 /*WithFoldingSetNode=*/false);
5622 TD->TypeForDecl = T;
5623 return QualType(T, 0);
5624 }
5625
5626 llvm::FoldingSetNodeID ID;
5627 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5628 OwnsTag, IsInjected);
5629
5630 llvm::FoldingSetInsertToken Token;
5631 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5632 return QualType(T->getTagType(), 0);
5633
5634 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5635 TagType *T =
5636 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5637 CanonicalType, /*WithFoldingSetNode=*/true);
5638 TagTypes.insert(N: TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5639 return QualType(T, 0);
5640}
5641
5642bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5643 unsigned NumPositiveBits,
5644 QualType &BestType,
5645 QualType &BestPromotionType) {
5646 unsigned IntWidth = Target->getIntWidth();
5647 unsigned CharWidth = Target->getCharWidth();
5648 unsigned ShortWidth = Target->getShortWidth();
5649 bool EnumTooLarge = false;
5650 unsigned BestWidth;
5651 if (NumNegativeBits) {
5652 // If there is a negative value, figure out the smallest integer type (of
5653 // int/long/longlong) that fits.
5654 // If it's packed, check also if it fits a char or a short.
5655 if (IsPacked && NumNegativeBits <= CharWidth &&
5656 NumPositiveBits < CharWidth) {
5657 BestType = SignedCharTy;
5658 BestWidth = CharWidth;
5659 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5660 NumPositiveBits < ShortWidth) {
5661 BestType = ShortTy;
5662 BestWidth = ShortWidth;
5663 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5664 BestType = IntTy;
5665 BestWidth = IntWidth;
5666 } else {
5667 BestWidth = Target->getLongWidth();
5668
5669 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5670 BestType = LongTy;
5671 } else {
5672 BestWidth = Target->getLongLongWidth();
5673
5674 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5675 EnumTooLarge = true;
5676 BestType = LongLongTy;
5677 }
5678 }
5679 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5680 } else {
5681 // If there is no negative value, figure out the smallest type that fits
5682 // all of the enumerator values.
5683 // If it's packed, check also if it fits a char or a short.
5684 if (IsPacked && NumPositiveBits <= CharWidth) {
5685 BestType = UnsignedCharTy;
5686 BestPromotionType = IntTy;
5687 BestWidth = CharWidth;
5688 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5689 BestType = UnsignedShortTy;
5690 BestPromotionType = IntTy;
5691 BestWidth = ShortWidth;
5692 } else if (NumPositiveBits <= IntWidth) {
5693 BestType = UnsignedIntTy;
5694 BestWidth = IntWidth;
5695 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5696 ? UnsignedIntTy
5697 : IntTy;
5698 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5699 BestType = UnsignedLongTy;
5700 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5701 ? UnsignedLongTy
5702 : LongTy;
5703 } else {
5704 BestWidth = Target->getLongLongWidth();
5705 if (NumPositiveBits > BestWidth) {
5706 // This can happen with bit-precise integer types, but those are not
5707 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5708 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5709 // a 128-bit integer, we should consider doing the same.
5710 EnumTooLarge = true;
5711 }
5712 BestType = UnsignedLongLongTy;
5713 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5714 ? UnsignedLongLongTy
5715 : LongLongTy;
5716 }
5717 }
5718 return EnumTooLarge;
5719}
5720
5721bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5722 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5723 "Integral type required!");
5724 unsigned BitWidth = getIntWidth(T);
5725
5726 if (Value.isUnsigned() || Value.isNonNegative()) {
5727 if (T->isSignedIntegerOrEnumerationType())
5728 --BitWidth;
5729 return Value.getActiveBits() <= BitWidth;
5730 }
5731 return Value.getSignificantBits() <= BitWidth;
5732}
5733
5734UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5735 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5736 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5737 const Type *CanonicalType) const {
5738 void *Mem = Allocate(
5739 Size: UnresolvedUsingType::totalSizeToAlloc<
5740 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5741 Counts: !!Token, Counts: !!Qualifier),
5742 Align: alignof(UnresolvedUsingType));
5743 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5744 if (Token) {
5745 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5746 FoldingSetPlaceholder<UnresolvedUsingType>();
5747 UnresolvedUsingTypes.insert(N: Placeholder, Token);
5748 }
5749 Types.push_back(Elt: T);
5750 return T;
5751}
5752
5753CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5754 const UnresolvedUsingTypenameDecl *D) const {
5755 D = D->getCanonicalDecl();
5756 if (D->TypeForDecl)
5757 return D->TypeForDecl->getCanonicalTypeUnqualified();
5758
5759 const Type *CanonicalType =
5760 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5761 /*Qualifier=*/std::nullopt, D,
5762 /*Token=*/{}, /*CanonicalType=*/nullptr);
5763 D->TypeForDecl = CanonicalType;
5764 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5765}
5766
5767QualType
5768ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5769 NestedNameSpecifier Qualifier,
5770 const UnresolvedUsingTypenameDecl *D) const {
5771 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5772 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5773 return QualType(T, 0);
5774
5775 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5776 const Type *T =
5777 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5778 /*Qualifier=*/std::nullopt, D,
5779 /*Token=*/{}, CanonicalType);
5780 D->TypeForDecl = T;
5781 return QualType(T, 0);
5782 }
5783
5784 llvm::FoldingSetNodeID ID;
5785 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5786
5787 llvm::FoldingSetInsertToken Token;
5788 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5789 UnresolvedUsingTypes.lookup(ID, Token))
5790 return QualType(Placeholder->getType(), 0);
5791 assert(Token);
5792
5793 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5794 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5795 CanonicalType);
5796 return QualType(T, 0);
5797}
5798
5799QualType ASTContext::getAttributedType(attr::Kind attrKind,
5800 QualType modifiedType,
5801 QualType equivalentType,
5802 const Attr *attr) const {
5803 llvm::FoldingSetNodeID id;
5804 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5805 attr);
5806
5807 llvm::FoldingSetInsertToken Token;
5808 AttributedType *type = AttributedTypes.lookup(ID: id, Token);
5809 if (type) return QualType(type, 0);
5810
5811 assert(!attr || attr->getKind() == attrKind);
5812
5813 QualType canon = getCanonicalType(T: equivalentType);
5814 type = new (*this, alignof(AttributedType))
5815 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5816
5817 Types.push_back(Elt: type);
5818 AttributedTypes.insert(N: type, Token);
5819
5820 return QualType(type, 0);
5821}
5822
5823QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5824 QualType equivalentType) const {
5825 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5826}
5827
5828QualType ASTContext::getAttributedType(NullabilityKind nullability,
5829 QualType modifiedType,
5830 QualType equivalentType) const {
5831 switch (nullability) {
5832 case NullabilityKind::NonNull:
5833 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5834
5835 case NullabilityKind::Nullable:
5836 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5837
5838 case NullabilityKind::NullableResult:
5839 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5840 equivalentType);
5841
5842 case NullabilityKind::Unspecified:
5843 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5844 equivalentType);
5845 }
5846
5847 llvm_unreachable("Unknown nullability kind");
5848}
5849
5850QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5851 QualType Wrapped) const {
5852 llvm::FoldingSetNodeID ID;
5853 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5854
5855 llvm::FoldingSetInsertToken Token;
5856 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5857 if (Ty)
5858 return QualType(Ty, 0);
5859
5860 QualType Canon = getCanonicalType(T: Wrapped);
5861 Ty = new (*this, alignof(BTFTagAttributedType))
5862 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5863
5864 Types.push_back(Elt: Ty);
5865 BTFTagAttributedTypes.insert(N: Ty, Token);
5866
5867 return QualType(Ty, 0);
5868}
5869
5870QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5871 QualType Underlying) const {
5872 const IdentifierInfo *II = Attr->getBehaviorKind();
5873 StringRef IdentName = II->getName();
5874 OverflowBehaviorType::OverflowBehaviorKind Kind;
5875 if (IdentName == "wrap") {
5876 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5877 } else if (IdentName == "trap") {
5878 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5879 } else {
5880 return Underlying;
5881 }
5882
5883 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5884}
5885
5886QualType ASTContext::getOverflowBehaviorType(
5887 OverflowBehaviorType::OverflowBehaviorKind Kind,
5888 QualType Underlying) const {
5889 assert(!Underlying->isOverflowBehaviorType() &&
5890 "Cannot have underlying types that are themselves OBTs");
5891
5892 llvm::FoldingSetInsertToken Token;
5893 if (OverflowBehaviorType *OBT =
5894 OverflowBehaviorTypes.lookup(Key: {Underlying, Kind}, Token)) {
5895 return QualType(OBT, 0);
5896 }
5897
5898 QualType Canonical;
5899 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5900 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5901 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5902 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5903 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5904 "Shouldn't be in the map");
5905 }
5906
5907 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5908 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5909
5910 Types.push_back(Elt: Ty);
5911 OverflowBehaviorTypes.insert(N: Ty, Token);
5912 return QualType(Ty, 0);
5913}
5914
5915QualType ASTContext::getHLSLAttributedResourceType(
5916 QualType Wrapped, QualType Contained,
5917 const HLSLAttributedResourceType::Attributes &Attrs) {
5918
5919 llvm::FoldingSetNodeID ID;
5920 HLSLAttributedResourceType::Profile(ID, Ctx: *this, Wrapped, Contained, Attrs);
5921
5922 llvm::FoldingSetInsertToken Token;
5923 HLSLAttributedResourceType *Ty =
5924 HLSLAttributedResourceTypes.lookup(ID, Token);
5925 if (Ty)
5926 return QualType(Ty, 0);
5927
5928 Ty = new (*this, alignof(HLSLAttributedResourceType))
5929 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5930
5931 Types.push_back(Elt: Ty);
5932 HLSLAttributedResourceTypes.insert(N: Ty, Token);
5933
5934 return QualType(Ty, 0);
5935}
5936
5937QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5938 uint32_t Alignment,
5939 ArrayRef<SpirvOperand> Operands) {
5940 llvm::FoldingSetNodeID ID;
5941 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5942
5943 llvm::FoldingSetInsertToken Token;
5944 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5945 if (Ty)
5946 return QualType(Ty, 0);
5947
5948 void *Mem = Allocate(
5949 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5950 Align: alignof(HLSLInlineSpirvType));
5951
5952 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5953
5954 Types.push_back(Elt: Ty);
5955 HLSLInlineSpirvTypes.insert(N: Ty, Token);
5956
5957 return QualType(Ty, 0);
5958}
5959
5960/// Retrieve a substitution-result type.
5961QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5962 Decl *AssociatedDecl,
5963 unsigned Index,
5964 UnsignedOrNone PackIndex,
5965 bool Final) const {
5966 auto Key =
5967 std::make_tuple(args&: Replacement, args&: AssociatedDecl, args&: Index,
5968 args: PackIndex.toInternalRepresentation(), args: unsigned(Final));
5969 llvm::FoldingSetInsertToken Token;
5970 SubstTemplateTypeParmType *SubstParm =
5971 SubstTemplateTypeParmTypes.lookup(Key, Token);
5972
5973 if (!SubstParm) {
5974 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5975 Counts: !Replacement.isCanonical()),
5976 Align: alignof(SubstTemplateTypeParmType));
5977 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5978 Index, PackIndex, Final);
5979 Types.push_back(Elt: SubstParm);
5980 SubstTemplateTypeParmTypes.insert(N: SubstParm, Token);
5981 }
5982
5983 return QualType(SubstParm, 0);
5984}
5985
5986QualType
5987ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5988 unsigned Index, bool Final,
5989 const TemplateArgument &ArgPack) {
5990#ifndef NDEBUG
5991 for (const auto &P : ArgPack.pack_elements())
5992 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5993#endif
5994
5995 llvm::FoldingSetNodeID ID;
5996 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5997 ArgPack);
5998 llvm::FoldingSetInsertToken Token;
5999 if (SubstTemplateTypeParmPackType *SubstParm =
6000 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
6001 return QualType(SubstParm, 0);
6002
6003 QualType Canon;
6004 {
6005 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6006 if (!AssociatedDecl->isCanonicalDecl() ||
6007 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
6008 Canon = getSubstTemplateTypeParmPackType(
6009 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
6010 [[maybe_unused]] const auto *Nothing =
6011 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6012 assert(!Nothing);
6013 }
6014 }
6015
6016 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6017 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6018 ArgPack);
6019 Types.push_back(Elt: SubstParm);
6020 SubstTemplateTypeParmPackTypes.insert(N: SubstParm, Token);
6021 return QualType(SubstParm, 0);
6022}
6023
6024QualType
6025ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
6026 assert(llvm::all_of(ArgPack.pack_elements(),
6027 [](const auto &P) {
6028 return P.getKind() == TemplateArgument::Type;
6029 }) &&
6030 "Pack contains a non-type");
6031
6032 llvm::FoldingSetNodeID ID;
6033 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6034
6035 llvm::FoldingSetInsertToken Token;
6036 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6037 return QualType(T, 0);
6038
6039 QualType Canon;
6040 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6041 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6042 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6043 // Refresh Token, in case the recursive call above caused rehashing,
6044 // which would invalidate the bucket pointer.
6045 [[maybe_unused]] const auto *Nothing =
6046 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6047 assert(!Nothing);
6048 }
6049
6050 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6051 SubstBuiltinTemplatePackType(Canon, ArgPack);
6052 Types.push_back(Elt: PackType);
6053 SubstBuiltinTemplatePackTypes.insert(N: PackType, Token);
6054 return QualType(PackType, 0);
6055}
6056
6057/// Retrieve the template type parameter type for a template
6058/// parameter or parameter pack with the given depth, index, and (optionally)
6059/// name.
6060QualType
6061ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6062 TemplateTypeParmDecl *TTPDecl) const {
6063 assert(Depth >= 0 && "Depth must be non-negative");
6064 assert(Index >= 0 && "Index must be non-negative");
6065
6066 auto Key = std::make_tuple(args: unsigned(Depth), args: unsigned(Index),
6067 args: unsigned(ParameterPack), args&: TTPDecl);
6068 llvm::FoldingSetInsertToken Token;
6069 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6070
6071 if (TypeParm)
6072 return QualType(TypeParm, 0);
6073
6074 if (TTPDecl) {
6075 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6076 TypeParm = new (*this, alignof(TemplateTypeParmType))
6077 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6078 } else
6079 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6080 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6081
6082 Types.push_back(Elt: TypeParm);
6083 TemplateTypeParmTypes.insert(N: TypeParm, Token);
6084
6085 return QualType(TypeParm, 0);
6086}
6087
6088static ElaboratedTypeKeyword
6089getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6090 switch (Keyword) {
6091 // These are just themselves.
6092 case ElaboratedTypeKeyword::None:
6093 case ElaboratedTypeKeyword::Struct:
6094 case ElaboratedTypeKeyword::Union:
6095 case ElaboratedTypeKeyword::Enum:
6096 case ElaboratedTypeKeyword::Interface:
6097 return Keyword;
6098
6099 // These are equivalent.
6100 case ElaboratedTypeKeyword::Typename:
6101 return ElaboratedTypeKeyword::None;
6102
6103 // These are functionally equivalent, so relying on their equivalence is
6104 // IFNDR. By making them equivalent, we disallow overloading, which at least
6105 // can produce a diagnostic.
6106 case ElaboratedTypeKeyword::Class:
6107 return ElaboratedTypeKeyword::Struct;
6108 }
6109 llvm_unreachable("unexpected keyword kind");
6110}
6111
6112TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6113 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6114 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6115 TemplateName Name, SourceLocation NameLoc,
6116 const TemplateArgumentListInfo &SpecifiedArgs,
6117 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6118 QualType TST = getTemplateSpecializationType(
6119 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6120
6121 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6122 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6123 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6124 TAL: SpecifiedArgs);
6125 return TSI;
6126}
6127
6128QualType ASTContext::getTemplateSpecializationType(
6129 ElaboratedTypeKeyword Keyword, TemplateName Template,
6130 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6131 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6132 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6133 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6134 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6135 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6136
6137 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6138 CanonicalArgs, Underlying);
6139}
6140
6141[[maybe_unused]] static bool
6142hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6143 for (const TemplateArgument &Arg : Args)
6144 if (Arg.isPackExpansion())
6145 return true;
6146 return false;
6147}
6148
6149QualType ASTContext::getCanonicalTemplateSpecializationType(
6150 ElaboratedTypeKeyword Keyword, TemplateName Template,
6151 ArrayRef<TemplateArgument> Args) const {
6152 assert(Template ==
6153 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6154 assert((Keyword == ElaboratedTypeKeyword::None ||
6155 Template.getAsDependentTemplateName()));
6156#ifndef NDEBUG
6157 for (const auto &Arg : Args)
6158 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6159#endif
6160
6161 llvm::FoldingSetNodeID ID;
6162 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6163 Context: *this);
6164 llvm::FoldingSetInsertToken Token;
6165 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6166 return QualType(T, 0);
6167
6168 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6169 sizeof(TemplateArgument) * Args.size(),
6170 Align: alignof(TemplateSpecializationType));
6171 auto *Spec =
6172 new (Mem) TemplateSpecializationType(Keyword, Template,
6173 /*IsAlias=*/false, Args, QualType());
6174 assert(Spec->isDependentType() &&
6175 "canonical template specialization must be dependent");
6176 Types.push_back(Elt: Spec);
6177 TemplateSpecializationTypes.insert(N: Spec, Token);
6178 return QualType(Spec, 0);
6179}
6180
6181QualType ASTContext::getTemplateSpecializationType(
6182 ElaboratedTypeKeyword Keyword, TemplateName Template,
6183 ArrayRef<TemplateArgument> SpecifiedArgs,
6184 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6185 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6186 bool IsTypeAlias = TD && TD->isTypeAlias();
6187 if (Underlying.isNull()) {
6188 TemplateName CanonTemplate =
6189 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6190 ElaboratedTypeKeyword CanonKeyword =
6191 CanonTemplate.getAsDependentTemplateName()
6192 ? getCanonicalElaboratedTypeKeyword(Keyword)
6193 : ElaboratedTypeKeyword::None;
6194 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6195 SmallVector<TemplateArgument, 4> CanonArgsVec;
6196 if (CanonicalArgs.empty()) {
6197 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6198 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6199 CanonicalArgs = CanonArgsVec;
6200 } else {
6201 NonCanonical |= !llvm::equal(
6202 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6203 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6204 return A.structurallyEquals(Other: B);
6205 });
6206 }
6207
6208 // We can get here with an alias template when the specialization
6209 // contains a pack expansion that does not match up with a parameter
6210 // pack, or a builtin template which cannot be resolved due to dependency.
6211 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6212 hasAnyPackExpansions(CanonicalArgs)) &&
6213 "Caller must compute aliased type");
6214 IsTypeAlias = false;
6215
6216 Underlying = getCanonicalTemplateSpecializationType(
6217 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6218 if (!NonCanonical)
6219 return Underlying;
6220 }
6221 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6222 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6223 (IsTypeAlias ? sizeof(QualType) : 0),
6224 Align: alignof(TemplateSpecializationType));
6225 auto *Spec = new (Mem) TemplateSpecializationType(
6226 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6227 Types.push_back(Elt: Spec);
6228 return QualType(Spec, 0);
6229}
6230
6231QualType
6232ASTContext::getParenType(QualType InnerType) const {
6233 llvm::FoldingSetInsertToken Token;
6234 ParenType *T = ParenTypes.lookup(Key: InnerType, Token);
6235 if (T)
6236 return QualType(T, 0);
6237
6238 QualType Canon = InnerType;
6239 if (!Canon.isCanonical()) {
6240 Canon = getCanonicalType(T: InnerType);
6241 assert(!ParenTypes.lookup(InnerType, Token) &&
6242 "Paren canonical type broken");
6243 }
6244
6245 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6246 Types.push_back(Elt: T);
6247 ParenTypes.insert(N: T, Token);
6248 return QualType(T, 0);
6249}
6250
6251QualType
6252ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6253 const IdentifierInfo *MacroII) const {
6254 QualType Canon = UnderlyingTy;
6255 if (!Canon.isCanonical())
6256 Canon = getCanonicalType(T: UnderlyingTy);
6257
6258 auto *newType = new (*this, alignof(MacroQualifiedType))
6259 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6260 Types.push_back(Elt: newType);
6261 return QualType(newType, 0);
6262}
6263
6264QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6265 NestedNameSpecifier NNS,
6266 const IdentifierInfo *Name) const {
6267 llvm::FoldingSetNodeID ID;
6268 DependentNameType::Profile(ID, Keyword, NNS, Name);
6269
6270 llvm::FoldingSetInsertToken Token;
6271 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6272 return QualType(T, 0);
6273
6274 ElaboratedTypeKeyword CanonKeyword =
6275 getCanonicalElaboratedTypeKeyword(Keyword);
6276 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6277
6278 QualType Canon;
6279 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6280 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6281 [[maybe_unused]] DependentNameType *T =
6282 DependentNameTypes.lookup(ID, Token);
6283 assert(!T && "broken canonicalization");
6284 assert(Canon.isCanonical());
6285 }
6286
6287 DependentNameType *T = new (*this, alignof(DependentNameType))
6288 DependentNameType(Keyword, NNS, Name, Canon);
6289 Types.push_back(Elt: T);
6290 DependentNameTypes.insert(N: T, Token);
6291 return QualType(T, 0);
6292}
6293
6294TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6295 TemplateArgument Arg;
6296 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6297 QualType ArgType = getTypeDeclType(Decl: TTP);
6298 if (TTP->isParameterPack())
6299 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6300
6301 Arg = TemplateArgument(ArgType);
6302 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6303 QualType T =
6304 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6305 // For class NTTPs, ensure we include the 'const' so the type matches that
6306 // of a real template argument.
6307 // FIXME: It would be more faithful to model this as something like an
6308 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6309 ExprValueKind VK = VK_PRValue;
6310 if (NTTP->getType()->isReferenceType()) {
6311 // As in Sema::BuildDeclarationNameExpr, a parameter of reference
6312 // type, even an rvalue reference, is an lvalue.
6313 VK = VK_LValue;
6314 } else if (T->isRecordType()) {
6315 // C++ [temp.param]p8: An id-expression naming a non-type
6316 // template-parameter of class type T denotes a static storage duration
6317 // object of type const T.
6318 T.addConst();
6319 VK = VK_LValue;
6320 }
6321 Expr *E = new (*this)
6322 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6323 T, VK, NTTP->getLocation());
6324
6325 if (NTTP->isParameterPack())
6326 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6327 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6328 } else {
6329 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6330 TemplateName Name = getQualifiedTemplateName(
6331 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6332 Template: TemplateName(TTP));
6333 if (TTP->isParameterPack())
6334 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6335 else
6336 Arg = TemplateArgument(Name);
6337 }
6338
6339 if (Param->isTemplateParameterPack())
6340 Arg =
6341 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6342
6343 return Arg;
6344}
6345
6346QualType ASTContext::getPackExpansionType(QualType Pattern,
6347 UnsignedOrNone NumExpansions,
6348 bool ExpectPackInType) const {
6349 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6350 "Pack expansions must expand one or more parameter packs");
6351
6352 auto Key = std::make_pair(x&: Pattern, y: NumExpansions.toInternalRepresentation());
6353
6354 llvm::FoldingSetInsertToken Token;
6355 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6356 if (T)
6357 return QualType(T, 0);
6358
6359 QualType Canon;
6360 if (!Pattern.isCanonical()) {
6361 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6362 /*ExpectPackInType=*/false);
6363
6364 // Find the insert position again, in case we inserted an element into
6365 // PackExpansionTypes and invalidated our insert position.
6366 PackExpansionTypes.lookup(Key, Token);
6367 }
6368
6369 T = new (*this, alignof(PackExpansionType))
6370 PackExpansionType(Pattern, Canon, NumExpansions);
6371 Types.push_back(Elt: T);
6372 PackExpansionTypes.insert(N: T, Token);
6373 return QualType(T, 0);
6374}
6375
6376/// CmpProtocolNames - Comparison predicate for sorting protocols
6377/// alphabetically.
6378static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6379 ObjCProtocolDecl *const *RHS) {
6380 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6381}
6382
6383static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6384 if (Protocols.empty()) return true;
6385
6386 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6387 return false;
6388
6389 for (unsigned i = 1; i != Protocols.size(); ++i)
6390 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6391 Protocols[i]->getCanonicalDecl() != Protocols[i])
6392 return false;
6393 return true;
6394}
6395
6396static void
6397SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6398 // Sort protocols, keyed by name.
6399 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6400
6401 // Canonicalize.
6402 for (ObjCProtocolDecl *&P : Protocols)
6403 P = P->getCanonicalDecl();
6404
6405 // Remove duplicates.
6406 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6407 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6408}
6409
6410QualType ASTContext::getObjCObjectType(QualType BaseType,
6411 ObjCProtocolDecl * const *Protocols,
6412 unsigned NumProtocols) const {
6413 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6414 /*isKindOf=*/false);
6415}
6416
6417QualType ASTContext::getObjCObjectType(
6418 QualType baseType,
6419 ArrayRef<QualType> typeArgs,
6420 ArrayRef<ObjCProtocolDecl *> protocols,
6421 bool isKindOf) const {
6422 // If the base type is an interface and there aren't any protocols or
6423 // type arguments to add, then the interface type will do just fine.
6424 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6425 isa<ObjCInterfaceType>(Val: baseType))
6426 return baseType;
6427
6428 // Look in the folding set for an existing type.
6429 llvm::FoldingSetNodeID ID;
6430 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6431 llvm::FoldingSetInsertToken Token;
6432 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6433 return QualType(QT, 0);
6434
6435 // Determine the type arguments to be used for canonicalization,
6436 // which may be explicitly specified here or written on the base
6437 // type.
6438 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6439 if (effectiveTypeArgs.empty()) {
6440 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6441 effectiveTypeArgs = baseObject->getTypeArgs();
6442 }
6443
6444 // Build the canonical type, which has the canonical base type and a
6445 // sorted-and-uniqued list of protocols and the type arguments
6446 // canonicalized.
6447 QualType canonical;
6448 bool typeArgsAreCanonical = llvm::all_of(
6449 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6450 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6451 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6452 // Determine the canonical type arguments.
6453 ArrayRef<QualType> canonTypeArgs;
6454 SmallVector<QualType, 4> canonTypeArgsVec;
6455 if (!typeArgsAreCanonical) {
6456 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6457 for (auto typeArg : effectiveTypeArgs)
6458 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6459 canonTypeArgs = canonTypeArgsVec;
6460 } else {
6461 canonTypeArgs = effectiveTypeArgs;
6462 }
6463
6464 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6465 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6466 if (!protocolsSorted) {
6467 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6468 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6469 canonProtocols = canonProtocolsVec;
6470 } else {
6471 canonProtocols = protocols;
6472 }
6473
6474 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6475 protocols: canonProtocols, isKindOf);
6476
6477 // Regenerate Token.
6478 ObjCObjectTypes.lookup(ID, Token);
6479 }
6480
6481 unsigned size = sizeof(ObjCObjectTypeImpl);
6482 size += typeArgs.size() * sizeof(QualType);
6483 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6484 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6485 auto *T =
6486 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6487 isKindOf);
6488
6489 Types.push_back(Elt: T);
6490 ObjCObjectTypes.insert(N: T, Token);
6491 return QualType(T, 0);
6492}
6493
6494/// Apply Objective-C protocol qualifiers to the given type.
6495/// If this is for the canonical type of a type parameter, we can apply
6496/// protocol qualifiers on the ObjCObjectPointerType.
6497QualType
6498ASTContext::applyObjCProtocolQualifiers(QualType type,
6499 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6500 bool allowOnPointerType) const {
6501 hasError = false;
6502
6503 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6504 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6505 }
6506
6507 // Apply protocol qualifiers to ObjCObjectPointerType.
6508 if (allowOnPointerType) {
6509 if (const auto *objPtr =
6510 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6511 const ObjCObjectType *objT = objPtr->getObjectType();
6512 // Merge protocol lists and construct ObjCObjectType.
6513 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6514 protocolsVec.append(in_start: objT->qual_begin(),
6515 in_end: objT->qual_end());
6516 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6517 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6518 type = getObjCObjectType(
6519 baseType: objT->getBaseType(),
6520 typeArgs: objT->getTypeArgsAsWritten(),
6521 protocols,
6522 isKindOf: objT->isKindOfTypeAsWritten());
6523 return getObjCObjectPointerType(OIT: type);
6524 }
6525 }
6526
6527 // Apply protocol qualifiers to ObjCObjectType.
6528 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6529 // FIXME: Check for protocols to which the class type is already
6530 // known to conform.
6531
6532 return getObjCObjectType(baseType: objT->getBaseType(),
6533 typeArgs: objT->getTypeArgsAsWritten(),
6534 protocols,
6535 isKindOf: objT->isKindOfTypeAsWritten());
6536 }
6537
6538 // If the canonical type is ObjCObjectType, ...
6539 if (type->isObjCObjectType()) {
6540 // Silently overwrite any existing protocol qualifiers.
6541 // TODO: determine whether that's the right thing to do.
6542
6543 // FIXME: Check for protocols to which the class type is already
6544 // known to conform.
6545 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6546 }
6547
6548 // id<protocol-list>
6549 if (type->isObjCIdType()) {
6550 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6551 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6552 isKindOf: objPtr->isKindOfType());
6553 return getObjCObjectPointerType(OIT: type);
6554 }
6555
6556 // Class<protocol-list>
6557 if (type->isObjCClassType()) {
6558 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6559 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6560 isKindOf: objPtr->isKindOfType());
6561 return getObjCObjectPointerType(OIT: type);
6562 }
6563
6564 hasError = true;
6565 return type;
6566}
6567
6568QualType
6569ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6570 ArrayRef<ObjCProtocolDecl *> protocols) const {
6571 // We canonicalize to the underlying type.
6572 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6573 if (!protocols.empty()) {
6574 // Apply the protocol qualifers.
6575 bool hasError;
6576 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6577 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6578 assert(!hasError && "Error when apply protocol qualifier to bound type");
6579 }
6580
6581 // Key on the canonical type the node is constructed with, which is what
6582 // Profile() reports; the decl's underlying type can be updated later.
6583 auto Key = std::make_tuple(args&: Decl, args&: Canonical, args&: protocols);
6584 llvm::FoldingSetInsertToken Token;
6585 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6586 return QualType(TypeParam, 0);
6587
6588 unsigned size = sizeof(ObjCTypeParamType);
6589 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6590 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6591 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6592
6593 Types.push_back(Elt: newType);
6594 ObjCTypeParamTypes.insert(N: newType, Token);
6595 return QualType(newType, 0);
6596}
6597
6598void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6599 ObjCTypeParamDecl *New) const {
6600 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6601 // Update TypeForDecl after updating TypeSourceInfo.
6602 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6603 SmallVector<ObjCProtocolDecl *, 8> protocols;
6604 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6605 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6606 New->TypeForDecl = UpdatedTy.getTypePtr();
6607}
6608
6609/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6610/// protocol list adopt all protocols in QT's qualified-id protocol
6611/// list.
6612bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6613 ObjCInterfaceDecl *IC) {
6614 if (!QT->isObjCQualifiedIdType())
6615 return false;
6616
6617 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6618 // If both the right and left sides have qualifiers.
6619 for (auto *Proto : OPT->quals()) {
6620 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6621 return false;
6622 }
6623 return true;
6624 }
6625 return false;
6626}
6627
6628/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6629/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6630/// of protocols.
6631bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6632 ObjCInterfaceDecl *IDecl) {
6633 if (!QT->isObjCQualifiedIdType())
6634 return false;
6635 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6636 if (!OPT)
6637 return false;
6638 if (!IDecl->hasDefinition())
6639 return false;
6640 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6641 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6642 if (InheritedProtocols.empty())
6643 return false;
6644 // Check that if every protocol in list of id<plist> conforms to a protocol
6645 // of IDecl's, then bridge casting is ok.
6646 bool Conforms = false;
6647 for (auto *Proto : OPT->quals()) {
6648 Conforms = false;
6649 for (auto *PI : InheritedProtocols) {
6650 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6651 Conforms = true;
6652 break;
6653 }
6654 }
6655 if (!Conforms)
6656 break;
6657 }
6658 if (Conforms)
6659 return true;
6660
6661 for (auto *PI : InheritedProtocols) {
6662 // If both the right and left sides have qualifiers.
6663 bool Adopts = false;
6664 for (auto *Proto : OPT->quals()) {
6665 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6666 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6667 break;
6668 }
6669 if (!Adopts)
6670 return false;
6671 }
6672 return true;
6673}
6674
6675/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6676/// the given object type.
6677QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6678 llvm::FoldingSetInsertToken Token;
6679 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(Key: ObjectT, Token))
6680 return QualType(QT, 0);
6681
6682 // Find the canonical object type.
6683 QualType Canonical;
6684 if (!ObjectT.isCanonical())
6685 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6686
6687 // No match.
6688 void *Mem =
6689 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6690 auto *QType =
6691 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6692
6693 Types.push_back(Elt: QType);
6694 ObjCObjectPointerTypes.insert(N: QType, Token);
6695 return QualType(QType, 0);
6696}
6697
6698/// getObjCInterfaceType - Return the unique reference to the type for the
6699/// specified ObjC interface decl. The list of protocols is optional.
6700QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6701 ObjCInterfaceDecl *PrevDecl) const {
6702 if (Decl->TypeForDecl)
6703 return QualType(Decl->TypeForDecl, 0);
6704
6705 if (PrevDecl) {
6706 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6707 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6708 return QualType(PrevDecl->TypeForDecl, 0);
6709 }
6710
6711 // Prefer the definition, if there is one.
6712 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6713 Decl = Def;
6714
6715 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6716 auto *T = new (Mem) ObjCInterfaceType(Decl);
6717 Decl->TypeForDecl = T;
6718 Types.push_back(Elt: T);
6719 return QualType(T, 0);
6720}
6721
6722/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6723/// TypeOfExprType AST's (since expression's are never shared). For example,
6724/// multiple declarations that refer to "typeof(x)" all contain different
6725/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6726/// on canonical type's (which are always unique).
6727QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6728 TypeOfExprType *toe;
6729 if (tofExpr->isTypeDependent()) {
6730 llvm::FoldingSetNodeID ID;
6731 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6732 IsUnqual: Kind == TypeOfKind::Unqualified);
6733
6734 llvm::FoldingSetInsertToken Token;
6735 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6736 if (Canon) {
6737 // We already have a "canonical" version of an identical, dependent
6738 // typeof(expr) type. Use that as our canonical type.
6739 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6740 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6741 } else {
6742 // Build a new, canonical typeof(expr) type.
6743 Canon = new (*this, alignof(DependentTypeOfExprType))
6744 DependentTypeOfExprType(*this, tofExpr, Kind);
6745 DependentTypeOfExprTypes.insert(N: Canon, Token);
6746 toe = Canon;
6747 }
6748 } else {
6749 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6750 toe = new (*this, alignof(TypeOfExprType))
6751 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6752 }
6753 Types.push_back(Elt: toe);
6754 return QualType(toe, 0);
6755}
6756
6757/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6758/// TypeOfType nodes. The only motivation to unique these nodes would be
6759/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6760/// an issue. This doesn't affect the type checker, since it operates
6761/// on canonical types (which are always unique).
6762QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6763 QualType Canonical = getCanonicalType(T: tofType);
6764 auto *tot = new (*this, alignof(TypeOfType))
6765 TypeOfType(*this, tofType, Canonical, Kind);
6766 Types.push_back(Elt: tot);
6767 return QualType(tot, 0);
6768}
6769
6770/// getReferenceQualifiedType - Given an expr, will return the type for
6771/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6772/// and class member access into account.
6773QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6774 // C++11 [dcl.type.simple]p4:
6775 // [...]
6776 QualType T = E->getType();
6777 switch (E->getValueKind()) {
6778 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6779 // type of e;
6780 case VK_XValue:
6781 return getRValueReferenceType(T);
6782 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6783 // type of e;
6784 case VK_LValue:
6785 return getLValueReferenceType(T);
6786 // - otherwise, decltype(e) is the type of e.
6787 case VK_PRValue:
6788 return T;
6789 }
6790 llvm_unreachable("Unknown value kind");
6791}
6792
6793/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6794/// nodes. This would never be helpful, since each such type has its own
6795/// expression, and would not give a significant memory saving, since there
6796/// is an Expr tree under each such type.
6797QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6798 // C++11 [temp.type]p2:
6799 // If an expression e involves a template parameter, decltype(e) denotes a
6800 // unique dependent type. Two such decltype-specifiers refer to the same
6801 // type only if their expressions are equivalent (14.5.6.1).
6802 QualType CanonType;
6803 if (!E->isInstantiationDependent()) {
6804 CanonType = getCanonicalType(T: UnderlyingType);
6805 } else if (!UnderlyingType.isNull()) {
6806 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6807 } else {
6808 llvm::FoldingSetNodeID ID;
6809 DependentDecltypeType::Profile(ID, Context: *this, E);
6810
6811 llvm::FoldingSetInsertToken Token;
6812 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6813 return QualType(Canon, 0);
6814
6815 // Build a new, canonical decltype(expr) type.
6816 auto *DT =
6817 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6818 DependentDecltypeTypes.insert(N: DT, Token);
6819 Types.push_back(Elt: DT);
6820 return QualType(DT, 0);
6821 }
6822 auto *DT = new (*this, alignof(DecltypeType))
6823 DecltypeType(E, UnderlyingType, CanonType);
6824 Types.push_back(Elt: DT);
6825 return QualType(DT, 0);
6826}
6827
6828QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6829 bool FullySubstituted,
6830 ArrayRef<QualType> Expansions,
6831 UnsignedOrNone Index) const {
6832 QualType Canonical;
6833 if (FullySubstituted && Index) {
6834 Canonical = getCanonicalType(T: Expansions[*Index]);
6835 } else {
6836 llvm::FoldingSetNodeID ID;
6837 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6838 FullySubstituted, Expansions);
6839 llvm::FoldingSetInsertToken Token;
6840 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6841 if (!Canon) {
6842 void *Mem = Allocate(
6843 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6844 Align: TypeAlignment);
6845 Canon =
6846 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6847 IndexExpr, FullySubstituted, Expansions);
6848 DependentPackIndexingTypes.insert(N: Canon, Token);
6849 }
6850 Canonical = QualType(Canon, 0);
6851 }
6852
6853 void *Mem =
6854 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6855 Align: TypeAlignment);
6856 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6857 FullySubstituted, Expansions);
6858 Types.push_back(Elt: T);
6859 return QualType(T, 0);
6860}
6861
6862/// getUnaryTransformationType - We don't unique these, since the memory
6863/// savings are minimal and these are rare.
6864QualType
6865ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6866 UnaryTransformType::UTTKind Kind) const {
6867 // Clear UnderlyingType for a dependent base before building the ID: that is
6868 // what the node is constructed with, and what Profile() reports.
6869 if (BaseType->isDependentType()) {
6870 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6871 UnderlyingType = QualType();
6872 }
6873
6874 auto Key = std::make_tuple(args&: BaseType, args&: UnderlyingType, args&: Kind);
6875
6876 llvm::FoldingSetInsertToken Token;
6877 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6878 return QualType(UT, 0);
6879
6880 QualType CanonType;
6881 if (!BaseType->isDependentType()) {
6882 CanonType = UnderlyingType.getCanonicalType();
6883 } else {
6884 if (QualType CanonBase = BaseType.getCanonicalType();
6885 BaseType != CanonBase) {
6886 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6887 assert(CanonType.isCanonical());
6888 }
6889 }
6890
6891 auto *UT = new (*this, alignof(UnaryTransformType))
6892 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6893 UnaryTransformTypes.insert(N: UT, Token);
6894 Types.push_back(Elt: UT);
6895 return QualType(UT, 0);
6896}
6897
6898/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6899/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6900/// canonical deduced-but-dependent 'auto' type.
6901QualType
6902ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6903 AutoTypeKeyword Keyword,
6904 TemplateName TypeConstraintConcept,
6905 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6906 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6907 TypeConstraintConcept.isNull()) {
6908 assert(DeducedAsType.isNull() && "");
6909 assert(TypeConstraintArgs.empty() && "");
6910 return getAutoDeductType();
6911 }
6912
6913 // Look in the folding set for an existing type.
6914 llvm::FoldingSetNodeID ID;
6915 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6916 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6917 if (auto const AT_iter = AutoTypes.find_as(Val: ID); AT_iter != AutoTypes.end())
6918 return QualType(AT_iter->getSecond(), 0);
6919
6920 if (DK == DeducedKind::Deduced) {
6921 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6922 } else {
6923 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6924 if (!TypeConstraintConcept.isNull()) {
6925 bool AnyNonCanonArgs = false;
6926 TemplateName CanonicalConcept =
6927 getCanonicalTemplateName(Name: TypeConstraintConcept);
6928 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6929 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6930 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6931 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6932 TypeConstraintArgs: CanonicalConceptArgs);
6933 }
6934 }
6935
6936 void *Mem = Allocate(Size: sizeof(AutoType) +
6937 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6938 Align: alignof(AutoType));
6939 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6940 TypeConstraintConcept, TypeConstraintArgs);
6941#ifndef NDEBUG
6942 llvm::FoldingSetNodeID InsertedID;
6943 AT->Profile(InsertedID, *this);
6944 assert(InsertedID == ID && "ID does not match");
6945#endif
6946 Types.push_back(Elt: AT);
6947 AutoTypes.try_emplace(Key: ID.Intern(Allocator&: BumpAlloc), Args&: AT);
6948 return QualType(AT, 0);
6949}
6950
6951QualType ASTContext::getUnconstrainedType(QualType T) const {
6952 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6953
6954 // Remove a type-constraint from a top-level auto or decltype(auto).
6955 if (auto *AT = CanonT->getAs<AutoType>()) {
6956 if (!AT->isConstrained())
6957 return T;
6958 return getQualifiedType(
6959 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6960 Qs: T.getQualifiers());
6961 }
6962
6963 // FIXME: We only support constrained auto at the top level in the type of a
6964 // non-type template parameter at the moment. Once we lift that restriction,
6965 // we'll need to recursively build types containing auto here.
6966 assert(!CanonT->getContainedAutoType() ||
6967 !CanonT->getContainedAutoType()->isConstrained());
6968 return T;
6969}
6970
6971/// Return the uniqued reference to the deduced template specialization type
6972/// which has been deduced to the given type, or to the canonical undeduced
6973/// such type, or the canonical deduced-but-dependent such type.
6974QualType ASTContext::getDeducedTemplateSpecializationType(
6975 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6976 TemplateName Template) const {
6977 // Look in the folding set for an existing type.
6978 llvm::FoldingSetInsertToken Token;
6979 llvm::FoldingSetNodeID ID;
6980 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6981 Template);
6982 if (DeducedTemplateSpecializationType *DTST =
6983 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6984 return QualType(DTST, 0);
6985
6986 if (DK == DeducedKind::Deduced) {
6987 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6988 } else {
6989 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6990 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
6991 // FIXME: Can this be formed from a DependentTemplateName, such that the
6992 // keyword should be part of the canonical type?
6993 if (Keyword != ElaboratedTypeKeyword::None ||
6994 Template != CanonTemplateName) {
6995 DeducedAsType = getDeducedTemplateSpecializationType(
6996 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
6997 // Find the insertion position again.
6998 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6999 DeducedTemplateSpecializationTypes.lookup(ID, Token);
7000 assert(!DTST && "broken canonicalization");
7001 }
7002 }
7003
7004 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7005 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7006
7007#ifndef NDEBUG
7008 llvm::FoldingSetNodeID TempID;
7009 DTST->Profile(TempID);
7010 assert(ID == TempID && "ID does not match");
7011#endif
7012 Types.push_back(Elt: DTST);
7013 DeducedTemplateSpecializationTypes.insert(N: DTST, Token);
7014 return QualType(DTST, 0);
7015}
7016
7017/// getAtomicType - Return the uniqued reference to the atomic type for
7018/// the given value type.
7019QualType ASTContext::getAtomicType(QualType T) const {
7020 // Unique pointers, to guarantee there is only one pointer of a particular
7021 // structure.
7022 llvm::FoldingSetInsertToken Token;
7023 if (AtomicType *AT = AtomicTypes.lookup(Key: T, Token))
7024 return QualType(AT, 0);
7025
7026 // If the atomic value type isn't canonical, this won't be a canonical type
7027 // either, so fill in the canonical type field.
7028 QualType Canonical;
7029 if (!T.isCanonical()) {
7030 Canonical = getAtomicType(T: getCanonicalType(T));
7031
7032 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7033 }
7034 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7035 Types.push_back(Elt: New);
7036 AtomicTypes.insert(N: New, Token);
7037 return QualType(New, 0);
7038}
7039
7040/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7041QualType ASTContext::getAutoDeductType() const {
7042 if (AutoDeductTy.isNull())
7043 AutoDeductTy = QualType(
7044 new (*this, alignof(AutoType))
7045 AutoType(DeducedKind::Undeduced, QualType(), AutoTypeKeyword::Auto,
7046 /*TypeConstraintConcept=*/TemplateName(),
7047 /*TypeConstraintArgs=*/{}),
7048 0);
7049 return AutoDeductTy;
7050}
7051
7052/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7053QualType ASTContext::getAutoRRefDeductType() const {
7054 if (AutoRRefDeductTy.isNull())
7055 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7056 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7057 return AutoRRefDeductTy;
7058}
7059
7060/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7061/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7062/// needs to agree with the definition in <stddef.h>.
7063QualType ASTContext::getSizeType() const {
7064 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7065}
7066
7067CanQualType ASTContext::getCanonicalSizeType() const {
7068 return getFromTargetType(Type: Target->getSizeType());
7069}
7070
7071/// Return the unique signed counterpart of the integer type
7072/// corresponding to size_t.
7073QualType ASTContext::getSignedSizeType() const {
7074 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7075}
7076
7077/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7078/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7079QualType ASTContext::getPointerDiffType() const {
7080 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7081}
7082
7083/// Return the unique unsigned counterpart of "ptrdiff_t"
7084/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7085/// in the definition of %tu format specifier.
7086QualType ASTContext::getUnsignedPointerDiffType() const {
7087 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7088}
7089
7090/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7091CanQualType ASTContext::getIntMaxType() const {
7092 return getFromTargetType(Type: Target->getIntMaxType());
7093}
7094
7095/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7096CanQualType ASTContext::getUIntMaxType() const {
7097 return getFromTargetType(Type: Target->getUIntMaxType());
7098}
7099
7100/// getSignedWCharType - Return the type of "signed wchar_t".
7101/// Used when in C++, as a GCC extension.
7102QualType ASTContext::getSignedWCharType() const {
7103 // FIXME: derive from "Target" ?
7104 return WCharTy;
7105}
7106
7107/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7108/// Used when in C++, as a GCC extension.
7109QualType ASTContext::getUnsignedWCharType() const {
7110 // FIXME: derive from "Target" ?
7111 return UnsignedIntTy;
7112}
7113
7114QualType ASTContext::getIntPtrType() const {
7115 return getFromTargetType(Type: Target->getIntPtrType());
7116}
7117
7118QualType ASTContext::getUIntPtrType() const {
7119 return getCorrespondingUnsignedType(T: getIntPtrType());
7120}
7121
7122/// Return the unique type for "pid_t" defined in
7123/// <sys/types.h>. We need this to compute the correct type for vfork().
7124QualType ASTContext::getProcessIDType() const {
7125 return getFromTargetType(Type: Target->getProcessIDType());
7126}
7127
7128//===----------------------------------------------------------------------===//
7129// Type Operators
7130//===----------------------------------------------------------------------===//
7131
7132CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7133 // Push qualifiers into arrays, and then discard any remaining
7134 // qualifiers.
7135 T = getCanonicalType(T);
7136 T = getVariableArrayDecayedType(type: T);
7137 const Type *Ty = T.getTypePtr();
7138 QualType Result;
7139 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7140 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7141 } else if (isa<ArrayType>(Val: Ty)) {
7142 Result = getArrayDecayedType(T: QualType(Ty,0));
7143 } else if (isa<FunctionType>(Val: Ty)) {
7144 Result = getPointerType(T: QualType(Ty, 0));
7145 } else {
7146 Result = QualType(Ty, 0);
7147 }
7148
7149 return CanQualType::CreateUnsafe(Other: Result);
7150}
7151
7152QualType ASTContext::getUnqualifiedArrayType(QualType type,
7153 Qualifiers &quals) const {
7154 SplitQualType splitType = type.getSplitUnqualifiedType();
7155
7156 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7157 // the unqualified desugared type and then drops it on the floor.
7158 // We then have to strip that sugar back off with
7159 // getUnqualifiedDesugaredType(), which is silly.
7160 const auto *AT =
7161 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7162
7163 // If we don't have an array, just use the results in splitType.
7164 if (!AT) {
7165 quals = splitType.Quals;
7166 return QualType(splitType.Ty, 0);
7167 }
7168
7169 // Otherwise, recurse on the array's element type.
7170 QualType elementType = AT->getElementType();
7171 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7172
7173 // If that didn't change the element type, AT has no qualifiers, so we
7174 // can just use the results in splitType.
7175 if (elementType == unqualElementType) {
7176 assert(quals.empty()); // from the recursive call
7177 quals = splitType.Quals;
7178 return QualType(splitType.Ty, 0);
7179 }
7180
7181 // Otherwise, add in the qualifiers from the outermost type, then
7182 // build the type back up.
7183 quals.addConsistentQualifiers(qs: splitType.Quals);
7184
7185 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7186 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7187 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7188 }
7189
7190 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7191 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7192 }
7193
7194 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7195 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7196 ASM: VAT->getSizeModifier(),
7197 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7198 }
7199
7200 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7201 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7202 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7203}
7204
7205/// Attempt to unwrap two types that may both be array types with the same bound
7206/// (or both be array types of unknown bound) for the purpose of comparing the
7207/// cv-decomposition of two types per C++ [conv.qual].
7208///
7209/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7210/// C++20 [conv.qual], if permitted by the current language mode.
7211void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7212 bool AllowPiMismatch) const {
7213 while (true) {
7214 auto *AT1 = getAsArrayType(T: T1);
7215 if (!AT1)
7216 return;
7217
7218 auto *AT2 = getAsArrayType(T: T2);
7219 if (!AT2)
7220 return;
7221
7222 // If we don't have two array types with the same constant bound nor two
7223 // incomplete array types, we've unwrapped everything we can.
7224 // C++20 also permits one type to be a constant array type and the other
7225 // to be an incomplete array type.
7226 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7227 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7228 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7229 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7230 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7231 isa<IncompleteArrayType>(Val: AT2))))
7232 return;
7233 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7234 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7235 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7236 isa<ConstantArrayType>(Val: AT2))))
7237 return;
7238 } else {
7239 return;
7240 }
7241
7242 T1 = AT1->getElementType();
7243 T2 = AT2->getElementType();
7244 }
7245}
7246
7247/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7248///
7249/// If T1 and T2 are both pointer types of the same kind, or both array types
7250/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7251/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7252///
7253/// This function will typically be called in a loop that successively
7254/// "unwraps" pointer and pointer-to-member types to compare them at each
7255/// level.
7256///
7257/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7258/// C++20 [conv.qual], if permitted by the current language mode.
7259///
7260/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7261/// pair of types that can't be unwrapped further.
7262bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7263 bool AllowPiMismatch) const {
7264 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7265
7266 const auto *T1PtrType = T1->getAs<PointerType>();
7267 const auto *T2PtrType = T2->getAs<PointerType>();
7268 if (T1PtrType && T2PtrType) {
7269 T1 = T1PtrType->getPointeeType();
7270 T2 = T2PtrType->getPointeeType();
7271 return true;
7272 }
7273
7274 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7275 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7276 T1MPType && T2MPType) {
7277 // Compare the qualifiers of the canonical type, as the non-canonical type
7278 // may have qualifiers pointing to a base or derived class.
7279 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7280 return false;
7281 // Get the pointee types of the non-canonical type, in order to preserve
7282 // their sugar.
7283 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7284 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7285 return true;
7286 }
7287
7288 if (getLangOpts().ObjC) {
7289 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7290 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7291 if (T1OPType && T2OPType) {
7292 T1 = T1OPType->getPointeeType();
7293 T2 = T2OPType->getPointeeType();
7294 return true;
7295 }
7296 }
7297
7298 // FIXME: Block pointers, too?
7299
7300 return false;
7301}
7302
7303bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7304 while (true) {
7305 Qualifiers Quals;
7306 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7307 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7308 if (hasSameType(T1, T2))
7309 return true;
7310 if (!UnwrapSimilarTypes(T1, T2))
7311 return false;
7312 }
7313}
7314
7315bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7316 while (true) {
7317 Qualifiers Quals1, Quals2;
7318 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7319 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7320
7321 Quals1.removeCVRQualifiers();
7322 Quals2.removeCVRQualifiers();
7323 if (Quals1 != Quals2)
7324 return false;
7325
7326 if (hasSameType(T1, T2))
7327 return true;
7328
7329 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7330 return false;
7331 }
7332}
7333
7334DeclarationNameInfo
7335ASTContext::getNameForTemplate(TemplateName Name,
7336 SourceLocation NameLoc) const {
7337 switch (Name.getKind()) {
7338 case TemplateName::QualifiedTemplate:
7339 case TemplateName::Template:
7340 // DNInfo work in progress: CHECKME: what about DNLoc?
7341 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7342 NameLoc);
7343
7344 case TemplateName::OverloadedTemplate: {
7345 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7346 // DNInfo work in progress: CHECKME: what about DNLoc?
7347 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7348 }
7349
7350 case TemplateName::AssumedTemplate: {
7351 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7352 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7353 }
7354
7355 case TemplateName::DependentTemplate: {
7356 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7357 IdentifierOrOverloadedOperator TN = DTN->getName();
7358 DeclarationName DName;
7359 if (const IdentifierInfo *II = TN.getIdentifier()) {
7360 DName = DeclarationNames.getIdentifier(ID: II);
7361 return DeclarationNameInfo(DName, NameLoc);
7362 } else {
7363 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7364 // DNInfo work in progress: FIXME: source locations?
7365 DeclarationNameLoc DNLoc =
7366 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7367 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7368 }
7369 }
7370
7371 case TemplateName::SubstTemplateTemplateParm: {
7372 SubstTemplateTemplateParmStorage *subst
7373 = Name.getAsSubstTemplateTemplateParm();
7374 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7375 NameLoc);
7376 }
7377
7378 case TemplateName::SubstTemplateTemplateParmPack: {
7379 SubstTemplateTemplateParmPackStorage *subst
7380 = Name.getAsSubstTemplateTemplateParmPack();
7381 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7382 NameLoc);
7383 }
7384 case TemplateName::UsingTemplate:
7385 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7386 NameLoc);
7387 case TemplateName::DeducedTemplate: {
7388 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7389 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7390 }
7391 case TemplateName::PackIndexingTemplate: {
7392 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7393 return getNameForTemplate(Name: PI->getPattern(), NameLoc);
7394 }
7395 }
7396
7397 llvm_unreachable("bad template name kind!");
7398}
7399
7400const TemplateArgument *
7401ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7402 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7403 if (!TP->hasDefaultArgument())
7404 return nullptr;
7405 return &TP->getDefaultArgument().getArgument();
7406 };
7407 switch (P->getKind()) {
7408 case NamedDecl::TemplateTypeParm:
7409 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7410 case NamedDecl::NonTypeTemplateParm:
7411 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7412 case NamedDecl::TemplateTemplateParm:
7413 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7414 default:
7415 llvm_unreachable("Unexpected template parameter kind");
7416 }
7417}
7418
7419TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7420 bool IgnoreDeduced) const {
7421 while (std::optional<TemplateName> UnderlyingOrNone =
7422 Name.desugar(IgnoreDeduced))
7423 Name = *UnderlyingOrNone;
7424
7425 switch (Name.getKind()) {
7426 case TemplateName::Template: {
7427 TemplateDecl *Template = Name.getAsTemplateDecl();
7428 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7429 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7430
7431 // The canonical template name is the canonical template declaration.
7432 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7433 }
7434
7435 case TemplateName::AssumedTemplate:
7436 // An assumed template is just a name, so it is already canonical.
7437 return Name;
7438
7439 case TemplateName::OverloadedTemplate:
7440 llvm_unreachable("cannot canonicalize overloaded template");
7441
7442 case TemplateName::DependentTemplate: {
7443 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7444 assert(DTN && "Non-dependent template names must refer to template decls.");
7445 NestedNameSpecifier Qualifier = DTN->getQualifier();
7446 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7447 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7448 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7449 /*HasTemplateKeyword=*/true});
7450 return Name;
7451 }
7452
7453 case TemplateName::SubstTemplateTemplateParmPack: {
7454 SubstTemplateTemplateParmPackStorage *subst =
7455 Name.getAsSubstTemplateTemplateParmPack();
7456 TemplateArgument canonArgPack =
7457 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7458 return getSubstTemplateTemplateParmPack(
7459 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7460 Index: subst->getIndex(), Final: subst->getFinal());
7461 }
7462
7463 case TemplateName::PackIndexingTemplate: {
7464 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7465 SmallVector<TemplateName, 4> CanonExpansions;
7466 for (TemplateName T : PI->getExpansions())
7467 CanonExpansions.push_back(Elt: getCanonicalTemplateName(Name: T, IgnoreDeduced));
7468 return getPackIndexingTemplateName(
7469 Pattern: getCanonicalTemplateName(Name: PI->getPattern(), IgnoreDeduced),
7470 IndexExpr: PI->getIndexExpr(), FullySubstituted: PI->isFullySubstituted(), Expansions: CanonExpansions);
7471 }
7472 case TemplateName::DeducedTemplate: {
7473 assert(IgnoreDeduced == false);
7474 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7475 DefaultArguments DefArgs = DTS->getDefaultArguments();
7476 TemplateName Underlying = DTS->getUnderlying();
7477
7478 TemplateName CanonUnderlying =
7479 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7480 bool NonCanonical = CanonUnderlying != Underlying;
7481 auto CanonArgs =
7482 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7483
7484 ArrayRef<NamedDecl *> Params =
7485 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7486 assert(CanonArgs.size() <= Params.size());
7487 // A deduced template name which deduces the same default arguments already
7488 // declared in the underlying template is the same template as the
7489 // underlying template. We need need to note any arguments which differ from
7490 // the corresponding declaration. If any argument differs, we must build a
7491 // deduced template name.
7492 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7493 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7494 if (!A)
7495 break;
7496 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7497 TemplateArgument &CanonDefArg = CanonArgs[I];
7498 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7499 continue;
7500 // Keep popping from the back any deault arguments which are the same.
7501 if (I == int(CanonArgs.size() - 1))
7502 CanonArgs.pop_back();
7503 NonCanonical = true;
7504 }
7505 return NonCanonical ? getDeducedTemplateName(
7506 Underlying: CanonUnderlying,
7507 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7508 : Name;
7509 }
7510 case TemplateName::UsingTemplate:
7511 case TemplateName::QualifiedTemplate:
7512 case TemplateName::SubstTemplateTemplateParm:
7513 llvm_unreachable("always sugar node");
7514 }
7515
7516 llvm_unreachable("bad template name!");
7517}
7518
7519bool ASTContext::hasSameTemplateName(const TemplateName &X,
7520 const TemplateName &Y,
7521 bool IgnoreDeduced) const {
7522 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7523 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7524}
7525
7526bool ASTContext::isSameAssociatedConstraint(
7527 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7528 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7529 return false;
7530 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7531 return false;
7532 return true;
7533}
7534
7535bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7536 if (!XCE != !YCE)
7537 return false;
7538
7539 if (!XCE)
7540 return true;
7541
7542 llvm::FoldingSetNodeID XCEID, YCEID;
7543 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7544 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7545 return XCEID == YCEID;
7546}
7547
7548bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7549 const TypeConstraint *YTC) const {
7550 if (!XTC != !YTC)
7551 return false;
7552
7553 if (!XTC)
7554 return true;
7555
7556 TemplateDecl *NCX = XTC->getNamedConcept().getAsTemplateDecl();
7557 TemplateDecl *NCY = YTC->getNamedConcept().getAsTemplateDecl();
7558 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7559 return false;
7560 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7561 YTC->getConceptReference()->hasExplicitTemplateArgs())
7562 return false;
7563 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7564 if (XTC->getConceptReference()
7565 ->getTemplateArgsAsWritten()
7566 ->NumTemplateArgs !=
7567 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7568 return false;
7569
7570 // Compare slowly by profiling.
7571 //
7572 // We couldn't compare the profiling result for the template
7573 // args here. Consider the following example in different modules:
7574 //
7575 // template <__integer_like _Tp, C<_Tp> Sentinel>
7576 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7577 // return __t;
7578 // }
7579 //
7580 // When we compare the profiling result for `C<_Tp>` in different
7581 // modules, it will compare the type of `_Tp` in different modules.
7582 // However, the type of `_Tp` in different modules refer to different
7583 // types here naturally. So we couldn't compare the profiling result
7584 // for the template args directly.
7585 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7586 YCE: YTC->getImmediatelyDeclaredConstraint());
7587}
7588
7589bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7590 const NamedDecl *Y) const {
7591 if (X->getKind() != Y->getKind())
7592 return false;
7593
7594 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7595 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7596 if (TX->isParameterPack() != TY->isParameterPack())
7597 return false;
7598 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7599 return false;
7600 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7601 YTC: TY->getTypeConstraint());
7602 }
7603
7604 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7605 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7606 return TX->isParameterPack() == TY->isParameterPack() &&
7607 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7608 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7609 YCE: TY->getPlaceholderTypeConstraint());
7610 }
7611
7612 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7613 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7614 return TX->isParameterPack() == TY->isParameterPack() &&
7615 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7616 Y: TY->getTemplateParameters());
7617}
7618
7619bool ASTContext::isSameTemplateParameterList(
7620 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7621 if (X->size() != Y->size())
7622 return false;
7623
7624 for (unsigned I = 0, N = X->size(); I != N; ++I)
7625 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7626 return false;
7627
7628 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7629}
7630
7631bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7632 const NamedDecl *Y) const {
7633 // If the type parameter isn't the same already, we don't need to check the
7634 // default argument further.
7635 if (!isSameTemplateParameter(X, Y))
7636 return false;
7637
7638 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7639 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7640 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7641 return false;
7642
7643 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7644 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7645 }
7646
7647 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7648 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7649 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7650 return false;
7651
7652 Expr *DefaultArgumentX =
7653 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7654 Expr *DefaultArgumentY =
7655 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7656 llvm::FoldingSetNodeID XID, YID;
7657 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7658 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7659 return XID == YID;
7660 }
7661
7662 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7663 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7664
7665 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7666 return false;
7667
7668 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7669 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7670 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7671}
7672
7673static bool isSameQualifier(const NestedNameSpecifier X,
7674 const NestedNameSpecifier Y) {
7675 if (X == Y)
7676 return true;
7677 if (!X || !Y)
7678 return false;
7679
7680 auto Kind = X.getKind();
7681 if (Kind != Y.getKind())
7682 return false;
7683
7684 // FIXME: For namespaces and types, we're permitted to check that the entity
7685 // is named via the same tokens. We should probably do so.
7686 switch (Kind) {
7687 case NestedNameSpecifier::Kind::Namespace: {
7688 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7689 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7690 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7691 D2: NamespaceY->getNamespace()))
7692 return false;
7693 return isSameQualifier(X: PrefixX, Y: PrefixY);
7694 }
7695 case NestedNameSpecifier::Kind::Type: {
7696 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7697 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7698 return false;
7699 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7700 }
7701 case NestedNameSpecifier::Kind::Null:
7702 case NestedNameSpecifier::Kind::Global:
7703 case NestedNameSpecifier::Kind::MicrosoftSuper:
7704 return true;
7705 }
7706 llvm_unreachable("unhandled qualifier kind");
7707}
7708
7709static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7710 if (!A->getASTContext().getLangOpts().CUDA)
7711 return true; // Target attributes are overloadable in CUDA compilation only.
7712 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7713 return false;
7714 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7715 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7716 return true; // unattributed and __host__ functions are the same.
7717}
7718
7719/// Determine whether the attributes we can overload on are identical for A and
7720/// B. Will ignore any overloadable attrs represented in the type of A and B.
7721static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7722 const FunctionDecl *B) {
7723 // Note that pass_object_size attributes are represented in the function's
7724 // ExtParameterInfo, so we don't need to check them here.
7725
7726 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7727 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7728 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7729
7730 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7731 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7732 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7733
7734 // Return false if the number of enable_if attributes is different.
7735 if (!Cand1A || !Cand2A)
7736 return false;
7737
7738 Cand1ID.clear();
7739 Cand2ID.clear();
7740
7741 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7742 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7743
7744 // Return false if any of the enable_if expressions of A and B are
7745 // different.
7746 if (Cand1ID != Cand2ID)
7747 return false;
7748 }
7749 return hasSameCudaAttrs(A, B);
7750}
7751
7752bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7753 // Caution: this function is called by the AST reader during deserialization,
7754 // so it cannot rely on AST invariants being met. Non-trivial accessors
7755 // should be avoided, along with any traversal of redeclaration chains.
7756
7757 if (X == Y)
7758 return true;
7759
7760 if (X->getDeclName() != Y->getDeclName())
7761 return false;
7762
7763 // Must be in the same context.
7764 //
7765 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7766 // could be two different declarations of the same function. (We will fix the
7767 // semantic DC to refer to the primary definition after merging.)
7768 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7769 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7770 return false;
7771
7772 // If either X or Y are local to the owning module, they are only possible to
7773 // be the same entity if they are in the same module, or if they are members
7774 // of a lambda closure type. Closure types are merged by identity, and a class
7775 // definition determines its members, so the members of a merged closure type
7776 // are the same entity even if they are module-local to different modules.
7777 // Two distinct closure types are still not merged, so their members are never
7778 // compared.
7779 if (X->isModuleLocal() || Y->isModuleLocal()) {
7780 auto *RD = dyn_cast<CXXRecordDecl>(Val: X->getDeclContext());
7781 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()) &&
7782 !(RD && RD->isLambda()))
7783 return false;
7784 }
7785
7786 // Two typedefs refer to the same entity if they have the same underlying
7787 // type.
7788 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7789 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7790 return hasSameType(T1: TypedefX->getUnderlyingType(),
7791 T2: TypedefY->getUnderlyingType());
7792
7793 // Must have the same kind.
7794 if (X->getKind() != Y->getKind())
7795 return false;
7796
7797 // Objective-C classes and protocols with the same name always match.
7798 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7799 return true;
7800
7801 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7802 // No need to handle these here: we merge them when adding them to the
7803 // template.
7804 return false;
7805 }
7806
7807 // Compatible tags match.
7808 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7809 const auto *TagY = cast<TagDecl>(Val: Y);
7810 return (TagX->getTagKind() == TagY->getTagKind()) ||
7811 ((TagX->getTagKind() == TagTypeKind::Struct ||
7812 TagX->getTagKind() == TagTypeKind::Class ||
7813 TagX->getTagKind() == TagTypeKind::Interface) &&
7814 (TagY->getTagKind() == TagTypeKind::Struct ||
7815 TagY->getTagKind() == TagTypeKind::Class ||
7816 TagY->getTagKind() == TagTypeKind::Interface));
7817 }
7818
7819 // Functions with the same type and linkage match.
7820 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7821 // functions, etc.
7822 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7823 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7824 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7825 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7826 if (CtorX->getInheritedConstructor() &&
7827 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7828 Y: CtorY->getInheritedConstructor().getConstructor()))
7829 return false;
7830 }
7831
7832 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7833 return false;
7834
7835 // Multiversioned functions with different feature strings are represented
7836 // as separate declarations.
7837 if (FuncX->isMultiVersion()) {
7838 const auto *TAX = FuncX->getAttr<TargetAttr>();
7839 const auto *TAY = FuncY->getAttr<TargetAttr>();
7840 assert(TAX && TAY && "Multiversion Function without target attribute");
7841
7842 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7843 return false;
7844 }
7845
7846 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7847 // not the same entity if they are constrained.
7848 if ((FuncX->isMemberLikeConstrainedFriend() ||
7849 FuncY->isMemberLikeConstrainedFriend()) &&
7850 !FuncX->getLexicalDeclContext()->Equals(
7851 DC: FuncY->getLexicalDeclContext())) {
7852 return false;
7853 }
7854
7855 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7856 ACY: FuncY->getTrailingRequiresClause()))
7857 return false;
7858
7859 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7860 // Map to the first declaration that we've already merged into this one.
7861 // The TSI of redeclarations might not match (due to calling conventions
7862 // being inherited onto the type but not the TSI), but the TSI type of
7863 // the first declaration of the function should match across modules.
7864 FD = FD->getCanonicalDecl();
7865 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7866 : FD->getType();
7867 };
7868 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7869 if (!hasSameType(T1: XT, T2: YT)) {
7870 // We can get functions with different types on the redecl chain in C++17
7871 // if they have differing exception specifications and at least one of
7872 // the excpetion specs is unresolved.
7873 auto *XFPT = XT->getAs<FunctionProtoType>();
7874 auto *YFPT = YT->getAs<FunctionProtoType>();
7875 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7876 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7877 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7878 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7879 return true;
7880 return false;
7881 }
7882
7883 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7884 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7885 }
7886
7887 // Variables with the same type and linkage match.
7888 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7889 const auto *VarY = cast<VarDecl>(Val: Y);
7890 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7891 // During deserialization, we might compare variables before we load
7892 // their types. Assume the types will end up being the same.
7893 if (VarX->getType().isNull() || VarY->getType().isNull())
7894 return true;
7895
7896 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7897 return true;
7898
7899 // We can get decls with different types on the redecl chain. Eg.
7900 // template <typename T> struct S { static T Var[]; }; // #1
7901 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7902 // Only? happens when completing an incomplete array type. In this case
7903 // when comparing #1 and #2 we should go through their element type.
7904 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7905 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7906 if (!VarXTy || !VarYTy)
7907 return false;
7908 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7909 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7910 }
7911 return false;
7912 }
7913
7914 // Namespaces with the same name and inlinedness match.
7915 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7916 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7917 return NamespaceX->isInline() == NamespaceY->isInline();
7918 }
7919
7920 // Identical template names and kinds match if their template parameter lists
7921 // and patterns match.
7922 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7923 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7924
7925 // ConceptDecl wouldn't be the same if their constraint expression differs.
7926 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7927 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7928 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7929 YCE: ConceptY->getConstraintExpr()))
7930 return false;
7931 }
7932
7933 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7934 Y: TemplateY->getTemplatedDecl()) &&
7935 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7936 Y: TemplateY->getTemplateParameters());
7937 }
7938
7939 // Fields with the same name and the same type match.
7940 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7941 const auto *FDY = cast<FieldDecl>(Val: Y);
7942 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7943 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7944 }
7945
7946 // Indirect fields with the same target field match.
7947 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7948 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7949 return IFDX->getAnonField()->getCanonicalDecl() ==
7950 IFDY->getAnonField()->getCanonicalDecl();
7951 }
7952
7953 // Enumerators with the same name match.
7954 if (isa<EnumConstantDecl>(Val: X))
7955 // FIXME: Also check the value is odr-equivalent.
7956 return true;
7957
7958 // Using shadow declarations with the same target match.
7959 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7960 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7961 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7962 }
7963
7964 // Using declarations with the same qualifier match. (We already know that
7965 // the name matches.)
7966 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7967 const auto *UY = cast<UsingDecl>(Val: Y);
7968 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7969 UX->hasTypename() == UY->hasTypename() &&
7970 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7971 }
7972 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7973 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7974 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7975 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7976 }
7977 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7978 return isSameQualifier(
7979 X: UX->getQualifier(),
7980 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7981 }
7982
7983 // Using-pack declarations are only created by instantiation, and match if
7984 // they're instantiated from matching UnresolvedUsing...Decls.
7985 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7986 return declaresSameEntity(
7987 D1: UX->getInstantiatedFromUsingDecl(),
7988 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7989 }
7990
7991 // Namespace alias definitions with the same target match.
7992 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7993 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
7994 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
7995 }
7996
7997 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
7998 const auto *UY = cast<UsingEnumDecl>(Val: Y);
7999 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
8000 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
8001 }
8002
8003 return false;
8004}
8005
8006TemplateArgument
8007ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
8008 switch (Arg.getKind()) {
8009 case TemplateArgument::Null:
8010 return Arg;
8011
8012 case TemplateArgument::Expression:
8013 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8014 Arg.getIsDefaulted());
8015
8016 case TemplateArgument::Declaration: {
8017 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
8018 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
8019 Arg.getIsDefaulted());
8020 }
8021
8022 case TemplateArgument::NullPtr:
8023 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
8024 /*isNullPtr*/ true, Arg.getIsDefaulted());
8025
8026 case TemplateArgument::Template:
8027 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
8028 Arg.getIsDefaulted());
8029
8030 case TemplateArgument::TemplateExpansion:
8031 return TemplateArgument(
8032 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
8033 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
8034
8035 case TemplateArgument::Integral:
8036 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
8037
8038 case TemplateArgument::StructuralValue:
8039 return TemplateArgument(*this,
8040 getCanonicalType(T: Arg.getStructuralValueType()),
8041 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
8042
8043 case TemplateArgument::Type:
8044 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
8045 /*isNullPtr*/ false, Arg.getIsDefaulted());
8046
8047 case TemplateArgument::Pack: {
8048 bool AnyNonCanonArgs = false;
8049 auto CanonArgs = ::getCanonicalTemplateArguments(
8050 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8051 if (!AnyNonCanonArgs)
8052 return Arg;
8053 auto NewArg = TemplateArgument::CreatePackCopy(
8054 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8055 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8056 return NewArg;
8057 }
8058 }
8059
8060 // Silence GCC warning
8061 llvm_unreachable("Unhandled template argument kind");
8062}
8063
8064bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8065 const TemplateArgument &Arg2) const {
8066 if (Arg1.getKind() != Arg2.getKind())
8067 return false;
8068
8069 switch (Arg1.getKind()) {
8070 case TemplateArgument::Null:
8071 llvm_unreachable("Comparing NULL template argument");
8072
8073 case TemplateArgument::Type:
8074 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8075
8076 case TemplateArgument::Declaration:
8077 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8078 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8079
8080 case TemplateArgument::NullPtr:
8081 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8082
8083 case TemplateArgument::Template:
8084 case TemplateArgument::TemplateExpansion:
8085 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8086 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8087
8088 case TemplateArgument::Integral:
8089 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8090 I2: Arg2.getAsIntegral());
8091
8092 case TemplateArgument::StructuralValue:
8093 return Arg1.structurallyEquals(Other: Arg2);
8094
8095 case TemplateArgument::Expression: {
8096 llvm::FoldingSetNodeID ID1, ID2;
8097 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8098 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8099 return ID1 == ID2;
8100 }
8101
8102 case TemplateArgument::Pack:
8103 return llvm::equal(
8104 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8105 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8106 return isSameTemplateArgument(Arg1, Arg2);
8107 });
8108 }
8109
8110 llvm_unreachable("Unhandled template argument kind");
8111}
8112
8113const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8114 // Handle the non-qualified case efficiently.
8115 if (!T.hasLocalQualifiers()) {
8116 // Handle the common positive case fast.
8117 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8118 return AT;
8119 }
8120
8121 // Handle the common negative case fast.
8122 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8123 return nullptr;
8124
8125 // Apply any qualifiers from the array type to the element type. This
8126 // implements C99 6.7.3p8: "If the specification of an array type includes
8127 // any type qualifiers, the element type is so qualified, not the array type."
8128
8129 // If we get here, we either have type qualifiers on the type, or we have
8130 // sugar such as a typedef in the way. If we have type qualifiers on the type
8131 // we must propagate them down into the element type.
8132
8133 SplitQualType split = T.getSplitDesugaredType();
8134 Qualifiers qs = split.Quals;
8135
8136 // If we have a simple case, just return now.
8137 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8138 if (!ATy || qs.empty())
8139 return ATy;
8140
8141 // Otherwise, we have an array and we have qualifiers on it. Push the
8142 // qualifiers into the array element type and return a new array type.
8143 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8144
8145 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8146 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8147 SizeExpr: CAT->getSizeExpr(),
8148 ASM: CAT->getSizeModifier(),
8149 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8150 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8151 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8152 ASM: IAT->getSizeModifier(),
8153 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8154
8155 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8156 return cast<ArrayType>(Val: getDependentSizedArrayType(
8157 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8158 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8159
8160 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8161 return cast<ArrayType>(
8162 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8163 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8164}
8165
8166QualType ASTContext::getAdjustedParameterType(QualType T) const {
8167 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8168 return getLValueReferenceType(T);
8169 if (getLangOpts().HLSL && T->isConstantArrayType())
8170 return getArrayParameterType(Ty: T);
8171 if (T->isArrayType() || T->isFunctionType())
8172 return getDecayedType(T);
8173 return T;
8174}
8175
8176QualType ASTContext::getSignatureParameterType(QualType T) const {
8177 T = getVariableArrayDecayedType(type: T);
8178 T = getAdjustedParameterType(T);
8179 return T.getUnqualifiedType();
8180}
8181
8182QualType ASTContext::getExceptionObjectType(QualType T) const {
8183 // C++ [except.throw]p3:
8184 // A throw-expression initializes a temporary object, called the exception
8185 // object, the type of which is determined by removing any top-level
8186 // cv-qualifiers from the static type of the operand of throw and adjusting
8187 // the type from "array of T" or "function returning T" to "pointer to T"
8188 // or "pointer to function returning T", [...]
8189 T = getVariableArrayDecayedType(type: T);
8190 if (T->isArrayType() || T->isFunctionType())
8191 T = getDecayedType(T);
8192 return T.getUnqualifiedType();
8193}
8194
8195/// getArrayDecayedType - Return the properly qualified result of decaying the
8196/// specified array type to a pointer. This operation is non-trivial when
8197/// handling typedefs etc. The canonical type of "T" must be an array type,
8198/// this returns a pointer to a properly qualified element of the array.
8199///
8200/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8201QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8202 // Get the element type with 'getAsArrayType' so that we don't lose any
8203 // typedefs in the element type of the array. This also handles propagation
8204 // of type qualifiers from the array type into the element type if present
8205 // (C99 6.7.3p8).
8206 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8207 assert(PrettyArrayType && "Not an array type!");
8208
8209 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8210
8211 // int x[restrict 4] -> int *restrict
8212 QualType Result = getQualifiedType(T: PtrTy,
8213 Qs: PrettyArrayType->getIndexTypeQualifiers());
8214
8215 // int x[_Nullable] -> int * _Nullable
8216 if (auto Nullability = Ty->getNullability()) {
8217 Result = getAttributedType(nullability: *Nullability, modifiedType: Result, equivalentType: Result);
8218 }
8219 return Result;
8220}
8221
8222QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8223 return getBaseElementType(QT: array->getElementType());
8224}
8225
8226QualType ASTContext::getBaseElementType(QualType type) const {
8227 Qualifiers qs;
8228 while (true) {
8229 SplitQualType split = type.getSplitDesugaredType();
8230 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8231 if (!array) break;
8232
8233 type = array->getElementType();
8234 qs.addConsistentQualifiers(qs: split.Quals);
8235 }
8236
8237 return getQualifiedType(T: type, Qs: qs);
8238}
8239
8240uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) {
8241 uint64_t ElementCount = 1;
8242 do {
8243 ElementCount *= CA->getZExtSize();
8244 CA = dyn_cast_if_present<ConstantArrayType>(
8245 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8246 } while (CA);
8247 return ElementCount;
8248}
8249
8250uint64_t
8251ASTContext::getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) {
8252 if (!AILE)
8253 return 0;
8254
8255 uint64_t ElementCount = 1;
8256
8257 do {
8258 ElementCount *= AILE->getArraySize().getZExtValue();
8259 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8260 } while (AILE);
8261
8262 return ElementCount;
8263}
8264
8265/// getFloatingRank - Return a relative rank for floating point types.
8266/// This routine will assert if passed a built-in type that isn't a float.
8267static FloatingRank getFloatingRank(QualType T) {
8268 if (const auto *CT = T->getAs<ComplexType>())
8269 return getFloatingRank(T: CT->getElementType());
8270
8271 switch (T->castAs<BuiltinType>()->getKind()) {
8272 default: llvm_unreachable("getFloatingRank(): not a floating type");
8273 case BuiltinType::Float16: return Float16Rank;
8274 case BuiltinType::Half: return HalfRank;
8275 case BuiltinType::Float: return FloatRank;
8276 case BuiltinType::Double: return DoubleRank;
8277 case BuiltinType::LongDouble: return LongDoubleRank;
8278 case BuiltinType::Float128: return Float128Rank;
8279 case BuiltinType::BFloat16: return BFloat16Rank;
8280 case BuiltinType::Ibm128: return Ibm128Rank;
8281 }
8282}
8283
8284/// getFloatingTypeOrder - Compare the rank of the two specified floating
8285/// point types, ignoring the domain of the type (i.e. 'double' ==
8286/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8287/// LHS < RHS, return -1.
8288int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8289 FloatingRank LHSR = getFloatingRank(T: LHS);
8290 FloatingRank RHSR = getFloatingRank(T: RHS);
8291
8292 if (LHSR == RHSR)
8293 return 0;
8294 if (LHSR > RHSR)
8295 return 1;
8296 return -1;
8297}
8298
8299int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8300 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8301 return 0;
8302 return getFloatingTypeOrder(LHS, RHS);
8303}
8304
8305/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8306/// routine will assert if passed a built-in type that isn't an integer or enum,
8307/// or if it is not canonicalized.
8308unsigned ASTContext::getIntegerRank(const Type *T) const {
8309 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8310
8311 // Results in this 'losing' to any type of the same size, but winning if
8312 // larger.
8313 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8314 return 0 + (EIT->getNumBits() << 3);
8315
8316 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8317 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8318
8319 switch (cast<BuiltinType>(Val: T)->getKind()) {
8320 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8321 case BuiltinType::Bool:
8322 return 1 + (getIntWidth(T: BoolTy) << 3);
8323 case BuiltinType::Char_S:
8324 case BuiltinType::Char_U:
8325 case BuiltinType::SChar:
8326 case BuiltinType::UChar:
8327 return 2 + (getIntWidth(T: CharTy) << 3);
8328 case BuiltinType::Short:
8329 case BuiltinType::UShort:
8330 return 3 + (getIntWidth(T: ShortTy) << 3);
8331 case BuiltinType::Int:
8332 case BuiltinType::UInt:
8333 return 4 + (getIntWidth(T: IntTy) << 3);
8334 case BuiltinType::Long:
8335 case BuiltinType::ULong:
8336 return 5 + (getIntWidth(T: LongTy) << 3);
8337 case BuiltinType::LongLong:
8338 case BuiltinType::ULongLong:
8339 return 6 + (getIntWidth(T: LongLongTy) << 3);
8340 case BuiltinType::Int128:
8341 case BuiltinType::UInt128:
8342 return 7 + (getIntWidth(T: Int128Ty) << 3);
8343
8344 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8345 // their underlying types" [c++20 conv.rank]
8346 case BuiltinType::Char8:
8347 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8348 case BuiltinType::Char16:
8349 return getIntegerRank(
8350 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8351 case BuiltinType::Char32:
8352 return getIntegerRank(
8353 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8354 case BuiltinType::WChar_S:
8355 case BuiltinType::WChar_U:
8356 return getIntegerRank(
8357 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8358 }
8359}
8360
8361/// Whether this is a promotable bitfield reference according
8362/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8363///
8364/// \returns the type this bit-field will promote to, or NULL if no
8365/// promotion occurs.
8366QualType ASTContext::isPromotableBitField(Expr *E) const {
8367 if (E->isTypeDependent() || E->isValueDependent())
8368 return {};
8369
8370 // C++ [conv.prom]p5:
8371 // If the bit-field has an enumerated type, it is treated as any other
8372 // value of that type for promotion purposes.
8373 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8374 return {};
8375
8376 // FIXME: We should not do this unless E->refersToBitField() is true. This
8377 // matters in C where getSourceBitField() will find bit-fields for various
8378 // cases where the source expression is not a bit-field designator.
8379
8380 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8381 if (!Field)
8382 return {};
8383
8384 QualType FT = Field->getType();
8385
8386 uint64_t BitWidth = Field->getBitWidthValue();
8387 uint64_t IntSize = getTypeSize(T: IntTy);
8388 // C++ [conv.prom]p5:
8389 // A prvalue for an integral bit-field can be converted to a prvalue of type
8390 // int if int can represent all the values of the bit-field; otherwise, it
8391 // can be converted to unsigned int if unsigned int can represent all the
8392 // values of the bit-field. If the bit-field is larger yet, no integral
8393 // promotion applies to it.
8394 // C11 6.3.1.1/2:
8395 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8396 // If an int can represent all values of the original type (as restricted by
8397 // the width, for a bit-field), the value is converted to an int; otherwise,
8398 // it is converted to an unsigned int.
8399 //
8400 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8401 // We perform that promotion here to match GCC and C++.
8402 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8403 // greater than that of 'int'. We perform that promotion to match GCC.
8404 //
8405 // C23 6.3.1.1p2:
8406 // The value from a bit-field of a bit-precise integer type is converted to
8407 // the corresponding bit-precise integer type. (The rest is the same as in
8408 // C11.)
8409 if (QualType QT = Field->getType(); QT->isBitIntType())
8410 return QT;
8411
8412 if (BitWidth < IntSize)
8413 return IntTy;
8414
8415 if (BitWidth == IntSize)
8416 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8417
8418 // Bit-fields wider than int are not subject to promotions, and therefore act
8419 // like the base type. GCC has some weird bugs in this area that we
8420 // deliberately do not follow (GCC follows a pre-standard resolution to
8421 // C's DR315 which treats bit-width as being part of the type, and this leaks
8422 // into their semantics in some cases).
8423 return {};
8424}
8425
8426/// getPromotedIntegerType - Returns the type that Promotable will
8427/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8428/// integer type.
8429QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8430 assert(!Promotable.isNull());
8431 assert(isPromotableIntegerType(Promotable));
8432 if (const auto *ED = Promotable->getAsEnumDecl())
8433 return ED->getPromotionType();
8434
8435 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8436 // qualifier.
8437 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8438 QualType PromotedUnderlying =
8439 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8440 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8441 }
8442
8443 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8444 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8445 // (3.9.1) can be converted to a prvalue of the first of the following
8446 // types that can represent all the values of its underlying type:
8447 // int, unsigned int, long int, unsigned long int, long long int, or
8448 // unsigned long long int [...]
8449 // FIXME: Is there some better way to compute this?
8450 if (BT->getKind() == BuiltinType::WChar_S ||
8451 BT->getKind() == BuiltinType::WChar_U ||
8452 BT->getKind() == BuiltinType::Char8 ||
8453 BT->getKind() == BuiltinType::Char16 ||
8454 BT->getKind() == BuiltinType::Char32) {
8455 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8456 uint64_t FromSize = getTypeSize(T: BT);
8457 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8458 LongLongTy, UnsignedLongLongTy };
8459 for (const auto &PT : PromoteTypes) {
8460 uint64_t ToSize = getTypeSize(T: PT);
8461 if (FromSize < ToSize ||
8462 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8463 return PT;
8464 }
8465 llvm_unreachable("char type should fit into long long");
8466 }
8467 }
8468
8469 // At this point, we should have a signed or unsigned integer type.
8470 if (Promotable->isSignedIntegerType())
8471 return IntTy;
8472 uint64_t PromotableSize = getIntWidth(T: Promotable);
8473 uint64_t IntSize = getIntWidth(T: IntTy);
8474 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8475 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8476}
8477
8478/// Recurses in pointer/array types until it finds an objc retainable
8479/// type and returns its ownership.
8480Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8481 while (!T.isNull()) {
8482 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8483 return T.getObjCLifetime();
8484 if (T->isArrayType())
8485 T = getBaseElementType(type: T);
8486 else if (const auto *PT = T->getAs<PointerType>())
8487 T = PT->getPointeeType();
8488 else if (const auto *RT = T->getAs<ReferenceType>())
8489 T = RT->getPointeeType();
8490 else
8491 break;
8492 }
8493
8494 return Qualifiers::OCL_None;
8495}
8496
8497static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8498 // Incomplete enum types are not treated as integer types.
8499 // FIXME: In C++, enum types are never integer types.
8500 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8501 if (ED->isComplete() && !ED->isScoped())
8502 return ED->getIntegerType().getTypePtr();
8503 return nullptr;
8504}
8505
8506/// getIntegerTypeOrder - Returns the highest ranked integer type:
8507/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8508/// LHS < RHS, return -1.
8509int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8510 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8511 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8512
8513 // Unwrap enums to their underlying type.
8514 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8515 LHSC = getIntegerTypeForEnum(ET);
8516 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8517 RHSC = getIntegerTypeForEnum(ET);
8518
8519 if (LHSC == RHSC) return 0;
8520
8521 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8522 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8523
8524 unsigned LHSRank = getIntegerRank(T: LHSC);
8525 unsigned RHSRank = getIntegerRank(T: RHSC);
8526
8527 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8528 if (LHSRank == RHSRank) return 0;
8529 return LHSRank > RHSRank ? 1 : -1;
8530 }
8531
8532 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8533 if (LHSUnsigned) {
8534 // If the unsigned [LHS] type is larger, return it.
8535 if (LHSRank >= RHSRank)
8536 return 1;
8537
8538 // If the signed type can represent all values of the unsigned type, it
8539 // wins. Because we are dealing with 2's complement and types that are
8540 // powers of two larger than each other, this is always safe.
8541 return -1;
8542 }
8543
8544 // If the unsigned [RHS] type is larger, return it.
8545 if (RHSRank >= LHSRank)
8546 return -1;
8547
8548 // If the signed type can represent all values of the unsigned type, it
8549 // wins. Because we are dealing with 2's complement and types that are
8550 // powers of two larger than each other, this is always safe.
8551 return 1;
8552}
8553
8554TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8555 if (CFConstantStringTypeDecl)
8556 return CFConstantStringTypeDecl;
8557
8558 assert(!CFConstantStringTagDecl &&
8559 "tag and typedef should be initialized together");
8560 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8561 CFConstantStringTagDecl->startDefinition();
8562
8563 struct {
8564 QualType Type;
8565 const char *Name;
8566 } Fields[5];
8567 unsigned Count = 0;
8568
8569 /// Objective-C ABI
8570 ///
8571 /// typedef struct __NSConstantString_tag {
8572 /// const int *isa;
8573 /// int flags;
8574 /// const char *str;
8575 /// long length;
8576 /// } __NSConstantString;
8577 ///
8578 /// Swift ABI (4.1, 4.2)
8579 ///
8580 /// typedef struct __NSConstantString_tag {
8581 /// uintptr_t _cfisa;
8582 /// uintptr_t _swift_rc;
8583 /// _Atomic(uint64_t) _cfinfoa;
8584 /// const char *_ptr;
8585 /// uint32_t _length;
8586 /// } __NSConstantString;
8587 ///
8588 /// Swift ABI (5.0)
8589 ///
8590 /// typedef struct __NSConstantString_tag {
8591 /// uintptr_t _cfisa;
8592 /// uintptr_t _swift_rc;
8593 /// _Atomic(uint64_t) _cfinfoa;
8594 /// const char *_ptr;
8595 /// uintptr_t _length;
8596 /// } __NSConstantString;
8597
8598 const auto CFRuntime = getLangOpts().CFRuntime;
8599 if (static_cast<unsigned>(CFRuntime) <
8600 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8601 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8602 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8603 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8604 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8605 } else {
8606 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8607 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8608 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8609 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8610 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8611 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8612 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8613 else
8614 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8615 }
8616
8617 // Create fields
8618 for (unsigned i = 0; i < Count; ++i) {
8619 FieldDecl *Field =
8620 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8621 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8622 T: Fields[i].Type, /*TInfo=*/nullptr,
8623 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8624 Field->setAccess(AS_public);
8625 CFConstantStringTagDecl->addDecl(D: Field);
8626 }
8627
8628 CFConstantStringTagDecl->completeDefinition();
8629 // This type is designed to be compatible with NSConstantString, but cannot
8630 // use the same name, since NSConstantString is an interface.
8631 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8632 CFConstantStringTypeDecl =
8633 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8634
8635 return CFConstantStringTypeDecl;
8636}
8637
8638RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8639 if (!CFConstantStringTagDecl)
8640 getCFConstantStringDecl(); // Build the tag and the typedef.
8641 return CFConstantStringTagDecl;
8642}
8643
8644// getCFConstantStringType - Return the type used for constant CFStrings.
8645QualType ASTContext::getCFConstantStringType() const {
8646 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8647 Decl: getCFConstantStringDecl());
8648}
8649
8650QualType ASTContext::getObjCSuperType() const {
8651 if (ObjCSuperType.isNull()) {
8652 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8653 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8654 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8655 }
8656 return ObjCSuperType;
8657}
8658
8659void ASTContext::setCFConstantStringType(QualType T) {
8660 const auto *TT = T->castAs<TypedefType>();
8661 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8662 CFConstantStringTagDecl = TT->castAsRecordDecl();
8663}
8664
8665QualType ASTContext::getBlockDescriptorType() const {
8666 if (BlockDescriptorType)
8667 return getCanonicalTagType(TD: BlockDescriptorType);
8668
8669 RecordDecl *RD;
8670 // FIXME: Needs the FlagAppleBlock bit.
8671 RD = buildImplicitRecord(Name: "__block_descriptor");
8672 RD->startDefinition();
8673
8674 QualType FieldTypes[] = {
8675 UnsignedLongTy,
8676 UnsignedLongTy,
8677 };
8678
8679 static const char *const FieldNames[] = {
8680 "reserved",
8681 "Size"
8682 };
8683
8684 for (size_t i = 0; i < 2; ++i) {
8685 FieldDecl *Field = FieldDecl::Create(
8686 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8687 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8688 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8689 Field->setAccess(AS_public);
8690 RD->addDecl(D: Field);
8691 }
8692
8693 RD->completeDefinition();
8694
8695 BlockDescriptorType = RD;
8696
8697 return getCanonicalTagType(TD: BlockDescriptorType);
8698}
8699
8700QualType ASTContext::getBlockDescriptorExtendedType() const {
8701 if (BlockDescriptorExtendedType)
8702 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8703
8704 RecordDecl *RD;
8705 // FIXME: Needs the FlagAppleBlock bit.
8706 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8707 RD->startDefinition();
8708
8709 QualType FieldTypes[] = {
8710 UnsignedLongTy,
8711 UnsignedLongTy,
8712 getPointerType(T: VoidPtrTy),
8713 getPointerType(T: VoidPtrTy)
8714 };
8715
8716 static const char *const FieldNames[] = {
8717 "reserved",
8718 "Size",
8719 "CopyFuncPtr",
8720 "DestroyFuncPtr"
8721 };
8722
8723 for (size_t i = 0; i < 4; ++i) {
8724 FieldDecl *Field = FieldDecl::Create(
8725 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8726 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8727 /*BitWidth=*/BW: nullptr,
8728 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8729 Field->setAccess(AS_public);
8730 RD->addDecl(D: Field);
8731 }
8732
8733 RD->completeDefinition();
8734
8735 BlockDescriptorExtendedType = RD;
8736 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8737}
8738
8739OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8740 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8741
8742 if (!BT) {
8743 if (isa<PipeType>(Val: T))
8744 return OCLTK_Pipe;
8745
8746 return OCLTK_Default;
8747 }
8748
8749 switch (BT->getKind()) {
8750#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8751 case BuiltinType::Id: \
8752 return OCLTK_Image;
8753#include "clang/Basic/OpenCLImageTypes.def"
8754
8755 case BuiltinType::OCLClkEvent:
8756 return OCLTK_ClkEvent;
8757
8758 case BuiltinType::OCLEvent:
8759 return OCLTK_Event;
8760
8761 case BuiltinType::OCLQueue:
8762 return OCLTK_Queue;
8763
8764 case BuiltinType::OCLReserveID:
8765 return OCLTK_ReserveID;
8766
8767 case BuiltinType::OCLSampler:
8768 return OCLTK_Sampler;
8769
8770 default:
8771 return OCLTK_Default;
8772 }
8773}
8774
8775LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8776 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8777}
8778
8779/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8780/// requires copy/dispose. Note that this must match the logic
8781/// in buildByrefHelpers.
8782bool ASTContext::BlockRequiresCopying(QualType Ty,
8783 const VarDecl *D) {
8784 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8785 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8786 if (!copyExpr && record->hasTrivialDestructor()) return false;
8787
8788 return true;
8789 }
8790
8791 if (Ty.hasAddressDiscriminatedPointerAuth())
8792 return true;
8793
8794 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8795 // move or destroy.
8796 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8797 return true;
8798
8799 if (!Ty->isObjCRetainableType()) return false;
8800
8801 Qualifiers qs = Ty.getQualifiers();
8802
8803 // If we have lifetime, that dominates.
8804 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8805 switch (lifetime) {
8806 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8807
8808 // These are just bits as far as the runtime is concerned.
8809 case Qualifiers::OCL_ExplicitNone:
8810 case Qualifiers::OCL_Autoreleasing:
8811 return false;
8812
8813 // These cases should have been taken care of when checking the type's
8814 // non-triviality.
8815 case Qualifiers::OCL_Weak:
8816 case Qualifiers::OCL_Strong:
8817 llvm_unreachable("impossible");
8818 }
8819 llvm_unreachable("fell out of lifetime switch!");
8820 }
8821 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8822 Ty->isObjCObjectPointerType());
8823}
8824
8825bool ASTContext::getByrefLifetime(QualType Ty,
8826 Qualifiers::ObjCLifetime &LifeTime,
8827 bool &HasByrefExtendedLayout) const {
8828 if (!getLangOpts().ObjC ||
8829 getLangOpts().getGC() != LangOptions::NonGC)
8830 return false;
8831
8832 HasByrefExtendedLayout = false;
8833 if (Ty->isRecordType()) {
8834 HasByrefExtendedLayout = true;
8835 LifeTime = Qualifiers::OCL_None;
8836 } else if ((LifeTime = Ty.getObjCLifetime())) {
8837 // Honor the ARC qualifiers.
8838 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8839 // The MRR rule.
8840 LifeTime = Qualifiers::OCL_ExplicitNone;
8841 } else {
8842 LifeTime = Qualifiers::OCL_None;
8843 }
8844 return true;
8845}
8846
8847CanQualType ASTContext::getNSUIntegerType() const {
8848 assert(Target && "Expected target to be initialized");
8849 const llvm::Triple &T = Target->getTriple();
8850 // Windows is LLP64 rather than LP64
8851 if (T.isOSWindows() && T.isArch64Bit())
8852 return UnsignedLongLongTy;
8853 return UnsignedLongTy;
8854}
8855
8856CanQualType ASTContext::getNSIntegerType() const {
8857 assert(Target && "Expected target to be initialized");
8858 const llvm::Triple &T = Target->getTriple();
8859 // Windows is LLP64 rather than LP64
8860 if (T.isOSWindows() && T.isArch64Bit())
8861 return LongLongTy;
8862 return LongTy;
8863}
8864
8865TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8866 if (!ObjCInstanceTypeDecl)
8867 ObjCInstanceTypeDecl =
8868 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8869 return ObjCInstanceTypeDecl;
8870}
8871
8872// This returns true if a type has been typedefed to BOOL:
8873// typedef <type> BOOL;
8874static bool isTypeTypedefedAsBOOL(QualType T) {
8875 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8876 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8877 return II->isStr(Str: "BOOL");
8878
8879 return false;
8880}
8881
8882/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8883/// purpose.
8884CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8885 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8886 return CharUnits::Zero();
8887
8888 CharUnits sz = getTypeSizeInChars(T: type);
8889
8890 // Make all integer and enum types at least as large as an int
8891 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8892 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8893 // Treat arrays as pointers, since that's how they're passed in.
8894 else if (type->isArrayType())
8895 sz = getTypeSizeInChars(T: VoidPtrTy);
8896 return sz;
8897}
8898
8899bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8900 return getTargetInfo().getCXXABI().isMicrosoft() &&
8901 VD->isStaticDataMember() &&
8902 VD->getType()->isIntegralOrEnumerationType() &&
8903 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8904}
8905
8906ASTContext::InlineVariableDefinitionKind
8907ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8908 if (!VD->isInline())
8909 return InlineVariableDefinitionKind::None;
8910
8911 // In almost all cases, it's a weak definition.
8912 auto *First = VD->getFirstDecl();
8913 if (First->isInlineSpecified() || !First->isStaticDataMember())
8914 return InlineVariableDefinitionKind::Weak;
8915
8916 // If there's a file-context declaration in this translation unit, it's a
8917 // non-discardable definition.
8918 for (auto *D : VD->redecls())
8919 if (D->getLexicalDeclContext()->isFileContext() &&
8920 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8921 return InlineVariableDefinitionKind::Strong;
8922
8923 // If we've not seen one yet, we don't know.
8924 return InlineVariableDefinitionKind::WeakUnknown;
8925}
8926
8927static std::string charUnitsToString(CharUnits CU) {
8928 return llvm::itostr(X: CU.getQuantity());
8929}
8930
8931/// getObjCEncodingForBlock - Return the encoded type for this block
8932/// declaration.
8933std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8934 std::string S;
8935
8936 const BlockDecl *Decl = Expr->getBlockDecl();
8937 QualType BlockTy =
8938 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8939 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8940 // Encode result type.
8941 if (getLangOpts().EncodeExtendedBlockSig)
8942 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8943 Extended: true /*Extended*/);
8944 else
8945 getObjCEncodingForType(T: BlockReturnTy, S);
8946 // Compute size of all parameters.
8947 // Start with computing size of a pointer in number of bytes.
8948 // FIXME: There might(should) be a better way of doing this computation!
8949 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8950 CharUnits ParmOffset = PtrSize;
8951 for (auto *PI : Decl->parameters()) {
8952 QualType PType = PI->getType();
8953 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8954 if (sz.isZero())
8955 continue;
8956 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8957 ParmOffset += sz;
8958 }
8959 // Size of the argument frame
8960 S += charUnitsToString(CU: ParmOffset);
8961 // Block pointer and offset.
8962 S += "@?0";
8963
8964 // Argument types.
8965 ParmOffset = PtrSize;
8966 for (auto *PVDecl : Decl->parameters()) {
8967 QualType PType = PVDecl->getOriginalType();
8968 if (const auto *AT =
8969 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8970 // Use array's original type only if it has known number of
8971 // elements.
8972 if (!isa<ConstantArrayType>(Val: AT))
8973 PType = PVDecl->getType();
8974 } else if (PType->isFunctionType())
8975 PType = PVDecl->getType();
8976 if (getLangOpts().EncodeExtendedBlockSig)
8977 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8978 S, Extended: true /*Extended*/);
8979 else
8980 getObjCEncodingForType(T: PType, S);
8981 S += charUnitsToString(CU: ParmOffset);
8982 ParmOffset += getObjCEncodingTypeSize(type: PType);
8983 }
8984
8985 return S;
8986}
8987
8988std::string
8989ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8990 std::string S;
8991 // Encode result type.
8992 getObjCEncodingForType(T: Decl->getReturnType(), S);
8993 CharUnits ParmOffset;
8994 // Compute size of all parameters.
8995 for (auto *PI : Decl->parameters()) {
8996 QualType PType = PI->getType();
8997 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8998 if (sz.isZero())
8999 continue;
9000
9001 assert(sz.isPositive() &&
9002 "getObjCEncodingForFunctionDecl - Incomplete param type");
9003 ParmOffset += sz;
9004 }
9005 S += charUnitsToString(CU: ParmOffset);
9006 ParmOffset = CharUnits::Zero();
9007
9008 // Argument types.
9009 for (auto *PVDecl : Decl->parameters()) {
9010 QualType PType = PVDecl->getOriginalType();
9011 if (const auto *AT =
9012 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9013 // Use array's original type only if it has known number of
9014 // elements.
9015 if (!isa<ConstantArrayType>(Val: AT))
9016 PType = PVDecl->getType();
9017 } else if (PType->isFunctionType())
9018 PType = PVDecl->getType();
9019 getObjCEncodingForType(T: PType, S);
9020 S += charUnitsToString(CU: ParmOffset);
9021 ParmOffset += getObjCEncodingTypeSize(type: PType);
9022 }
9023
9024 return S;
9025}
9026
9027/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9028/// method parameter or return type. If Extended, include class names and
9029/// block object types.
9030void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
9031 QualType T, std::string& S,
9032 bool Extended) const {
9033 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9034 getObjCEncodingForTypeQualifier(QT, S);
9035 // Encode parameter type.
9036 ObjCEncOptions Options = ObjCEncOptions()
9037 .setExpandPointedToStructures()
9038 .setExpandStructures()
9039 .setIsOutermostType();
9040 if (Extended)
9041 Options.setEncodeBlockParameters().setEncodeClassNames();
9042 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
9043}
9044
9045/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9046/// declaration.
9047std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9048 bool Extended) const {
9049 // FIXME: This is not very efficient.
9050 // Encode return type.
9051 std::string S;
9052 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9053 T: Decl->getReturnType(), S, Extended);
9054 // Compute size of all parameters.
9055 // Start with computing size of a pointer in number of bytes.
9056 // FIXME: There might(should) be a better way of doing this computation!
9057 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9058 // The first two arguments (self and _cmd) are pointers; account for
9059 // their size.
9060 CharUnits ParmOffset = 2 * PtrSize;
9061 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9062 E = Decl->sel_param_end(); PI != E; ++PI) {
9063 QualType PType = (*PI)->getType();
9064 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9065 if (sz.isZero())
9066 continue;
9067
9068 assert(sz.isPositive() &&
9069 "getObjCEncodingForMethodDecl - Incomplete param type");
9070 ParmOffset += sz;
9071 }
9072 S += charUnitsToString(CU: ParmOffset);
9073 S += "@0:";
9074 S += charUnitsToString(CU: PtrSize);
9075
9076 // Argument types.
9077 ParmOffset = 2 * PtrSize;
9078 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9079 E = Decl->sel_param_end(); PI != E; ++PI) {
9080 const ParmVarDecl *PVDecl = *PI;
9081 QualType PType = PVDecl->getOriginalType();
9082 if (const auto *AT =
9083 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9084 // Use array's original type only if it has known number of
9085 // elements.
9086 if (!isa<ConstantArrayType>(Val: AT))
9087 PType = PVDecl->getType();
9088 } else if (PType->isFunctionType())
9089 PType = PVDecl->getType();
9090 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9091 T: PType, S, Extended);
9092 S += charUnitsToString(CU: ParmOffset);
9093 ParmOffset += getObjCEncodingTypeSize(type: PType);
9094 }
9095
9096 return S;
9097}
9098
9099ObjCPropertyImplDecl *
9100ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9101 const ObjCPropertyDecl *PD,
9102 const Decl *Container) const {
9103 if (!Container)
9104 return nullptr;
9105 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9106 for (auto *PID : CID->property_impls())
9107 if (PID->getPropertyDecl() == PD)
9108 return PID;
9109 } else {
9110 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9111 for (auto *PID : OID->property_impls())
9112 if (PID->getPropertyDecl() == PD)
9113 return PID;
9114 }
9115 return nullptr;
9116}
9117
9118/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9119/// property declaration. If non-NULL, Container must be either an
9120/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9121/// NULL when getting encodings for protocol properties.
9122/// Property attributes are stored as a comma-delimited C string. The simple
9123/// attributes readonly and bycopy are encoded as single characters. The
9124/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9125/// encoded as single characters, followed by an identifier. Property types
9126/// are also encoded as a parametrized attribute. The characters used to encode
9127/// these attributes are defined by the following enumeration:
9128/// @code
9129/// enum PropertyAttributes {
9130/// kPropertyReadOnly = 'R', // property is read-only.
9131/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9132/// kPropertyByref = '&', // property is a reference to the value last assigned
9133/// kPropertyDynamic = 'D', // property is dynamic
9134/// kPropertyGetter = 'G', // followed by getter selector name
9135/// kPropertySetter = 'S', // followed by setter selector name
9136/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9137/// kPropertyType = 'T' // followed by old-style type encoding.
9138/// kPropertyWeak = 'W' // 'weak' property
9139/// kPropertyStrong = 'P' // property GC'able
9140/// kPropertyNonAtomic = 'N' // property non-atomic
9141/// kPropertyOptional = '?' // property optional
9142/// };
9143/// @endcode
9144std::string
9145ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9146 const Decl *Container) const {
9147 // Collect information from the property implementation decl(s).
9148 bool Dynamic = false;
9149 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9150
9151 if (ObjCPropertyImplDecl *PropertyImpDecl =
9152 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9153 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9154 Dynamic = true;
9155 else
9156 SynthesizePID = PropertyImpDecl;
9157 }
9158
9159 // FIXME: This is not very efficient.
9160 std::string S = "T";
9161
9162 // Encode result type.
9163 // GCC has some special rules regarding encoding of properties which
9164 // closely resembles encoding of ivars.
9165 getObjCEncodingForPropertyType(T: PD->getType(), S);
9166
9167 if (PD->isOptional())
9168 S += ",?";
9169
9170 if (PD->isReadOnly()) {
9171 S += ",R";
9172 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9173 S += ",C";
9174 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9175 S += ",&";
9176 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9177 S += ",W";
9178 } else {
9179 switch (PD->getSetterKind()) {
9180 case ObjCPropertyDecl::Assign: break;
9181 case ObjCPropertyDecl::Copy: S += ",C"; break;
9182 case ObjCPropertyDecl::Retain: S += ",&"; break;
9183 case ObjCPropertyDecl::Weak: S += ",W"; break;
9184 }
9185 }
9186
9187 // It really isn't clear at all what this means, since properties
9188 // are "dynamic by default".
9189 if (Dynamic)
9190 S += ",D";
9191
9192 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9193 S += ",N";
9194
9195 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9196 S += ",G";
9197 S += PD->getGetterName().getAsString();
9198 }
9199
9200 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9201 S += ",S";
9202 S += PD->getSetterName().getAsString();
9203 }
9204
9205 if (SynthesizePID) {
9206 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9207 S += ",V";
9208 S += OID->getNameAsString();
9209 }
9210
9211 // FIXME: OBJCGC: weak & strong
9212 return S;
9213}
9214
9215/// getLegacyIntegralTypeEncoding -
9216/// Another legacy compatibility encoding: 32-bit longs are encoded as
9217/// 'l' or 'L' , but not always. For typedefs, we need to use
9218/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9219void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9220 if (PointeeTy->getAs<TypedefType>()) {
9221 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9222 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9223 PointeeTy = UnsignedIntTy;
9224 else
9225 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9226 PointeeTy = IntTy;
9227 }
9228 }
9229}
9230
9231void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9232 const FieldDecl *Field,
9233 QualType *NotEncodedT) const {
9234 // We follow the behavior of gcc, expanding structures which are
9235 // directly pointed to, and expanding embedded structures. Note that
9236 // these rules are sufficient to prevent recursive encoding of the
9237 // same type.
9238 getObjCEncodingForTypeImpl(t: T, S,
9239 Options: ObjCEncOptions()
9240 .setExpandPointedToStructures()
9241 .setExpandStructures()
9242 .setIsOutermostType(),
9243 Field, NotEncodedT);
9244}
9245
9246void ASTContext::getObjCEncodingForPropertyType(QualType T,
9247 std::string& S) const {
9248 // Encode result type.
9249 // GCC has some special rules regarding encoding of properties which
9250 // closely resembles encoding of ivars.
9251 getObjCEncodingForTypeImpl(t: T, S,
9252 Options: ObjCEncOptions()
9253 .setExpandPointedToStructures()
9254 .setExpandStructures()
9255 .setIsOutermostType()
9256 .setEncodingProperty(),
9257 /*Field=*/nullptr);
9258}
9259
9260static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9261 const BuiltinType *BT) {
9262 BuiltinType::Kind kind = BT->getKind();
9263 switch (kind) {
9264 case BuiltinType::Void: return 'v';
9265 case BuiltinType::Bool: return 'B';
9266 case BuiltinType::Char8:
9267 case BuiltinType::Char_U:
9268 case BuiltinType::UChar: return 'C';
9269 case BuiltinType::Char16:
9270 case BuiltinType::UShort: return 'S';
9271 case BuiltinType::Char32:
9272 case BuiltinType::UInt: return 'I';
9273 case BuiltinType::ULong:
9274 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9275 case BuiltinType::UInt128: return 'T';
9276 case BuiltinType::ULongLong: return 'Q';
9277 case BuiltinType::Char_S:
9278 case BuiltinType::SChar: return 'c';
9279 case BuiltinType::Short: return 's';
9280 case BuiltinType::WChar_S:
9281 case BuiltinType::WChar_U:
9282 case BuiltinType::Int: return 'i';
9283 case BuiltinType::Long:
9284 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9285 case BuiltinType::LongLong: return 'q';
9286 case BuiltinType::Int128: return 't';
9287 case BuiltinType::Float: return 'f';
9288 case BuiltinType::Double: return 'd';
9289 case BuiltinType::LongDouble: return 'D';
9290 case BuiltinType::NullPtr: return '*'; // like char*
9291
9292 case BuiltinType::BFloat16:
9293 case BuiltinType::Float16:
9294 case BuiltinType::Float128:
9295 case BuiltinType::Ibm128:
9296 case BuiltinType::Half:
9297 case BuiltinType::ShortAccum:
9298 case BuiltinType::Accum:
9299 case BuiltinType::LongAccum:
9300 case BuiltinType::UShortAccum:
9301 case BuiltinType::UAccum:
9302 case BuiltinType::ULongAccum:
9303 case BuiltinType::ShortFract:
9304 case BuiltinType::Fract:
9305 case BuiltinType::LongFract:
9306 case BuiltinType::UShortFract:
9307 case BuiltinType::UFract:
9308 case BuiltinType::ULongFract:
9309 case BuiltinType::SatShortAccum:
9310 case BuiltinType::SatAccum:
9311 case BuiltinType::SatLongAccum:
9312 case BuiltinType::SatUShortAccum:
9313 case BuiltinType::SatUAccum:
9314 case BuiltinType::SatULongAccum:
9315 case BuiltinType::SatShortFract:
9316 case BuiltinType::SatFract:
9317 case BuiltinType::SatLongFract:
9318 case BuiltinType::SatUShortFract:
9319 case BuiltinType::SatUFract:
9320 case BuiltinType::SatULongFract:
9321 // FIXME: potentially need @encodes for these!
9322 return ' ';
9323
9324#define SVE_TYPE(Name, Id, SingletonId) \
9325 case BuiltinType::Id:
9326#include "clang/Basic/AArch64ACLETypes.def"
9327#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9328#include "clang/Basic/RISCVVTypes.def"
9329#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9330#include "clang/Basic/WebAssemblyReferenceTypes.def"
9331#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9332#include "clang/Basic/AMDGPUTypes.def"
9333#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9334#include "clang/Basic/SPIRVTypes.def"
9335 {
9336 DiagnosticsEngine &Diags = C->getDiagnostics();
9337 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9338 << QualType(BT, 0);
9339 return ' ';
9340 }
9341
9342 case BuiltinType::ObjCId:
9343 case BuiltinType::ObjCClass:
9344 case BuiltinType::ObjCSel:
9345 llvm_unreachable("@encoding ObjC primitive type");
9346
9347 // OpenCL and placeholder types don't need @encodings.
9348#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9349 case BuiltinType::Id:
9350#include "clang/Basic/OpenCLImageTypes.def"
9351#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9352 case BuiltinType::Id:
9353#include "clang/Basic/OpenCLExtensionTypes.def"
9354 case BuiltinType::OCLEvent:
9355 case BuiltinType::OCLClkEvent:
9356 case BuiltinType::OCLQueue:
9357 case BuiltinType::OCLReserveID:
9358 case BuiltinType::OCLSampler:
9359 case BuiltinType::Dependent:
9360 case BuiltinType::MetaInfo:
9361#define PPC_VECTOR_TYPE(Name, Id, Size) \
9362 case BuiltinType::Id:
9363#include "clang/Basic/PPCTypes.def"
9364#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9365#include "clang/Basic/HLSLIntangibleTypes.def"
9366#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9367#include "clang/Basic/HLSLPackedTypes.def"
9368#define BUILTIN_TYPE(KIND, ID)
9369#define PLACEHOLDER_TYPE(KIND, ID) \
9370 case BuiltinType::KIND:
9371#include "clang/AST/BuiltinTypes.def"
9372 llvm_unreachable("invalid builtin type for @encode");
9373 }
9374 llvm_unreachable("invalid BuiltinType::Kind value");
9375}
9376
9377static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9378 EnumDecl *Enum = ED->getDefinitionOrSelf();
9379
9380 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9381 if (!Enum->isFixed())
9382 return 'i';
9383
9384 // The encoding of a fixed enum type matches its fixed underlying type.
9385 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9386 return getObjCEncodingForPrimitiveType(C, BT);
9387}
9388
9389static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9390 QualType T, const FieldDecl *FD) {
9391 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9392 S += 'b';
9393 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9394 // The GNU runtime requires more information; bitfields are encoded as b,
9395 // then the offset (in bits) of the first element, then the type of the
9396 // bitfield, then the size in bits. For example, in this structure:
9397 //
9398 // struct
9399 // {
9400 // int integer;
9401 // int flags:2;
9402 // };
9403 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9404 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9405 // information is not especially sensible, but we're stuck with it for
9406 // compatibility with GCC, although providing it breaks anything that
9407 // actually uses runtime introspection and wants to work on both runtimes...
9408 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9409 uint64_t Offset;
9410
9411 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9412 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9413 } else {
9414 const RecordDecl *RD = FD->getParent();
9415 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9416 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9417 }
9418
9419 S += llvm::utostr(X: Offset);
9420
9421 if (const auto *ET = T->getAsCanonical<EnumType>())
9422 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9423 else {
9424 const auto *BT = T->castAs<BuiltinType>();
9425 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9426 }
9427 }
9428 S += llvm::utostr(X: FD->getBitWidthValue());
9429}
9430
9431// Helper function for determining whether the encoded type string would include
9432// a template specialization type.
9433static bool hasTemplateSpecializationInEncodedString(const Type *T,
9434 bool VisitBasesAndFields) {
9435 T = T->getBaseElementTypeUnsafe();
9436
9437 if (auto *PT = T->getAs<PointerType>())
9438 return hasTemplateSpecializationInEncodedString(
9439 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9440
9441 auto *CXXRD = T->getAsCXXRecordDecl();
9442
9443 if (!CXXRD)
9444 return false;
9445
9446 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9447 return true;
9448
9449 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9450 return false;
9451
9452 for (const auto &B : CXXRD->bases())
9453 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9454 VisitBasesAndFields: true))
9455 return true;
9456
9457 for (auto *FD : CXXRD->fields())
9458 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9459 VisitBasesAndFields: true))
9460 return true;
9461
9462 return false;
9463}
9464
9465// FIXME: Use SmallString for accumulating string.
9466void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9467 const ObjCEncOptions Options,
9468 const FieldDecl *FD,
9469 QualType *NotEncodedT) const {
9470 CanQualType CT = getCanonicalType(T);
9471 switch (CT->getTypeClass()) {
9472 case Type::Builtin:
9473 case Type::Enum:
9474 if (FD && FD->isBitField())
9475 return EncodeBitField(Ctx: this, S, T, FD);
9476 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9477 S += getObjCEncodingForPrimitiveType(C: this, BT);
9478 else
9479 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9480 return;
9481
9482 case Type::Complex:
9483 S += 'j';
9484 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9485 Options: ObjCEncOptions(),
9486 /*Field=*/FD: nullptr);
9487 return;
9488
9489 case Type::Atomic:
9490 S += 'A';
9491 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9492 Options: ObjCEncOptions(),
9493 /*Field=*/FD: nullptr);
9494 return;
9495
9496 // encoding for pointer or reference types.
9497 case Type::Pointer:
9498 case Type::LValueReference:
9499 case Type::RValueReference: {
9500 QualType PointeeTy;
9501 if (isa<PointerType>(Val: CT)) {
9502 const auto *PT = T->castAs<PointerType>();
9503 if (PT->isObjCSelType()) {
9504 S += ':';
9505 return;
9506 }
9507 PointeeTy = PT->getPointeeType();
9508 } else {
9509 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9510 }
9511
9512 bool isReadOnly = false;
9513 // For historical/compatibility reasons, the read-only qualifier of the
9514 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9515 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9516 // Also, do not emit the 'r' for anything but the outermost type!
9517 if (T->getAs<TypedefType>()) {
9518 if (Options.IsOutermostType() && T.isConstQualified()) {
9519 isReadOnly = true;
9520 S += 'r';
9521 }
9522 } else if (Options.IsOutermostType()) {
9523 QualType P = PointeeTy;
9524 while (auto PT = P->getAs<PointerType>())
9525 P = PT->getPointeeType();
9526 if (P.isConstQualified()) {
9527 isReadOnly = true;
9528 S += 'r';
9529 }
9530 }
9531 if (isReadOnly) {
9532 // Another legacy compatibility encoding. Some ObjC qualifier and type
9533 // combinations need to be rearranged.
9534 // Rewrite "in const" from "nr" to "rn"
9535 if (StringRef(S).ends_with(Suffix: "nr"))
9536 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9537 }
9538
9539 if (PointeeTy->isCharType()) {
9540 // char pointer types should be encoded as '*' unless it is a
9541 // type that has been typedef'd to 'BOOL'.
9542 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9543 S += '*';
9544 return;
9545 }
9546 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9547 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9548 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9549 if (II == &Idents.get(Name: "objc_class")) {
9550 S += '#';
9551 return;
9552 }
9553 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9554 if (II == &Idents.get(Name: "objc_object")) {
9555 S += '@';
9556 return;
9557 }
9558 // If the encoded string for the class includes template names, just emit
9559 // "^v" for pointers to the class.
9560 if (getLangOpts().CPlusPlus &&
9561 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9562 hasTemplateSpecializationInEncodedString(
9563 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9564 S += "^v";
9565 return;
9566 }
9567 // fall through...
9568 }
9569 S += '^';
9570 getLegacyIntegralTypeEncoding(PointeeTy);
9571
9572 ObjCEncOptions NewOptions;
9573 if (Options.ExpandPointedToStructures())
9574 NewOptions.setExpandStructures();
9575 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9576 /*Field=*/FD: nullptr, NotEncodedT);
9577 return;
9578 }
9579
9580 case Type::ConstantArray:
9581 case Type::IncompleteArray:
9582 case Type::VariableArray: {
9583 const auto *AT = cast<ArrayType>(Val&: CT);
9584
9585 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9586 // Incomplete arrays are encoded as a pointer to the array element.
9587 S += '^';
9588
9589 getObjCEncodingForTypeImpl(
9590 T: AT->getElementType(), S,
9591 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9592 } else {
9593 S += '[';
9594
9595 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9596 S += llvm::utostr(X: CAT->getZExtSize());
9597 else {
9598 //Variable length arrays are encoded as a regular array with 0 elements.
9599 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9600 "Unknown array type!");
9601 S += '0';
9602 }
9603
9604 getObjCEncodingForTypeImpl(
9605 T: AT->getElementType(), S,
9606 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9607 NotEncodedT);
9608 S += ']';
9609 }
9610 return;
9611 }
9612
9613 case Type::FunctionNoProto:
9614 case Type::FunctionProto:
9615 S += '?';
9616 return;
9617
9618 case Type::Record: {
9619 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9620 S += RDecl->isUnion() ? '(' : '{';
9621 // Anonymous structures print as '?'
9622 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9623 S += II->getName();
9624 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9625 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9626 llvm::raw_string_ostream OS(S);
9627 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9628 Policy: getPrintingPolicy());
9629 }
9630 } else {
9631 S += '?';
9632 }
9633 if (Options.ExpandStructures()) {
9634 S += '=';
9635 if (!RDecl->isUnion()) {
9636 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9637 } else {
9638 for (const auto *Field : RDecl->fields()) {
9639 if (FD) {
9640 S += '"';
9641 S += Field->getNameAsString();
9642 S += '"';
9643 }
9644
9645 // Special case bit-fields.
9646 if (Field->isBitField()) {
9647 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9648 Options: ObjCEncOptions().setExpandStructures(),
9649 FD: Field);
9650 } else {
9651 QualType qt = Field->getType();
9652 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9653 getObjCEncodingForTypeImpl(
9654 T: qt, S,
9655 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9656 NotEncodedT);
9657 }
9658 }
9659 }
9660 }
9661 S += RDecl->isUnion() ? ')' : '}';
9662 return;
9663 }
9664
9665 case Type::BlockPointer: {
9666 const auto *BT = T->castAs<BlockPointerType>();
9667 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9668 if (Options.EncodeBlockParameters()) {
9669 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9670
9671 S += '<';
9672 // Block return type
9673 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9674 Options: Options.forComponentType(), FD, NotEncodedT);
9675 // Block self
9676 S += "@?";
9677 // Block parameters
9678 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9679 for (const auto &I : FPT->param_types())
9680 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9681 NotEncodedT);
9682 }
9683 S += '>';
9684 }
9685 return;
9686 }
9687
9688 case Type::ObjCObject: {
9689 // hack to match legacy encoding of *id and *Class
9690 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9691 if (Ty->isObjCIdType()) {
9692 S += "{objc_object=}";
9693 return;
9694 }
9695 else if (Ty->isObjCClassType()) {
9696 S += "{objc_class=}";
9697 return;
9698 }
9699 // TODO: Double check to make sure this intentionally falls through.
9700 [[fallthrough]];
9701 }
9702
9703 case Type::ObjCInterface: {
9704 // Ignore protocol qualifiers when mangling at this level.
9705 // @encode(class_name)
9706 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9707 S += '{';
9708 S += OI->getObjCRuntimeNameAsString();
9709 if (Options.ExpandStructures()) {
9710 S += '=';
9711 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9712 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9713 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9714 const FieldDecl *Field = Ivars[i];
9715 if (Field->isBitField())
9716 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9717 Options: ObjCEncOptions().setExpandStructures(),
9718 FD: Field);
9719 else
9720 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9721 Options: ObjCEncOptions().setExpandStructures(), FD,
9722 NotEncodedT);
9723 }
9724 }
9725 S += '}';
9726 return;
9727 }
9728
9729 case Type::ObjCObjectPointer: {
9730 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9731 if (OPT->isObjCIdType()) {
9732 S += '@';
9733 return;
9734 }
9735
9736 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9737 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9738 // Since this is a binary compatibility issue, need to consult with
9739 // runtime folks. Fortunately, this is a *very* obscure construct.
9740 S += '#';
9741 return;
9742 }
9743
9744 if (OPT->isObjCQualifiedIdType()) {
9745 getObjCEncodingForTypeImpl(
9746 T: getObjCIdType(), S,
9747 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9748 .setExpandPointedToStructures()
9749 .setExpandStructures()),
9750 FD);
9751 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9752 // Note that we do extended encoding of protocol qualifier list
9753 // Only when doing ivar or property encoding.
9754 S += '"';
9755 for (const auto *I : OPT->quals()) {
9756 S += '<';
9757 S += I->getObjCRuntimeNameAsString();
9758 S += '>';
9759 }
9760 S += '"';
9761 }
9762 return;
9763 }
9764
9765 S += '@';
9766 if (OPT->getInterfaceDecl() &&
9767 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9768 S += '"';
9769 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9770 for (const auto *I : OPT->quals()) {
9771 S += '<';
9772 S += I->getObjCRuntimeNameAsString();
9773 S += '>';
9774 }
9775 S += '"';
9776 }
9777 return;
9778 }
9779
9780 // gcc just blithely ignores member pointers.
9781 // FIXME: we should do better than that. 'M' is available.
9782 case Type::MemberPointer:
9783 // This matches gcc's encoding, even though technically it is insufficient.
9784 //FIXME. We should do a better job than gcc.
9785 case Type::Vector:
9786 case Type::ExtVector:
9787 // Until we have a coherent encoding of these three types, issue warning.
9788 if (NotEncodedT)
9789 *NotEncodedT = T;
9790 return;
9791
9792 case Type::ConstantMatrix:
9793 if (NotEncodedT)
9794 *NotEncodedT = T;
9795 return;
9796
9797 case Type::BitInt:
9798 if (NotEncodedT)
9799 *NotEncodedT = T;
9800 return;
9801
9802 // We could see an undeduced auto type here during error recovery.
9803 // Just ignore it.
9804 case Type::Auto:
9805 case Type::DeducedTemplateSpecialization:
9806 return;
9807
9808 // An overflow behavior type has the representation of its underlying type.
9809 case Type::OverflowBehavior:
9810 getObjCEncodingForTypeImpl(
9811 T: cast<OverflowBehaviorType>(Val&: CT)->getUnderlyingType(), S, Options, FD,
9812 NotEncodedT);
9813 return;
9814
9815 case Type::HLSLAttributedResource:
9816 case Type::HLSLInlineSpirv:
9817 llvm_unreachable("unexpected type");
9818
9819 case Type::ArrayParameter:
9820 case Type::Pipe:
9821#define ABSTRACT_TYPE(KIND, BASE)
9822#define TYPE(KIND, BASE)
9823#define DEPENDENT_TYPE(KIND, BASE) \
9824 case Type::KIND:
9825#define NON_CANONICAL_TYPE(KIND, BASE) \
9826 case Type::KIND:
9827#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9828 case Type::KIND:
9829#include "clang/AST/TypeNodes.inc"
9830 llvm_unreachable("@encode for dependent type!");
9831 }
9832 llvm_unreachable("bad type kind!");
9833}
9834
9835void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9836 std::string &S,
9837 const FieldDecl *FD,
9838 bool includeVBases,
9839 QualType *NotEncodedT) const {
9840 assert(RDecl && "Expected non-null RecordDecl");
9841 assert(!RDecl->isUnion() && "Should not be called for unions");
9842 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9843 return;
9844
9845 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9846 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9847 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9848
9849 if (CXXRec) {
9850 for (const auto &BI : CXXRec->bases()) {
9851 if (!BI.isVirtual()) {
9852 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9853 if (base->isEmpty())
9854 continue;
9855 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9856 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9857 x: std::make_pair(x&: offs, y&: base));
9858 }
9859 }
9860 }
9861
9862 for (FieldDecl *Field : RDecl->fields()) {
9863 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9864 continue;
9865 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9866 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9867 x: std::make_pair(x&: offs, y&: Field));
9868 }
9869
9870 if (CXXRec && includeVBases) {
9871 for (const auto &BI : CXXRec->vbases()) {
9872 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9873 if (base->isEmpty())
9874 continue;
9875 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9876 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9877 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9878 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9879 x: std::make_pair(x&: offs, y&: base));
9880 }
9881 }
9882
9883 CharUnits size;
9884 if (CXXRec) {
9885 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9886 } else {
9887 size = layout.getSize();
9888 }
9889
9890#ifndef NDEBUG
9891 uint64_t CurOffs = 0;
9892#endif
9893 std::multimap<uint64_t, NamedDecl *>::iterator
9894 CurLayObj = FieldOrBaseOffsets.begin();
9895
9896 if (CXXRec && CXXRec->isDynamicClass() &&
9897 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9898 if (FD) {
9899 S += "\"_vptr$";
9900 std::string recname = CXXRec->getNameAsString();
9901 if (recname.empty()) recname = "?";
9902 S += recname;
9903 S += '"';
9904 }
9905 S += "^^?";
9906#ifndef NDEBUG
9907 CurOffs += getTypeSize(VoidPtrTy);
9908#endif
9909 }
9910
9911 if (!RDecl->hasFlexibleArrayMember()) {
9912 // Mark the end of the structure.
9913 uint64_t offs = toBits(CharSize: size);
9914 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9915 x: std::make_pair(x&: offs, y: nullptr));
9916 }
9917
9918 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9919#ifndef NDEBUG
9920 assert(CurOffs <= CurLayObj->first);
9921 if (CurOffs < CurLayObj->first) {
9922 uint64_t padding = CurLayObj->first - CurOffs;
9923 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9924 // packing/alignment of members is different that normal, in which case
9925 // the encoding will be out-of-sync with the real layout.
9926 // If the runtime switches to just consider the size of types without
9927 // taking into account alignment, we could make padding explicit in the
9928 // encoding (e.g. using arrays of chars). The encoding strings would be
9929 // longer then though.
9930 CurOffs += padding;
9931 }
9932#endif
9933
9934 NamedDecl *dcl = CurLayObj->second;
9935 if (!dcl)
9936 break; // reached end of structure.
9937
9938 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9939 // We expand the bases without their virtual bases since those are going
9940 // in the initial structure. Note that this differs from gcc which
9941 // expands virtual bases each time one is encountered in the hierarchy,
9942 // making the encoding type bigger than it really is.
9943 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9944 NotEncodedT);
9945 assert(!base->isEmpty());
9946#ifndef NDEBUG
9947 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9948#endif
9949 } else {
9950 const auto *field = cast<FieldDecl>(Val: dcl);
9951 if (FD) {
9952 S += '"';
9953 S += field->getNameAsString();
9954 S += '"';
9955 }
9956
9957 if (field->isBitField()) {
9958 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9959#ifndef NDEBUG
9960 CurOffs += field->getBitWidthValue();
9961#endif
9962 } else {
9963 QualType qt = field->getType();
9964 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9965 getObjCEncodingForTypeImpl(
9966 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9967 FD, NotEncodedT);
9968#ifndef NDEBUG
9969 CurOffs += getTypeSize(field->getType());
9970#endif
9971 }
9972 }
9973 }
9974}
9975
9976void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9977 std::string& S) const {
9978 if (QT & Decl::OBJC_TQ_In)
9979 S += 'n';
9980 if (QT & Decl::OBJC_TQ_Inout)
9981 S += 'N';
9982 if (QT & Decl::OBJC_TQ_Out)
9983 S += 'o';
9984 if (QT & Decl::OBJC_TQ_Bycopy)
9985 S += 'O';
9986 if (QT & Decl::OBJC_TQ_Byref)
9987 S += 'R';
9988 if (QT & Decl::OBJC_TQ_Oneway)
9989 S += 'V';
9990}
9991
9992TypedefDecl *ASTContext::getObjCIdDecl() const {
9993 if (!ObjCIdDecl) {
9994 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9995 T = getObjCObjectPointerType(ObjectT: T);
9996 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9997 }
9998 return ObjCIdDecl;
9999}
10000
10001TypedefDecl *ASTContext::getObjCSelDecl() const {
10002 if (!ObjCSelDecl) {
10003 QualType T = getPointerType(T: ObjCBuiltinSelTy);
10004 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
10005 }
10006 return ObjCSelDecl;
10007}
10008
10009TypedefDecl *ASTContext::getObjCClassDecl() const {
10010 if (!ObjCClassDecl) {
10011 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
10012 T = getObjCObjectPointerType(ObjectT: T);
10013 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
10014 }
10015 return ObjCClassDecl;
10016}
10017
10018ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
10019 if (!ObjCProtocolClassDecl) {
10020 ObjCProtocolClassDecl
10021 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
10022 atLoc: SourceLocation(),
10023 Id: &Idents.get(Name: "Protocol"),
10024 /*typeParamList=*/nullptr,
10025 /*PrevDecl=*/nullptr,
10026 ClassLoc: SourceLocation(), isInternal: true);
10027 }
10028
10029 return ObjCProtocolClassDecl;
10030}
10031
10032PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
10033 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10034 return PointerAuthQualifier();
10035 return PointerAuthQualifier::Create(
10036 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
10037 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
10038 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
10039 /*isIsaPointer=*/IsIsaPointer: false,
10040 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
10041}
10042
10043//===----------------------------------------------------------------------===//
10044// __builtin_va_list Construction Functions
10045//===----------------------------------------------------------------------===//
10046
10047static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
10048 StringRef Name) {
10049 // typedef char* __builtin[_ms]_va_list;
10050 QualType T = Context->getPointerType(T: Context->CharTy);
10051 return Context->buildImplicitTypedef(T, Name);
10052}
10053
10054static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10055 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10056}
10057
10058static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10059 // typedef char *__builtin_zos_va_list[2];
10060 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10061 QualType T = Context->getPointerType(T: Context->CharTy);
10062 QualType ArrayType = Context->getConstantArrayType(
10063 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10064 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10065}
10066
10067static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10068 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10069}
10070
10071static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10072 // typedef void* __builtin_va_list;
10073 QualType T = Context->getPointerType(T: Context->VoidTy);
10074 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10075}
10076
10077static TypedefDecl *
10078CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10079 // struct __va_list
10080 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10081 if (Context->getLangOpts().CPlusPlus) {
10082 // namespace std { struct __va_list {
10083 auto *NS = NamespaceDecl::Create(
10084 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10085 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10086 Id: &Context->Idents.get(Name: "std"),
10087 /*PrevDecl=*/nullptr, /*Nested=*/false);
10088 NS->setImplicit();
10089 VaListTagDecl->setDeclContext(NS);
10090 }
10091
10092 VaListTagDecl->startDefinition();
10093
10094 const size_t NumFields = 5;
10095 QualType FieldTypes[NumFields];
10096 const char *FieldNames[NumFields];
10097
10098 // void *__stack;
10099 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10100 FieldNames[0] = "__stack";
10101
10102 // void *__gr_top;
10103 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10104 FieldNames[1] = "__gr_top";
10105
10106 // void *__vr_top;
10107 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10108 FieldNames[2] = "__vr_top";
10109
10110 // int __gr_offs;
10111 FieldTypes[3] = Context->IntTy;
10112 FieldNames[3] = "__gr_offs";
10113
10114 // int __vr_offs;
10115 FieldTypes[4] = Context->IntTy;
10116 FieldNames[4] = "__vr_offs";
10117
10118 // Create fields
10119 for (unsigned i = 0; i < NumFields; ++i) {
10120 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10121 DC: VaListTagDecl,
10122 StartLoc: SourceLocation(),
10123 IdLoc: SourceLocation(),
10124 Id: &Context->Idents.get(Name: FieldNames[i]),
10125 T: FieldTypes[i], /*TInfo=*/nullptr,
10126 /*BitWidth=*/BW: nullptr,
10127 /*Mutable=*/false,
10128 InitStyle: ICIS_NoInit);
10129 Field->setAccess(AS_public);
10130 VaListTagDecl->addDecl(D: Field);
10131 }
10132 VaListTagDecl->completeDefinition();
10133 Context->VaListTagDecl = VaListTagDecl;
10134 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10135
10136 // } __builtin_va_list;
10137 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10138}
10139
10140static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10141 // typedef struct __va_list_tag {
10142 RecordDecl *VaListTagDecl;
10143
10144 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10145 VaListTagDecl->startDefinition();
10146
10147 const size_t NumFields = 5;
10148 QualType FieldTypes[NumFields];
10149 const char *FieldNames[NumFields];
10150
10151 // unsigned char gpr;
10152 FieldTypes[0] = Context->UnsignedCharTy;
10153 FieldNames[0] = "gpr";
10154
10155 // unsigned char fpr;
10156 FieldTypes[1] = Context->UnsignedCharTy;
10157 FieldNames[1] = "fpr";
10158
10159 // unsigned short reserved;
10160 FieldTypes[2] = Context->UnsignedShortTy;
10161 FieldNames[2] = "reserved";
10162
10163 // void* overflow_arg_area;
10164 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10165 FieldNames[3] = "overflow_arg_area";
10166
10167 // void* reg_save_area;
10168 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10169 FieldNames[4] = "reg_save_area";
10170
10171 // Create fields
10172 for (unsigned i = 0; i < NumFields; ++i) {
10173 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10174 StartLoc: SourceLocation(),
10175 IdLoc: SourceLocation(),
10176 Id: &Context->Idents.get(Name: FieldNames[i]),
10177 T: FieldTypes[i], /*TInfo=*/nullptr,
10178 /*BitWidth=*/BW: nullptr,
10179 /*Mutable=*/false,
10180 InitStyle: ICIS_NoInit);
10181 Field->setAccess(AS_public);
10182 VaListTagDecl->addDecl(D: Field);
10183 }
10184 VaListTagDecl->completeDefinition();
10185 Context->VaListTagDecl = VaListTagDecl;
10186 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10187
10188 // } __va_list_tag;
10189 TypedefDecl *VaListTagTypedefDecl =
10190 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10191
10192 QualType VaListTagTypedefType =
10193 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10194 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10195
10196 // typedef __va_list_tag __builtin_va_list[1];
10197 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10198 QualType VaListTagArrayType = Context->getConstantArrayType(
10199 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10200 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10201}
10202
10203static TypedefDecl *
10204CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10205 // struct __va_list_tag {
10206 RecordDecl *VaListTagDecl;
10207 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10208 VaListTagDecl->startDefinition();
10209
10210 const size_t NumFields = 4;
10211 QualType FieldTypes[NumFields];
10212 const char *FieldNames[NumFields];
10213
10214 // unsigned gp_offset;
10215 FieldTypes[0] = Context->UnsignedIntTy;
10216 FieldNames[0] = "gp_offset";
10217
10218 // unsigned fp_offset;
10219 FieldTypes[1] = Context->UnsignedIntTy;
10220 FieldNames[1] = "fp_offset";
10221
10222 // void* overflow_arg_area;
10223 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10224 FieldNames[2] = "overflow_arg_area";
10225
10226 // void* reg_save_area;
10227 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10228 FieldNames[3] = "reg_save_area";
10229
10230 // Create fields
10231 for (unsigned i = 0; i < NumFields; ++i) {
10232 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10233 DC: VaListTagDecl,
10234 StartLoc: SourceLocation(),
10235 IdLoc: SourceLocation(),
10236 Id: &Context->Idents.get(Name: FieldNames[i]),
10237 T: FieldTypes[i], /*TInfo=*/nullptr,
10238 /*BitWidth=*/BW: nullptr,
10239 /*Mutable=*/false,
10240 InitStyle: ICIS_NoInit);
10241 Field->setAccess(AS_public);
10242 VaListTagDecl->addDecl(D: Field);
10243 }
10244 VaListTagDecl->completeDefinition();
10245 Context->VaListTagDecl = VaListTagDecl;
10246 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10247
10248 // };
10249
10250 // typedef struct __va_list_tag __builtin_va_list[1];
10251 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10252 QualType VaListTagArrayType = Context->getConstantArrayType(
10253 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10254 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10255}
10256
10257static TypedefDecl *
10258CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10259 // struct __va_list
10260 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10261 if (Context->getLangOpts().CPlusPlus) {
10262 // namespace std { struct __va_list {
10263 NamespaceDecl *NS;
10264 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10265 DC: Context->getTranslationUnitDecl(),
10266 /*Inline=*/false, StartLoc: SourceLocation(),
10267 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10268 /*PrevDecl=*/nullptr, /*Nested=*/false);
10269 NS->setImplicit();
10270 VaListDecl->setDeclContext(NS);
10271 }
10272
10273 VaListDecl->startDefinition();
10274
10275 // void * __ap;
10276 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10277 DC: VaListDecl,
10278 StartLoc: SourceLocation(),
10279 IdLoc: SourceLocation(),
10280 Id: &Context->Idents.get(Name: "__ap"),
10281 T: Context->getPointerType(T: Context->VoidTy),
10282 /*TInfo=*/nullptr,
10283 /*BitWidth=*/BW: nullptr,
10284 /*Mutable=*/false,
10285 InitStyle: ICIS_NoInit);
10286 Field->setAccess(AS_public);
10287 VaListDecl->addDecl(D: Field);
10288
10289 // };
10290 VaListDecl->completeDefinition();
10291 Context->VaListTagDecl = VaListDecl;
10292
10293 // typedef struct __va_list __builtin_va_list;
10294 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10295 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10296}
10297
10298static TypedefDecl *
10299CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10300 // struct __va_list_tag {
10301 RecordDecl *VaListTagDecl;
10302 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10303 VaListTagDecl->startDefinition();
10304
10305 const size_t NumFields = 4;
10306 QualType FieldTypes[NumFields];
10307 const char *FieldNames[NumFields];
10308
10309 // long __gpr;
10310 FieldTypes[0] = Context->LongTy;
10311 FieldNames[0] = "__gpr";
10312
10313 // long __fpr;
10314 FieldTypes[1] = Context->LongTy;
10315 FieldNames[1] = "__fpr";
10316
10317 // void *__overflow_arg_area;
10318 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10319 FieldNames[2] = "__overflow_arg_area";
10320
10321 // void *__reg_save_area;
10322 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10323 FieldNames[3] = "__reg_save_area";
10324
10325 // Create fields
10326 for (unsigned i = 0; i < NumFields; ++i) {
10327 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10328 DC: VaListTagDecl,
10329 StartLoc: SourceLocation(),
10330 IdLoc: SourceLocation(),
10331 Id: &Context->Idents.get(Name: FieldNames[i]),
10332 T: FieldTypes[i], /*TInfo=*/nullptr,
10333 /*BitWidth=*/BW: nullptr,
10334 /*Mutable=*/false,
10335 InitStyle: ICIS_NoInit);
10336 Field->setAccess(AS_public);
10337 VaListTagDecl->addDecl(D: Field);
10338 }
10339 VaListTagDecl->completeDefinition();
10340 Context->VaListTagDecl = VaListTagDecl;
10341 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10342
10343 // };
10344
10345 // typedef __va_list_tag __builtin_va_list[1];
10346 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10347 QualType VaListTagArrayType = Context->getConstantArrayType(
10348 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10349
10350 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10351}
10352
10353static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10354 // typedef struct __va_list_tag {
10355 RecordDecl *VaListTagDecl;
10356 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10357 VaListTagDecl->startDefinition();
10358
10359 const size_t NumFields = 3;
10360 QualType FieldTypes[NumFields];
10361 const char *FieldNames[NumFields];
10362
10363 // void *CurrentSavedRegisterArea;
10364 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10365 FieldNames[0] = "__current_saved_reg_area_pointer";
10366
10367 // void *SavedRegAreaEnd;
10368 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10369 FieldNames[1] = "__saved_reg_area_end_pointer";
10370
10371 // void *OverflowArea;
10372 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10373 FieldNames[2] = "__overflow_area_pointer";
10374
10375 // Create fields
10376 for (unsigned i = 0; i < NumFields; ++i) {
10377 FieldDecl *Field = FieldDecl::Create(
10378 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10379 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10380 /*TInfo=*/nullptr,
10381 /*BitWidth=*/BW: nullptr,
10382 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10383 Field->setAccess(AS_public);
10384 VaListTagDecl->addDecl(D: Field);
10385 }
10386 VaListTagDecl->completeDefinition();
10387 Context->VaListTagDecl = VaListTagDecl;
10388 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10389
10390 // } __va_list_tag;
10391 TypedefDecl *VaListTagTypedefDecl =
10392 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10393
10394 QualType VaListTagTypedefType =
10395 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10396 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10397
10398 // typedef __va_list_tag __builtin_va_list[1];
10399 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10400 QualType VaListTagArrayType = Context->getConstantArrayType(
10401 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10402
10403 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10404}
10405
10406static TypedefDecl *
10407CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10408 // typedef struct __va_list_tag {
10409 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10410
10411 VaListTagDecl->startDefinition();
10412
10413 // int* __va_stk;
10414 // int* __va_reg;
10415 // int __va_ndx;
10416 constexpr size_t NumFields = 3;
10417 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10418 Context->getPointerType(T: Context->IntTy),
10419 Context->IntTy};
10420 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10421
10422 // Create fields
10423 for (unsigned i = 0; i < NumFields; ++i) {
10424 FieldDecl *Field = FieldDecl::Create(
10425 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10426 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10427 /*BitWidth=*/BW: nullptr,
10428 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10429 Field->setAccess(AS_public);
10430 VaListTagDecl->addDecl(D: Field);
10431 }
10432 VaListTagDecl->completeDefinition();
10433 Context->VaListTagDecl = VaListTagDecl;
10434 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10435
10436 // } __va_list_tag;
10437 TypedefDecl *VaListTagTypedefDecl =
10438 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10439
10440 return VaListTagTypedefDecl;
10441}
10442
10443static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10444 TargetInfo::BuiltinVaListKind Kind) {
10445 switch (Kind) {
10446 case TargetInfo::CharPtrBuiltinVaList:
10447 return CreateCharPtrBuiltinVaListDecl(Context);
10448 case TargetInfo::VoidPtrBuiltinVaList:
10449 return CreateVoidPtrBuiltinVaListDecl(Context);
10450 case TargetInfo::AArch64ABIBuiltinVaList:
10451 return CreateAArch64ABIBuiltinVaListDecl(Context);
10452 case TargetInfo::PowerABIBuiltinVaList:
10453 return CreatePowerABIBuiltinVaListDecl(Context);
10454 case TargetInfo::X86_64ABIBuiltinVaList:
10455 return CreateX86_64ABIBuiltinVaListDecl(Context);
10456 case TargetInfo::AAPCSABIBuiltinVaList:
10457 return CreateAAPCSABIBuiltinVaListDecl(Context);
10458 case TargetInfo::SystemZBuiltinVaList:
10459 return CreateSystemZBuiltinVaListDecl(Context);
10460 case TargetInfo::HexagonBuiltinVaList:
10461 return CreateHexagonBuiltinVaListDecl(Context);
10462 case TargetInfo::XtensaABIBuiltinVaList:
10463 return CreateXtensaABIBuiltinVaListDecl(Context);
10464 }
10465
10466 llvm_unreachable("Unhandled __builtin_va_list type kind");
10467}
10468
10469TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10470 if (!BuiltinVaListDecl) {
10471 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10472 assert(BuiltinVaListDecl->isImplicit());
10473 }
10474
10475 return BuiltinVaListDecl;
10476}
10477
10478Decl *ASTContext::getVaListTagDecl() const {
10479 // Force the creation of VaListTagDecl by building the __builtin_va_list
10480 // declaration.
10481 if (!VaListTagDecl)
10482 (void)getBuiltinVaListDecl();
10483
10484 return VaListTagDecl;
10485}
10486
10487TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10488 if (!BuiltinMSVaListDecl)
10489 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10490
10491 return BuiltinMSVaListDecl;
10492}
10493
10494TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10495 if (!BuiltinZOSVaListDecl)
10496 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10497
10498 return BuiltinZOSVaListDecl;
10499}
10500
10501bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10502 // Allow redecl custom type checking builtin for HLSL.
10503 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10504 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10505 return true;
10506 // Allow redecl custom type checking builtin for SPIR-V.
10507 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10508 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10509 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10510 return true;
10511 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10512}
10513
10514void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10515 assert(ObjCConstantStringType.isNull() &&
10516 "'NSConstantString' type already set!");
10517
10518 ObjCConstantStringType = getObjCInterfaceType(Decl);
10519}
10520
10521/// Retrieve the template name that corresponds to a non-empty
10522/// lookup.
10523TemplateName
10524ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10525 UnresolvedSetIterator End) const {
10526 unsigned size = End - Begin;
10527 assert(size > 1 && "set is not overloaded!");
10528
10529 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10530 size * sizeof(FunctionTemplateDecl*));
10531 auto *OT = new (memory) OverloadedTemplateStorage(size);
10532
10533 NamedDecl **Storage = OT->getStorage();
10534 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10535 NamedDecl *D = *I;
10536 assert(isa<FunctionTemplateDecl>(D) ||
10537 isa<UnresolvedUsingValueDecl>(D) ||
10538 (isa<UsingShadowDecl>(D) &&
10539 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10540 *Storage++ = D;
10541 }
10542
10543 return TemplateName(OT);
10544}
10545
10546/// Retrieve a template name representing an unqualified-id that has been
10547/// assumed to name a template for ADL purposes.
10548TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10549 auto *OT = new (*this) AssumedTemplateStorage(Name);
10550 return TemplateName(OT);
10551}
10552
10553/// Retrieve the template name that represents a qualified
10554/// template name such as \c std::vector.
10555TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10556 bool TemplateKeyword,
10557 TemplateName Template) const {
10558 assert(Template.getKind() == TemplateName::Template ||
10559 Template.getKind() == TemplateName::UsingTemplate);
10560
10561 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10562 assert(!Qualifier && "unexpected qualified template template parameter");
10563 assert(TemplateKeyword == false);
10564 return Template;
10565 }
10566
10567 // FIXME: Canonicalization?
10568 llvm::FoldingSetNodeID ID;
10569 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10570
10571 llvm::FoldingSetInsertToken Token;
10572 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10573 if (!QTN) {
10574 QTN = new (*this, alignof(QualifiedTemplateName))
10575 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10576 QualifiedTemplateNames.insert(N: QTN, Token);
10577 }
10578
10579 return TemplateName(QTN);
10580}
10581
10582/// Retrieve the template name that represents a dependent
10583/// template name such as \c MetaFun::template operator+.
10584TemplateName
10585ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10586 llvm::FoldingSetNodeID ID;
10587 S.Profile(ID);
10588
10589 llvm::FoldingSetInsertToken Token;
10590 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10591 return TemplateName(QTN);
10592
10593 DependentTemplateName *QTN =
10594 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10595 DependentTemplateNames.insert(N: QTN, Token);
10596 return TemplateName(QTN);
10597}
10598
10599TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10600 Decl *AssociatedDecl,
10601 unsigned Index,
10602 UnsignedOrNone PackIndex,
10603 bool Final) const {
10604 llvm::FoldingSetNodeID ID;
10605 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10606 Index, PackIndex, Final);
10607
10608 llvm::FoldingSetInsertToken Token;
10609 SubstTemplateTemplateParmStorage *subst =
10610 SubstTemplateTemplateParms.lookup(ID, Token);
10611
10612 if (!subst) {
10613 subst = new (*this) SubstTemplateTemplateParmStorage(
10614 Replacement, AssociatedDecl, Index, PackIndex, Final);
10615 SubstTemplateTemplateParms.insert(N: subst, Token);
10616 }
10617
10618 return TemplateName(subst);
10619}
10620
10621TemplateName
10622ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10623 Decl *AssociatedDecl,
10624 unsigned Index, bool Final) const {
10625 auto &Self = const_cast<ASTContext &>(*this);
10626 llvm::FoldingSetNodeID ID;
10627 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10628 AssociatedDecl, Index, Final);
10629
10630 llvm::FoldingSetInsertToken Token;
10631 SubstTemplateTemplateParmPackStorage *Subst =
10632 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10633
10634 if (!Subst) {
10635 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10636 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10637 SubstTemplateTemplateParmPacks.insert(N: Subst, Token);
10638 }
10639
10640 return TemplateName(Subst);
10641}
10642
10643/// Retrieve the template name that represents a template name
10644/// deduced from a specialization.
10645TemplateName
10646ASTContext::getDeducedTemplateName(TemplateName Underlying,
10647 DefaultArguments DefaultArgs) const {
10648 if (!DefaultArgs)
10649 return Underlying;
10650
10651 llvm::FoldingSetNodeID ID;
10652 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10653
10654 llvm::FoldingSetInsertToken Token;
10655 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10656 if (!DTS) {
10657 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10658 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10659 Align: alignof(DeducedTemplateStorage));
10660 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10661 DeducedTemplates.insert(N: DTS, Token);
10662 }
10663 return TemplateName(DTS);
10664}
10665
10666TemplateName ASTContext::getPackIndexingTemplateName(
10667 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10668 ArrayRef<TemplateName> Expansions) const {
10669 auto &Self = const_cast<ASTContext &>(*this);
10670 llvm::FoldingSetNodeID ID;
10671 PackIndexingTemplateStorage::Profile(ID, Context: Self, Pattern, IndexExpr,
10672 FullySubstituted, Expansions);
10673
10674 llvm::FoldingSetInsertToken Token;
10675 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10676 if (!PI) {
10677 void *Mem =
10678 Allocate(Size: PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10679 Counts: Expansions.size()),
10680 Align: alignof(PackIndexingTemplateStorage));
10681 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10682 FullySubstituted, Expansions);
10683 PackIndexingTemplates.insert(N: PI, Token);
10684 }
10685 return TemplateName(PI);
10686}
10687
10688/// getFromTargetType - Given one of the integer types provided by
10689/// TargetInfo, produce the corresponding type. The unsigned @p Type
10690/// is actually a value of type @c TargetInfo::IntType.
10691CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10692 switch (Type) {
10693 case TargetInfo::NoInt: return {};
10694 case TargetInfo::SignedChar: return SignedCharTy;
10695 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10696 case TargetInfo::SignedShort: return ShortTy;
10697 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10698 case TargetInfo::SignedInt: return IntTy;
10699 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10700 case TargetInfo::SignedLong: return LongTy;
10701 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10702 case TargetInfo::SignedLongLong: return LongLongTy;
10703 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10704 }
10705
10706 llvm_unreachable("Unhandled TargetInfo::IntType value");
10707}
10708
10709//===----------------------------------------------------------------------===//
10710// Type Predicates.
10711//===----------------------------------------------------------------------===//
10712
10713/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10714/// garbage collection attribute.
10715///
10716Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10717 if (getLangOpts().getGC() == LangOptions::NonGC)
10718 return Qualifiers::GCNone;
10719
10720 assert(getLangOpts().ObjC);
10721 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10722
10723 // Default behaviour under objective-C's gc is for ObjC pointers
10724 // (or pointers to them) be treated as though they were declared
10725 // as __strong.
10726 if (GCAttrs == Qualifiers::GCNone) {
10727 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10728 return Qualifiers::Strong;
10729 else if (Ty->isPointerType())
10730 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10731 } else {
10732 // It's not valid to set GC attributes on anything that isn't a
10733 // pointer.
10734#ifndef NDEBUG
10735 QualType CT = Ty->getCanonicalTypeInternal();
10736 while (const auto *AT = dyn_cast<ArrayType>(CT))
10737 CT = AT->getElementType();
10738 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10739#endif
10740 }
10741 return GCAttrs;
10742}
10743
10744//===----------------------------------------------------------------------===//
10745// Type Compatibility Testing
10746//===----------------------------------------------------------------------===//
10747
10748/// areCompatVectorTypes - Return true if the two specified vector types are
10749/// compatible.
10750static bool areCompatVectorTypes(const VectorType *LHS,
10751 const VectorType *RHS) {
10752 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10753 return LHS->getElementType() == RHS->getElementType() &&
10754 LHS->getNumElements() == RHS->getNumElements();
10755}
10756
10757/// areCompatMatrixTypes - Return true if the two specified matrix types are
10758/// compatible.
10759static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10760 const ConstantMatrixType *RHS) {
10761 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10762 return LHS->getElementType() == RHS->getElementType() &&
10763 LHS->getNumRows() == RHS->getNumRows() &&
10764 LHS->getNumColumns() == RHS->getNumColumns();
10765}
10766
10767bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10768 QualType SecondVec) {
10769 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10770 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10771
10772 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10773 return true;
10774
10775 // Treat Neon vector types and most AltiVec vector types as if they are the
10776 // equivalent GCC vector types.
10777 const auto *First = FirstVec->castAs<VectorType>();
10778 const auto *Second = SecondVec->castAs<VectorType>();
10779 if (First->getNumElements() == Second->getNumElements() &&
10780 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10781 First->getVectorKind() != VectorKind::AltiVecPixel &&
10782 First->getVectorKind() != VectorKind::AltiVecBool &&
10783 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10784 Second->getVectorKind() != VectorKind::AltiVecBool &&
10785 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10786 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10787 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10788 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10789 !isRVVFixedLengthVectorKind(VK: First->getVectorKind()) &&
10790 !isRVVFixedLengthVectorKind(VK: Second->getVectorKind()))
10791 return true;
10792
10793 // In OpenCL, treat half and _Float16 vector types as compatible.
10794 if (getLangOpts().OpenCL &&
10795 First->getNumElements() == Second->getNumElements()) {
10796 QualType FirstElt = First->getElementType();
10797 QualType SecondElt = Second->getElementType();
10798
10799 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10800 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10801 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10802 First->getVectorKind() != VectorKind::AltiVecBool &&
10803 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10804 Second->getVectorKind() != VectorKind::AltiVecBool)
10805 return true;
10806 }
10807 }
10808 return false;
10809}
10810
10811bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10812 QualType RHS) {
10813 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10814 return Result != OBTAssignResult::IncompatibleKinds;
10815}
10816
10817ASTContext::OBTAssignResult
10818ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10819 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10820 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10821
10822 if (!LHSOBT && !RHSOBT)
10823 return OBTAssignResult::Compatible;
10824
10825 if (LHSOBT && RHSOBT) {
10826 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10827 return OBTAssignResult::IncompatibleKinds;
10828 return OBTAssignResult::Compatible;
10829 }
10830
10831 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10832 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10833
10834 if (RHSOBT && !LHSOBT) {
10835 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10836 return OBTAssignResult::Discards;
10837 }
10838
10839 return OBTAssignResult::NotApplicable;
10840}
10841
10842/// getRVVTypeSize - Return RVV vector register size.
10843static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10844 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10845 auto VScale = Context.getTargetInfo().getVScaleRange(
10846 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10847 if (!VScale)
10848 return 0;
10849
10850 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10851
10852 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10853 if (Info.ElementType == Context.BoolTy)
10854 EltSize = 1;
10855
10856 uint64_t MinElts = Info.EC.getKnownMinValue();
10857 return VScale->first * MinElts * EltSize;
10858}
10859
10860bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10861 QualType SecondType) {
10862 assert(
10863 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10864 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10865 "Expected RVV builtin type and vector type!");
10866
10867 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10868 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10869 if (const auto *VT = SecondType->getAs<VectorType>()) {
10870 if (isRVVFixedLengthMaskVectorKind(VK: VT->getVectorKind())) {
10871 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10872 // A mask typedef converts to and from the vbool<R>_t type it was
10873 // written against: vbool<R>_t has RVVBitsPerBlock / R lanes at
10874 // vscale=1.
10875 return FirstType->isRVVVLSBuiltinType() &&
10876 Info.ElementType == BoolTy &&
10877 (llvm::RISCV::RVVBitsPerBlock >>
10878 getRVVFixedLengthMaskRatioLog2(VK: VT->getVectorKind())) ==
10879 Info.EC.getKnownMinValue() &&
10880 VT->getRVVFixedLengthMaskLanes() == getRVVTypeSize(Context&: *this, Ty: BT);
10881 }
10882 if (isRVVFixedLengthDataVectorKind(VK: VT->getVectorKind()) ||
10883 VT->getVectorKind() == VectorKind::Generic)
10884 return FirstType->isRVVVLSBuiltinType() &&
10885 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10886 hasSameType(T1: VT->getElementType(),
10887 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10888 }
10889 }
10890 return false;
10891 };
10892
10893 return IsValidCast(FirstType, SecondType) ||
10894 IsValidCast(SecondType, FirstType);
10895}
10896
10897bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10898 QualType SecondType) {
10899 assert(
10900 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10901 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10902 "Expected RVV builtin type and vector type!");
10903
10904 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10905 const auto *BT = FirstType->getAs<BuiltinType>();
10906 if (!BT)
10907 return false;
10908
10909 if (!BT->isRVVVLSBuiltinType())
10910 return false;
10911
10912 const auto *VecTy = SecondType->getAs<VectorType>();
10913 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10914 const LangOptions::LaxVectorConversionKind LVCKind =
10915 getLangOpts().getLaxVectorConversions();
10916
10917 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10918 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10919 return false;
10920
10921 // If -flax-vector-conversions=all is specified, the types are
10922 // certainly compatible.
10923 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10924 return true;
10925
10926 // If -flax-vector-conversions=integer is specified, the types are
10927 // compatible if the elements are integer types.
10928 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10929 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10930 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10931 }
10932
10933 return false;
10934 };
10935
10936 return IsLaxCompatible(FirstType, SecondType) ||
10937 IsLaxCompatible(SecondType, FirstType);
10938}
10939
10940bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10941 while (true) {
10942 // __strong id
10943 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10944 if (Attr->getAttrKind() == attr::ObjCOwnership)
10945 return true;
10946
10947 Ty = Attr->getModifiedType();
10948
10949 // X *__strong (...)
10950 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10951 Ty = Paren->getInnerType();
10952
10953 // We do not want to look through typedefs, typeof(expr),
10954 // typeof(type), or any other way that the type is somehow
10955 // abstracted.
10956 } else {
10957 return false;
10958 }
10959 }
10960}
10961
10962//===----------------------------------------------------------------------===//
10963// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10964//===----------------------------------------------------------------------===//
10965
10966/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10967/// inheritance hierarchy of 'rProto'.
10968bool
10969ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10970 ObjCProtocolDecl *rProto) const {
10971 if (declaresSameEntity(D1: lProto, D2: rProto))
10972 return true;
10973 for (auto *PI : rProto->protocols())
10974 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10975 return true;
10976 return false;
10977}
10978
10979/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10980/// Class<pr1, ...>.
10981bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10982 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10983 for (auto *lhsProto : lhs->quals()) {
10984 bool match = false;
10985 for (auto *rhsProto : rhs->quals()) {
10986 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
10987 match = true;
10988 break;
10989 }
10990 }
10991 if (!match)
10992 return false;
10993 }
10994 return true;
10995}
10996
10997/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10998/// ObjCQualifiedIDType.
10999bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
11000 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11001 bool compare) {
11002 // Allow id<P..> and an 'id' in all cases.
11003 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11004 return true;
11005
11006 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11007 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11008 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
11009 return false;
11010
11011 if (lhs->isObjCQualifiedIdType()) {
11012 if (rhs->qual_empty()) {
11013 // If the RHS is a unqualified interface pointer "NSString*",
11014 // make sure we check the class hierarchy.
11015 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11016 for (auto *I : lhs->quals()) {
11017 // when comparing an id<P> on lhs with a static type on rhs,
11018 // see if static class implements all of id's protocols, directly or
11019 // through its super class and categories.
11020 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
11021 return false;
11022 }
11023 }
11024 // If there are no qualifiers and no interface, we have an 'id'.
11025 return true;
11026 }
11027 // Both the right and left sides have qualifiers.
11028 for (auto *lhsProto : lhs->quals()) {
11029 bool match = false;
11030
11031 // when comparing an id<P> on lhs with a static type on rhs,
11032 // see if static class implements all of id's protocols, directly or
11033 // through its super class and categories.
11034 for (auto *rhsProto : rhs->quals()) {
11035 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11036 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11037 match = true;
11038 break;
11039 }
11040 }
11041 // If the RHS is a qualified interface pointer "NSString<P>*",
11042 // make sure we check the class hierarchy.
11043 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11044 for (auto *I : lhs->quals()) {
11045 // when comparing an id<P> on lhs with a static type on rhs,
11046 // see if static class implements all of id's protocols, directly or
11047 // through its super class and categories.
11048 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11049 match = true;
11050 break;
11051 }
11052 }
11053 }
11054 if (!match)
11055 return false;
11056 }
11057
11058 return true;
11059 }
11060
11061 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11062
11063 if (lhs->getInterfaceType()) {
11064 // If both the right and left sides have qualifiers.
11065 for (auto *lhsProto : lhs->quals()) {
11066 bool match = false;
11067
11068 // when comparing an id<P> on rhs with a static type on lhs,
11069 // see if static class implements all of id's protocols, directly or
11070 // through its super class and categories.
11071 // First, lhs protocols in the qualifier list must be found, direct
11072 // or indirect in rhs's qualifier list or it is a mismatch.
11073 for (auto *rhsProto : rhs->quals()) {
11074 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11075 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11076 match = true;
11077 break;
11078 }
11079 }
11080 if (!match)
11081 return false;
11082 }
11083
11084 // Static class's protocols, or its super class or category protocols
11085 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11086 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11087 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11088 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11089 // This is rather dubious but matches gcc's behavior. If lhs has
11090 // no type qualifier and its class has no static protocol(s)
11091 // assume that it is mismatch.
11092 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11093 return false;
11094 for (auto *lhsProto : LHSInheritedProtocols) {
11095 bool match = false;
11096 for (auto *rhsProto : rhs->quals()) {
11097 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11098 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11099 match = true;
11100 break;
11101 }
11102 }
11103 if (!match)
11104 return false;
11105 }
11106 }
11107 return true;
11108 }
11109 return false;
11110}
11111
11112/// canAssignObjCInterfaces - Return true if the two interface types are
11113/// compatible for assignment from RHS to LHS. This handles validation of any
11114/// protocol qualifiers on the LHS or RHS.
11115bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11116 const ObjCObjectPointerType *RHSOPT) {
11117 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11118 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11119
11120 // If either type represents the built-in 'id' type, return true.
11121 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11122 return true;
11123
11124 // Function object that propagates a successful result or handles
11125 // __kindof types.
11126 auto finish = [&](bool succeeded) -> bool {
11127 if (succeeded)
11128 return true;
11129
11130 if (!RHS->isKindOfType())
11131 return false;
11132
11133 // Strip off __kindof and protocol qualifiers, then check whether
11134 // we can assign the other way.
11135 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11136 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11137 };
11138
11139 // Casts from or to id<P> are allowed when the other side has compatible
11140 // protocols.
11141 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11142 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11143 }
11144
11145 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11146 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11147 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11148 }
11149
11150 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11151 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11152 return true;
11153 }
11154
11155 // If we have 2 user-defined types, fall into that path.
11156 if (LHS->getInterface() && RHS->getInterface()) {
11157 return finish(canAssignObjCInterfaces(LHS, RHS));
11158 }
11159
11160 return false;
11161}
11162
11163/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11164/// for providing type-safety for objective-c pointers used to pass/return
11165/// arguments in block literals. When passed as arguments, passing 'A*' where
11166/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11167/// not OK. For the return type, the opposite is not OK.
11168bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11169 const ObjCObjectPointerType *LHSOPT,
11170 const ObjCObjectPointerType *RHSOPT,
11171 bool BlockReturnType) {
11172
11173 // Function object that propagates a successful result or handles
11174 // __kindof types.
11175 auto finish = [&](bool succeeded) -> bool {
11176 if (succeeded)
11177 return true;
11178
11179 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11180 if (!Expected->isKindOfType())
11181 return false;
11182
11183 // Strip off __kindof and protocol qualifiers, then check whether
11184 // we can assign the other way.
11185 return canAssignObjCInterfacesInBlockPointer(
11186 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11187 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11188 BlockReturnType);
11189 };
11190
11191 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11192 return true;
11193
11194 if (LHSOPT->isObjCBuiltinType()) {
11195 return finish(RHSOPT->isObjCBuiltinType() ||
11196 RHSOPT->isObjCQualifiedIdType());
11197 }
11198
11199 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11200 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11201 // Use for block parameters previous type checking for compatibility.
11202 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11203 // Or corrected type checking as in non-compat mode.
11204 (!BlockReturnType &&
11205 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11206 else
11207 return finish(ObjCQualifiedIdTypesAreCompatible(
11208 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11209 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11210 }
11211
11212 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11213 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11214 if (LHS && RHS) { // We have 2 user-defined types.
11215 if (LHS != RHS) {
11216 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11217 return finish(BlockReturnType);
11218 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11219 return finish(!BlockReturnType);
11220 }
11221 else
11222 return true;
11223 }
11224 return false;
11225}
11226
11227/// Comparison routine for Objective-C protocols to be used with
11228/// llvm::array_pod_sort.
11229static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11230 ObjCProtocolDecl * const *rhs) {
11231 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11232}
11233
11234/// getIntersectionOfProtocols - This routine finds the intersection of set
11235/// of protocols inherited from two distinct objective-c pointer objects with
11236/// the given common base.
11237/// It is used to build composite qualifier list of the composite type of
11238/// the conditional expression involving two objective-c pointer objects.
11239static
11240void getIntersectionOfProtocols(ASTContext &Context,
11241 const ObjCInterfaceDecl *CommonBase,
11242 const ObjCObjectPointerType *LHSOPT,
11243 const ObjCObjectPointerType *RHSOPT,
11244 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11245
11246 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11247 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11248 assert(LHS->getInterface() && "LHS must have an interface base");
11249 assert(RHS->getInterface() && "RHS must have an interface base");
11250
11251 // Add all of the protocols for the LHS.
11252 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11253
11254 // Start with the protocol qualifiers.
11255 for (auto *proto : LHS->quals()) {
11256 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11257 }
11258
11259 // Also add the protocols associated with the LHS interface.
11260 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11261
11262 // Add all of the protocols for the RHS.
11263 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11264
11265 // Start with the protocol qualifiers.
11266 for (auto *proto : RHS->quals()) {
11267 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11268 }
11269
11270 // Also add the protocols associated with the RHS interface.
11271 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11272
11273 // Compute the intersection of the collected protocol sets.
11274 for (auto *proto : LHSProtocolSet) {
11275 if (RHSProtocolSet.count(Ptr: proto))
11276 IntersectionSet.push_back(Elt: proto);
11277 }
11278
11279 // Compute the set of protocols that is implied by either the common type or
11280 // the protocols within the intersection.
11281 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11282 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11283
11284 // Remove any implied protocols from the list of inherited protocols.
11285 if (!ImpliedProtocols.empty()) {
11286 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11287 return ImpliedProtocols.contains(Ptr: proto);
11288 });
11289 }
11290
11291 // Sort the remaining protocols by name.
11292 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11293 Compare: compareObjCProtocolsByName);
11294}
11295
11296/// Determine whether the first type is a subtype of the second.
11297static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11298 QualType rhs) {
11299 // Common case: two object pointers.
11300 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11301 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11302 if (lhsOPT && rhsOPT)
11303 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11304
11305 // Two block pointers.
11306 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11307 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11308 if (lhsBlock && rhsBlock)
11309 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11310
11311 // If either is an unqualified 'id' and the other is a block, it's
11312 // acceptable.
11313 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11314 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11315 return true;
11316
11317 return false;
11318}
11319
11320// Check that the given Objective-C type argument lists are equivalent.
11321static bool sameObjCTypeArgs(ASTContext &ctx,
11322 const ObjCInterfaceDecl *iface,
11323 ArrayRef<QualType> lhsArgs,
11324 ArrayRef<QualType> rhsArgs,
11325 bool stripKindOf) {
11326 if (lhsArgs.size() != rhsArgs.size())
11327 return false;
11328
11329 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11330 if (!typeParams)
11331 return false;
11332
11333 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11334 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11335 continue;
11336
11337 switch (typeParams->begin()[i]->getVariance()) {
11338 case ObjCTypeParamVariance::Invariant:
11339 if (!stripKindOf ||
11340 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11341 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11342 return false;
11343 }
11344 break;
11345
11346 case ObjCTypeParamVariance::Covariant:
11347 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11348 return false;
11349 break;
11350
11351 case ObjCTypeParamVariance::Contravariant:
11352 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11353 return false;
11354 break;
11355 }
11356 }
11357
11358 return true;
11359}
11360
11361QualType ASTContext::areCommonBaseCompatible(
11362 const ObjCObjectPointerType *Lptr,
11363 const ObjCObjectPointerType *Rptr) {
11364 const ObjCObjectType *LHS = Lptr->getObjectType();
11365 const ObjCObjectType *RHS = Rptr->getObjectType();
11366 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11367 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11368
11369 if (!LDecl || !RDecl)
11370 return {};
11371
11372 // When either LHS or RHS is a kindof type, we should return a kindof type.
11373 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11374 // kindof(A).
11375 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11376
11377 // Follow the left-hand side up the class hierarchy until we either hit a
11378 // root or find the RHS. Record the ancestors in case we don't find it.
11379 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11380 LHSAncestors;
11381 while (true) {
11382 // Record this ancestor. We'll need this if the common type isn't in the
11383 // path from the LHS to the root.
11384 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11385
11386 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11387 // Get the type arguments.
11388 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11389 bool anyChanges = false;
11390 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11391 // Both have type arguments, compare them.
11392 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11393 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11394 /*stripKindOf=*/true))
11395 return {};
11396 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11397 // If only one has type arguments, the result will not have type
11398 // arguments.
11399 LHSTypeArgs = {};
11400 anyChanges = true;
11401 }
11402
11403 // Compute the intersection of protocols.
11404 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11405 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11406 IntersectionSet&: Protocols);
11407 if (!Protocols.empty())
11408 anyChanges = true;
11409
11410 // If anything in the LHS will have changed, build a new result type.
11411 // If we need to return a kindof type but LHS is not a kindof type, we
11412 // build a new result type.
11413 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11414 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11415 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11416 isKindOf: anyKindOf || LHS->isKindOfType());
11417 return getObjCObjectPointerType(ObjectT: Result);
11418 }
11419
11420 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11421 }
11422
11423 // Find the superclass.
11424 QualType LHSSuperType = LHS->getSuperClassType();
11425 if (LHSSuperType.isNull())
11426 break;
11427
11428 LHS = LHSSuperType->castAs<ObjCObjectType>();
11429 }
11430
11431 // We didn't find anything by following the LHS to its root; now check
11432 // the RHS against the cached set of ancestors.
11433 while (true) {
11434 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11435 if (KnownLHS != LHSAncestors.end()) {
11436 LHS = KnownLHS->second;
11437
11438 // Get the type arguments.
11439 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11440 bool anyChanges = false;
11441 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11442 // Both have type arguments, compare them.
11443 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11444 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11445 /*stripKindOf=*/true))
11446 return {};
11447 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11448 // If only one has type arguments, the result will not have type
11449 // arguments.
11450 RHSTypeArgs = {};
11451 anyChanges = true;
11452 }
11453
11454 // Compute the intersection of protocols.
11455 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11456 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11457 IntersectionSet&: Protocols);
11458 if (!Protocols.empty())
11459 anyChanges = true;
11460
11461 // If we need to return a kindof type but RHS is not a kindof type, we
11462 // build a new result type.
11463 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11464 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11465 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11466 isKindOf: anyKindOf || RHS->isKindOfType());
11467 return getObjCObjectPointerType(ObjectT: Result);
11468 }
11469
11470 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11471 }
11472
11473 // Find the superclass of the RHS.
11474 QualType RHSSuperType = RHS->getSuperClassType();
11475 if (RHSSuperType.isNull())
11476 break;
11477
11478 RHS = RHSSuperType->castAs<ObjCObjectType>();
11479 }
11480
11481 return {};
11482}
11483
11484bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11485 const ObjCObjectType *RHS) {
11486 assert(LHS->getInterface() && "LHS is not an interface type");
11487 assert(RHS->getInterface() && "RHS is not an interface type");
11488
11489 // Verify that the base decls are compatible: the RHS must be a subclass of
11490 // the LHS.
11491 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11492 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11493 if (!IsSuperClass)
11494 return false;
11495
11496 // If the LHS has protocol qualifiers, determine whether all of them are
11497 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11498 // LHS).
11499 if (LHS->getNumProtocols() > 0) {
11500 // OK if conversion of LHS to SuperClass results in narrowing of types
11501 // ; i.e., SuperClass may implement at least one of the protocols
11502 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11503 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11504 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11505 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11506 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11507 // qualifiers.
11508 for (auto *RHSPI : RHS->quals())
11509 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11510 // If there is no protocols associated with RHS, it is not a match.
11511 if (SuperClassInheritedProtocols.empty())
11512 return false;
11513
11514 for (const auto *LHSProto : LHS->quals()) {
11515 bool SuperImplementsProtocol = false;
11516 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11517 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11518 SuperImplementsProtocol = true;
11519 break;
11520 }
11521 if (!SuperImplementsProtocol)
11522 return false;
11523 }
11524 }
11525
11526 // If the LHS is specialized, we may need to check type arguments.
11527 if (LHS->isSpecialized()) {
11528 // Follow the superclass chain until we've matched the LHS class in the
11529 // hierarchy. This substitutes type arguments through.
11530 const ObjCObjectType *RHSSuper = RHS;
11531 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11532 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11533
11534 // If the RHS is specializd, compare type arguments.
11535 if (RHSSuper->isSpecialized() &&
11536 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11537 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11538 /*stripKindOf=*/true)) {
11539 return false;
11540 }
11541 }
11542
11543 return true;
11544}
11545
11546bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11547 // get the "pointed to" types
11548 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11549 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11550
11551 if (!LHSOPT || !RHSOPT)
11552 return false;
11553
11554 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11555 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11556}
11557
11558bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11559 return canAssignObjCInterfaces(
11560 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11561 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11562}
11563
11564/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11565/// both shall have the identically qualified version of a compatible type.
11566/// C99 6.2.7p1: Two types have compatible types if their types are the
11567/// same. See 6.7.[2,3,5] for additional rules.
11568bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11569 bool CompareUnqualified) {
11570 if (getLangOpts().CPlusPlus)
11571 return hasSameType(T1: LHS, T2: RHS);
11572
11573 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11574}
11575
11576bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11577 return typesAreCompatible(LHS, RHS);
11578}
11579
11580bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11581 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11582}
11583
11584/// mergeTransparentUnionType - if T is a transparent union type and a member
11585/// of T is compatible with SubType, return the merged type, else return
11586/// QualType()
11587QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11588 bool OfBlockPointer,
11589 bool Unqualified) {
11590 if (const RecordType *UT = T->getAsUnionType()) {
11591 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11592 if (UD->hasAttr<TransparentUnionAttr>()) {
11593 for (const auto *I : UD->fields()) {
11594 QualType ET = I->getType().getUnqualifiedType();
11595 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11596 if (!MT.isNull())
11597 return MT;
11598 }
11599 }
11600 }
11601
11602 return {};
11603}
11604
11605/// mergeFunctionParameterTypes - merge two types which appear as function
11606/// parameter types
11607QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11608 bool OfBlockPointer,
11609 bool Unqualified) {
11610 // GNU extension: two types are compatible if they appear as a function
11611 // argument, one of the types is a transparent union type and the other
11612 // type is compatible with a union member
11613 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11614 Unqualified);
11615 if (!lmerge.isNull())
11616 return lmerge;
11617
11618 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11619 Unqualified);
11620 if (!rmerge.isNull())
11621 return rmerge;
11622
11623 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11624}
11625
11626QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11627 bool OfBlockPointer, bool Unqualified,
11628 bool AllowCXX,
11629 bool IsConditionalOperator) {
11630 const auto *lbase = lhs->castAs<FunctionType>();
11631 const auto *rbase = rhs->castAs<FunctionType>();
11632 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11633 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11634 bool allLTypes = true;
11635 bool allRTypes = true;
11636
11637 // Check return type
11638 QualType retType;
11639 if (OfBlockPointer) {
11640 QualType RHS = rbase->getReturnType();
11641 QualType LHS = lbase->getReturnType();
11642 bool UnqualifiedResult = Unqualified;
11643 if (!UnqualifiedResult)
11644 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11645 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11646 }
11647 else
11648 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11649 Unqualified);
11650 if (retType.isNull())
11651 return {};
11652
11653 if (Unqualified)
11654 retType = retType.getUnqualifiedType();
11655
11656 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11657 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11658 if (Unqualified) {
11659 LRetType = LRetType.getUnqualifiedType();
11660 RRetType = RRetType.getUnqualifiedType();
11661 }
11662
11663 if (getCanonicalType(T: retType) != LRetType)
11664 allLTypes = false;
11665 if (getCanonicalType(T: retType) != RRetType)
11666 allRTypes = false;
11667
11668 // FIXME: double check this
11669 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11670 // rbase->getRegParmAttr() != 0 &&
11671 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11672 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11673 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11674
11675 // Compatible functions must have compatible calling conventions
11676 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11677 return {};
11678
11679 // Regparm is part of the calling convention.
11680 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11681 return {};
11682 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11683 return {};
11684
11685 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11686 return {};
11687 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11688 return {};
11689 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11690 return {};
11691
11692 // When merging declarations, it's common for supplemental information like
11693 // attributes to only be present in one of the declarations, and we generally
11694 // want type merging to preserve the union of information. So a merged
11695 // function type should be noreturn if it was noreturn in *either* operand
11696 // type.
11697 //
11698 // But for the conditional operator, this is backwards. The result of the
11699 // operator could be either operand, and its type should conservatively
11700 // reflect that. So a function type in a composite type is noreturn only
11701 // if it's noreturn in *both* operand types.
11702 //
11703 // Arguably, noreturn is a kind of subtype, and the conditional operator
11704 // ought to produce the most specific common supertype of its operand types.
11705 // That would differ from this rule in contravariant positions. However,
11706 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11707 // as a practical matter, it would only affect C code that does abstraction of
11708 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11709 // say the least. So we use the simpler rule.
11710 bool NoReturn = IsConditionalOperator
11711 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11712 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11713 if (lbaseInfo.getNoReturn() != NoReturn)
11714 allLTypes = false;
11715 if (rbaseInfo.getNoReturn() != NoReturn)
11716 allRTypes = false;
11717
11718 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11719
11720 std::optional<FunctionEffectSet> MergedFX;
11721
11722 if (lproto && rproto) { // two C99 style function prototypes
11723 assert((AllowCXX ||
11724 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11725 "C++ shouldn't be here");
11726 // Compatible functions must have the same number of parameters
11727 if (lproto->getNumParams() != rproto->getNumParams())
11728 return {};
11729
11730 // Variadic and non-variadic functions aren't compatible
11731 if (lproto->isVariadic() != rproto->isVariadic())
11732 return {};
11733
11734 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11735 return {};
11736
11737 // Function protos with different 'cfi_salt' values aren't compatible.
11738 if (lproto->getExtraAttributeInfo().CFISalt !=
11739 rproto->getExtraAttributeInfo().CFISalt)
11740 return {};
11741
11742 // Function effects are handled similarly to noreturn, see above.
11743 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11744 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11745 if (LHSFX != RHSFX) {
11746 if (IsConditionalOperator)
11747 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11748 else {
11749 FunctionEffectSet::Conflicts Errs;
11750 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11751 // Here we're discarding a possible error due to conflicts in the effect
11752 // sets. But we're not in a context where we can report it. The
11753 // operation does however guarantee maintenance of invariants.
11754 }
11755 if (*MergedFX != LHSFX)
11756 allLTypes = false;
11757 if (*MergedFX != RHSFX)
11758 allRTypes = false;
11759 }
11760
11761 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11762 bool canUseLeft, canUseRight;
11763 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11764 NewParamInfos&: newParamInfos))
11765 return {};
11766
11767 if (!canUseLeft)
11768 allLTypes = false;
11769 if (!canUseRight)
11770 allRTypes = false;
11771
11772 // Check parameter type compatibility
11773 SmallVector<QualType, 10> types;
11774 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11775 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11776 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11777 QualType paramType = mergeFunctionParameterTypes(
11778 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11779 if (paramType.isNull())
11780 return {};
11781
11782 if (Unqualified)
11783 paramType = paramType.getUnqualifiedType();
11784
11785 types.push_back(Elt: paramType);
11786 if (Unqualified) {
11787 lParamType = lParamType.getUnqualifiedType();
11788 rParamType = rParamType.getUnqualifiedType();
11789 }
11790
11791 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11792 allLTypes = false;
11793 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11794 allRTypes = false;
11795 }
11796
11797 if (allLTypes) return lhs;
11798 if (allRTypes) return rhs;
11799
11800 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11801 EPI.ExtInfo = einfo;
11802 EPI.ExtParameterInfos =
11803 newParamInfos.empty() ? nullptr : newParamInfos.data();
11804 if (MergedFX)
11805 EPI.FunctionEffects = *MergedFX;
11806 return getFunctionType(ResultTy: retType, Args: types, EPI);
11807 }
11808
11809 if (lproto) allRTypes = false;
11810 if (rproto) allLTypes = false;
11811
11812 const FunctionProtoType *proto = lproto ? lproto : rproto;
11813 if (proto) {
11814 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11815 if (proto->isVariadic())
11816 return {};
11817 // Check that the types are compatible with the types that
11818 // would result from default argument promotions (C99 6.7.5.3p15).
11819 // The only types actually affected are promotable integer
11820 // types and floats, which would be passed as a different
11821 // type depending on whether the prototype is visible.
11822 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11823 QualType paramTy = proto->getParamType(i);
11824
11825 // Look at the converted type of enum types, since that is the type used
11826 // to pass enum values.
11827 if (const auto *ED = paramTy->getAsEnumDecl()) {
11828 paramTy = ED->getIntegerType();
11829 if (paramTy.isNull())
11830 return {};
11831 }
11832
11833 if (isPromotableIntegerType(T: paramTy) ||
11834 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11835 return {};
11836 }
11837
11838 if (allLTypes) return lhs;
11839 if (allRTypes) return rhs;
11840
11841 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11842 EPI.ExtInfo = einfo;
11843 if (MergedFX)
11844 EPI.FunctionEffects = *MergedFX;
11845 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11846 }
11847
11848 if (allLTypes) return lhs;
11849 if (allRTypes) return rhs;
11850 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11851}
11852
11853/// Given that we have an enum type and a non-enum type, try to merge them.
11854static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11855 QualType other, bool isBlockReturnType) {
11856 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11857 // a signed integer type, or an unsigned integer type.
11858 // Compatibility is based on the underlying type, not the promotion
11859 // type.
11860 QualType underlyingType =
11861 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11862 if (underlyingType.isNull())
11863 return {};
11864 if (Context.hasSameType(T1: underlyingType, T2: other))
11865 return other;
11866
11867 // In block return types, we're more permissive and accept any
11868 // integral type of the same size.
11869 if (isBlockReturnType && other->isIntegerType() &&
11870 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11871 return other;
11872
11873 return {};
11874}
11875
11876QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11877 // C17 and earlier and C++ disallow two tag definitions within the same TU
11878 // from being compatible.
11879 if (LangOpts.CPlusPlus || !LangOpts.C23)
11880 return {};
11881
11882 // Nameless tags are comparable only within outer definitions. At the top
11883 // level they are not comparable.
11884 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11885 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11886 return {};
11887
11888 // C23, on the other hand, requires the members to be "the same enough", so
11889 // we use a structural equivalence check.
11890 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11891 StructuralEquivalenceContext Ctx(
11892 getLangOpts(), *this, *this, NonEquivalentDecls,
11893 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11894 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11895 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11896}
11897
11898std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11899 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11900 bool BlockReturnType, bool IsConditionalOperator) {
11901 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11902 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11903
11904 if (!LHSOBT && !RHSOBT)
11905 return std::nullopt;
11906
11907 if (LHSOBT) {
11908 if (RHSOBT) {
11909 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11910 return QualType();
11911
11912 QualType MergedUnderlying = mergeTypes(
11913 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11914 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11915
11916 if (MergedUnderlying.isNull())
11917 return QualType();
11918
11919 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11920 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11921 return getCommonSugaredType(X: LHS, Y: RHS);
11922 return getOverflowBehaviorType(
11923 Kind: LHSOBT->getBehaviorKind(),
11924 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11925 }
11926
11927 // For different underlying types that successfully merge, wrap the
11928 // merged underlying type with the common overflow behavior
11929 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11930 Underlying: MergedUnderlying);
11931 }
11932 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11933 Unqualified, BlockReturnType, IsConditionalOperator);
11934 }
11935
11936 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11937 Unqualified, BlockReturnType, IsConditionalOperator);
11938}
11939
11940QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11941 bool Unqualified, bool BlockReturnType,
11942 bool IsConditionalOperator) {
11943 // For C++ we will not reach this code with reference types (see below),
11944 // for OpenMP variant call overloading we might.
11945 //
11946 // C++ [expr]: If an expression initially has the type "reference to T", the
11947 // type is adjusted to "T" prior to any further analysis, the expression
11948 // designates the object or function denoted by the reference, and the
11949 // expression is an lvalue unless the reference is an rvalue reference and
11950 // the expression is a function call (possibly inside parentheses).
11951 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11952 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11953 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11954 LHS->getTypeClass() == RHS->getTypeClass())
11955 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11956 OfBlockPointer, Unqualified, BlockReturnType);
11957 if (LHSRefTy || RHSRefTy)
11958 return {};
11959
11960 if (std::optional<QualType> MergedOBT =
11961 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11962 BlockReturnType, IsConditionalOperator))
11963 return *MergedOBT;
11964
11965 if (Unqualified) {
11966 LHS = LHS.getUnqualifiedType();
11967 RHS = RHS.getUnqualifiedType();
11968 }
11969
11970 QualType LHSCan = getCanonicalType(T: LHS),
11971 RHSCan = getCanonicalType(T: RHS);
11972
11973 // If two types are identical, they are compatible.
11974 if (LHSCan == RHSCan)
11975 return LHS;
11976
11977 // If the qualifiers are different, the types aren't compatible... mostly.
11978 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11979 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11980 if (LQuals != RQuals) {
11981 // If any of these qualifiers are different, we have a type
11982 // mismatch.
11983 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11984 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11985 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11986 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
11987 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11988 return {};
11989
11990 // Exactly one GC qualifier difference is allowed: __strong is
11991 // okay if the other type has no GC qualifier but is an Objective
11992 // C object pointer (i.e. implicitly strong by default). We fix
11993 // this by pretending that the unqualified type was actually
11994 // qualified __strong.
11995 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11996 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11997 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11998
11999 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12000 return {};
12001
12002 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12003 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
12004 }
12005 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12006 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
12007 }
12008 return {};
12009 }
12010
12011 // Okay, qualifiers are equal.
12012
12013 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12014 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12015
12016 // We want to consider the two function types to be the same for these
12017 // comparisons, just force one to the other.
12018 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12019 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12020
12021 // Same as above for arrays
12022 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12023 LHSClass = Type::ConstantArray;
12024 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12025 RHSClass = Type::ConstantArray;
12026
12027 // ObjCInterfaces are just specialized ObjCObjects.
12028 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12029 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12030
12031 // Canonicalize ExtVector -> Vector.
12032 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12033 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12034
12035 // If the canonical type classes don't match.
12036 if (LHSClass != RHSClass) {
12037 // Note that we only have special rules for turning block enum
12038 // returns into block int returns, not vice-versa.
12039 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12040 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12041 }
12042 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12043 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12044 }
12045 // allow block pointer type to match an 'id' type.
12046 if (OfBlockPointer && !BlockReturnType) {
12047 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12048 return LHS;
12049 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12050 return RHS;
12051 }
12052 // Allow __auto_type to match anything; it merges to the type with more
12053 // information.
12054 if (const auto *AT = LHS->getAs<AutoType>()) {
12055 if (!AT->isDeduced() && AT->isGNUAutoType())
12056 return RHS;
12057 }
12058 if (const auto *AT = RHS->getAs<AutoType>()) {
12059 if (!AT->isDeduced() && AT->isGNUAutoType())
12060 return LHS;
12061 }
12062 return {};
12063 }
12064
12065 // The canonical type classes match.
12066 switch (LHSClass) {
12067#define TYPE(Class, Base)
12068#define ABSTRACT_TYPE(Class, Base)
12069#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12070#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12071#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12072#include "clang/AST/TypeNodes.inc"
12073 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12074
12075 case Type::Auto:
12076 case Type::DeducedTemplateSpecialization:
12077 case Type::LValueReference:
12078 case Type::RValueReference:
12079 case Type::MemberPointer:
12080 llvm_unreachable("C++ should never be in mergeTypes");
12081
12082 case Type::ObjCInterface:
12083 case Type::IncompleteArray:
12084 case Type::VariableArray:
12085 case Type::FunctionProto:
12086 case Type::ExtVector:
12087 case Type::OverflowBehavior:
12088 llvm_unreachable("Types are eliminated above");
12089
12090 case Type::Pointer:
12091 {
12092 // Merge two pointer types, while trying to preserve typedef info
12093 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12094 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12095 if (Unqualified) {
12096 LHSPointee = LHSPointee.getUnqualifiedType();
12097 RHSPointee = RHSPointee.getUnqualifiedType();
12098 }
12099 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12100 Unqualified);
12101 if (ResultType.isNull())
12102 return {};
12103 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12104 return LHS;
12105 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12106 return RHS;
12107 return getPointerType(T: ResultType);
12108 }
12109 case Type::BlockPointer:
12110 {
12111 // Merge two block pointer types, while trying to preserve typedef info
12112 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12113 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12114 if (Unqualified) {
12115 LHSPointee = LHSPointee.getUnqualifiedType();
12116 RHSPointee = RHSPointee.getUnqualifiedType();
12117 }
12118 if (getLangOpts().OpenCL) {
12119 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12120 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12121 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12122 // 6.12.5) thus the following check is asymmetric.
12123 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12124 return {};
12125 LHSPteeQual.removeAddressSpace();
12126 RHSPteeQual.removeAddressSpace();
12127 LHSPointee =
12128 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12129 RHSPointee =
12130 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12131 }
12132 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12133 Unqualified);
12134 if (ResultType.isNull())
12135 return {};
12136 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12137 return LHS;
12138 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12139 return RHS;
12140 return getBlockPointerType(T: ResultType);
12141 }
12142 case Type::Atomic:
12143 {
12144 // Merge two pointer types, while trying to preserve typedef info
12145 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12146 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12147 if (Unqualified) {
12148 LHSValue = LHSValue.getUnqualifiedType();
12149 RHSValue = RHSValue.getUnqualifiedType();
12150 }
12151 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12152 Unqualified);
12153 if (ResultType.isNull())
12154 return {};
12155 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12156 return LHS;
12157 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12158 return RHS;
12159 return getAtomicType(T: ResultType);
12160 }
12161 case Type::ConstantArray:
12162 {
12163 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12164 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12165 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12166 return {};
12167
12168 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12169 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12170 if (Unqualified) {
12171 LHSElem = LHSElem.getUnqualifiedType();
12172 RHSElem = RHSElem.getUnqualifiedType();
12173 }
12174
12175 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12176 if (ResultType.isNull())
12177 return {};
12178
12179 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12180 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12181
12182 // If either side is a variable array, and both are complete, check whether
12183 // the current dimension is definite.
12184 if (LVAT || RVAT) {
12185 auto SizeFetch = [this](const VariableArrayType* VAT,
12186 const ConstantArrayType* CAT)
12187 -> std::pair<bool,llvm::APInt> {
12188 if (VAT) {
12189 std::optional<llvm::APSInt> TheInt;
12190 Expr *E = VAT->getSizeExpr();
12191 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12192 return std::make_pair(x: true, y&: *TheInt);
12193 return std::make_pair(x: false, y: llvm::APSInt());
12194 }
12195 if (CAT)
12196 return std::make_pair(x: true, y: CAT->getSize());
12197 return std::make_pair(x: false, y: llvm::APInt());
12198 };
12199
12200 bool HaveLSize, HaveRSize;
12201 llvm::APInt LSize, RSize;
12202 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12203 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12204 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12205 return {}; // Definite, but unequal, array dimension
12206 }
12207
12208 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12209 return LHS;
12210 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12211 return RHS;
12212 if (LCAT)
12213 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12214 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12215 if (RCAT)
12216 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12217 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12218 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12219 return LHS;
12220 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12221 return RHS;
12222 if (LVAT) {
12223 // FIXME: This isn't correct! But tricky to implement because
12224 // the array's size has to be the size of LHS, but the type
12225 // has to be different.
12226 return LHS;
12227 }
12228 if (RVAT) {
12229 // FIXME: This isn't correct! But tricky to implement because
12230 // the array's size has to be the size of RHS, but the type
12231 // has to be different.
12232 return RHS;
12233 }
12234 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12235 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12236 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12237 }
12238 case Type::FunctionNoProto:
12239 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12240 /*AllowCXX=*/false, IsConditionalOperator);
12241 case Type::Record:
12242 case Type::Enum:
12243 return mergeTagDefinitions(LHS, RHS);
12244 case Type::Builtin:
12245 // Only exactly equal builtin types are compatible, which is tested above.
12246 return {};
12247 case Type::Complex:
12248 // Distinct complex types are incompatible.
12249 return {};
12250 case Type::Vector:
12251 // FIXME: The merged type should be an ExtVector!
12252 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12253 RHS: RHSCan->castAs<VectorType>()))
12254 return LHS;
12255 return {};
12256 case Type::ConstantMatrix:
12257 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12258 RHS: RHSCan->castAs<ConstantMatrixType>()))
12259 return LHS;
12260 return {};
12261 case Type::ObjCObject: {
12262 // Check if the types are assignment compatible.
12263 // FIXME: This should be type compatibility, e.g. whether
12264 // "LHS x; RHS x;" at global scope is legal.
12265 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12266 RHS: RHS->castAs<ObjCObjectType>()))
12267 return LHS;
12268 return {};
12269 }
12270 case Type::ObjCObjectPointer:
12271 if (OfBlockPointer) {
12272 if (canAssignObjCInterfacesInBlockPointer(
12273 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12274 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12275 return LHS;
12276 return {};
12277 }
12278 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12279 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12280 return LHS;
12281 return {};
12282 case Type::Pipe:
12283 assert(LHS != RHS &&
12284 "Equivalent pipe types should have already been handled!");
12285 return {};
12286 case Type::ArrayParameter:
12287 assert(LHS != RHS &&
12288 "Equivalent ArrayParameter types should have already been handled!");
12289 return {};
12290 case Type::BitInt: {
12291 // Merge two bit-precise int types, while trying to preserve typedef info.
12292 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12293 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12294 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12295 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12296
12297 // Like unsigned/int, shouldn't have a type if they don't match.
12298 if (LHSUnsigned != RHSUnsigned)
12299 return {};
12300
12301 if (LHSBits != RHSBits)
12302 return {};
12303 return LHS;
12304 }
12305 case Type::HLSLAttributedResource: {
12306 const HLSLAttributedResourceType *LHSTy =
12307 LHS->castAs<HLSLAttributedResourceType>();
12308 const HLSLAttributedResourceType *RHSTy =
12309 RHS->castAs<HLSLAttributedResourceType>();
12310 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12311 LHSTy->getWrappedType()->isHLSLResourceType() &&
12312 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12313
12314 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12315 LHSTy->getContainedType() == RHSTy->getContainedType())
12316 return LHS;
12317 return {};
12318 }
12319 case Type::HLSLInlineSpirv:
12320 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12321 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12322
12323 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12324 LHSTy->getSize() == RHSTy->getSize() &&
12325 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12326 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12327 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12328 return {};
12329
12330 return LHS;
12331 }
12332 return {};
12333 }
12334
12335 llvm_unreachable("Invalid Type::Class!");
12336}
12337
12338bool ASTContext::mergeExtParameterInfo(
12339 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12340 bool &CanUseFirst, bool &CanUseSecond,
12341 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12342 assert(NewParamInfos.empty() && "param info list not empty");
12343 CanUseFirst = CanUseSecond = true;
12344 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12345 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12346
12347 // Fast path: if the first type doesn't have ext parameter infos,
12348 // we match if and only if the second type also doesn't have them.
12349 if (!FirstHasInfo && !SecondHasInfo)
12350 return true;
12351
12352 bool NeedParamInfo = false;
12353 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12354 : SecondFnType->getExtParameterInfos().size();
12355
12356 for (size_t I = 0; I < E; ++I) {
12357 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12358 if (FirstHasInfo)
12359 FirstParam = FirstFnType->getExtParameterInfo(I);
12360 if (SecondHasInfo)
12361 SecondParam = SecondFnType->getExtParameterInfo(I);
12362
12363 // Cannot merge unless everything except the noescape flag matches.
12364 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12365 return false;
12366
12367 bool FirstNoEscape = FirstParam.isNoEscape();
12368 bool SecondNoEscape = SecondParam.isNoEscape();
12369 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12370 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12371 if (NewParamInfos.back().getOpaqueValue())
12372 NeedParamInfo = true;
12373 if (FirstNoEscape != IsNoEscape)
12374 CanUseFirst = false;
12375 if (SecondNoEscape != IsNoEscape)
12376 CanUseSecond = false;
12377 }
12378
12379 if (!NeedParamInfo)
12380 NewParamInfos.clear();
12381
12382 return true;
12383}
12384
12385void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12386 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12387 It->second = nullptr;
12388 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12389 ResetObjCLayout(D: SubClass);
12390 }
12391}
12392
12393/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12394/// 'RHS' attributes and returns the merged version; including for function
12395/// return types.
12396QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12397 QualType LHSCan = getCanonicalType(T: LHS),
12398 RHSCan = getCanonicalType(T: RHS);
12399 // If two types are identical, they are compatible.
12400 if (LHSCan == RHSCan)
12401 return LHS;
12402 if (RHSCan->isFunctionType()) {
12403 if (!LHSCan->isFunctionType())
12404 return {};
12405 QualType OldReturnType =
12406 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12407 QualType NewReturnType =
12408 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12409 QualType ResReturnType =
12410 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12411 if (ResReturnType.isNull())
12412 return {};
12413 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12414 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12415 // In either case, use OldReturnType to build the new function type.
12416 const auto *F = LHS->castAs<FunctionType>();
12417 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12418 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12419 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12420 QualType ResultType =
12421 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12422 return ResultType;
12423 }
12424 }
12425 return {};
12426 }
12427
12428 // If the qualifiers are different, the types can still be merged.
12429 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12430 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12431
12432 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12433 // Reject immediately, if anything but the GC qualifiers is different.
12434 return {};
12435 }
12436
12437 if (LQuals != RQuals) {
12438 // Exactly one GC qualifier difference is allowed: __strong is
12439 // okay if the other type has no GC qualifier but is an Objective
12440 // C object pointer (i.e. implicitly strong by default). We fix
12441 // this by pretending that the unqualified type was actually
12442 // qualified __strong.
12443 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12444 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12445 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12446
12447 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12448 return {};
12449
12450 if (GC_L == Qualifiers::Strong)
12451 return LHS;
12452 if (GC_R == Qualifiers::Strong)
12453 return RHS;
12454 return {};
12455 }
12456
12457 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12458 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12459 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12460 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12461 if (ResQT == LHSBaseQT)
12462 return LHS;
12463 if (ResQT == RHSBaseQT)
12464 return RHS;
12465 }
12466 return {};
12467}
12468
12469//===----------------------------------------------------------------------===//
12470// Integer Predicates
12471//===----------------------------------------------------------------------===//
12472
12473unsigned ASTContext::getIntWidth(QualType T) const {
12474 if (const auto *ED = T->getAsEnumDecl())
12475 T = ED->getIntegerType();
12476 if (T->isBooleanType())
12477 return 1;
12478 if (const auto *EIT = T->getAs<BitIntType>())
12479 return EIT->getNumBits();
12480 // For builtin types, just use the standard type sizing method
12481 return (unsigned)getTypeSize(T);
12482}
12483
12484QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12485 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12486 T->isFixedPointType()) &&
12487 "Unexpected type");
12488
12489 // Turn <4 x signed int> -> <4 x unsigned int>
12490 if (const auto *VTy = T->getAs<VectorType>())
12491 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12492 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12493
12494 // For _BitInt, return an unsigned _BitInt with same width.
12495 if (const auto *EITy = T->getAs<BitIntType>())
12496 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12497
12498 // For the overflow behavior types, construct a new unsigned variant
12499 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12500 return getOverflowBehaviorType(
12501 Kind: OBT->getBehaviorKind(),
12502 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12503
12504 // For enums, get the underlying integer type of the enum, and let the general
12505 // integer type signchanging code handle it.
12506 if (const auto *ED = T->getAsEnumDecl())
12507 T = ED->getIntegerType();
12508
12509 switch (T->castAs<BuiltinType>()->getKind()) {
12510 case BuiltinType::Char_U:
12511 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12512 case BuiltinType::Char_S:
12513 case BuiltinType::SChar:
12514 case BuiltinType::Char8:
12515 return UnsignedCharTy;
12516 case BuiltinType::Short:
12517 return UnsignedShortTy;
12518 case BuiltinType::Int:
12519 return UnsignedIntTy;
12520 case BuiltinType::Long:
12521 return UnsignedLongTy;
12522 case BuiltinType::LongLong:
12523 return UnsignedLongLongTy;
12524 case BuiltinType::Int128:
12525 return UnsignedInt128Ty;
12526 // wchar_t is special. It is either signed or not, but when it's signed,
12527 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12528 // version of its underlying type instead.
12529 case BuiltinType::WChar_S:
12530 return getUnsignedWCharType();
12531
12532 case BuiltinType::ShortAccum:
12533 return UnsignedShortAccumTy;
12534 case BuiltinType::Accum:
12535 return UnsignedAccumTy;
12536 case BuiltinType::LongAccum:
12537 return UnsignedLongAccumTy;
12538 case BuiltinType::SatShortAccum:
12539 return SatUnsignedShortAccumTy;
12540 case BuiltinType::SatAccum:
12541 return SatUnsignedAccumTy;
12542 case BuiltinType::SatLongAccum:
12543 return SatUnsignedLongAccumTy;
12544 case BuiltinType::ShortFract:
12545 return UnsignedShortFractTy;
12546 case BuiltinType::Fract:
12547 return UnsignedFractTy;
12548 case BuiltinType::LongFract:
12549 return UnsignedLongFractTy;
12550 case BuiltinType::SatShortFract:
12551 return SatUnsignedShortFractTy;
12552 case BuiltinType::SatFract:
12553 return SatUnsignedFractTy;
12554 case BuiltinType::SatLongFract:
12555 return SatUnsignedLongFractTy;
12556 default:
12557 assert((T->hasUnsignedIntegerRepresentation() ||
12558 T->isUnsignedFixedPointType()) &&
12559 "Unexpected signed integer or fixed point type");
12560 return T;
12561 }
12562}
12563
12564QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12565 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12566 T->isFixedPointType()) &&
12567 "Unexpected type");
12568
12569 // Turn <4 x unsigned int> -> <4 x signed int>
12570 if (const auto *VTy = T->getAs<VectorType>())
12571 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12572 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12573
12574 // For _BitInt, return a signed _BitInt with same width.
12575 if (const auto *EITy = T->getAs<BitIntType>())
12576 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12577
12578 // For enums, get the underlying integer type of the enum, and let the general
12579 // integer type signchanging code handle it.
12580 if (const auto *ED = T->getAsEnumDecl())
12581 T = ED->getIntegerType();
12582
12583 switch (T->castAs<BuiltinType>()->getKind()) {
12584 case BuiltinType::Char_S:
12585 // Plain `char` is mapped to `signed char` even if it's already signed
12586 case BuiltinType::Char_U:
12587 case BuiltinType::UChar:
12588 case BuiltinType::Char8:
12589 return SignedCharTy;
12590 case BuiltinType::UShort:
12591 return ShortTy;
12592 case BuiltinType::UInt:
12593 return IntTy;
12594 case BuiltinType::ULong:
12595 return LongTy;
12596 case BuiltinType::ULongLong:
12597 return LongLongTy;
12598 case BuiltinType::UInt128:
12599 return Int128Ty;
12600 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12601 // there's no matching "signed wchar_t". Therefore we return the signed
12602 // version of its underlying type instead.
12603 case BuiltinType::WChar_U:
12604 return getSignedWCharType();
12605
12606 case BuiltinType::UShortAccum:
12607 return ShortAccumTy;
12608 case BuiltinType::UAccum:
12609 return AccumTy;
12610 case BuiltinType::ULongAccum:
12611 return LongAccumTy;
12612 case BuiltinType::SatUShortAccum:
12613 return SatShortAccumTy;
12614 case BuiltinType::SatUAccum:
12615 return SatAccumTy;
12616 case BuiltinType::SatULongAccum:
12617 return SatLongAccumTy;
12618 case BuiltinType::UShortFract:
12619 return ShortFractTy;
12620 case BuiltinType::UFract:
12621 return FractTy;
12622 case BuiltinType::ULongFract:
12623 return LongFractTy;
12624 case BuiltinType::SatUShortFract:
12625 return SatShortFractTy;
12626 case BuiltinType::SatUFract:
12627 return SatFractTy;
12628 case BuiltinType::SatULongFract:
12629 return SatLongFractTy;
12630 default:
12631 assert(
12632 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12633 "Unexpected signed integer or fixed point type");
12634 return T;
12635 }
12636}
12637
12638ASTMutationListener::~ASTMutationListener() = default;
12639
12640void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12641 QualType ReturnType) {}
12642
12643//===----------------------------------------------------------------------===//
12644// Builtin Type Computation
12645//===----------------------------------------------------------------------===//
12646
12647/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12648/// pointer over the consumed characters. This returns the resultant type. If
12649/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12650/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12651/// a vector of "i*".
12652///
12653/// RequiresICE is filled in on return to indicate whether the value is required
12654/// to be an Integer Constant Expression.
12655static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12656 ASTContext::GetBuiltinTypeError &Error,
12657 bool &RequiresICE,
12658 bool AllowTypeModifiers) {
12659 // Modifiers.
12660 int HowLong = 0;
12661 bool Signed = false, Unsigned = false;
12662 bool IsChar = false, IsShort = false;
12663 bool IsLeast = false;
12664 RequiresICE = false;
12665
12666 // Read the prefixed modifiers first.
12667 bool Done = false;
12668 #ifndef NDEBUG
12669 bool IsSpecial = false;
12670 #endif
12671 while (!Done) {
12672 switch (*Str++) {
12673 default: Done = true; --Str; break;
12674 case 'I':
12675 RequiresICE = true;
12676 break;
12677 case 'S':
12678 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12679 assert(!Signed && "Can't use 'S' modifier multiple times!");
12680 Signed = true;
12681 break;
12682 case 'U':
12683 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12684 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12685 Unsigned = true;
12686 break;
12687 case 'l':
12688 // This modifier represents the least-width type (e.g. uint_least8_t).
12689 assert(!IsLeast && "Can't use 'l' modifier multiple times!");
12690 IsLeast = true;
12691 break;
12692 case 'B':
12693 // This modifier represents int8 type (byte-width).
12694 assert(!IsSpecial &&
12695 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12696 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12697#ifndef NDEBUG
12698 IsSpecial = true;
12699#endif
12700 IsChar = true;
12701 break;
12702 case 'T':
12703 // This modifier represents int16 type (short-width).
12704 assert(!IsSpecial &&
12705 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12706 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12707#ifndef NDEBUG
12708 IsSpecial = true;
12709#endif
12710 IsShort = true;
12711 break;
12712 case 'L':
12713 assert(!IsSpecial &&
12714 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12715 assert(HowLong <= 2 && "Can't have LLLL modifier");
12716 ++HowLong;
12717 break;
12718 case 'N':
12719 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12720 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12721 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12722 #ifndef NDEBUG
12723 IsSpecial = true;
12724 #endif
12725 if (Context.getTargetInfo().getLongWidth() == 32)
12726 ++HowLong;
12727 break;
12728 case 'W':
12729 // This modifier represents int64 type.
12730 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12731 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12732 #ifndef NDEBUG
12733 IsSpecial = true;
12734 #endif
12735 switch (Context.getTargetInfo().getInt64Type()) {
12736 default:
12737 llvm_unreachable("Unexpected integer type");
12738 case TargetInfo::SignedLong:
12739 HowLong = 1;
12740 break;
12741 case TargetInfo::SignedLongLong:
12742 HowLong = 2;
12743 break;
12744 }
12745 break;
12746 case 'Z':
12747 // This modifier represents int32 type.
12748 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12749 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12750 #ifndef NDEBUG
12751 IsSpecial = true;
12752 #endif
12753 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12754 default:
12755 llvm_unreachable("Unexpected integer type");
12756 case TargetInfo::SignedInt:
12757 HowLong = 0;
12758 break;
12759 case TargetInfo::SignedLong:
12760 HowLong = 1;
12761 break;
12762 case TargetInfo::SignedLongLong:
12763 HowLong = 2;
12764 break;
12765 }
12766 break;
12767 case 'O':
12768 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12769 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12770 #ifndef NDEBUG
12771 IsSpecial = true;
12772 #endif
12773 if (Context.getLangOpts().OpenCL)
12774 HowLong = 1;
12775 else
12776 HowLong = 2;
12777 break;
12778 }
12779 }
12780
12781 QualType Type;
12782
12783 // Read the base type.
12784 switch (*Str++) {
12785 default:
12786 llvm_unreachable("Unknown builtin type letter!");
12787 case 'x':
12788 assert(HowLong == 0 && !Signed && !Unsigned &&
12789 "Bad modifiers used with 'x'!");
12790 Type = Context.Float16Ty;
12791 break;
12792 case 'y':
12793 assert(HowLong == 0 && !Signed && !Unsigned &&
12794 "Bad modifiers used with 'y'!");
12795 Type = Context.BFloat16Ty;
12796 break;
12797 case 'v':
12798 assert(HowLong == 0 && !Signed && !Unsigned &&
12799 "Bad modifiers used with 'v'!");
12800 Type = Context.VoidTy;
12801 break;
12802 case 'h':
12803 assert(HowLong == 0 && !Signed && !Unsigned &&
12804 "Bad modifiers used with 'h'!");
12805 Type = Context.HalfTy;
12806 break;
12807 case 'f':
12808 assert(HowLong == 0 && !Signed && !Unsigned &&
12809 "Bad modifiers used with 'f'!");
12810 Type = Context.FloatTy;
12811 break;
12812 case 'd':
12813 assert(HowLong < 3 && !Signed && !Unsigned &&
12814 "Bad modifiers used with 'd'!");
12815 if (HowLong == 1)
12816 Type = Context.LongDoubleTy;
12817 else if (HowLong == 2)
12818 Type = Context.Float128Ty;
12819 else
12820 Type = Context.DoubleTy;
12821 break;
12822 case 's':
12823 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12824 if (Unsigned)
12825 Type = Context.UnsignedShortTy;
12826 else
12827 Type = Context.ShortTy;
12828 break;
12829 case 'i':
12830 if (IsChar)
12831 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12832 else if (IsShort)
12833 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12834 else if (HowLong == 3)
12835 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12836 else if (HowLong == 2)
12837 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12838 else if (HowLong == 1)
12839 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12840 else
12841 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12842 if (IsLeast)
12843 Type = Context.getLeastIntTypeForBitwidth(DestWidth: Context.getIntWidth(T: Type),
12844 /*Signed=*/!Unsigned);
12845 break;
12846 case 'c':
12847 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12848 if (Signed)
12849 Type = Context.SignedCharTy;
12850 else if (Unsigned)
12851 Type = Context.UnsignedCharTy;
12852 else
12853 Type = Context.CharTy;
12854 break;
12855 case 'b': // boolean
12856 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12857 Type = Context.BoolTy;
12858 break;
12859 case 'z': // size_t.
12860 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12861 Type = Context.getSizeType();
12862 break;
12863 case 'w': // wchar_t.
12864 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12865 Type = Context.getWideCharType();
12866 break;
12867 case 'F':
12868 Type = Context.getCFConstantStringType();
12869 break;
12870 case 'G':
12871 Type = Context.getObjCIdType();
12872 break;
12873 case 'H':
12874 Type = Context.getObjCSelType();
12875 break;
12876 case 'M':
12877 Type = Context.getObjCSuperType();
12878 break;
12879 case 'r':
12880 Type = Context.MetaInfoTy;
12881 break;
12882 case 'a':
12883 Type = Context.getBuiltinVaListType();
12884 assert(!Type.isNull() && "builtin va list type not initialized!");
12885 break;
12886 case 'A':
12887 // This is a "reference" to a va_list; however, what exactly
12888 // this means depends on how va_list is defined. There are two
12889 // different kinds of va_list: ones passed by value, and ones
12890 // passed by reference. An example of a by-value va_list is
12891 // x86, where va_list is a char*. An example of by-ref va_list
12892 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12893 // we want this argument to be a char*&; for x86-64, we want
12894 // it to be a __va_list_tag*.
12895 Type = Context.getBuiltinVaListType();
12896 assert(!Type.isNull() && "builtin va list type not initialized!");
12897 if (Type->isArrayType())
12898 Type = Context.getArrayDecayedType(Ty: Type);
12899 else
12900 Type = Context.getLValueReferenceType(T: Type);
12901 break;
12902 case 'q': {
12903 char *End;
12904 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12905 assert(End != Str && "Missing vector size");
12906 Str = End;
12907
12908 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12909 RequiresICE, AllowTypeModifiers: false);
12910 assert(!RequiresICE && "Can't require vector ICE");
12911
12912 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12913 break;
12914 }
12915 case 'Q': {
12916 switch (*Str++) {
12917 case 'a': {
12918 Type = Context.SveCountTy;
12919 break;
12920 }
12921 case 'b': {
12922 Type = Context.AMDGPUBufferRsrcTy;
12923 break;
12924 }
12925 case 'c': {
12926 Type = Context.AMDGPUFeaturePredicateTy;
12927 break;
12928 }
12929 case 't': {
12930 Type = Context.AMDGPUTextureTy;
12931 break;
12932 }
12933 case 'r': {
12934 Type = Context.HLSLResourceTy;
12935 break;
12936 }
12937 default:
12938 llvm_unreachable("Unexpected target builtin type");
12939 }
12940 break;
12941 }
12942 case 'V': {
12943 char *End;
12944 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12945 assert(End != Str && "Missing vector size");
12946 Str = End;
12947
12948 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12949 RequiresICE, AllowTypeModifiers: false);
12950 assert(!RequiresICE && "Can't require vector ICE");
12951
12952 // TODO: No way to make AltiVec vectors in builtins yet.
12953 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12954 break;
12955 }
12956 case 'E': {
12957 char *End;
12958
12959 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12960 assert(End != Str && "Missing vector size");
12961
12962 Str = End;
12963
12964 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12965 AllowTypeModifiers: false);
12966 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12967 break;
12968 }
12969 case 'X': {
12970 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12971 AllowTypeModifiers: false);
12972 assert(!RequiresICE && "Can't require complex ICE");
12973 Type = Context.getComplexType(T: ElementType);
12974 break;
12975 }
12976 case 'Y':
12977 Type = Context.getPointerDiffType();
12978 break;
12979 case 'P':
12980 Type = Context.getFILEType();
12981 if (Type.isNull()) {
12982 Error = ASTContext::GE_Missing_stdio;
12983 return {};
12984 }
12985 break;
12986 case 'J':
12987 if (Signed)
12988 Type = Context.getsigjmp_bufType();
12989 else
12990 Type = Context.getjmp_bufType();
12991
12992 if (Type.isNull()) {
12993 Error = ASTContext::GE_Missing_setjmp;
12994 return {};
12995 }
12996 break;
12997 case 'K':
12998 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12999 Type = Context.getucontext_tType();
13000
13001 if (Type.isNull()) {
13002 Error = ASTContext::GE_Missing_ucontext;
13003 return {};
13004 }
13005 break;
13006 case 'p':
13007 Type = Context.getProcessIDType();
13008 break;
13009 case 'm':
13010 Type = Context.MFloat8Ty;
13011 break;
13012 }
13013
13014 // If there are modifiers and if we're allowed to parse them, go for it.
13015 Done = !AllowTypeModifiers;
13016 while (!Done) {
13017 switch (char c = *Str++) {
13018 default: Done = true; --Str; break;
13019 case '*':
13020 case '&': {
13021 // Both pointers and references can have their pointee types
13022 // qualified with an address space.
13023 char *End;
13024 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
13025 if (End != Str) {
13026 // Note AddrSpace == 0 is not the same as an unspecified address space.
13027 Type = Context.getAddrSpaceQualType(
13028 T: Type,
13029 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
13030 Str = End;
13031 }
13032 if (c == '*')
13033 Type = Context.getPointerType(T: Type);
13034 else
13035 Type = Context.getLValueReferenceType(T: Type);
13036 break;
13037 }
13038 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13039 case 'C':
13040 Type = Type.withConst();
13041 break;
13042 case 'D':
13043 Type = Context.getVolatileType(T: Type);
13044 break;
13045 case 'R':
13046 Type = Type.withRestrict();
13047 break;
13048 }
13049 }
13050
13051 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13052 "Integer constant 'I' type must be an integer");
13053
13054 return Type;
13055}
13056
13057// On some targets such as PowerPC, some of the builtins are defined with custom
13058// type descriptors for target-dependent types. These descriptors are decoded in
13059// other functions, but it may be useful to be able to fall back to default
13060// descriptor decoding to define builtins mixing target-dependent and target-
13061// independent types. This function allows decoding one type descriptor with
13062// default decoding.
13063QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13064 GetBuiltinTypeError &Error, bool &RequireICE,
13065 bool AllowTypeModifiers) const {
13066 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13067}
13068
13069/// GetBuiltinType - Return the type for the specified builtin.
13070QualType ASTContext::GetBuiltinType(unsigned Id,
13071 GetBuiltinTypeError &Error,
13072 unsigned *IntegerConstantArgs) const {
13073 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13074 if (TypeStr[0] == '\0') {
13075 Error = GE_Missing_type;
13076 return {};
13077 }
13078
13079 SmallVector<QualType, 8> ArgTypes;
13080
13081 bool RequiresICE = false;
13082 Error = GE_None;
13083 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13084 RequiresICE, AllowTypeModifiers: true);
13085 if (Error != GE_None)
13086 return {};
13087
13088 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13089
13090 while (TypeStr[0] && TypeStr[0] != '.') {
13091 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13092 if (Error != GE_None)
13093 return {};
13094
13095 // If this argument is required to be an IntegerConstantExpression and the
13096 // caller cares, fill in the bitmask we return.
13097 if (RequiresICE && IntegerConstantArgs)
13098 *IntegerConstantArgs |= 1 << ArgTypes.size();
13099
13100 // Do array -> pointer decay. The builtin should use the decayed type.
13101 if (Ty->isArrayType())
13102 Ty = getArrayDecayedType(Ty);
13103
13104 ArgTypes.push_back(Elt: Ty);
13105 }
13106
13107 if (Id == Builtin::BI__GetExceptionInfo)
13108 return {};
13109
13110 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13111 "'.' should only occur at end of builtin type list!");
13112
13113 bool Variadic = (TypeStr[0] == '.');
13114
13115 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13116 if (BuiltinInfo.isNoReturn(ID: Id))
13117 EI = EI.withNoReturn(noReturn: true);
13118
13119 // We really shouldn't be making a no-proto type here.
13120 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13121 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13122
13123 FunctionProtoType::ExtProtoInfo EPI;
13124 EPI.ExtInfo = EI;
13125 EPI.Variadic = Variadic;
13126 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13127 EPI.ExceptionSpec.Type =
13128 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13129
13130 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13131}
13132
13133static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13134 const FunctionDecl *FD) {
13135 if (!FD->isExternallyVisible())
13136 return GVA_Internal;
13137
13138 // Non-user-provided functions get emitted as weak definitions with every
13139 // use, no matter whether they've been explicitly instantiated etc.
13140 if (!FD->isUserProvided())
13141 return GVA_DiscardableODR;
13142
13143 GVALinkage External;
13144 switch (FD->getTemplateSpecializationKind()) {
13145 case TSK_Undeclared:
13146 case TSK_ExplicitSpecialization:
13147 External = GVA_StrongExternal;
13148 break;
13149
13150 case TSK_ExplicitInstantiationDefinition:
13151 return GVA_StrongODR;
13152
13153 // C++11 [temp.explicit]p10:
13154 // [ Note: The intent is that an inline function that is the subject of
13155 // an explicit instantiation declaration will still be implicitly
13156 // instantiated when used so that the body can be considered for
13157 // inlining, but that no out-of-line copy of the inline function would be
13158 // generated in the translation unit. -- end note ]
13159 case TSK_ExplicitInstantiationDeclaration:
13160 return GVA_AvailableExternally;
13161
13162 case TSK_ImplicitInstantiation:
13163 External = GVA_DiscardableODR;
13164 break;
13165 }
13166
13167 if (!FD->isInlined())
13168 return External;
13169
13170 if ((!Context.getLangOpts().CPlusPlus &&
13171 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13172 !FD->hasAttr<DLLExportAttr>()) ||
13173 FD->hasAttr<GNUInlineAttr>()) {
13174 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13175
13176 // GNU or C99 inline semantics. Determine whether this symbol should be
13177 // externally visible.
13178 if (auto *Def = FD->getDefinition();
13179 Def && Def->isInlineDefinitionExternallyVisible())
13180 return External;
13181
13182 // C99 inline semantics, where the symbol is not externally visible.
13183 return GVA_AvailableExternally;
13184 }
13185
13186 // Functions specified with extern and inline in -fms-compatibility mode
13187 // forcibly get emitted. While the body of the function cannot be later
13188 // replaced, the function definition cannot be discarded.
13189 if (FD->isMSExternInline())
13190 return GVA_StrongODR;
13191
13192 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13193 isa<CXXConstructorDecl>(Val: FD) &&
13194 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13195 !FD->hasAttr<DLLExportAttr>()) {
13196 // Both Clang and MSVC implement inherited constructors as forwarding
13197 // thunks that delegate to the base constructor. Keep non-dllexport
13198 // inheriting constructor thunks internal since they are not needed
13199 // outside the translation unit.
13200 //
13201 // dllexport inherited constructors are exempted so they are externally
13202 // visible, matching MSVC's export behavior. Inherited constructors
13203 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13204 // cleanup types) are excluded from export in Sema to avoid silent
13205 // runtime mismatches.
13206 return GVA_Internal;
13207 }
13208
13209 return GVA_DiscardableODR;
13210}
13211
13212static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13213 const Decl *D, GVALinkage L) {
13214 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13215 // dllexport/dllimport on inline functions.
13216 if (D->hasAttr<DLLImportAttr>()) {
13217 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13218 return GVA_AvailableExternally;
13219 } else if (D->hasAttr<DLLExportAttr>()) {
13220 if (L == GVA_DiscardableODR)
13221 return GVA_StrongODR;
13222 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13223 // Device-side functions with __global__ attribute must always be
13224 // visible externally so they can be launched from host.
13225 if (D->hasAttr<CUDAGlobalAttr>() &&
13226 (L == GVA_DiscardableODR || L == GVA_Internal))
13227 return GVA_StrongODR;
13228 // Single source offloading languages like CUDA/HIP need to be able to
13229 // access static device variables from host code of the same compilation
13230 // unit. This is done by externalizing the static variable with a shared
13231 // name between the host and device compilation which is the same for the
13232 // same compilation unit whereas different among different compilation
13233 // units.
13234 if (Context.shouldExternalize(D))
13235 return GVA_StrongExternal;
13236 }
13237 return L;
13238}
13239
13240/// Adjust the GVALinkage for a declaration based on what an external AST source
13241/// knows about whether there can be other definitions of this declaration.
13242static GVALinkage
13243adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13244 GVALinkage L) {
13245 ExternalASTSource *Source = Ctx.getExternalSource();
13246 if (!Source)
13247 return L;
13248
13249 switch (Source->hasExternalDefinitions(D)) {
13250 case ExternalASTSource::EK_Never:
13251 // Other translation units rely on us to provide the definition.
13252 if (L == GVA_DiscardableODR)
13253 return GVA_StrongODR;
13254 break;
13255
13256 case ExternalASTSource::EK_Always:
13257 return GVA_AvailableExternally;
13258
13259 case ExternalASTSource::EK_ReplyHazy:
13260 break;
13261 }
13262 return L;
13263}
13264
13265GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13266 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13267 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13268 L: basicGVALinkageForFunction(Context: *this, FD)));
13269}
13270
13271static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13272 const VarDecl *VD) {
13273 // As an extension for interactive REPLs, make sure constant variables are
13274 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13275 // marking them as internal.
13276 if (Context.getLangOpts().CPlusPlus &&
13277 Context.getLangOpts().IncrementalExtensions &&
13278 VD->getType().isConstQualified() &&
13279 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13280 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13281 return GVA_DiscardableODR;
13282
13283 if (!VD->isExternallyVisible())
13284 return GVA_Internal;
13285
13286 if (VD->isStaticLocal()) {
13287 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13288 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13289 LexicalContext = LexicalContext->getLexicalParent();
13290
13291 // ObjC Blocks can create local variables that don't have a FunctionDecl
13292 // LexicalContext.
13293 if (!LexicalContext)
13294 return GVA_DiscardableODR;
13295
13296 // Otherwise, let the static local variable inherit its linkage from the
13297 // nearest enclosing function.
13298 auto StaticLocalLinkage =
13299 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13300
13301 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13302 // be emitted in any object with references to the symbol for the object it
13303 // contains, whether inline or out-of-line."
13304 // Similar behavior is observed with MSVC. An alternative ABI could use
13305 // StrongODR/AvailableExternally to match the function, but none are
13306 // known/supported currently.
13307 if (StaticLocalLinkage == GVA_StrongODR ||
13308 StaticLocalLinkage == GVA_AvailableExternally)
13309 return GVA_DiscardableODR;
13310 return StaticLocalLinkage;
13311 }
13312
13313 // MSVC treats in-class initialized static data members as definitions.
13314 // By giving them non-strong linkage, out-of-line definitions won't
13315 // cause link errors.
13316 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13317 return GVA_DiscardableODR;
13318
13319 // Most non-template variables have strong linkage; inline variables are
13320 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13321 GVALinkage StrongLinkage;
13322 switch (Context.getInlineVariableDefinitionKind(VD)) {
13323 case ASTContext::InlineVariableDefinitionKind::None:
13324 StrongLinkage = GVA_StrongExternal;
13325 break;
13326 case ASTContext::InlineVariableDefinitionKind::Weak:
13327 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13328 StrongLinkage = GVA_DiscardableODR;
13329 break;
13330 case ASTContext::InlineVariableDefinitionKind::Strong:
13331 StrongLinkage = GVA_StrongODR;
13332 break;
13333 }
13334
13335 switch (VD->getTemplateSpecializationKind()) {
13336 case TSK_Undeclared:
13337 return StrongLinkage;
13338
13339 case TSK_ExplicitSpecialization:
13340 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13341 VD->isStaticDataMember()
13342 ? GVA_StrongODR
13343 : StrongLinkage;
13344
13345 case TSK_ExplicitInstantiationDefinition:
13346 return GVA_StrongODR;
13347
13348 case TSK_ExplicitInstantiationDeclaration:
13349 return GVA_AvailableExternally;
13350
13351 case TSK_ImplicitInstantiation:
13352 return GVA_DiscardableODR;
13353 }
13354
13355 llvm_unreachable("Invalid Linkage!");
13356}
13357
13358GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13359 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13360 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13361 L: basicGVALinkageForVariable(Context: *this, VD)));
13362}
13363
13364bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13365 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13366 if (!VD->isFileVarDecl())
13367 return false;
13368 // Global named register variables (GNU extension) are never emitted.
13369 if (VD->getStorageClass() == SC_Register)
13370 return false;
13371 if (VD->getDescribedVarTemplate() ||
13372 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13373 return false;
13374 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13375 // We never need to emit an uninstantiated function template.
13376 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13377 return false;
13378 } else if (isa<PragmaCommentDecl>(Val: D))
13379 return true;
13380 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13381 return true;
13382 else if (isa<OMPRequiresDecl>(Val: D))
13383 return true;
13384 else if (isa<OMPThreadPrivateDecl>(Val: D))
13385 return !D->getDeclContext()->isDependentContext();
13386 else if (isa<OMPAllocateDecl>(Val: D))
13387 return !D->getDeclContext()->isDependentContext();
13388 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13389 return !D->getDeclContext()->isDependentContext();
13390 else if (isa<ImportDecl>(Val: D))
13391 return true;
13392 else
13393 return false;
13394
13395 // If this is a member of a class template, we do not need to emit it.
13396 if (D->getDeclContext()->isDependentContext())
13397 return false;
13398
13399 // Weak references don't produce any output by themselves.
13400 if (D->hasAttr<WeakRefAttr>())
13401 return false;
13402
13403 // SYCL device compilation requires that functions defined with the
13404 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13405 // other entities are emitted only if they are used by a function
13406 // defined with one of those attributes.
13407 if (LangOpts.SYCLIsDevice)
13408 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13409 D->hasAttr<SYCLExternalAttr>());
13410
13411 // Aliases and used decls are required.
13412 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13413 return true;
13414
13415 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13416 // Forward declarations aren't required.
13417 if (!FD->doesThisDeclarationHaveABody())
13418 return FD->doesDeclarationForceExternallyVisibleDefinition();
13419
13420 // Constructors and destructors are required.
13421 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13422 return true;
13423
13424 // The key function for a class is required. This rule only comes
13425 // into play when inline functions can be key functions, though.
13426 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13427 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13428 const CXXRecordDecl *RD = MD->getParent();
13429 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13430 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13431 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13432 return true;
13433 }
13434 }
13435 }
13436
13437 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13438
13439 // static, static inline, always_inline, and extern inline functions can
13440 // always be deferred. Normal inline functions can be deferred in C99/C++.
13441 // Implicit template instantiations can also be deferred in C++.
13442 return !isDiscardableGVALinkage(L: Linkage);
13443 }
13444
13445 const auto *VD = cast<VarDecl>(Val: D);
13446 assert(VD->isFileVarDecl() && "Expected file scoped var");
13447
13448 // If the decl is marked as `declare target to`, it should be emitted for the
13449 // host and for the device.
13450 if (LangOpts.OpenMP &&
13451 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13452 return true;
13453
13454 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13455 !isMSStaticDataMemberInlineDefinition(VD))
13456 return false;
13457
13458 if (VD->shouldEmitInExternalSource())
13459 return false;
13460
13461 // Variables that can be needed in other TUs are required.
13462 auto Linkage = GetGVALinkageForVariable(VD);
13463 if (!isDiscardableGVALinkage(L: Linkage))
13464 return true;
13465
13466 // We never need to emit a variable that is available in another TU.
13467 if (Linkage == GVA_AvailableExternally)
13468 return false;
13469
13470 // Variables that have destruction with side-effects are required.
13471 if (VD->needsDestruction(Ctx: *this))
13472 return true;
13473
13474 // Variables that have initialization with side-effects are required.
13475 if (VD->hasInitWithSideEffects())
13476 return true;
13477
13478 // Likewise, variables with tuple-like bindings are required if their
13479 // bindings have side-effects.
13480 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13481 for (const auto *BD : DD->flat_bindings())
13482 if (const auto *BindingVD = BD->getHoldingVar())
13483 if (DeclMustBeEmitted(D: BindingVD))
13484 return true;
13485 }
13486
13487 return false;
13488}
13489
13490template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
13491 if (auto *A = D->getAttr<AttrT>())
13492 return A->isImplicit();
13493 return D->isImplicit();
13494}
13495
13496bool ASTContext::shouldEmitCUDADecl(const ValueDecl *D) const {
13497 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
13498 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
13499 "Expected Variable or Function");
13500
13501 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13502 // We need to emit host-side 'shadows' for all global device-side variables
13503 // because the CUDA runtime needs their size and host-side address in order
13504 // to provide access to their device-side incarnations.
13505 return !LangOpts.CUDAIsDevice || VD->hasAttr<CUDADeviceAttr>() ||
13506 VD->hasAttr<CUDAConstantAttr>() || VD->hasAttr<CUDASharedAttr>() ||
13507 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
13508 VD->getType()->isCUDADeviceBuiltinTextureType();
13509 }
13510
13511 const auto *FD = cast<FunctionDecl>(Val: D);
13512 // Device-only functions are the only things we skip on the host.
13513 if (!LangOpts.CUDAIsDevice)
13514 return FD->hasAttr<CUDAHostAttr>() || !FD->hasAttr<CUDADeviceAttr>();
13515
13516 // Non-constexpr non-lambda implicit host device functions are not emitted
13517 // unless they are used on device side.
13518 return (FD->hasAttr<CUDADeviceAttr>() &&
13519 !(LangOpts.OffloadImplicitHostDeviceTemplates &&
13520 hasImplicitAttr<CUDAHostAttr>(D: FD) &&
13521 hasImplicitAttr<CUDADeviceAttr>(D: FD) && !FD->isConstexpr() &&
13522 !isLambdaCallOperator(DC: FD) &&
13523 !CUDAImplicitHostDeviceFunUsedByDevice.count(V: FD))) ||
13524 FD->hasAttr<CUDAGlobalAttr>() ||
13525 (LangOpts.HIPStdPar && !FD->hasAttr<CUDAHostAttr>());
13526}
13527
13528void ASTContext::forEachMultiversionedFunctionVersion(
13529 const FunctionDecl *FD,
13530 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13531 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13532 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13533 FD = FD->getMostRecentDecl();
13534 // FIXME: The order of traversal here matters and depends on the order of
13535 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13536 // shouldn't rely on that.
13537 for (auto *CurDecl :
13538 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13539 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13540 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13541 SeenDecls.insert(V: CurFD).second) {
13542 Pred(CurFD);
13543 }
13544 }
13545}
13546
13547CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13548 bool IsCXXMethod) const {
13549 // Pass through to the C++ ABI object
13550 if (IsCXXMethod)
13551 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13552
13553 switch (LangOpts.getDefaultCallingConv()) {
13554 case LangOptions::DCC_None:
13555 break;
13556 case LangOptions::DCC_CDecl:
13557 return CC_C;
13558 case LangOptions::DCC_FastCall:
13559 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13560 return CC_X86FastCall;
13561 break;
13562 case LangOptions::DCC_StdCall:
13563 if (!IsVariadic)
13564 return CC_X86StdCall;
13565 break;
13566 case LangOptions::DCC_VectorCall:
13567 // __vectorcall cannot be applied to variadic functions.
13568 if (!IsVariadic)
13569 return CC_X86VectorCall;
13570 break;
13571 case LangOptions::DCC_RegCall:
13572 // __regcall cannot be applied to variadic functions.
13573 if (!IsVariadic)
13574 return CC_X86RegCall;
13575 break;
13576 case LangOptions::DCC_RtdCall:
13577 if (!IsVariadic)
13578 return CC_M68kRTD;
13579 break;
13580 }
13581 return Target->getDefaultCallingConv();
13582}
13583
13584bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13585 // Pass through to the C++ ABI object
13586 return ABI->isNearlyEmpty(RD);
13587}
13588
13589VTableContextBase *ASTContext::getVTableContext() {
13590 if (!VTContext) {
13591 auto ABI = Target->getCXXABI();
13592 if (ABI.isMicrosoft())
13593 VTContext.reset(p: new MicrosoftVTableContext(*this));
13594 else {
13595 VTContext.reset(p: new ItaniumVTableContext(*this));
13596 }
13597 }
13598 return VTContext.get();
13599}
13600
13601MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13602 if (!T)
13603 T = Target;
13604 switch (T->getCXXABI().getKind()) {
13605 case TargetCXXABI::AppleARM64:
13606 case TargetCXXABI::Fuchsia:
13607 case TargetCXXABI::GenericAArch64:
13608 case TargetCXXABI::GenericItanium:
13609 case TargetCXXABI::GenericARM:
13610 case TargetCXXABI::GenericMIPS:
13611 case TargetCXXABI::iOS:
13612 case TargetCXXABI::WebAssembly:
13613 case TargetCXXABI::WatchOS:
13614 case TargetCXXABI::XL:
13615 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13616 case TargetCXXABI::Microsoft:
13617 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13618 }
13619 llvm_unreachable("Unsupported ABI");
13620}
13621
13622MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13623 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13624 "Device mangle context does not support Microsoft mangling.");
13625 switch (T.getCXXABI().getKind()) {
13626 case TargetCXXABI::AppleARM64:
13627 case TargetCXXABI::Fuchsia:
13628 case TargetCXXABI::GenericAArch64:
13629 case TargetCXXABI::GenericItanium:
13630 case TargetCXXABI::GenericARM:
13631 case TargetCXXABI::GenericMIPS:
13632 case TargetCXXABI::iOS:
13633 case TargetCXXABI::WebAssembly:
13634 case TargetCXXABI::WatchOS:
13635 case TargetCXXABI::XL:
13636 return ItaniumMangleContext::create(
13637 Context&: *this, Diags&: getDiagnostics(),
13638 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13639 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13640 return RD->getDeviceLambdaManglingNumber();
13641 return std::nullopt;
13642 },
13643 /*IsAux=*/true);
13644 case TargetCXXABI::Microsoft:
13645 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13646 /*IsAux=*/true);
13647 }
13648 llvm_unreachable("Unsupported ABI");
13649}
13650
13651MangleContext *ASTContext::cudaNVInitDeviceMC() {
13652 // If the host and device have different C++ ABIs, mark it as the device
13653 // mangle context so that the mangling needs to retrieve the additional
13654 // device lambda mangling number instead of the regular host one.
13655 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13656 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13657 return createDeviceMangleContext(T: *getAuxTargetInfo());
13658 }
13659
13660 return createMangleContext(T: getAuxTargetInfo());
13661}
13662
13663CXXABI::~CXXABI() = default;
13664
13665size_t ASTContext::getSideTableAllocatedMemory() const {
13666 return ASTRecordLayouts.getMemorySize() +
13667 llvm::capacity_in_bytes(X: ObjCLayouts) +
13668 llvm::capacity_in_bytes(X: KeyFunctions) +
13669 llvm::capacity_in_bytes(X: ObjCImpls) +
13670 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13671 DeclAttrAllocator.getTotalMemory() +
13672 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13673 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13674 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13675 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13676 llvm::capacity_in_bytes(X: OverriddenMethods) +
13677 llvm::capacity_in_bytes(X: Types) +
13678 llvm::capacity_in_bytes(x: VariableArrayTypes);
13679}
13680
13681/// getIntTypeForBitwidth -
13682/// sets integer QualTy according to specified details:
13683/// bitwidth, signed/unsigned.
13684/// Returns empty type if there is no appropriate target types.
13685QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13686 unsigned Signed) const {
13687 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13688 CanQualType QualTy = getFromTargetType(Type: Ty);
13689 if (!QualTy && DestWidth == 128)
13690 return Signed ? Int128Ty : UnsignedInt128Ty;
13691 return QualTy;
13692}
13693
13694QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13695 unsigned Signed) const {
13696 return getFromTargetType(
13697 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13698}
13699
13700/// getRealTypeForBitwidth -
13701/// sets floating point QualTy according to specified bitwidth.
13702/// Returns empty type if there is no appropriate target types.
13703QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13704 FloatModeKind ExplicitType) const {
13705 FloatModeKind Ty =
13706 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13707 switch (Ty) {
13708 case FloatModeKind::Half:
13709 return HalfTy;
13710 case FloatModeKind::Float:
13711 return FloatTy;
13712 case FloatModeKind::Double:
13713 return DoubleTy;
13714 case FloatModeKind::LongDouble:
13715 return LongDoubleTy;
13716 case FloatModeKind::Float128:
13717 return Float128Ty;
13718 case FloatModeKind::Ibm128:
13719 return Ibm128Ty;
13720 case FloatModeKind::NoFloat:
13721 return {};
13722 }
13723
13724 llvm_unreachable("Unhandled TargetInfo::RealType value");
13725}
13726
13727void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13728 if (Number <= 1)
13729 return;
13730
13731 MangleNumbers[ND] = Number;
13732
13733 if (Listener)
13734 Listener->AddedManglingNumber(D: ND, Number);
13735}
13736
13737unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13738 bool ForAuxTarget) const {
13739 auto I = MangleNumbers.find(Key: ND);
13740 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13741 // CUDA/HIP host compilation encodes host and device mangling numbers
13742 // as lower and upper half of 32 bit integer.
13743 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13744 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13745 } else {
13746 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13747 "number for aux target");
13748 }
13749 return Res > 1 ? Res : 1;
13750}
13751
13752void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13753 if (Number <= 1)
13754 return;
13755
13756 StaticLocalNumbers[VD] = Number;
13757
13758 if (Listener)
13759 Listener->AddedStaticLocalNumbers(D: VD, Number);
13760}
13761
13762unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13763 auto I = StaticLocalNumbers.find(Key: VD);
13764 return I != StaticLocalNumbers.end() ? I->second : 1;
13765}
13766
13767void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13768 bool IsDestroying) {
13769 if (!IsDestroying) {
13770 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13771 return;
13772 }
13773 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13774}
13775
13776bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13777 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13778}
13779
13780void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13781 bool IsTypeAware) {
13782 if (!IsTypeAware) {
13783 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13784 return;
13785 }
13786 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13787}
13788
13789bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13790 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13791}
13792
13793void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13794 FunctionDecl *OperatorDelete,
13795 OperatorDeleteKind K) const {
13796 switch (K) {
13797 case OperatorDeleteKind::Regular:
13798 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13799 break;
13800 case OperatorDeleteKind::GlobalRegular:
13801 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13802 OperatorDelete;
13803 break;
13804 case OperatorDeleteKind::Array:
13805 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13806 OperatorDelete;
13807 break;
13808 case OperatorDeleteKind::ArrayGlobal:
13809 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13810 OperatorDelete;
13811 break;
13812 }
13813}
13814
13815bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13816 OperatorDeleteKind K) const {
13817 switch (K) {
13818 case OperatorDeleteKind::Regular:
13819 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13820 case OperatorDeleteKind::GlobalRegular:
13821 return GlobalOperatorDeletesForVirtualDtor.contains(
13822 Val: Dtor->getCanonicalDecl());
13823 case OperatorDeleteKind::Array:
13824 return ArrayOperatorDeletesForVirtualDtor.contains(
13825 Val: Dtor->getCanonicalDecl());
13826 case OperatorDeleteKind::ArrayGlobal:
13827 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13828 Val: Dtor->getCanonicalDecl());
13829 }
13830 return false;
13831}
13832
13833FunctionDecl *
13834ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13835 OperatorDeleteKind K) const {
13836 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13837 switch (K) {
13838 case OperatorDeleteKind::Regular:
13839 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13840 return OperatorDeletesForVirtualDtor[Canon];
13841 return nullptr;
13842 case OperatorDeleteKind::GlobalRegular:
13843 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13844 return GlobalOperatorDeletesForVirtualDtor[Canon];
13845 return nullptr;
13846 case OperatorDeleteKind::Array:
13847 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13848 return ArrayOperatorDeletesForVirtualDtor[Canon];
13849 return nullptr;
13850 case OperatorDeleteKind::ArrayGlobal:
13851 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13852 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13853 return nullptr;
13854 }
13855 return nullptr;
13856}
13857
13858bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13859 const CXXRecordDecl *RD) {
13860 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13861 return false;
13862
13863 return MaybeRequireVectorDeletingDtor.count(V: RD);
13864}
13865
13866void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13867 const CXXRecordDecl *RD) {
13868 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13869 return;
13870
13871 MaybeRequireVectorDeletingDtor.insert(V: RD);
13872}
13873
13874MangleNumberingContext &
13875ASTContext::getManglingNumberContext(const DeclContext *DC) {
13876 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13877 // Reopened namespaces share a mangling context so that declarations in
13878 // different namespace blocks do not receive duplicate mangling numbers.
13879 DC = DC->getPrimaryContext();
13880 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13881 if (!MCtx)
13882 MCtx = createMangleNumberingContext();
13883 return *MCtx;
13884}
13885
13886MangleNumberingContext &
13887ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13888 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13889 std::unique_ptr<MangleNumberingContext> &MCtx =
13890 ExtraMangleNumberingContexts[D];
13891 if (!MCtx)
13892 MCtx = createMangleNumberingContext();
13893 return *MCtx;
13894}
13895
13896std::unique_ptr<MangleNumberingContext>
13897ASTContext::createMangleNumberingContext() const {
13898 return ABI->createMangleNumberingContext();
13899}
13900
13901const CXXConstructorDecl *
13902ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13903 return ABI->getCopyConstructorForExceptionObject(
13904 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13905}
13906
13907void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13908 CXXConstructorDecl *CD) {
13909 return ABI->addCopyConstructorForExceptionObject(
13910 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13911 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13912}
13913
13914void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13915 TypedefNameDecl *DD) {
13916 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13917}
13918
13919TypedefNameDecl *
13920ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13921 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13922}
13923
13924void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13925 DeclaratorDecl *DD) {
13926 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13927}
13928
13929DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13930 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13931}
13932
13933void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13934 ParamIndices[D] = index;
13935}
13936
13937unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13938 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13939 assert(I != ParamIndices.end() &&
13940 "ParmIndices lacks entry set by ParmVarDecl");
13941 return I->second;
13942}
13943
13944QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13945 unsigned Length) const {
13946 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13947 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13948 EltTy = EltTy.withConst();
13949
13950 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13951
13952 // Get an array type for the string, according to C99 6.4.5. This includes
13953 // the null terminator character.
13954 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13955 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13956}
13957
13958StringLiteral *
13959ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13960 StringLiteral *&Result = StringLiteralCache[Key];
13961 if (!Result)
13962 Result = StringLiteral::Create(
13963 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13964 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13965 Locs: SourceLocation());
13966 return Result;
13967}
13968
13969MSGuidDecl *
13970ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13971 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13972
13973 llvm::FoldingSetNodeID ID;
13974 MSGuidDecl::Profile(ID, P: Parts);
13975
13976 llvm::FoldingSetInsertToken Token;
13977 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13978 return Existing;
13979
13980 QualType GUIDType = getMSGuidType().withConst();
13981 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13982 MSGuidDecls.insert(N: New, Token);
13983 return New;
13984}
13985
13986UnnamedGlobalConstantDecl *
13987ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13988 const APValue &APVal) const {
13989 llvm::FoldingSetNodeID ID;
13990 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13991
13992 llvm::FoldingSetInsertToken Token;
13993 if (UnnamedGlobalConstantDecl *Existing =
13994 UnnamedGlobalConstantDecls.lookup(ID, Token))
13995 return Existing;
13996
13997 UnnamedGlobalConstantDecl *New =
13998 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13999 UnnamedGlobalConstantDecls.insert(N: New, Token);
14000 return New;
14001}
14002
14003TemplateParamObjectDecl *
14004ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
14005 assert(T->isRecordType() && "template param object of unexpected type");
14006
14007 // C++ [temp.param]p8:
14008 // [...] a static storage duration object of type 'const T' [...]
14009 T.addConst();
14010
14011 llvm::FoldingSetNodeID ID;
14012 TemplateParamObjectDecl::Profile(ID, T, V);
14013
14014 llvm::FoldingSetInsertToken Token;
14015 if (TemplateParamObjectDecl *Existing =
14016 TemplateParamObjectDecls.lookup(ID, Token))
14017 return Existing;
14018
14019 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
14020 TemplateParamObjectDecls.insert(N: New, Token);
14021 return New;
14022}
14023
14024bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
14025 const llvm::Triple &T = getTargetInfo().getTriple();
14026 if (!T.isOSDarwin())
14027 return false;
14028
14029 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
14030 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
14031 return false;
14032
14033 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14034 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
14035 uint64_t Size = sizeChars.getQuantity();
14036 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
14037 unsigned Align = alignChars.getQuantity();
14038 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14039 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
14040}
14041
14042bool
14043ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
14044 const ObjCMethodDecl *MethodImpl) {
14045 // No point trying to match an unavailable/deprecated mothod.
14046 if (MethodDecl->hasAttr<UnavailableAttr>()
14047 || MethodDecl->hasAttr<DeprecatedAttr>())
14048 return false;
14049 if (MethodDecl->getObjCDeclQualifier() !=
14050 MethodImpl->getObjCDeclQualifier())
14051 return false;
14052 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
14053 return false;
14054
14055 if (MethodDecl->param_size() != MethodImpl->param_size())
14056 return false;
14057
14058 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14059 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14060 EF = MethodDecl->param_end();
14061 IM != EM && IF != EF; ++IM, ++IF) {
14062 const ParmVarDecl *DeclVar = (*IF);
14063 const ParmVarDecl *ImplVar = (*IM);
14064 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14065 return false;
14066 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
14067 return false;
14068 }
14069
14070 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14071}
14072
14073uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
14074 LangAS AS;
14075 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
14076 AS = LangAS::Default;
14077 else
14078 AS = QT->getPointeeType().getAddressSpace();
14079
14080 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
14081}
14082
14083unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
14084 return getTargetInfo().getTargetAddressSpace(AS);
14085}
14086
14087bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14088 if (X == Y)
14089 return true;
14090 if (!X || !Y)
14091 return false;
14092 llvm::FoldingSetNodeID IDX, IDY;
14093 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14094 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14095 return IDX == IDY;
14096}
14097
14098// The getCommon* helpers return, for given 'same' X and Y entities given as
14099// inputs, another entity which is also the 'same' as the inputs, but which
14100// is closer to the canonical form of the inputs, each according to a given
14101// criteria.
14102// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14103// the regular ones.
14104
14105static Decl *getCommonDecl(Decl *X, Decl *Y) {
14106 if (!declaresSameEntity(D1: X, D2: Y))
14107 return nullptr;
14108 for (const Decl *DX : X->redecls()) {
14109 // If we reach Y before reaching the first decl, that means X is older.
14110 if (DX == Y)
14111 return X;
14112 // If we reach the first decl, then Y is older.
14113 if (DX->isFirstDecl())
14114 return Y;
14115 }
14116 llvm_unreachable("Corrupt redecls chain");
14117}
14118
14119template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14120static T *getCommonDecl(T *X, T *Y) {
14121 return cast_or_null<T>(
14122 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14123 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14124}
14125
14126template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14127static T *getCommonDeclChecked(T *X, T *Y) {
14128 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14129 Y: const_cast<Decl *>(cast<Decl>(Y))));
14130}
14131
14132static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14133 TemplateName Y,
14134 bool IgnoreDeduced = false) {
14135 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14136 return X;
14137 // FIXME: There are cases here where we could find a common template name
14138 // with more sugar. For example one could be a SubstTemplateTemplate*
14139 // replacing the other.
14140 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14141 if (CX.getAsVoidPointer() !=
14142 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14143 return TemplateName();
14144 return CX;
14145}
14146
14147static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14148 TemplateName X, TemplateName Y,
14149 bool IgnoreDeduced) {
14150 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14151 assert(R.getAsVoidPointer() != nullptr);
14152 return R;
14153}
14154
14155static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14156 ArrayRef<QualType> Ys, bool Unqualified = false) {
14157 assert(Xs.size() == Ys.size());
14158 SmallVector<QualType, 8> Rs(Xs.size());
14159 for (size_t I = 0; I < Rs.size(); ++I)
14160 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14161 return Rs;
14162}
14163
14164template <class T>
14165static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14166 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14167 : SourceLocation();
14168}
14169
14170static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14171 const TemplateArgument &X,
14172 const TemplateArgument &Y) {
14173 if (X.getKind() != Y.getKind())
14174 return TemplateArgument();
14175
14176 switch (X.getKind()) {
14177 case TemplateArgument::ArgKind::Type:
14178 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14179 return TemplateArgument();
14180 return TemplateArgument(
14181 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14182 case TemplateArgument::ArgKind::NullPtr:
14183 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14184 return TemplateArgument();
14185 return TemplateArgument(
14186 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14187 /*Unqualified=*/true);
14188 case TemplateArgument::ArgKind::Expression:
14189 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14190 return TemplateArgument();
14191 // FIXME: Try to keep the common sugar.
14192 return X;
14193 case TemplateArgument::ArgKind::Template: {
14194 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14195 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14196 if (!CTN.getAsVoidPointer())
14197 return TemplateArgument();
14198 return TemplateArgument(CTN);
14199 }
14200 case TemplateArgument::ArgKind::TemplateExpansion: {
14201 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14202 TY = Y.getAsTemplateOrTemplatePattern();
14203 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14204 if (!CTN.getAsVoidPointer())
14205 return TemplateName();
14206 auto NExpX = X.getNumTemplateExpansions();
14207 assert(NExpX == Y.getNumTemplateExpansions());
14208 return TemplateArgument(CTN, NExpX);
14209 }
14210 default:
14211 // FIXME: Handle the other argument kinds.
14212 return X;
14213 }
14214}
14215
14216static bool getCommonTemplateArguments(const ASTContext &Ctx,
14217 SmallVectorImpl<TemplateArgument> &R,
14218 ArrayRef<TemplateArgument> Xs,
14219 ArrayRef<TemplateArgument> Ys) {
14220 if (Xs.size() != Ys.size())
14221 return true;
14222 R.resize(N: Xs.size());
14223 for (size_t I = 0; I < R.size(); ++I) {
14224 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14225 if (R[I].isNull())
14226 return true;
14227 }
14228 return false;
14229}
14230
14231static auto getCommonTemplateArguments(const ASTContext &Ctx,
14232 ArrayRef<TemplateArgument> Xs,
14233 ArrayRef<TemplateArgument> Ys) {
14234 SmallVector<TemplateArgument, 8> R;
14235 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14236 assert(!Different);
14237 (void)Different;
14238 return R;
14239}
14240
14241template <class T>
14242static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14243 bool IsSame) {
14244 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14245 if (KX == KY)
14246 return KX;
14247 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14248 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14249 return KX;
14250}
14251
14252/// Returns a NestedNameSpecifier which has only the common sugar
14253/// present in both NNS1 and NNS2.
14254static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14255 NestedNameSpecifier NNS1,
14256 NestedNameSpecifier NNS2, bool IsSame) {
14257 // If they are identical, all sugar is common.
14258 if (NNS1 == NNS2)
14259 return NNS1;
14260
14261 // IsSame implies both Qualifiers are equivalent.
14262 NestedNameSpecifier Canon = NNS1.getCanonical();
14263 if (Canon != NNS2.getCanonical()) {
14264 assert(!IsSame && "Should be the same NestedNameSpecifier");
14265 // If they are not the same, there is nothing to unify.
14266 return std::nullopt;
14267 }
14268
14269 NestedNameSpecifier R = std::nullopt;
14270 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14271 assert(Kind == NNS2.getKind());
14272 switch (Kind) {
14273 case NestedNameSpecifier::Kind::Namespace: {
14274 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14275 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14276 auto Kind = Namespace1->getKind();
14277 if (Kind != Namespace2->getKind() ||
14278 (Kind == Decl::NamespaceAlias &&
14279 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14280 R = NestedNameSpecifier(
14281 Ctx,
14282 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14283 Y: Namespace2->getNamespace()),
14284 /*Prefix=*/std::nullopt);
14285 break;
14286 }
14287 // The prefixes for namespaces are not significant, its declaration
14288 // identifies it uniquely.
14289 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14290 /*IsSame=*/false);
14291 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14292 Prefix);
14293 break;
14294 }
14295 case NestedNameSpecifier::Kind::Type: {
14296 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14297 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14298 /*Unqualified=*/true)
14299 .getTypePtr();
14300 R = NestedNameSpecifier(T);
14301 break;
14302 }
14303 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14304 // FIXME: Can __super even be used with data members?
14305 // If it's only usable in functions, we will never see it here,
14306 // unless we save the qualifiers used in function types.
14307 // In that case, it might be possible NNS2 is a type,
14308 // in which case we should degrade the result to
14309 // a CXXRecordType.
14310 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14311 Y: NNS2.getAsMicrosoftSuper()));
14312 break;
14313 }
14314 case NestedNameSpecifier::Kind::Null:
14315 case NestedNameSpecifier::Kind::Global:
14316 // These are singletons.
14317 llvm_unreachable("singletons did not compare equal");
14318 }
14319 assert(R.getCanonical() == Canon);
14320 return R;
14321}
14322
14323template <class T>
14324static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14325 const T *Y, bool IsSame) {
14326 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14327}
14328
14329template <class T>
14330static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14331 const T *Y) {
14332 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14333}
14334
14335static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14336 QualType X, QualType Y,
14337 Qualifiers &QX,
14338 Qualifiers &QY) {
14339 QualType R = Ctx.getCommonSugaredType(X, Y,
14340 /*Unqualified=*/true);
14341 // Qualifiers common to both element types.
14342 Qualifiers RQ = R.getQualifiers();
14343 // For each side, move to the top level any qualifiers which are not common to
14344 // both element types. The caller must assume top level qualifiers might
14345 // be different, even if they are the same type, and can be treated as sugar.
14346 QX += X.getQualifiers() - RQ;
14347 QY += Y.getQualifiers() - RQ;
14348 return R;
14349}
14350
14351template <class T>
14352static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14353 Qualifiers &QX, const T *Y,
14354 Qualifiers &QY) {
14355 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14356 Y->getElementType(), QX, QY);
14357}
14358
14359template <class T>
14360static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14361 const T *Y) {
14362 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14363}
14364
14365template <class T>
14366static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14367 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14368 return X->getSizeExpr();
14369}
14370
14371static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14372 assert(X->getSizeModifier() == Y->getSizeModifier());
14373 return X->getSizeModifier();
14374}
14375
14376static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14377 const ArrayType *Y) {
14378 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14379 return X->getIndexTypeCVRQualifiers();
14380}
14381
14382// Merges two type lists such that the resulting vector will contain
14383// each type (in a canonical sense) only once, in the order they appear
14384// from X to Y. If they occur in both X and Y, the result will contain
14385// the common sugared type between them.
14386static void mergeTypeLists(const ASTContext &Ctx,
14387 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14388 ArrayRef<QualType> Y) {
14389 llvm::DenseMap<QualType, unsigned> Found;
14390 for (auto Ts : {X, Y}) {
14391 for (QualType T : Ts) {
14392 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14393 if (!Res.second) {
14394 QualType &U = Out[Res.first->second];
14395 U = Ctx.getCommonSugaredType(X: U, Y: T);
14396 } else {
14397 Out.emplace_back(Args&: T);
14398 }
14399 }
14400 }
14401}
14402
14403FunctionProtoType::ExceptionSpecInfo
14404ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14405 FunctionProtoType::ExceptionSpecInfo ESI2,
14406 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14407 bool AcceptDependent) const {
14408 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14409
14410 // If either of them can throw anything, that is the result.
14411 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14412 if (EST1 == I)
14413 return ESI1;
14414 if (EST2 == I)
14415 return ESI2;
14416 }
14417
14418 // If either of them is non-throwing, the result is the other.
14419 for (auto I :
14420 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14421 if (EST1 == I)
14422 return ESI2;
14423 if (EST2 == I)
14424 return ESI1;
14425 }
14426
14427 // If we're left with value-dependent computed noexcept expressions, we're
14428 // stuck. Before C++17, we can just drop the exception specification entirely,
14429 // since it's not actually part of the canonical type. And this should never
14430 // happen in C++17, because it would mean we were computing the composite
14431 // pointer type of dependent types, which should never happen.
14432 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14433 assert(AcceptDependent &&
14434 "computing composite pointer type of dependent types");
14435 return FunctionProtoType::ExceptionSpecInfo();
14436 }
14437
14438 // Switch over the possibilities so that people adding new values know to
14439 // update this function.
14440 switch (EST1) {
14441 case EST_None:
14442 case EST_DynamicNone:
14443 case EST_MSAny:
14444 case EST_BasicNoexcept:
14445 case EST_DependentNoexcept:
14446 case EST_NoexceptFalse:
14447 case EST_NoexceptTrue:
14448 case EST_NoThrow:
14449 llvm_unreachable("These ESTs should be handled above");
14450
14451 case EST_Dynamic: {
14452 // This is the fun case: both exception specifications are dynamic. Form
14453 // the union of the two lists.
14454 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14455 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14456 Y: ESI2.Exceptions);
14457 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14458 Result.Exceptions = ExceptionTypeStorage;
14459 return Result;
14460 }
14461
14462 case EST_Unevaluated:
14463 case EST_Uninstantiated:
14464 case EST_Unparsed:
14465 llvm_unreachable("shouldn't see unresolved exception specifications here");
14466 }
14467
14468 llvm_unreachable("invalid ExceptionSpecificationType");
14469}
14470
14471static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14472 Qualifiers &QX, const Type *Y,
14473 Qualifiers &QY) {
14474 Type::TypeClass TC = X->getTypeClass();
14475 assert(TC == Y->getTypeClass());
14476 switch (TC) {
14477#define UNEXPECTED_TYPE(Class, Kind) \
14478 case Type::Class: \
14479 llvm_unreachable("Unexpected " Kind ": " #Class);
14480
14481#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14482#define TYPE(Class, Base)
14483#include "clang/AST/TypeNodes.inc"
14484
14485#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14486 SUGAR_FREE_TYPE(Builtin)
14487 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14488 SUGAR_FREE_TYPE(DependentBitInt)
14489 SUGAR_FREE_TYPE(BitInt)
14490 SUGAR_FREE_TYPE(ObjCInterface)
14491 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14492 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14493 SUGAR_FREE_TYPE(UnresolvedUsing)
14494 SUGAR_FREE_TYPE(HLSLAttributedResource)
14495 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14496#undef SUGAR_FREE_TYPE
14497#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14498 NON_UNIQUE_TYPE(TypeOfExpr)
14499 NON_UNIQUE_TYPE(VariableArray)
14500#undef NON_UNIQUE_TYPE
14501
14502 UNEXPECTED_TYPE(TypeOf, "sugar")
14503
14504#undef UNEXPECTED_TYPE
14505
14506 case Type::Auto: {
14507 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14508 assert(AX->getDeducedKind() == AY->getDeducedKind());
14509 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14510 assert(AX->getKeyword() == AY->getKeyword());
14511 TemplateDecl *CD =
14512 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14513 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14514 SmallVector<TemplateArgument, 8> As;
14515 if (CD &&
14516 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14517 Ys: AY->getTypeConstraintArguments())) {
14518 CD = nullptr; // The arguments differ, so make it unconstrained.
14519 As.clear();
14520 }
14521 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14522 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14523 }
14524 case Type::IncompleteArray: {
14525 const auto *AX = cast<IncompleteArrayType>(Val: X),
14526 *AY = cast<IncompleteArrayType>(Val: Y);
14527 return Ctx.getIncompleteArrayType(
14528 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14529 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14530 }
14531 case Type::DependentSizedArray: {
14532 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14533 *AY = cast<DependentSizedArrayType>(Val: Y);
14534 return Ctx.getDependentSizedArrayType(
14535 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14536 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14537 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14538 }
14539 case Type::ConstantArray: {
14540 const auto *AX = cast<ConstantArrayType>(Val: X),
14541 *AY = cast<ConstantArrayType>(Val: Y);
14542 assert(AX->getSize() == AY->getSize());
14543 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14544 ? AX->getSizeExpr()
14545 : nullptr;
14546 return Ctx.getConstantArrayType(
14547 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14548 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14549 }
14550 case Type::ArrayParameter: {
14551 const auto *AX = cast<ArrayParameterType>(Val: X),
14552 *AY = cast<ArrayParameterType>(Val: Y);
14553 assert(AX->getSize() == AY->getSize());
14554 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14555 ? AX->getSizeExpr()
14556 : nullptr;
14557 auto ArrayTy = Ctx.getConstantArrayType(
14558 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14559 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14560 return Ctx.getArrayParameterType(Ty: ArrayTy);
14561 }
14562 case Type::Atomic: {
14563 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14564 return Ctx.getAtomicType(
14565 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14566 }
14567 case Type::Complex: {
14568 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14569 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14570 }
14571 case Type::Pointer: {
14572 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14573 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14574 }
14575 case Type::BlockPointer: {
14576 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14577 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14578 }
14579 case Type::ObjCObjectPointer: {
14580 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14581 *PY = cast<ObjCObjectPointerType>(Val: Y);
14582 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14583 }
14584 case Type::MemberPointer: {
14585 const auto *PX = cast<MemberPointerType>(Val: X),
14586 *PY = cast<MemberPointerType>(Val: Y);
14587 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14588 PY->getMostRecentCXXRecordDecl()));
14589 return Ctx.getMemberPointerType(
14590 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14591 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14592 Cls: PX->getMostRecentCXXRecordDecl());
14593 }
14594 case Type::LValueReference: {
14595 const auto *PX = cast<LValueReferenceType>(Val: X),
14596 *PY = cast<LValueReferenceType>(Val: Y);
14597 // FIXME: Preserve PointeeTypeAsWritten.
14598 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14599 SpelledAsLValue: PX->isSpelledAsLValue() ||
14600 PY->isSpelledAsLValue());
14601 }
14602 case Type::RValueReference: {
14603 const auto *PX = cast<RValueReferenceType>(Val: X),
14604 *PY = cast<RValueReferenceType>(Val: Y);
14605 // FIXME: Preserve PointeeTypeAsWritten.
14606 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14607 }
14608 case Type::DependentAddressSpace: {
14609 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14610 *PY = cast<DependentAddressSpaceType>(Val: Y);
14611 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14612 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14613 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14614 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14615 }
14616 case Type::FunctionNoProto: {
14617 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14618 *FY = cast<FunctionNoProtoType>(Val: Y);
14619 assert(FX->getExtInfo() == FY->getExtInfo());
14620 return Ctx.getFunctionNoProtoType(
14621 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14622 Info: FX->getExtInfo());
14623 }
14624 case Type::FunctionProto: {
14625 const auto *FX = cast<FunctionProtoType>(Val: X),
14626 *FY = cast<FunctionProtoType>(Val: Y);
14627 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14628 EPIY = FY->getExtProtoInfo();
14629 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14630 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14631 assert(!EPIX.ExtParameterInfos ||
14632 llvm::equal(
14633 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14634 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14635 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14636 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14637 assert(EPIX.Variadic == EPIY.Variadic);
14638
14639 // FIXME: Can we handle an empty EllipsisLoc?
14640 // Use emtpy EllipsisLoc if X and Y differ.
14641
14642 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14643
14644 QualType R =
14645 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14646 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14647 /*Unqualified=*/true);
14648
14649 SmallVector<QualType, 8> Exceptions;
14650 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14651 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14652 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14653 }
14654 case Type::ObjCObject: {
14655 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14656 assert(
14657 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14658 OY->getProtocols().begin(), OY->getProtocols().end(),
14659 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14660 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14661 }) &&
14662 "protocol lists must be the same");
14663 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14664 Ys: OY->getTypeArgsAsWritten());
14665 return Ctx.getObjCObjectType(
14666 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14667 protocols: OX->getProtocols(),
14668 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14669 }
14670 case Type::ConstantMatrix: {
14671 const auto *MX = cast<ConstantMatrixType>(Val: X),
14672 *MY = cast<ConstantMatrixType>(Val: Y);
14673 assert(MX->getNumRows() == MY->getNumRows());
14674 assert(MX->getNumColumns() == MY->getNumColumns());
14675 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14676 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14677 }
14678 case Type::DependentSizedMatrix: {
14679 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14680 *MY = cast<DependentSizedMatrixType>(Val: Y);
14681 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14682 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14683 return Ctx.getDependentSizedMatrixType(
14684 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14685 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14686 }
14687 case Type::Vector: {
14688 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14689 assert(VX->getNumElements() == VY->getNumElements());
14690 assert(VX->getVectorKind() == VY->getVectorKind());
14691 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14692 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14693 }
14694 case Type::ExtVector: {
14695 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14696 assert(VX->getNumElements() == VY->getNumElements());
14697 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14698 NumElts: VX->getNumElements());
14699 }
14700 case Type::DependentSizedExtVector: {
14701 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14702 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14703 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14704 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14705 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14706 }
14707 case Type::DependentVector: {
14708 const auto *VX = cast<DependentVectorType>(Val: X),
14709 *VY = cast<DependentVectorType>(Val: Y);
14710 assert(VX->getVectorKind() == VY->getVectorKind());
14711 return Ctx.getDependentVectorType(
14712 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14713 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14714 }
14715 case Type::Enum:
14716 case Type::Record:
14717 case Type::InjectedClassName: {
14718 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14719 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14720 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14721 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14722 /*OwnedTag=*/OwnsTag: false);
14723 }
14724 case Type::TemplateSpecialization: {
14725 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14726 *TY = cast<TemplateSpecializationType>(Val: Y);
14727 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14728 Ys: TY->template_arguments());
14729 return Ctx.getTemplateSpecializationType(
14730 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14731 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14732 Y: TY->getTemplateName(),
14733 /*IgnoreDeduced=*/true),
14734 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14735 }
14736 case Type::Decltype: {
14737 const auto *DX = cast<DecltypeType>(Val: X);
14738 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14739 assert(DX->isDependentType());
14740 assert(DY->isDependentType());
14741 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14742 // As Decltype is not uniqued, building a common type would be wasteful.
14743 return QualType(DX, 0);
14744 }
14745 case Type::PackIndexing: {
14746 const auto *DX = cast<PackIndexingType>(Val: X);
14747 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14748 assert(DX->isDependentType());
14749 assert(DY->isDependentType());
14750 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14751 return QualType(DX, 0);
14752 }
14753 case Type::DependentName: {
14754 const auto *NX = cast<DependentNameType>(Val: X),
14755 *NY = cast<DependentNameType>(Val: Y);
14756 assert(NX->getIdentifier() == NY->getIdentifier());
14757 return Ctx.getDependentNameType(
14758 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14759 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14760 }
14761 case Type::OverflowBehavior: {
14762 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14763 *NY = cast<OverflowBehaviorType>(Val: Y);
14764 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14765 return Ctx.getOverflowBehaviorType(
14766 Kind: NX->getBehaviorKind(),
14767 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14768 Y: NY->getUnderlyingType(), QX, QY));
14769 }
14770 case Type::UnaryTransform: {
14771 const auto *TX = cast<UnaryTransformType>(Val: X),
14772 *TY = cast<UnaryTransformType>(Val: Y);
14773 assert(TX->getUTTKind() == TY->getUTTKind());
14774 return Ctx.getUnaryTransformType(
14775 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14776 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14777 Y: TY->getUnderlyingType()),
14778 Kind: TX->getUTTKind());
14779 }
14780 case Type::PackExpansion: {
14781 const auto *PX = cast<PackExpansionType>(Val: X),
14782 *PY = cast<PackExpansionType>(Val: Y);
14783 assert(PX->getNumExpansions() == PY->getNumExpansions());
14784 return Ctx.getPackExpansionType(
14785 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14786 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14787 }
14788 case Type::Pipe: {
14789 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14790 assert(PX->isReadOnly() == PY->isReadOnly());
14791 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14792 : &ASTContext::getWritePipeType;
14793 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14794 }
14795 case Type::TemplateTypeParm: {
14796 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14797 *TY = cast<TemplateTypeParmType>(Val: Y);
14798 assert(TX->getDepth() == TY->getDepth());
14799 assert(TX->getIndex() == TY->getIndex());
14800 assert(TX->isParameterPack() == TY->isParameterPack());
14801 return Ctx.getTemplateTypeParmType(
14802 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14803 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14804 }
14805 }
14806 llvm_unreachable("Unknown Type Class");
14807}
14808
14809static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14810 const Type *Y,
14811 SplitQualType Underlying) {
14812 Type::TypeClass TC = X->getTypeClass();
14813 if (TC != Y->getTypeClass())
14814 return QualType();
14815 switch (TC) {
14816#define UNEXPECTED_TYPE(Class, Kind) \
14817 case Type::Class: \
14818 llvm_unreachable("Unexpected " Kind ": " #Class);
14819#define TYPE(Class, Base)
14820#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14821#include "clang/AST/TypeNodes.inc"
14822
14823#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14824 CANONICAL_TYPE(Atomic)
14825 CANONICAL_TYPE(BitInt)
14826 CANONICAL_TYPE(BlockPointer)
14827 CANONICAL_TYPE(Builtin)
14828 CANONICAL_TYPE(Complex)
14829 CANONICAL_TYPE(ConstantArray)
14830 CANONICAL_TYPE(ArrayParameter)
14831 CANONICAL_TYPE(ConstantMatrix)
14832 CANONICAL_TYPE(Enum)
14833 CANONICAL_TYPE(ExtVector)
14834 CANONICAL_TYPE(FunctionNoProto)
14835 CANONICAL_TYPE(FunctionProto)
14836 CANONICAL_TYPE(IncompleteArray)
14837 CANONICAL_TYPE(HLSLAttributedResource)
14838 CANONICAL_TYPE(HLSLInlineSpirv)
14839 CANONICAL_TYPE(LValueReference)
14840 CANONICAL_TYPE(ObjCInterface)
14841 CANONICAL_TYPE(ObjCObject)
14842 CANONICAL_TYPE(ObjCObjectPointer)
14843 CANONICAL_TYPE(OverflowBehavior)
14844 CANONICAL_TYPE(Pipe)
14845 CANONICAL_TYPE(Pointer)
14846 CANONICAL_TYPE(Record)
14847 CANONICAL_TYPE(RValueReference)
14848 CANONICAL_TYPE(VariableArray)
14849 CANONICAL_TYPE(Vector)
14850#undef CANONICAL_TYPE
14851
14852#undef UNEXPECTED_TYPE
14853
14854 case Type::Adjusted: {
14855 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14856 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14857 if (!Ctx.hasSameType(T1: OX, T2: OY))
14858 return QualType();
14859 // FIXME: It's inefficient to have to unify the original types.
14860 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14861 New: Ctx.getQualifiedType(split: Underlying));
14862 }
14863 case Type::Decayed: {
14864 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14865 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14866 if (!Ctx.hasSameType(T1: OX, T2: OY))
14867 return QualType();
14868 // FIXME: It's inefficient to have to unify the original types.
14869 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14870 Decayed: Ctx.getQualifiedType(split: Underlying));
14871 }
14872 case Type::Attributed: {
14873 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14874 AttributedType::Kind Kind = AX->getAttrKind();
14875 if (Kind != AY->getAttrKind())
14876 return QualType();
14877 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14878 if (!Ctx.hasSameType(T1: MX, T2: MY))
14879 return QualType();
14880 // FIXME: It's inefficient to have to unify the modified types.
14881 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14882 equivalentType: Ctx.getQualifiedType(split: Underlying),
14883 attr: AX->getAttr());
14884 }
14885 case Type::BTFTagAttributed: {
14886 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14887 const BTFTypeTagAttr *AX = BX->getAttr();
14888 // The attribute is not uniqued, so just compare the tag.
14889 if (AX->getBTFTypeTag() !=
14890 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14891 return QualType();
14892 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14893 }
14894 case Type::Auto: {
14895 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14896 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14897 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14898
14899 AutoTypeKeyword KW = AX->getKeyword();
14900 if (KW != AY->getKeyword())
14901 return QualType();
14902
14903 TemplateDecl *CD =
14904 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14905 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14906 SmallVector<TemplateArgument, 8> As;
14907 if (CD &&
14908 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14909 Ys: AY->getTypeConstraintArguments())) {
14910 CD = nullptr; // The arguments differ, so make it unconstrained.
14911 As.clear();
14912 }
14913
14914 // Both auto types can't be dependent, otherwise they wouldn't have been
14915 // sugar. This implies they can't contain unexpanded packs either.
14916 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14917 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14918 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14919 }
14920 case Type::PackIndexing:
14921 case Type::Decltype:
14922 return QualType();
14923 case Type::DeducedTemplateSpecialization:
14924 // FIXME: Try to merge these.
14925 return QualType();
14926 case Type::MacroQualified: {
14927 const auto *MX = cast<MacroQualifiedType>(Val: X),
14928 *MY = cast<MacroQualifiedType>(Val: Y);
14929 const IdentifierInfo *IX = MX->getMacroIdentifier();
14930 if (IX != MY->getMacroIdentifier())
14931 return QualType();
14932 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14933 }
14934 case Type::SubstTemplateTypeParm: {
14935 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14936 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14937 Decl *CD =
14938 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14939 if (!CD)
14940 return QualType();
14941 unsigned Index = SX->getIndex();
14942 if (Index != SY->getIndex())
14943 return QualType();
14944 auto PackIndex = SX->getPackIndex();
14945 if (PackIndex != SY->getPackIndex())
14946 return QualType();
14947 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14948 AssociatedDecl: CD, Index, PackIndex,
14949 Final: SX->getFinal() && SY->getFinal());
14950 }
14951 case Type::ObjCTypeParam:
14952 // FIXME: Try to merge these.
14953 return QualType();
14954 case Type::Paren:
14955 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14956
14957 case Type::TemplateSpecialization: {
14958 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14959 *TY = cast<TemplateSpecializationType>(Val: Y);
14960 TemplateName CTN =
14961 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14962 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14963 if (!CTN.getAsVoidPointer())
14964 return QualType();
14965 SmallVector<TemplateArgument, 8> As;
14966 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14967 Ys: TY->template_arguments()))
14968 return QualType();
14969 return Ctx.getTemplateSpecializationType(
14970 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14971 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14972 }
14973 case Type::Typedef: {
14974 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14975 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14976 if (!CD)
14977 return QualType();
14978 return Ctx.getTypedefType(
14979 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14980 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14981 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14982 }
14983 case Type::TypeOf: {
14984 // The common sugar between two typeof expressions, where one is
14985 // potentially a typeof_unqual and the other is not, we unify to the
14986 // qualified type as that retains the most information along with the type.
14987 // We only return a typeof_unqual type when both types are unqual types.
14988 TypeOfKind Kind = TypeOfKind::Qualified;
14989 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14990 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14991 Kind = TypeOfKind::Unqualified;
14992 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14993 }
14994 case Type::TypeOfExpr:
14995 return QualType();
14996
14997 case Type::UnaryTransform: {
14998 const auto *UX = cast<UnaryTransformType>(Val: X),
14999 *UY = cast<UnaryTransformType>(Val: Y);
15000 UnaryTransformType::UTTKind KX = UX->getUTTKind();
15001 if (KX != UY->getUTTKind())
15002 return QualType();
15003 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
15004 if (!Ctx.hasSameType(T1: BX, T2: BY))
15005 return QualType();
15006 // FIXME: It's inefficient to have to unify the base types.
15007 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
15008 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
15009 }
15010 case Type::Using: {
15011 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
15012 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
15013 if (!CD)
15014 return QualType();
15015 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
15016 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
15017 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
15018 }
15019 case Type::MemberPointer: {
15020 const auto *PX = cast<MemberPointerType>(Val: X),
15021 *PY = cast<MemberPointerType>(Val: Y);
15022 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
15023 assert(Cls == PY->getMostRecentCXXRecordDecl());
15024 return Ctx.getMemberPointerType(
15025 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
15026 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
15027 }
15028 case Type::CountAttributed: {
15029 const auto *DX = cast<CountAttributedType>(Val: X),
15030 *DY = cast<CountAttributedType>(Val: Y);
15031 if (DX->isCountInBytes() != DY->isCountInBytes())
15032 return QualType();
15033 if (DX->isOrNull() != DY->isOrNull())
15034 return QualType();
15035 Expr *CEX = DX->getCountExpr();
15036 Expr *CEY = DY->getCountExpr();
15037 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15038 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
15039 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15040 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15041 DependentDecls: CDX);
15042 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15043 return QualType();
15044 // Two declarations with the same integer constant may still differ in their
15045 // expression pointers, so we need to evaluate them.
15046 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15047 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15048 if (VX != VY)
15049 return QualType();
15050 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15051 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15052 DependentDecls: CDX);
15053 }
15054
15055 case Type::LateParsedAttr:
15056 return QualType();
15057
15058 case Type::PredefinedSugar:
15059 assert(cast<PredefinedSugarType>(X)->getKind() !=
15060 cast<PredefinedSugarType>(Y)->getKind());
15061 return QualType();
15062 }
15063 llvm_unreachable("Unhandled Type Class");
15064}
15065
15066static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15067 SmallVector<SplitQualType, 8> R;
15068 while (true) {
15069 QTotal.addConsistentQualifiers(qs: T.Quals);
15070 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15071 if (NT == QualType(T.Ty, 0))
15072 break;
15073 R.push_back(Elt: T);
15074 T = NT.split();
15075 }
15076 return R;
15077}
15078
15079QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
15080 bool Unqualified) const {
15081 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15082 if (X == Y)
15083 return X;
15084 if (!Unqualified) {
15085 if (X.isCanonical())
15086 return X;
15087 if (Y.isCanonical())
15088 return Y;
15089 }
15090
15091 SplitQualType SX = X.split(), SY = Y.split();
15092 Qualifiers QX, QY;
15093 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15094 // until we reach their underlying "canonical nodes". Note these are not
15095 // necessarily canonical types, as they may still have sugared properties.
15096 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15097 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
15098
15099 // If this is an ArrayType, the element qualifiers are interchangeable with
15100 // the top level qualifiers.
15101 // * In case the canonical nodes are the same, the elements types are already
15102 // the same.
15103 // * Otherwise, the element types will be made the same, and any different
15104 // element qualifiers will be moved up to the top level qualifiers, per
15105 // 'getCommonArrayElementType'.
15106 // In both cases, this means there may be top level qualifiers which differ
15107 // between X and Y. If so, these differing qualifiers are redundant with the
15108 // element qualifiers, and can be removed without changing the canonical type.
15109 // The desired behaviour is the same as for the 'Unqualified' case here:
15110 // treat the redundant qualifiers as sugar, remove the ones which are not
15111 // common to both sides.
15112 bool KeepCommonQualifiers =
15113 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15114
15115 if (SX.Ty != SY.Ty) {
15116 // The canonical nodes differ. Build a common canonical node out of the two,
15117 // unifying their sugar. This may recurse back here.
15118 SX.Ty =
15119 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15120 } else {
15121 // The canonical nodes were identical: We may have desugared too much.
15122 // Add any common sugar back in.
15123 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15124 QX -= SX.Quals;
15125 QY -= SY.Quals;
15126 SX = Xs.pop_back_val();
15127 SY = Ys.pop_back_val();
15128 }
15129 }
15130 if (KeepCommonQualifiers)
15131 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15132 else
15133 assert(QX == QY);
15134
15135 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15136 // related. Walk up these nodes, unifying them and adding the result.
15137 while (!Xs.empty() && !Ys.empty()) {
15138 auto Underlying = SplitQualType(
15139 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15140 SX = Xs.pop_back_val();
15141 SY = Ys.pop_back_val();
15142 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15143 .getTypePtrOrNull();
15144 // Stop at the first pair which is unrelated.
15145 if (!SX.Ty) {
15146 SX.Ty = Underlying.Ty;
15147 break;
15148 }
15149 QX -= Underlying.Quals;
15150 };
15151
15152 // Add back the missing accumulated qualifiers, which were stripped off
15153 // with the sugar nodes we could not unify.
15154 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15155 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15156 return R;
15157}
15158
15159QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15160 assert(Ty->isFixedPointType());
15161
15162 if (Ty->isUnsaturatedFixedPointType())
15163 return Ty;
15164
15165 switch (Ty->castAs<BuiltinType>()->getKind()) {
15166 default:
15167 llvm_unreachable("Not a saturated fixed point type!");
15168 case BuiltinType::SatShortAccum:
15169 return ShortAccumTy;
15170 case BuiltinType::SatAccum:
15171 return AccumTy;
15172 case BuiltinType::SatLongAccum:
15173 return LongAccumTy;
15174 case BuiltinType::SatUShortAccum:
15175 return UnsignedShortAccumTy;
15176 case BuiltinType::SatUAccum:
15177 return UnsignedAccumTy;
15178 case BuiltinType::SatULongAccum:
15179 return UnsignedLongAccumTy;
15180 case BuiltinType::SatShortFract:
15181 return ShortFractTy;
15182 case BuiltinType::SatFract:
15183 return FractTy;
15184 case BuiltinType::SatLongFract:
15185 return LongFractTy;
15186 case BuiltinType::SatUShortFract:
15187 return UnsignedShortFractTy;
15188 case BuiltinType::SatUFract:
15189 return UnsignedFractTy;
15190 case BuiltinType::SatULongFract:
15191 return UnsignedLongFractTy;
15192 }
15193}
15194
15195QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15196 assert(Ty->isFixedPointType());
15197
15198 if (Ty->isSaturatedFixedPointType()) return Ty;
15199
15200 switch (Ty->castAs<BuiltinType>()->getKind()) {
15201 default:
15202 llvm_unreachable("Not a fixed point type!");
15203 case BuiltinType::ShortAccum:
15204 return SatShortAccumTy;
15205 case BuiltinType::Accum:
15206 return SatAccumTy;
15207 case BuiltinType::LongAccum:
15208 return SatLongAccumTy;
15209 case BuiltinType::UShortAccum:
15210 return SatUnsignedShortAccumTy;
15211 case BuiltinType::UAccum:
15212 return SatUnsignedAccumTy;
15213 case BuiltinType::ULongAccum:
15214 return SatUnsignedLongAccumTy;
15215 case BuiltinType::ShortFract:
15216 return SatShortFractTy;
15217 case BuiltinType::Fract:
15218 return SatFractTy;
15219 case BuiltinType::LongFract:
15220 return SatLongFractTy;
15221 case BuiltinType::UShortFract:
15222 return SatUnsignedShortFractTy;
15223 case BuiltinType::UFract:
15224 return SatUnsignedFractTy;
15225 case BuiltinType::ULongFract:
15226 return SatUnsignedLongFractTy;
15227 }
15228}
15229
15230LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15231 if (LangOpts.OpenCL)
15232 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15233
15234 if (LangOpts.CUDA)
15235 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15236
15237 return getLangASFromTargetAS(TargetAS: AS);
15238}
15239
15240unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15241 assert(Ty->isFixedPointType());
15242
15243 const TargetInfo &Target = getTargetInfo();
15244 switch (Ty->castAs<BuiltinType>()->getKind()) {
15245 default:
15246 llvm_unreachable("Not a fixed point type!");
15247 case BuiltinType::ShortAccum:
15248 case BuiltinType::SatShortAccum:
15249 return Target.getShortAccumScale();
15250 case BuiltinType::Accum:
15251 case BuiltinType::SatAccum:
15252 return Target.getAccumScale();
15253 case BuiltinType::LongAccum:
15254 case BuiltinType::SatLongAccum:
15255 return Target.getLongAccumScale();
15256 case BuiltinType::UShortAccum:
15257 case BuiltinType::SatUShortAccum:
15258 return Target.getUnsignedShortAccumScale();
15259 case BuiltinType::UAccum:
15260 case BuiltinType::SatUAccum:
15261 return Target.getUnsignedAccumScale();
15262 case BuiltinType::ULongAccum:
15263 case BuiltinType::SatULongAccum:
15264 return Target.getUnsignedLongAccumScale();
15265 case BuiltinType::ShortFract:
15266 case BuiltinType::SatShortFract:
15267 return Target.getShortFractScale();
15268 case BuiltinType::Fract:
15269 case BuiltinType::SatFract:
15270 return Target.getFractScale();
15271 case BuiltinType::LongFract:
15272 case BuiltinType::SatLongFract:
15273 return Target.getLongFractScale();
15274 case BuiltinType::UShortFract:
15275 case BuiltinType::SatUShortFract:
15276 return Target.getUnsignedShortFractScale();
15277 case BuiltinType::UFract:
15278 case BuiltinType::SatUFract:
15279 return Target.getUnsignedFractScale();
15280 case BuiltinType::ULongFract:
15281 case BuiltinType::SatULongFract:
15282 return Target.getUnsignedLongFractScale();
15283 }
15284}
15285
15286unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15287 assert(Ty->isFixedPointType());
15288
15289 const TargetInfo &Target = getTargetInfo();
15290 switch (Ty->castAs<BuiltinType>()->getKind()) {
15291 default:
15292 llvm_unreachable("Not a fixed point type!");
15293 case BuiltinType::ShortAccum:
15294 case BuiltinType::SatShortAccum:
15295 return Target.getShortAccumIBits();
15296 case BuiltinType::Accum:
15297 case BuiltinType::SatAccum:
15298 return Target.getAccumIBits();
15299 case BuiltinType::LongAccum:
15300 case BuiltinType::SatLongAccum:
15301 return Target.getLongAccumIBits();
15302 case BuiltinType::UShortAccum:
15303 case BuiltinType::SatUShortAccum:
15304 return Target.getUnsignedShortAccumIBits();
15305 case BuiltinType::UAccum:
15306 case BuiltinType::SatUAccum:
15307 return Target.getUnsignedAccumIBits();
15308 case BuiltinType::ULongAccum:
15309 case BuiltinType::SatULongAccum:
15310 return Target.getUnsignedLongAccumIBits();
15311 case BuiltinType::ShortFract:
15312 case BuiltinType::SatShortFract:
15313 case BuiltinType::Fract:
15314 case BuiltinType::SatFract:
15315 case BuiltinType::LongFract:
15316 case BuiltinType::SatLongFract:
15317 case BuiltinType::UShortFract:
15318 case BuiltinType::SatUShortFract:
15319 case BuiltinType::UFract:
15320 case BuiltinType::SatUFract:
15321 case BuiltinType::ULongFract:
15322 case BuiltinType::SatULongFract:
15323 return 0;
15324 }
15325}
15326
15327llvm::FixedPointSemantics
15328ASTContext::getFixedPointSemantics(QualType Ty) const {
15329 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15330 "Can only get the fixed point semantics for a "
15331 "fixed point or integer type.");
15332 if (Ty->isIntegerType())
15333 return llvm::FixedPointSemantics::GetIntegerSemantics(
15334 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15335
15336 bool isSigned = Ty->isSignedFixedPointType();
15337 return llvm::FixedPointSemantics(
15338 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15339 Ty->isSaturatedFixedPointType(),
15340 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15341}
15342
15343llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15344 assert(Ty->isFixedPointType());
15345 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15346}
15347
15348llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15349 assert(Ty->isFixedPointType());
15350 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15351}
15352
15353QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15354 assert(Ty->isUnsignedFixedPointType() &&
15355 "Expected unsigned fixed point type");
15356
15357 switch (Ty->castAs<BuiltinType>()->getKind()) {
15358 case BuiltinType::UShortAccum:
15359 return ShortAccumTy;
15360 case BuiltinType::UAccum:
15361 return AccumTy;
15362 case BuiltinType::ULongAccum:
15363 return LongAccumTy;
15364 case BuiltinType::SatUShortAccum:
15365 return SatShortAccumTy;
15366 case BuiltinType::SatUAccum:
15367 return SatAccumTy;
15368 case BuiltinType::SatULongAccum:
15369 return SatLongAccumTy;
15370 case BuiltinType::UShortFract:
15371 return ShortFractTy;
15372 case BuiltinType::UFract:
15373 return FractTy;
15374 case BuiltinType::ULongFract:
15375 return LongFractTy;
15376 case BuiltinType::SatUShortFract:
15377 return SatShortFractTy;
15378 case BuiltinType::SatUFract:
15379 return SatFractTy;
15380 case BuiltinType::SatULongFract:
15381 return SatLongFractTy;
15382 default:
15383 llvm_unreachable("Unexpected unsigned fixed point type");
15384 }
15385}
15386
15387// Given a list of FMV features, return a concatenated list of the
15388// corresponding backend features (which may contain duplicates).
15389static std::vector<std::string> getFMVBackendFeaturesFor(
15390 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15391 std::vector<std::string> BackendFeats;
15392 llvm::AArch64::ExtensionSet FeatureBits;
15393 for (StringRef F : FMVFeatStrings)
15394 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15395 if (FMVExt->ID)
15396 FeatureBits.enable(E: *FMVExt->ID);
15397 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15398 return BackendFeats;
15399}
15400
15401ParsedTargetAttr
15402ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15403 assert(TD != nullptr);
15404 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15405
15406 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15407 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15408 });
15409 return ParsedAttr;
15410}
15411
15412const llvm::StringMap<bool> &
15413ASTContext::getFunctionFeatureMap(const FunctionDecl *FD) const {
15414 return getFunctionFeatureMap(GD: GlobalDecl().getWithDecl(D: FD));
15415}
15416
15417const llvm::StringMap<bool> &
15418ASTContext::getFunctionFeatureMap(GlobalDecl GD) const {
15419 const auto *FD = GD.getDecl() ? GD.getDecl()->getAsFunction() : nullptr;
15420 if (!FD || !FD->hasAttrs())
15421 return Target->getTargetOpts().FeatureMap;
15422
15423 const Attr *FeatureAttr;
15424 StringRef FeatureText;
15425 if (const auto *TargetAttribute = FD->getAttr<TargetAttr>()) {
15426 FeatureAttr = TargetAttribute;
15427 FeatureText = TargetAttribute->getFeaturesStr();
15428 } else if (const auto *Specific = FD->getAttr<CPUSpecificAttr>()) {
15429 FeatureAttr = Specific;
15430 FeatureText = Specific->getCPUName(Index: GD.getMultiVersionIndex())->getName();
15431 } else if (const auto *Clones = FD->getAttr<TargetClonesAttr>()) {
15432 FeatureAttr = Clones;
15433 FeatureText = Clones->getFeatureStr(Index: GD.getMultiVersionIndex());
15434 } else if (const auto *Version = FD->getAttr<TargetVersionAttr>()) {
15435 FeatureAttr = Version;
15436 FeatureText = Version->getName();
15437 } else {
15438 return Target->getTargetOpts().FeatureMap;
15439 }
15440
15441 auto Key = std::make_pair(x&: FeatureText, y: unsigned(FeatureAttr->getKind()));
15442 auto It = FunctionFeatureMaps.find(Val: Key);
15443 if (It != FunctionFeatureMaps.end())
15444 return *It->second;
15445
15446 auto FeatureMap = std::make_unique<llvm::StringMap<bool>>();
15447 getFunctionFeatureMap(FeatureMap&: *FeatureMap, GD);
15448 return *FunctionFeatureMaps.try_emplace(Key, Args: std::move(FeatureMap))
15449 .first->second;
15450}
15451
15452void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15453 const FunctionDecl *FD) const {
15454 if (FD)
15455 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15456 else
15457 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15458 CPU: Target->getTargetOpts().CPU,
15459 FeatureVec: Target->getTargetOpts().Features);
15460}
15461
15462// Fills in the supplied string map with the set of target features for the
15463// passed in function.
15464void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15465 GlobalDecl GD) const {
15466 StringRef TargetCPU = Target->getTargetOpts().CPU;
15467 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15468 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15469 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15470
15471 // Make a copy of the features as passed on the command line into the
15472 // beginning of the additional features from the function to override.
15473 // AArch64 handles command line option features in parseTargetAttr().
15474 if (!Target->getTriple().isAArch64())
15475 ParsedAttr.Features.insert(
15476 position: ParsedAttr.Features.begin(),
15477 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15478 last: Target->getTargetOpts().FeaturesAsWritten.end());
15479
15480 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15481 TargetCPU = ParsedAttr.CPU;
15482
15483 // Now populate the feature map, first with the TargetCPU which is either
15484 // the default or a new one from the target attribute string. Then we'll use
15485 // the passed in features (FeaturesAsWritten) along with the new ones from
15486 // the attribute.
15487 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15488 FeatureVec: ParsedAttr.Features);
15489 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15490 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15491 Target->getCPUSpecificCPUDispatchFeatures(
15492 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15493 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15494 Features.insert(position: Features.begin(),
15495 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15496 last: Target->getTargetOpts().FeaturesAsWritten.end());
15497 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15498 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15499 if (Target->getTriple().isAArch64()) {
15500 llvm::SmallVector<StringRef, 8> Feats;
15501 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15502 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15503 Features.insert(position: Features.begin(),
15504 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15505 last: Target->getTargetOpts().FeaturesAsWritten.end());
15506 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15507 } else if (Target->getTriple().isRISCV()) {
15508 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15509 std::vector<std::string> Features;
15510 if (VersionStr != "default") {
15511 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15512 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15513 last: ParsedAttr.Features.end());
15514 }
15515 Features.insert(position: Features.begin(),
15516 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15517 last: Target->getTargetOpts().FeaturesAsWritten.end());
15518 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15519 } else if (Target->getTriple().isOSAIX()) {
15520 std::vector<std::string> Features;
15521 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15522 if (VersionStr.starts_with(Prefix: "cpu="))
15523 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15524 else if (VersionStr != "default")
15525 Features = Target->parseTargetAttr(Str: VersionStr).Features;
15526 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15527 } else {
15528 std::vector<std::string> Features;
15529 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15530 if (VersionStr.starts_with(Prefix: "arch="))
15531 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15532 else if (VersionStr != "default")
15533 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15534 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15535 }
15536 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15537 std::vector<std::string> Features;
15538 if (Target->getTriple().isRISCV()) {
15539 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15540 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15541 last: ParsedAttr.Features.end());
15542 } else {
15543 assert(Target->getTriple().isAArch64());
15544 llvm::SmallVector<StringRef, 8> Feats;
15545 TV->getFeatures(Out&: Feats);
15546 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15547 }
15548 Features.insert(position: Features.begin(),
15549 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15550 last: Target->getTargetOpts().FeaturesAsWritten.end());
15551 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15552 } else {
15553 FeatureMap = Target->getTargetOpts().FeatureMap;
15554 }
15555}
15556
15557static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15558 CanQualType KernelNameType,
15559 const FunctionDecl *FD) {
15560 // Host and device compilation may use different ABIs and different ABIs
15561 // may allocate name mangling discriminators differently. A discriminator
15562 // override is used to ensure consistent discriminator allocation across
15563 // host and device compilation.
15564 auto DeviceDiscriminatorOverrider =
15565 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15566 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15567 if (RD->isLambda())
15568 return RD->getDeviceLambdaManglingNumber();
15569 return std::nullopt;
15570 };
15571 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15572 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15573
15574 // Construct a mangled name for the SYCL kernel caller offload entry point.
15575 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15576 // name the SYCL kernel caller offload entry point function. This mangling
15577 // does not suffice to clearly identify symbols that correspond to SYCL
15578 // kernel caller functions, nor is this mangling natural for targets that
15579 // use a non-Itanium ABI.
15580 std::string Buffer;
15581 Buffer.reserve(res_arg: 128);
15582 llvm::raw_string_ostream Out(Buffer);
15583 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15584 std::string KernelName = Out.str();
15585
15586 return {KernelNameType, FD, KernelName};
15587}
15588
15589void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15590 // If the function declaration to register is invalid or dependent, the
15591 // registration attempt is ignored.
15592 if (FD->isInvalidDecl() || FD->isTemplated())
15593 return;
15594
15595 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15596 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15597
15598 // Be tolerant of multiple registration attempts so long as each attempt
15599 // is for the same entity. Callers are obligated to detect and diagnose
15600 // conflicting kernel names prior to calling this function.
15601 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15602 auto IT = SYCLKernels.find(Val: KernelNameType);
15603 assert((IT == SYCLKernels.end() ||
15604 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15605 "SYCL kernel name conflict");
15606 (void)IT;
15607 SYCLKernels.insert(KV: std::make_pair(
15608 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15609}
15610
15611const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15612 CanQualType KernelNameType = getCanonicalType(T);
15613 return SYCLKernels.at(Val: KernelNameType);
15614}
15615
15616const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15617 CanQualType KernelNameType = getCanonicalType(T);
15618 auto IT = SYCLKernels.find(Val: KernelNameType);
15619 if (IT != SYCLKernels.end())
15620 return &IT->second;
15621 return nullptr;
15622}
15623
15624OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15625 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15626 return *OMPTraitInfoVector.back();
15627}
15628
15629const StreamingDiagnostic &clang::
15630operator<<(const StreamingDiagnostic &DB,
15631 const ASTContext::SectionInfo &Section) {
15632 if (Section.Decl)
15633 return DB << Section.Decl;
15634 return DB << "a prior #pragma section";
15635}
15636
15637bool ASTContext::mayExternalize(const Decl *D) const {
15638 bool IsInternalVar =
15639 isa<VarDecl>(Val: D) &&
15640 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15641 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15642 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15643 (D->hasAttr<CUDAConstantAttr>() &&
15644 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15645 // CUDA/HIP: managed variables need to be externalized since it is
15646 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15647 // anonymous name space needs to be externalized to avoid duplicate symbols.
15648 return (IsInternalVar &&
15649 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15650 (D->hasAttr<CUDAGlobalAttr>() &&
15651 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15652 GVA_Internal);
15653}
15654
15655bool ASTContext::shouldExternalize(const Decl *D) const {
15656 return mayExternalize(D) &&
15657 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15658 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15659}
15660
15661StringRef ASTContext::getCUIDHash() const {
15662 if (!CUIDHash.empty())
15663 return CUIDHash;
15664 if (LangOpts.CUID.empty())
15665 return StringRef();
15666 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15667 return CUIDHash;
15668}
15669
15670const CXXRecordDecl *
15671ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15672 assert(ThisClass);
15673 assert(ThisClass->isPolymorphic());
15674 const CXXRecordDecl *PrimaryBase = ThisClass;
15675 while (1) {
15676 assert(PrimaryBase);
15677 assert(PrimaryBase->isPolymorphic());
15678 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15679 auto Base = Layout.getPrimaryBase();
15680 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15681 break;
15682 PrimaryBase = Base;
15683 }
15684 return PrimaryBase;
15685}
15686
15687bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15688 StringRef MangledName) {
15689 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15690 assert(Method->isVirtual());
15691 bool DefaultIncludesPointerAuth =
15692 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15693
15694 if (!DefaultIncludesPointerAuth)
15695 return true;
15696
15697 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15698 if (Existing != ThunksToBeAbbreviated.end())
15699 return Existing->second.contains(key: MangledName.str());
15700
15701 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15702 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15703 auto VtableContext = getVTableContext();
15704 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15705 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15706 for (const auto &Thunk : *ThunkInfos) {
15707 SmallString<256> ElidedName;
15708 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15709 if (Destructor)
15710 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15711 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15712 ElidedNameStream);
15713 else
15714 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15715 ElidedNameStream);
15716 SmallString<256> MangledName;
15717 llvm::raw_svector_ostream mangledNameStream(MangledName);
15718 if (Destructor)
15719 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15720 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15721 mangledNameStream);
15722 else
15723 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15724 mangledNameStream);
15725
15726 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15727 }
15728 }
15729 llvm::StringSet<> SimplifiedThunkNames;
15730 for (auto &ThunkList : Thunks) {
15731 llvm::sort(C&: ThunkList.second);
15732 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15733 }
15734 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15735 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15736 return Result;
15737}
15738
15739bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15740 // Check for trivially-destructible here because non-trivially-destructible
15741 // types will always cause the type and any types derived from it to be
15742 // considered non-trivially-copyable. The same cannot be said for
15743 // trivially-copyable because deleting special members of a type derived from
15744 // a non-trivially-copyable type can cause the derived type to be considered
15745 // trivially copyable.
15746 if (getLangOpts().PointerFieldProtectionTagged)
15747 return !isa<CXXRecordDecl>(Val: RD) ||
15748 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15749 return true;
15750}
15751
15752static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15753 std::vector<PFPField> &Fields, bool IncludeVBases) {
15754 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15755 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15756 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15757 for (unsigned i = 0; i != AT->getSize(); ++i)
15758 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15759 Fields, IncludeVBases: true);
15760 }
15761 }
15762 auto *Decl = Ty->getAsCXXRecordDecl();
15763 // isPFPType() is inherited from bases and members (including via arrays), so
15764 // we can early exit if it is false. Unions are excluded per the API
15765 // documentation.
15766 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15767 return;
15768 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15769 for (FieldDecl *Field : Decl->fields()) {
15770 CharUnits FieldOffset =
15771 Offset +
15772 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15773 if (Ctx.isPFPField(Field))
15774 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15775 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15776 /*IncludeVBases=*/true);
15777 }
15778 // Pass false for IncludeVBases below because vbases are only included in
15779 // layout for top-level types, i.e. not bases or vbases.
15780 for (CXXBaseSpecifier &Base : Decl->bases()) {
15781 if (Base.isVirtual())
15782 continue;
15783 CharUnits BaseOffset =
15784 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15785 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15786 /*IncludeVBases=*/false);
15787 }
15788 if (IncludeVBases) {
15789 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15790 CharUnits BaseOffset =
15791 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15792 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15793 /*IncludeVBases=*/false);
15794 }
15795 }
15796}
15797
15798std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15799 std::vector<PFPField> PFPFields;
15800 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15801 return PFPFields;
15802}
15803
15804bool ASTContext::hasPFPFields(QualType Ty) const {
15805 return !findPFPFields(Ty).empty();
15806}
15807
15808bool ASTContext::isPFPField(const FieldDecl *FD) {
15809 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15810 return RD->isPFPType() && FD->getType()->isPointerType() &&
15811 !FD->hasAttr<NoFieldProtectionAttr>();
15812 return false;
15813}
15814
15815void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15816 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15817 if (!FD)
15818 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15819 if (isPFPField(FD))
15820 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15821}
15822
15823void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15824 if (E->getNumComponents() == 0)
15825 return;
15826 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15827 if (Comp.getKind() != OffsetOfNode::Field)
15828 return;
15829 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15830 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15831}
15832
15833namespace {
15834// PaddingCalculator is a utility class that calculates the padding bits in a
15835// c/c++ type. It traverses the type recursively, collecting occupied
15836// bit intervals, and then computes the padding intervals.
15837// If a byte only contains some padding bits, it gets intervals for only those
15838// bits. This is the case for bit-fields.
15839struct PaddingCalculator {
15840 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15841
15842 void run(QualType Ty) {
15843 OccuppiedIntervals.clear();
15844 Stack.clear();
15845
15846 TySizeInBits = Ctx.getTypeSize(T: Ty);
15847
15848 Stack.push_back(Elt: Data{.StartBitOffset: 0, .Ty: Ty.getCanonicalType(), .VisitVirtualBase: true});
15849 while (!Stack.empty()) {
15850 Data Current = Stack.back();
15851 Stack.pop_back();
15852 Visit(D: Current);
15853 }
15854 MergeOccuppiedIntervals();
15855 }
15856
15857 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15858 llvm::SmallVector<ASTContext::BitInterval> Results;
15859 if (OccuppiedIntervals.size() == 1 &&
15860 OccuppiedIntervals.front().First == 0 &&
15861 OccuppiedIntervals.front().Last == TySizeInBits) {
15862 return Results;
15863 }
15864 Results.reserve(N: OccuppiedIntervals.size() + 1);
15865 uint64_t CurrentPos = 0;
15866 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15867 if (OccupiedInterval.First > CurrentPos) {
15868 Results.push_back(
15869 Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: OccupiedInterval.First});
15870 }
15871 CurrentPos = OccupiedInterval.Last;
15872 }
15873 if (TySizeInBits > CurrentPos) {
15874 Results.push_back(Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: TySizeInBits});
15875 }
15876 return Results;
15877 }
15878
15879private:
15880 struct Data {
15881 uint64_t StartBitOffset;
15882 QualType Ty;
15883 bool VisitVirtualBase;
15884 };
15885
15886 // Return the number of non padding bits of a scalar type.
15887 //
15888 // The property that we specifically care about here is whether the scalar
15889 // type has padding bits, i.e. are there bits in the type which are not
15890 // specified by the ABI.
15891 //
15892 // We currently don't care about this anywhere else in clang: layout cares
15893 // about the ABI size, calling convention code cares about specific types,
15894 // but nothing cares about padding specifically. And it's not something we can
15895 // easily query from LLVM due to the type system mismatches.
15896 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15897 // DataLayout methods aren't really designed for this usage.
15898 //
15899 // Therefore, it is better to explicitly list all the scalar types
15900 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15901 // double.
15902 //
15903 // FIXME: There are likely other scalar types we need to think about here, as
15904 // brought up in review for #215823:
15905 // - bool
15906 // - enums(both with/without fixed underlying type)
15907 // - nullptr_t
15908 // - more?
15909 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15910 if (const auto *BIT = Ty->getAs<BitIntType>())
15911 return BIT->getNumBits();
15912
15913 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15914 if (BT->getKind() == BuiltinType::LongDouble &&
15915 &Ctx.getTargetInfo().getLongDoubleFormat() ==
15916 &llvm::APFloat::x87DoubleExtended())
15917 return llvm::APFloat::getSizeInBits(
15918 Sem: Ctx.getTargetInfo().getLongDoubleFormat());
15919 }
15920
15921 return Ctx.getTypeSize(T: Ty);
15922 }
15923
15924 void Visit(const Data &D) {
15925 if (auto *AT = dyn_cast<ConstantArrayType>(Val: D.Ty)) {
15926 VisitArray(AT, StartBitOffset: D.StartBitOffset);
15927 return;
15928 }
15929
15930 if (auto *Record = D.Ty->getAsRecordDecl()) {
15931 VisitStruct(R: Record, StartBitOffset: D.StartBitOffset, VisitVirtualBase: D.VisitVirtualBase);
15932 return;
15933 }
15934
15935 if (D.Ty->isAtomicType()) {
15936 auto Unwrapped = D;
15937 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15938 Stack.push_back(Elt: Unwrapped);
15939 return;
15940 }
15941
15942 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15943 VisitComplex(CT: Complex, StartBitOffset: D.StartBitOffset);
15944 return;
15945 }
15946
15947 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15948 VisitVector(VT, StartBitOffset: D.StartBitOffset);
15949 return;
15950 }
15951
15952 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15953 VisitBitInt(Ty: BITy, StartBitOffset: D.StartBitOffset);
15954 return;
15955 }
15956
15957 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: D.Ty);
15958 OccuppiedIntervals.push_back(
15959 Elt: ASTContext::BitInterval{.First: D.StartBitOffset, .Last: D.StartBitOffset + SizeBit});
15960 }
15961
15962 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15963 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15964 ++ArrIndex) {
15965
15966 QualType ElementQualType = AT->getElementType();
15967 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15968 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15969 auto Offset = ElementSize.alignTo(Align: ElementAlign);
15970
15971 Stack.push_back(Elt: Data{
15972 .StartBitOffset: StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15973 .Ty: ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15974 }
15975 }
15976
15977 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15978 bool VisitVirtualBase) {
15979 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(D: R);
15980 auto *CXXRecord = dyn_cast<CXXRecordDecl>(Val: R);
15981
15982 unsigned PointerSizeInBits = Ctx.getTypeSize(T: Ctx.NullPtrTy);
15983
15984 if (CXXRecord) {
15985 if (ASTLayout.hasOwnVFPtr()) {
15986 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15987 .First: StartBitOffset, .Last: StartBitOffset + PointerSizeInBits});
15988 }
15989
15990 if (ASTLayout.hasOwnVBPtr()) {
15991 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15992 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15993 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15994 .First: StartVBPtr, .Last: StartVBPtr + PointerSizeInBits});
15995 }
15996
15997 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15998 const CXXBaseSpecifier &Base, auto GetOffset) {
15999 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
16000 if (!BaseRecord) {
16001 return;
16002 }
16003 auto BaseOffset =
16004 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
16005
16006 Stack.push_back(
16007 Elt: Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
16008 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
16009 false});
16010 };
16011
16012 for (auto Base : CXXRecord->bases()) {
16013 if (!Base.isVirtual()) {
16014 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
16015 }
16016 }
16017
16018 if (VisitVirtualBase) {
16019 for (auto VBase : CXXRecord->vbases()) {
16020 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
16021 }
16022 }
16023 }
16024
16025 for (auto *Field : R->fields()) {
16026 // Treat unnamed bitfields as padding.
16027 if (Field->isUnnamedBitField())
16028 continue;
16029
16030 auto FieldOffset = ASTLayout.getFieldOffset(FieldNo: Field->getFieldIndex());
16031 if (Field->isBitField()) {
16032 VisitBitfield(Field, StartBitOffset: StartBitOffset + FieldOffset);
16033 } else {
16034 Stack.push_back(Elt: Data{.StartBitOffset: StartBitOffset + FieldOffset,
16035 .Ty: Field->getType().getCanonicalType(),
16036 /*VisitVirtualBase*/ true});
16037 }
16038 }
16039 }
16040
16041 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
16042 assert(Field->isBitField() && !Field->isUnnamedBitField());
16043 if (Field->isZeroLengthBitField())
16044 return;
16045
16046 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
16047
16048 // Oversized bit-fields (declared width larger than the field type) occupy
16049 // only the type's width. The extra declared bits are padding and follow
16050 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
16051 // In case where the bitfield can only have values with a range smaller than
16052 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
16053 // within the bitfield are for sign or zero extension. These are considered
16054 // occupied as well.
16055 const uint64_t OccupiedSizeInBits =
16056 std::min(a: DeclaredSizeInBits, b: Ctx.getTypeSize(T: Field->getType()));
16057
16058 if (Ctx.getTargetInfo().isLittleEndian()) {
16059 OccuppiedIntervals.push_back(
16060 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16061 return;
16062 }
16063
16064 // In big endian mode, the sequence of occupied bits traverses bytes in
16065 // increasing address order, just like in little endian. However, within
16066 // each byte, the traversal starts from the most significant bit. This is
16067 // where it differs from little endian.
16068 //
16069 // If the interval contains whole bytes in the middle, then for these
16070 // nothing changes, and they constitute a contiguous interval. However for
16071 // the partially occupied bytes in either end, if present, their bit
16072 // intervals need to be adjusted so that they count from the MSB instead.
16073 //
16074 // Occupied bits are allocated first, and any padding follows them.
16075 const uint64_t Start = StartBitOffset;
16076 const uint64_t End = Start + OccupiedSizeInBits;
16077 const uint64_t CharWidth = Ctx.getCharWidth();
16078
16079 // Special case: all the occupied bits are contained within a single byte.
16080 const uint64_t ByteStart = llvm::alignDown(Value: Start, Align: CharWidth);
16081 const uint64_t ByteEnd = llvm::alignTo(Value: End, Align: CharWidth);
16082 if (ByteStart == ByteEnd - CharWidth) {
16083 const uint64_t Length = End - Start;
16084 const uint64_t Offset = Start - ByteStart;
16085 OccuppiedIntervals.push_back(
16086 Elt: {.First: ByteEnd - Offset - Length, .Last: ByteEnd - Offset});
16087 return;
16088 }
16089
16090 // Compute the contiguous interval in the middle, comprised of whole bytes,
16091 // if any.
16092 const uint64_t MiddleIntervalStart = llvm::alignTo(Value: Start, Align: CharWidth);
16093 const uint64_t MiddleIntervalEnd = llvm::alignDown(Value: End, Align: CharWidth);
16094 if (MiddleIntervalStart != MiddleIntervalEnd)
16095 OccuppiedIntervals.push_back(Elt: {.First: MiddleIntervalStart, .Last: MiddleIntervalEnd});
16096
16097 // Compute the partially occupied first byte's interval, if any, counting
16098 // from the MSB.
16099 if (Start != MiddleIntervalStart) {
16100 const uint64_t Length = MiddleIntervalStart - Start;
16101 OccuppiedIntervals.push_back(Elt: {.First: ByteStart, .Last: ByteStart + Length});
16102 }
16103
16104 // Compute the partially occupied last byte's interval, if any, counting
16105 // from the MSB.
16106 if (End != MiddleIntervalEnd) {
16107 const uint64_t Length = End - MiddleIntervalEnd;
16108 OccuppiedIntervals.push_back(Elt: {.First: ByteEnd - Length, .Last: ByteEnd});
16109 }
16110 }
16111
16112 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16113 QualType ElementQualType = CT->getElementType().getCanonicalType();
16114 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
16115 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
16116 auto ImgOffset = ElementSize.alignTo(Align: ElementAlign);
16117
16118 Stack.push_back(
16119 Elt: Data{.StartBitOffset: StartBitOffset, .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16120 Stack.push_back(
16121 Elt: Data{.StartBitOffset: StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16122 .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16123 }
16124
16125 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16126 if (VT->isPackedVectorBoolType(ctx: Ctx)) {
16127 VisitPackedBooleanVector(VTy: VT, StartBitOffset);
16128 return;
16129 }
16130
16131 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: VT->getElementType()) *
16132 VT->getNumElements();
16133 OccuppiedIntervals.push_back(
16134 Elt: ASTContext::BitInterval{.First: StartBitOffset, .Last: StartBitOffset + SizeBit});
16135 }
16136
16137 /// Compute the occupied bit intervals for a BitInt.
16138 ///
16139 /// In the case of little endian, the occupied bits are always contiguous so a
16140 /// single interval is sufficient. However in big endian, the intervals can be
16141 /// disjoint.
16142 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16143 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16144
16145 if (Ctx.getTargetInfo().isLittleEndian()) {
16146 OccuppiedIntervals.push_back(
16147 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16148 return;
16149 }
16150
16151 // In big endian mode, the layout of a BitInt in memory has its bytes in
16152 // reverse order, and is pictured in this order:
16153 // 1. Fully padding bytes.
16154 // 2. One partially occupied byte, with padding at the most significant
16155 // bits. ("remaining occupied bits")
16156 // 3. A sequence of fully occupied bytes up until the end of the storage.
16157 const uint64_t StorageSizeInBits = Ctx.getTypeSize(T: Ty);
16158 const uint64_t CharWidth = Ctx.getCharWidth();
16159 const uint64_t NumFullyPaddingBytes =
16160 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16161 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16162 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16163
16164 // Partially occupied byte
16165 if (NumRemainingOccupiedBits > 0)
16166 OccuppiedIntervals.push_back(
16167 Elt: {.First: StartBitOffset + NumFullyPaddingBytes * CharWidth,
16168 .Last: StartBitOffset + NumFullyPaddingBytes * CharWidth +
16169 NumRemainingOccupiedBits});
16170
16171 // Fully occupied bytes
16172 if (NumFullyOccupiedBytes > 0)
16173 OccuppiedIntervals.push_back(Elt: {.First: StartBitOffset + StorageSizeInBits -
16174 NumFullyOccupiedBytes * CharWidth,
16175 .Last: StartBitOffset + StorageSizeInBits});
16176 }
16177
16178 void VisitPackedBooleanVector(const VectorType *VTy,
16179 uint64_t StartBitOffset) {
16180 const uint64_t CharWidth = Ctx.getCharWidth();
16181 assert(StartBitOffset % CharWidth == 0 &&
16182 "Expected aligned packed boolean vector");
16183 assert(VTy->isPackedVectorBoolType(Ctx));
16184 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16185
16186 if (Ctx.getTargetInfo().isLittleEndian()) {
16187 OccuppiedIntervals.push_back(
16188 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16189 return;
16190 }
16191
16192 // Only the sequence of bytes containing occupied bits has its order
16193 // reversed, but the bits within each byte are still counted from the least
16194 // significant bit. So if there are fully padding bytes, they reside at the
16195 // higher addresses in both endiannesses.
16196 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16197 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16198
16199 uint64_t Start = StartBitOffset;
16200 // Partially occupied byte at the beginning
16201 if (NumRemainingOccupiedBits > 0) {
16202 const uint64_t ByteEnd = Start + CharWidth;
16203 OccuppiedIntervals.push_back(Elt: {.First: Start, .Last: Start + NumRemainingOccupiedBits});
16204 Start = ByteEnd;
16205 }
16206
16207 // The remaining fully occupied bytes form a contiguous interval
16208 if (NumFullyOccupiedBytes > 0) {
16209 OccuppiedIntervals.push_back(
16210 Elt: {.First: Start, .Last: Start + NumFullyOccupiedBytes * CharWidth});
16211 }
16212 }
16213
16214 void MergeOccuppiedIntervals() {
16215 std::sort(first: OccuppiedIntervals.begin(), last: OccuppiedIntervals.end(),
16216 comp: [](const ASTContext::BitInterval &lhs,
16217 const ASTContext::BitInterval &rhs) {
16218 return std::tie(args: lhs.First, args: lhs.Last) <
16219 std::tie(args: rhs.First, args: rhs.Last);
16220 });
16221
16222 llvm::SmallVector<ASTContext::BitInterval> Merged;
16223 Merged.reserve(N: OccuppiedIntervals.size());
16224
16225 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16226 if (Merged.empty()) {
16227 Merged.push_back(Elt: NextInterval);
16228 continue;
16229 }
16230 auto &LastInterval = Merged.back();
16231
16232 if (NextInterval.First > LastInterval.Last) {
16233 Merged.push_back(Elt: NextInterval);
16234 } else {
16235 LastInterval.Last = std::max(a: LastInterval.Last, b: NextInterval.Last);
16236 }
16237 }
16238
16239 OccuppiedIntervals = Merged;
16240 }
16241
16242 const ASTContext &Ctx;
16243 // unsigned PointerSizeInBits;
16244 uint64_t TySizeInBits = 0;
16245 llvm::SmallVector<Data> Stack;
16246 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16247};
16248} // namespace
16249
16250llvm::ArrayRef<ASTContext::BitInterval>
16251ASTContext::getPaddingIntervals(QualType Ty) const {
16252 Ty = Ty.getCanonicalType();
16253 auto cached = PaddingIntervalCache.find(Val: Ty);
16254 if (cached != PaddingIntervalCache.end())
16255 return cached->second;
16256
16257 PaddingCalculator pc{*this};
16258 pc.run(Ty);
16259
16260 auto [itr, res] =
16261 PaddingIntervalCache.insert_or_assign(Key: Ty, Val: pc.GetPaddingIntervals());
16262 assert(res && "Failed to insert?");
16263
16264 return itr->second;
16265}
16266