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/ASTMutationListener.h"
19#include "clang/AST/ASTStructuralEquivalence.h"
20#include "clang/AST/ASTTypeTraits.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/AttrIterator.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclContextInternals.h"
29#include "clang/AST/DeclObjC.h"
30#include "clang/AST/DeclOpenMP.h"
31#include "clang/AST/DeclTemplate.h"
32#include "clang/AST/DeclarationName.h"
33#include "clang/AST/DependenceFlags.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
36#include "clang/AST/ExternalASTSource.h"
37#include "clang/AST/Mangle.h"
38#include "clang/AST/MangleNumberingContext.h"
39#include "clang/AST/NestedNameSpecifier.h"
40#include "clang/AST/ParentMapContext.h"
41#include "clang/AST/RawCommentList.h"
42#include "clang/AST/RecordLayout.h"
43#include "clang/AST/Stmt.h"
44#include "clang/AST/TemplateBase.h"
45#include "clang/AST/TemplateName.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
48#include "clang/AST/UnresolvedSet.h"
49#include "clang/AST/VTableBuilder.h"
50#include "clang/Basic/AddressSpaces.h"
51#include "clang/Basic/Builtins.h"
52#include "clang/Basic/CommentOptions.h"
53#include "clang/Basic/DiagnosticAST.h"
54#include "clang/Basic/ExceptionSpecificationType.h"
55#include "clang/Basic/IdentifierTable.h"
56#include "clang/Basic/LLVM.h"
57#include "clang/Basic/LangOptions.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
60#include "clang/Basic/NoSanitizeList.h"
61#include "clang/Basic/ObjCRuntime.h"
62#include "clang/Basic/ProfileList.h"
63#include "clang/Basic/SourceLocation.h"
64#include "clang/Basic/SourceManager.h"
65#include "clang/Basic/Specifiers.h"
66#include "clang/Basic/TargetCXXABI.h"
67#include "clang/Basic/TargetInfo.h"
68#include "clang/Basic/XRayLists.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
108enum FloatingRank {
109 BFloat16Rank,
110 Float16Rank,
111 HalfRank,
112 FloatRank,
113 DoubleRank,
114 LongDoubleRank,
115 Float128Rank,
116 Ibm128Rank
117};
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
121static SmallVector<SourceLocation, 2>
122getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Val&: Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(Val: D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
196 if (isa<TemplateTypeParmDecl>(Val: D) ||
197 isa<NonTypeTemplateParmDecl>(Val: D) ||
198 isa<TemplateTemplateParmDecl>(Val: D))
199 return {};
200
201 SmallVector<SourceLocation, 2> Locations;
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
209 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
210 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
211 isa<ClassTemplateSpecializationDecl>(Val: D) ||
212 // Allow association with Y across {} in `typedef struct X {} Y`.
213 isa<TypedefDecl>(Val: D))
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(Args&: BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
245RawComment *ASTContext::getRawCommentNoCacheImpl(
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Val&: Key);
258 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(x: LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
276 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
277 isa<ObjCPropertyDecl>(Val: D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
282 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
283 Offset: OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(C: CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
326RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
335 if (ExternalSource && !CommentsLoaded) {
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
359void ASTContext::addComment(const RawComment &RC) {
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
363}
364
365const RawComment *
366ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Val: Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(Original: MI, Comment: *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Val&: Key);
390 D = &adjustDeclToTemplate(D: *D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(Val: D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
463void ASTContext::cacheRawComment(RawCommentLookupKey Original,
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Key: Original, Args: &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
470 CommentlessRedeclChains.erase(Val: CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
475 SmallVectorImpl<const NamedDecl *> &Redeclared) {
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(Sel: ObjCMethod->getSelector(),
485 isInstance: ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(Elt: RedeclaredMethod);
487 }
488 }
489}
490
491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(D: *D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(D: *D);
532
533 if (RawComments.count(Val: D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInThisFile)) {
544 cacheRawComment(Original: D, Comment: *DocComment);
545 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
553comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
562 comments::FullComment *CFC =
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
568comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
569 const RawComment *RC = getRawCommentNoCache(Key: D);
570 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
571}
572
573comments::FullComment *ASTContext::getCommentForDecl(
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(D: *D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Val: Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
587 comments::FullComment *CFC = cloneFullComment(FC, D);
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
596 if (!RC) {
597 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
598 SmallVector<const NamedDecl*, 8> Overridden;
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
606 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
622 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
628 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
645 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
659 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(D: OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
681 TemplateTemplateParmDecl *Parm) {
682 ID.AddInteger(I: Parm->getDepth());
683 ID.AddInteger(I: Parm->getPosition());
684 ID.AddBoolean(B: Parm->isParameterPack());
685 ID.AddInteger(I: Parm->templateParameterKind());
686
687 TemplateParameterList *Params = Parm->getTemplateParameters();
688 ID.AddInteger(I: Params->size());
689 for (TemplateParameterList::const_iterator P = Params->begin(),
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
693 ID.AddInteger(I: 0);
694 ID.AddBoolean(B: TTP->isParameterPack());
695 ID.AddInteger(
696 I: TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
701 ID.AddInteger(I: 1);
702 ID.AddBoolean(B: NTTP->isParameterPack());
703 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(B: true);
707 ID.AddInteger(I: NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(B: false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
718 ID.AddInteger(I: 2);
719 Profile(ID, C, Parm: TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
724ASTContext::getCanonicalTemplateTemplateParmDecl(
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
729 llvm::FoldingSetInsertToken Token;
730 CanonicalTemplateTemplateParm *Canonical =
731 CanonTemplateTemplateParms.lookup(ID, Token);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
736 TemplateParameterList *Params = TTP->getTemplateParameters();
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(N: Params->size());
739 for (TemplateParameterList::const_iterator P = Params->begin(),
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
745 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
746 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
747 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
748 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 NumExpanded: TTP->getNumExpansionParameters());
750 CanonParams.push_back(Elt: NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
752 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
753 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
754 NonTypeTemplateParmDecl *Param;
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
757 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
762 }
763
764 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
765 StartLoc: SourceLocation(),
766 IdLoc: SourceLocation(),
767 D: NTTP->getDepth(),
768 P: NTTP->getPosition(), Id: nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
774 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
775 StartLoc: SourceLocation(),
776 IdLoc: SourceLocation(),
777 D: NTTP->getDepth(),
778 P: NTTP->getPosition(), Id: nullptr,
779 T,
780 ParameterPack: NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Elt: Param);
784 } else
785 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
786 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
787 }
788
789 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
790 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
791 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
792 ParameterKind: TTP->templateParameterKind(),
793 /*Typename=*/false,
794 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
795 Params: CanonParams, RAngleLoc: SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.insert(N: Canonical, Token);
806 return CanonTTP;
807}
808
809TemplateTemplateParmDecl *
810ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
814 llvm::FoldingSetInsertToken Token;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.lookup(ID, Token);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
820TemplateTemplateParmDecl *
821ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
825 llvm::FoldingSetInsertToken Token;
826 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
827 return Existing->getParam();
828 CanonTemplateTemplateParms.insert(
829 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
830 return CanonTTP;
831}
832
833/// For the purposes of overflow pattern exclusion, does this match the
834/// while(i--) pattern?
835static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
836 if (UO->getOpcode() != UO_PostDec)
837 return false;
838
839 if (!UO->getType()->isUnsignedIntegerType())
840 return false;
841
842 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
843 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
844 Kind: LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
845 return false;
846
847 // all Parents (usually just one) must be a WhileStmt
848 return llvm::all_of(
849 Range: Ctx.getParentMapContext().getParents(Node: *UO),
850 P: [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
851}
852
853bool ASTContext::isUnaryOverflowPatternExcluded(const UnaryOperator *UO) {
854 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
855 // ... like -1UL;
856 if (UO->getOpcode() == UO_Minus &&
857 getLangOpts().isOverflowPatternExcluded(
858 Kind: LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
859 UO->isIntegerConstantExpr(Ctx: *this)) {
860 return true;
861 }
862
863 if (matchesPostDecrInWhile(UO, Ctx&: *this))
864 return true;
865
866 return false;
867}
868
869/// Check if a type can have its sanitizer instrumentation elided based on its
870/// presence within an ignorelist.
871bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
872 const QualType &Ty) const {
873 std::string TyName = Ty.getUnqualifiedType().getAsString(Policy: getPrintingPolicy());
874 return NoSanitizeL->containsType(Mask, MangledTypeName: TyName);
875}
876
877TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
878 auto Kind = getTargetInfo().getCXXABI().getKind();
879 return getLangOpts().CXXABI.value_or(u&: Kind);
880}
881
882CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
884
885 switch (getCXXABIKind()) {
886 case TargetCXXABI::AppleARM64:
887 case TargetCXXABI::Fuchsia:
888 case TargetCXXABI::GenericARM: // Same as Itanium at this level
889 case TargetCXXABI::iOS:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(Ctx&: *this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(Ctx&: *this);
899 }
900 llvm_unreachable("Invalid CXXABI type!");
901}
902
903interp::Context &ASTContext::getInterpContext() const {
904 if (!InterpContext) {
905 InterpContext.reset(p: new interp::Context(const_cast<ASTContext &>(*this)));
906 }
907 return *InterpContext;
908}
909
910ParentMapContext &ASTContext::getParentMapContext() {
911 if (!ParentMapCtx)
912 ParentMapCtx.reset(p: new ParentMapContext(*this));
913 return *ParentMapCtx;
914}
915
916static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
917 const LangOptions &LangOpts) {
918 switch (LangOpts.getAddressSpaceMapMangling()) {
919 case LangOptions::ASMM_Target:
920 return TI.useAddressSpaceMapMangling();
921 case LangOptions::ASMM_On:
922 return true;
923 case LangOptions::ASMM_Off:
924 return false;
925 }
926 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
927}
928
929ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
930 IdentifierTable &idents, SelectorTable &sels,
931 Builtin::Context &builtins, TranslationUnitKind TUKind)
932 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
933 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
934 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
935 DependentSizedMatrixTypes(this_()),
936 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
937 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
938 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
939 AttributedTypes(this_()), DependentBitIntTypes(this_()),
940 HLSLAttributedResourceTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
943 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
953 addTranslationUnitDecl();
954}
955
956void ASTContext::cleanup() {
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
969 const ASTRecordLayout *>::iterator
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(Ctx&: *this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(Ctx&: *this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 CtorClosureDefaultArgs.clear();
993
994 for (const auto &Value : ModuleInitializers)
995 Value.second->~PerModuleInitializers();
996 ModuleInitializers.clear();
997
998 TUDecl = nullptr;
999 XRayFilter.reset();
1000 NoSanitizeL.reset();
1001}
1002
1003ASTContext::~ASTContext() { cleanup(); }
1004
1005void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1006 TraversalScope = TopLevelDecls;
1007 getParentMapContext().clear();
1008}
1009
1010void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1011 Deallocations.push_back(Elt: {Callback, Data});
1012}
1013
1014void
1015ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1016 ExternalSource = std::move(Source);
1017}
1018
1019void ASTContext::PrintStats() const {
1020 llvm::errs() << "\n*** AST Context Stats:\n";
1021 llvm::errs() << " " << Types.size() << " types total.\n";
1022
1023 unsigned counts[] = {
1024#define TYPE(Name, Parent) 0,
1025#define ABSTRACT_TYPE(Name, Parent)
1026#include "clang/AST/TypeNodes.inc"
1027 0 // Extra
1028 };
1029
1030 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1031 Type *T = Types[i];
1032 counts[(unsigned)T->getTypeClass()]++;
1033 }
1034
1035 unsigned Idx = 0;
1036 unsigned TotalBytes = 0;
1037#define TYPE(Name, Parent) \
1038 if (counts[Idx]) \
1039 llvm::errs() << " " << counts[Idx] << " " << #Name \
1040 << " types, " << sizeof(Name##Type) << " each " \
1041 << "(" << counts[Idx] * sizeof(Name##Type) \
1042 << " bytes)\n"; \
1043 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1044 ++Idx;
1045#define ABSTRACT_TYPE(Name, Parent)
1046#include "clang/AST/TypeNodes.inc"
1047
1048 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1049
1050 // Implicit special member functions.
1051 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1052 << NumImplicitDefaultConstructors
1053 << " implicit default constructors created\n";
1054 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1055 << NumImplicitCopyConstructors
1056 << " implicit copy constructors created\n";
1057 if (getLangOpts().CPlusPlus)
1058 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1059 << NumImplicitMoveConstructors
1060 << " implicit move constructors created\n";
1061 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1062 << NumImplicitCopyAssignmentOperators
1063 << " implicit copy assignment operators created\n";
1064 if (getLangOpts().CPlusPlus)
1065 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1066 << NumImplicitMoveAssignmentOperators
1067 << " implicit move assignment operators created\n";
1068 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1069 << NumImplicitDestructors
1070 << " implicit destructors created\n";
1071
1072 if (ExternalSource) {
1073 llvm::errs() << "\n";
1074 ExternalSource->PrintStats();
1075 }
1076
1077 BumpAlloc.PrintStats();
1078}
1079
1080void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1081 bool NotifyListeners) {
1082 if (NotifyListeners)
1083 if (auto *Listener = getASTMutationListener();
1084 Listener && !ND->isUnconditionallyVisible())
1085 Listener->RedefinedHiddenDefinition(D: ND, M);
1086
1087 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1088}
1089
1090void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1091 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1092 if (It == MergedDefModules.end())
1093 return;
1094
1095 auto &Merged = It->second;
1096 llvm::DenseSet<Module*> Found;
1097 for (Module *&M : Merged)
1098 if (!Found.insert(V: M).second)
1099 M = nullptr;
1100 llvm::erase(C&: Merged, V: nullptr);
1101}
1102
1103ArrayRef<Module *>
1104ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1105 auto MergedIt =
1106 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1107 if (MergedIt == MergedDefModules.end())
1108 return {};
1109 return MergedIt->second;
1110}
1111
1112void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1113 if (LazyInitializers.empty())
1114 return;
1115
1116 auto *Source = Ctx.getExternalSource();
1117 assert(Source && "lazy initializers but no external source");
1118
1119 auto LazyInits = std::move(LazyInitializers);
1120 LazyInitializers.clear();
1121
1122 for (auto ID : LazyInits)
1123 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1124
1125 assert(LazyInitializers.empty() &&
1126 "GetExternalDecl for lazy module initializer added more inits");
1127}
1128
1129void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1130 // One special case: if we add a module initializer that imports another
1131 // module, and that module's only initializer is an ImportDecl, simplify.
1132 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1133 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1134
1135 // Maybe the ImportDecl does nothing at all. (Common case.)
1136 if (It == ModuleInitializers.end())
1137 return;
1138
1139 // Maybe the ImportDecl only imports another ImportDecl.
1140 auto &Imported = *It->second;
1141 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1142 Imported.resolve(Ctx&: *this);
1143 auto *OnlyDecl = Imported.Initializers.front();
1144 if (isa<ImportDecl>(Val: OnlyDecl))
1145 D = OnlyDecl;
1146 }
1147 }
1148
1149 auto *&Inits = ModuleInitializers[M];
1150 if (!Inits)
1151 Inits = new (*this) PerModuleInitializers;
1152 Inits->Initializers.push_back(Elt: D);
1153}
1154
1155void ASTContext::addLazyModuleInitializers(Module *M,
1156 ArrayRef<GlobalDeclID> IDs) {
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1161 From: IDs.begin(), To: IDs.end());
1162}
1163
1164ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1165 auto It = ModuleInitializers.find(Val: M);
1166 if (It == ModuleInitializers.end())
1167 return {};
1168
1169 auto *Inits = It->second;
1170 Inits->resolve(Ctx&: *this);
1171 return Inits->Initializers;
1172}
1173
1174void ASTContext::setCurrentNamedModule(Module *M) {
1175 assert(M->isNamedModule());
1176 assert(!CurrentCXXNamedModule &&
1177 "We should set named module for ASTContext for only once");
1178 CurrentCXXNamedModule = M;
1179}
1180
1181bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1182 if (!M1 != !M2)
1183 return false;
1184
1185 /// Get the representative module for M. The representative module is the
1186 /// first module unit for a specific primary module name. So that the module
1187 /// units have the same representative module belongs to the same module.
1188 ///
1189 /// The process is helpful to reduce the expensive string operations.
1190 auto GetRepresentativeModule = [this](const Module *M) {
1191 auto Iter = SameModuleLookupSet.find(Val: M);
1192 if (Iter != SameModuleLookupSet.end())
1193 return Iter->second;
1194
1195 const Module *RepresentativeModule =
1196 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1197 .first->second;
1198 SameModuleLookupSet[M] = RepresentativeModule;
1199 return RepresentativeModule;
1200 };
1201
1202 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1203 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1204}
1205
1206ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1207 if (!ExternCContext)
1208 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1209
1210 return ExternCContext;
1211}
1212
1213BuiltinTemplateDecl *
1214ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1215 const IdentifierInfo *II) const {
1216 auto *BuiltinTemplate =
1217 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1218 BuiltinTemplate->setImplicit();
1219 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1220
1221 return BuiltinTemplate;
1222}
1223
1224#define BuiltinTemplate(BTName) \
1225 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1226 if (!Decl##BTName) \
1227 Decl##BTName = \
1228 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1229 return Decl##BTName; \
1230 }
1231#include "clang/Basic/BuiltinTemplates.inc"
1232
1233RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1234 RecordDecl::TagKind TK) const {
1235 SourceLocation Loc;
1236 RecordDecl *NewDecl;
1237 if (getLangOpts().CPlusPlus)
1238 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1239 IdLoc: Loc, Id: &Idents.get(Name));
1240 else
1241 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1242 Id: &Idents.get(Name));
1243 NewDecl->setImplicit();
1244 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1245 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1246 return NewDecl;
1247}
1248
1249TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1250 StringRef Name) const {
1251 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1252 TypedefDecl *NewDecl = TypedefDecl::Create(
1253 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1254 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1255 NewDecl->setImplicit();
1256 return NewDecl;
1257}
1258
1259TypedefDecl *ASTContext::getInt128Decl() const {
1260 if (!Int128Decl)
1261 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1262 return Int128Decl;
1263}
1264
1265TypedefDecl *ASTContext::getUInt128Decl() const {
1266 if (!UInt128Decl)
1267 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1268 return UInt128Decl;
1269}
1270
1271void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1272 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1273 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1274 Types.push_back(Elt: Ty);
1275}
1276
1277void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1278 const TargetInfo *AuxTarget) {
1279 assert((!this->Target || this->Target == &Target) &&
1280 "Incorrect target reinitialization");
1281 assert(VoidTy.isNull() && "Context reinitialized?");
1282
1283 this->Target = &Target;
1284 this->AuxTarget = AuxTarget;
1285
1286 ABI.reset(p: createCXXABI(T: Target));
1287 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1288
1289 // C99 6.2.5p19.
1290 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1291
1292 // C99 6.2.5p2.
1293 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1294 // C99 6.2.5p3.
1295 if (LangOpts.CharIsSigned)
1296 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1297 else
1298 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1299 // C99 6.2.5p4.
1300 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1301 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1302 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1303 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1304 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1305
1306 // C99 6.2.5p6.
1307 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1308 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1309 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1310 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1311 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1312
1313 // C99 6.2.5p10.
1314 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1315 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1316 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1317
1318 // GNU extension, __float128 for IEEE quadruple precision
1319 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1320
1321 // __ibm128 for IBM extended precision
1322 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1323
1324 // C11 extension ISO/IEC TS 18661-3
1325 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1326
1327 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1328 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1329 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1330 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1331 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1332 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1333 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1334 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1335 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1336 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1337 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1338 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1339 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1340 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1341 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1342 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1343 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1344 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1345 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1346 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1347 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1348 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1349 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1350 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1351 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1352
1353 // GNU extension, 128-bit integers.
1354 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1355 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1356
1357 // C++ 3.9.1p5
1358 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1359 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1360 else // -fshort-wchar makes wchar_t be unsigned.
1361 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1362 if (LangOpts.CPlusPlus && LangOpts.WChar)
1363 WideCharTy = WCharTy;
1364 else {
1365 // C99 (or C++ using -fno-wchar).
1366 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1367 }
1368
1369 WIntTy = getFromTargetType(Type: Target.getWIntType());
1370
1371 // C++20 (proposed)
1372 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1373
1374 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1375 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1376 else // C99
1377 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1378
1379 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1380 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1381 else // C99
1382 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1383
1384 // Placeholder type for type-dependent expressions whose type is
1385 // completely unknown. No code should ever check a type against
1386 // DependentTy and users should never see it; however, it is here to
1387 // help diagnose failures to properly check for type-dependent
1388 // expressions.
1389 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1390
1391 // Placeholder type for functions.
1392 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1393
1394 // Placeholder type for bound members.
1395 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1396
1397 // Placeholder type for unresolved templates.
1398 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1399
1400 // Placeholder type for pseudo-objects.
1401 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1402
1403 // "any" type; useful for debugger-like clients.
1404 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1405
1406 // Placeholder type for unbridged ARC casts.
1407 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1408
1409 // Placeholder type for builtin functions.
1410 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1411
1412 // Placeholder type for OMP array sections.
1413 if (LangOpts.OpenMP) {
1414 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1415 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1416 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1417 }
1418 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1419 // don't bother, as we're just using the same type as OMP.
1420 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1421 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1422 }
1423 if (LangOpts.MatrixTypes)
1424 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1425
1426 // Builtin types for 'id', 'Class', and 'SEL'.
1427 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1428 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1429 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1430
1431 if (LangOpts.OpenCL) {
1432#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1433 InitBuiltinType(SingletonId, BuiltinType::Id);
1434#include "clang/Basic/OpenCLImageTypes.def"
1435
1436 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1437 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1438 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1439 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1440 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1441
1442#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/OpenCLExtensionTypes.def"
1445 }
1446
1447 if (LangOpts.HLSL) {
1448#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLIntangibleTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1482#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1483 InitBuiltinType(SingletonId, BuiltinType::Id);
1484#include "clang/Basic/AMDGPUTypes.def"
1485 }
1486
1487 if (Target.getTriple().isSPIRV() ||
1488 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1489#define SPIRV_TYPE(Name, Id, SingletonId) \
1490 InitBuiltinType(SingletonId, BuiltinType::Id);
1491#include "clang/Basic/SPIRVTypes.def"
1492 }
1493
1494 // Builtin type for __objc_yes and __objc_no
1495 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1496 SignedCharTy : BoolTy);
1497
1498 ObjCConstantStringType = QualType();
1499
1500 ObjCSuperType = QualType();
1501
1502 // void * type
1503 if (LangOpts.OpenCLGenericAddressSpace) {
1504 auto Q = VoidTy.getQualifiers();
1505 Q.setAddressSpace(LangAS::opencl_generic);
1506 VoidPtrTy = getPointerType(T: getCanonicalType(
1507 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1508 } else {
1509 VoidPtrTy = getPointerType(T: VoidTy);
1510 }
1511
1512 // nullptr type (C++0x 2.14.7)
1513 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1514
1515 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1516 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1517
1518 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1519
1520 // Builtin type used to help define __builtin_va_list.
1521 VaListTagDecl = nullptr;
1522
1523 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1524 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1525 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1526 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1527 }
1528}
1529
1530DiagnosticsEngine &ASTContext::getDiagnostics() const {
1531 return SourceMgr.getDiagnostics();
1532}
1533
1534AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1535 AttrVec *&Result = DeclAttrs[D];
1536 if (!Result) {
1537 void *Mem = Allocate(Size: sizeof(AttrVec));
1538 Result = new (Mem) AttrVec;
1539 }
1540
1541 return *Result;
1542}
1543
1544/// Erase the attributes corresponding to the given declaration.
1545void ASTContext::eraseDeclAttrs(const Decl *D) {
1546 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(Val: D);
1547 if (Pos != DeclAttrs.end()) {
1548 Pos->second->~AttrVec();
1549 DeclAttrs.erase(I: Pos);
1550 }
1551}
1552
1553ArrayRef<CXXDefaultArgExpr *>
1554ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1555 return CtorClosureDefaultArgs.lookup(Val: CD);
1556}
1557
1558void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1559 ArrayRef<CXXDefaultArgExpr *> Args) {
1560 assert(!CtorClosureDefaultArgs.contains(CD));
1561 CtorClosureDefaultArgs[CD] = Args;
1562}
1563
1564ArrayRef<ExplicitInstantiationDecl *>
1565ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1566 auto It =
1567 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1568 if (It != ExplicitInstantiations.end())
1569 return It->second;
1570 return {};
1571}
1572
1573void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1574 ExplicitInstantiationDecl *EID) {
1575 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1576 NewVal: EID);
1577}
1578
1579// FIXME: Remove ?
1580MemberSpecializationInfo *
1581ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1582 assert(Var->isStaticDataMember() && "Not a static data member");
1583 return getTemplateOrSpecializationInfo(Var)
1584 .dyn_cast<MemberSpecializationInfo *>();
1585}
1586
1587ASTContext::TemplateOrSpecializationInfo
1588ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1589 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1590 TemplateOrInstantiation.find(Val: Var);
1591 if (Pos == TemplateOrInstantiation.end())
1592 return {};
1593
1594 return Pos->second;
1595}
1596
1597void
1598ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1599 TemplateSpecializationKind TSK,
1600 SourceLocation PointOfInstantiation) {
1601 assert(Inst->isStaticDataMember() && "Not a static data member");
1602 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1603 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1604 Tmpl, TSK, PointOfInstantiation));
1605}
1606
1607void
1608ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1609 TemplateOrSpecializationInfo TSI) {
1610 assert(!TemplateOrInstantiation[Inst] &&
1611 "Already noted what the variable was instantiated from");
1612 TemplateOrInstantiation[Inst] = TSI;
1613}
1614
1615NamedDecl *
1616ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1617 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1618}
1619
1620void
1621ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1622 assert((isa<UsingDecl>(Pattern) ||
1623 isa<UnresolvedUsingValueDecl>(Pattern) ||
1624 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1625 "pattern decl is not a using decl");
1626 assert((isa<UsingDecl>(Inst) ||
1627 isa<UnresolvedUsingValueDecl>(Inst) ||
1628 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1629 "instantiation did not produce a using decl");
1630 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1631 InstantiatedFromUsingDecl[Inst] = Pattern;
1632}
1633
1634UsingEnumDecl *
1635ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1636 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1637}
1638
1639void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1640 UsingEnumDecl *Pattern) {
1641 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1642 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1643}
1644
1645UsingShadowDecl *
1646ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1647 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1648}
1649
1650void
1651ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1652 UsingShadowDecl *Pattern) {
1653 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1654 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1655}
1656
1657FieldDecl *
1658ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1659 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1660}
1661
1662void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1663 FieldDecl *Tmpl) {
1664 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1665 "Instantiated field decl is not unnamed");
1666 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1667 "Template field decl is not unnamed");
1668 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1669 "Already noted what unnamed field was instantiated from");
1670
1671 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1672}
1673
1674ASTContext::overridden_cxx_method_iterator
1675ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1676 return overridden_methods(Method).begin();
1677}
1678
1679ASTContext::overridden_cxx_method_iterator
1680ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1681 return overridden_methods(Method).end();
1682}
1683
1684unsigned
1685ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1686 auto Range = overridden_methods(Method);
1687 return Range.end() - Range.begin();
1688}
1689
1690ASTContext::overridden_method_range
1691ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1692 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1693 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1694 if (Pos == OverriddenMethods.end())
1695 return overridden_method_range(nullptr, nullptr);
1696 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1697}
1698
1699void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1700 const CXXMethodDecl *Overridden) {
1701 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1702 OverriddenMethods[Method].push_back(NewVal: Overridden);
1703}
1704
1705void ASTContext::getOverriddenMethods(
1706 const NamedDecl *D,
1707 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1708 assert(D);
1709
1710 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1711 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1712 in_end: overridden_methods_end(Method: CXXMethod));
1713 return;
1714 }
1715
1716 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1717 if (!Method)
1718 return;
1719
1720 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1721 Method->getOverriddenMethods(Overridden&: OverDecls);
1722 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1723}
1724
1725std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1726ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1727 assert(RD);
1728 CXXRecordDecl *D = RD->getDefinition();
1729 auto it = RelocatableClasses.find(Val: D);
1730 if (it != RelocatableClasses.end())
1731 return it->getSecond();
1732 return std::nullopt;
1733}
1734
1735void ASTContext::setRelocationInfoForCXXRecord(
1736 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1737 assert(RD);
1738 CXXRecordDecl *D = RD->getDefinition();
1739 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1740 RelocatableClasses.insert(KV: {D, Info});
1741}
1742
1743static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1744 const ASTContext &Context, const CXXRecordDecl *Class) {
1745 if (!Class->isPolymorphic())
1746 return false;
1747 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1748 using AuthAttr = VTablePointerAuthenticationAttr;
1749 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1750 if (!ExplicitAuth)
1751 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1752 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1753 ExplicitAuth->getAddressDiscrimination();
1754 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1755 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1756 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1757}
1758
1759ASTContext::PointerAuthContent
1760ASTContext::findPointerAuthContent(QualType T) const {
1761 assert(isPointerAuthenticationAvailable());
1762
1763 T = T.getCanonicalType();
1764 if (T->isDependentType())
1765 return PointerAuthContent::None;
1766
1767 if (T.hasAddressDiscriminatedPointerAuth())
1768 return PointerAuthContent::AddressDiscriminatedData;
1769 const RecordDecl *RD = T->getAsRecordDecl();
1770 if (!RD)
1771 return PointerAuthContent::None;
1772
1773 if (RD->isInvalidDecl())
1774 return PointerAuthContent::None;
1775
1776 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1777 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1778 return Existing->second;
1779
1780 PointerAuthContent Result = PointerAuthContent::None;
1781
1782 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1783 auto [ResultIter, DidAdd] =
1784 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1785 (void)ResultIter;
1786 (void)DidAdd;
1787 assert(DidAdd);
1788 return Result;
1789 };
1790 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1791 static_assert(PointerAuthContent::None <
1792 PointerAuthContent::AddressDiscriminatedVTable);
1793 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1794 PointerAuthContent::AddressDiscriminatedData);
1795 if (NewResult > Result)
1796 Result = NewResult;
1797 return Result != PointerAuthContent::AddressDiscriminatedData;
1798 };
1799 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1800 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1801 !ShouldContinueAfterUpdate(
1802 PointerAuthContent::AddressDiscriminatedVTable))
1803 return SaveResultAndReturn();
1804 for (auto Base : CXXRD->bases()) {
1805 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1806 return SaveResultAndReturn();
1807 }
1808 }
1809 for (auto *FieldDecl : RD->fields()) {
1810 if (!ShouldContinueAfterUpdate(
1811 findPointerAuthContent(T: FieldDecl->getType())))
1812 return SaveResultAndReturn();
1813 }
1814 return SaveResultAndReturn();
1815}
1816
1817void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1818 assert(!Import->getNextLocalImport() &&
1819 "Import declaration already in the chain");
1820 assert(!Import->isFromASTFile() && "Non-local import declaration");
1821 if (!FirstLocalImport) {
1822 FirstLocalImport = Import;
1823 LastLocalImport = Import;
1824 return;
1825 }
1826
1827 LastLocalImport->setNextLocalImport(Import);
1828 LastLocalImport = Import;
1829}
1830
1831//===----------------------------------------------------------------------===//
1832// Type Sizing and Analysis
1833//===----------------------------------------------------------------------===//
1834
1835/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1836/// scalar floating point type.
1837const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1838 switch (T->castAs<BuiltinType>()->getKind()) {
1839 default:
1840 llvm_unreachable("Not a floating point type!");
1841 case BuiltinType::BFloat16:
1842 return Target->getBFloat16Format();
1843 case BuiltinType::Float16:
1844 return Target->getHalfFormat();
1845 case BuiltinType::Half:
1846 return Target->getHalfFormat();
1847 case BuiltinType::Float: return Target->getFloatFormat();
1848 case BuiltinType::Double: return Target->getDoubleFormat();
1849 case BuiltinType::Ibm128:
1850 return Target->getIbm128Format();
1851 case BuiltinType::LongDouble:
1852 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1853 return AuxTarget->getLongDoubleFormat();
1854 return Target->getLongDoubleFormat();
1855 case BuiltinType::Float128:
1856 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1857 return AuxTarget->getFloat128Format();
1858 return Target->getFloat128Format();
1859 }
1860}
1861
1862CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1863 unsigned Align = Target->getCharWidth();
1864
1865 const unsigned AlignFromAttr = D->getMaxAlignment();
1866 if (AlignFromAttr)
1867 Align = AlignFromAttr;
1868
1869 // __attribute__((aligned)) can increase or decrease alignment
1870 // *except* on a struct or struct member, where it only increases
1871 // alignment unless 'packed' is also specified.
1872 //
1873 // It is an error for alignas to decrease alignment, so we can
1874 // ignore that possibility; Sema should diagnose it.
1875 bool UseAlignAttrOnly;
1876 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1877 UseAlignAttrOnly =
1878 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1879 else
1880 UseAlignAttrOnly = AlignFromAttr != 0;
1881 // If we're using the align attribute only, just ignore everything
1882 // else about the declaration and its type.
1883 if (UseAlignAttrOnly) {
1884 // do nothing
1885 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1886 QualType T = VD->getType();
1887 if (const auto *RT = T->getAs<ReferenceType>()) {
1888 if (ForAlignof)
1889 T = RT->getPointeeType();
1890 else
1891 T = getPointerType(T: RT->getPointeeType());
1892 }
1893 QualType BaseT = getBaseElementType(QT: T);
1894 if (T->isFunctionType())
1895 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1896 else if (!BaseT->isIncompleteType()) {
1897 // Adjust alignments of declarations with array type by the
1898 // large-array alignment on the target.
1899 if (const ArrayType *arrayType = getAsArrayType(T)) {
1900 unsigned MinWidth = Target->getLargeArrayMinWidth();
1901 if (!ForAlignof && MinWidth) {
1902 if (isa<VariableArrayType>(Val: arrayType))
1903 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1904 else if (isa<ConstantArrayType>(Val: arrayType) &&
1905 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1906 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1907 }
1908 }
1909 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1910 if (BaseT.getQualifiers().hasUnaligned())
1911 Align = Target->getCharWidth();
1912 }
1913
1914 // Ensure minimum alignment for global variables.
1915 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1916 if (VD->hasGlobalStorage() && !ForAlignof) {
1917 uint64_t TypeSize =
1918 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1919 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1920 }
1921
1922 // Fields can be subject to extra alignment constraints, like if
1923 // the field is packed, the struct is packed, or the struct has a
1924 // a max-field-alignment constraint (#pragma pack). So calculate
1925 // the actual alignment of the field within the struct, and then
1926 // (as we're expected to) constrain that by the alignment of the type.
1927 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1928 const RecordDecl *Parent = Field->getParent();
1929 // We can only produce a sensible answer if the record is valid.
1930 if (!Parent->isInvalidDecl()) {
1931 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1932
1933 // Start with the record's overall alignment.
1934 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1935
1936 // Use the GCD of that and the offset within the record.
1937 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1938 if (Offset > 0) {
1939 // Alignment is always a power of 2, so the GCD will be a power of 2,
1940 // which means we get to do this crazy thing instead of Euclid's.
1941 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1942 if (LowBitOfOffset < FieldAlign)
1943 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1944 }
1945
1946 Align = std::min(a: Align, b: FieldAlign);
1947 }
1948 }
1949 }
1950
1951 // Some targets have hard limitation on the maximum requestable alignment in
1952 // aligned attribute for static variables.
1953 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1954 const auto *VD = dyn_cast<VarDecl>(Val: D);
1955 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1956 Align = std::min(a: Align, b: MaxAlignedAttr);
1957
1958 return toCharUnitsFromBits(BitSize: Align);
1959}
1960
1961CharUnits ASTContext::getExnObjectAlignment() const {
1962 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1963}
1964
1965// getTypeInfoDataSizeInChars - Return the size of a type, in
1966// chars. If the type is a record, its data size is returned. This is
1967// the size of the memcpy that's performed when assigning this type
1968// using a trivial copy/move assignment operator.
1969TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1970 TypeInfoChars Info = getTypeInfoInChars(T);
1971
1972 // In C++, objects can sometimes be allocated into the tail padding
1973 // of a base-class subobject. We decide whether that's possible
1974 // during class layout, so here we can just trust the layout results.
1975 if (getLangOpts().CPlusPlus) {
1976 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1977 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1978 Info.Width = layout.getDataSize();
1979 }
1980 }
1981
1982 return Info;
1983}
1984
1985/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1986/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1987TypeInfoChars
1988static getConstantArrayInfoInChars(const ASTContext &Context,
1989 const ConstantArrayType *CAT) {
1990 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1991 uint64_t Size = CAT->getZExtSize();
1992 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1993 (uint64_t)(-1)/Size) &&
1994 "Overflow in array type char size evaluation");
1995 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1996 unsigned Align = EltInfo.Align.getQuantity();
1997 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1998 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
1999 Width = llvm::alignTo(Value: Width, Align);
2000 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
2001 CharUnits::fromQuantity(Quantity: Align),
2002 EltInfo.AlignRequirement);
2003}
2004
2005TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
2006 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2007 return getConstantArrayInfoInChars(Context: *this, CAT);
2008 TypeInfo Info = getTypeInfo(T);
2009 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
2010 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
2011}
2012
2013TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2014 return getTypeInfoInChars(T: T.getTypePtr());
2015}
2016
2017bool ASTContext::isPromotableIntegerType(QualType T) const {
2018 // HLSL doesn't promote all small integer types to int, it
2019 // just uses the rank-based promotion rules for all types.
2020 if (getLangOpts().HLSL)
2021 return false;
2022
2023 if (const auto *BT = T->getAs<BuiltinType>())
2024 switch (BT->getKind()) {
2025 case BuiltinType::Bool:
2026 case BuiltinType::Char_S:
2027 case BuiltinType::Char_U:
2028 case BuiltinType::SChar:
2029 case BuiltinType::UChar:
2030 case BuiltinType::Short:
2031 case BuiltinType::UShort:
2032 case BuiltinType::WChar_S:
2033 case BuiltinType::WChar_U:
2034 case BuiltinType::Char8:
2035 case BuiltinType::Char16:
2036 case BuiltinType::Char32:
2037 return true;
2038 default:
2039 return false;
2040 }
2041
2042 // Enumerated types are promotable to their compatible integer types
2043 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2044 if (const auto *ED = T->getAsEnumDecl()) {
2045 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2046 ED->isScoped())
2047 return false;
2048
2049 return true;
2050 }
2051
2052 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2053 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2054 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2055 }
2056
2057 return false;
2058}
2059
2060bool ASTContext::isAlignmentRequired(const Type *T) const {
2061 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
2062}
2063
2064bool ASTContext::isAlignmentRequired(QualType T) const {
2065 return isAlignmentRequired(T: T.getTypePtr());
2066}
2067
2068unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2069 bool NeedsPreferredAlignment) const {
2070 // An alignment on a typedef overrides anything else.
2071 if (const auto *TT = T->getAs<TypedefType>())
2072 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2073 return Align;
2074
2075 // If we have an (array of) complete type, we're done.
2076 T = getBaseElementType(QT: T);
2077 if (!T->isIncompleteType())
2078 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2079
2080 // If we had an array type, its element type might be a typedef
2081 // type with an alignment attribute.
2082 if (const auto *TT = T->getAs<TypedefType>())
2083 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2084 return Align;
2085
2086 // Otherwise, see if the declaration of the type had an attribute.
2087 if (const auto *TD = T->getAsTagDecl())
2088 return TD->getMaxAlignment();
2089
2090 return 0;
2091}
2092
2093TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2094 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2095 if (I != MemoizedTypeInfo.end())
2096 return I->second;
2097
2098 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2099 TypeInfo TI = getTypeInfoImpl(T);
2100 MemoizedTypeInfo[T] = TI;
2101 return TI;
2102}
2103
2104/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2105/// method does not work on incomplete types.
2106///
2107/// FIXME: Pointers into different addr spaces could have different sizes and
2108/// alignment requirements: getPointerInfo should take an AddrSpace, this
2109/// should take a QualType, &c.
2110TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2111 uint64_t Width = 0;
2112 unsigned Align = 8;
2113 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2114 LangAS AS = LangAS::Default;
2115 switch (T->getTypeClass()) {
2116#define TYPE(Class, Base)
2117#define ABSTRACT_TYPE(Class, Base)
2118#define NON_CANONICAL_TYPE(Class, Base)
2119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2121 case Type::Class: \
2122 assert(!T->isDependentType() && "should not see dependent types here"); \
2123 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2124#include "clang/AST/TypeNodes.inc"
2125 llvm_unreachable("Should not see dependent types");
2126
2127 case Type::FunctionNoProto:
2128 case Type::FunctionProto:
2129 // GCC extension: alignof(function) = 32 bits
2130 Width = 0;
2131 Align = 32;
2132 break;
2133
2134 case Type::IncompleteArray:
2135 case Type::VariableArray:
2136 case Type::ConstantArray:
2137 case Type::ArrayParameter: {
2138 // Model non-constant sized arrays as size zero, but track the alignment.
2139 uint64_t Size = 0;
2140 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2141 Size = CAT->getZExtSize();
2142
2143 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2144 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2145 "Overflow in array type bit size evaluation");
2146 Width = EltInfo.Width * Size;
2147 Align = EltInfo.Align;
2148 AlignRequirement = EltInfo.AlignRequirement;
2149 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2150 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2151 Width = llvm::alignTo(Value: Width, Align);
2152 break;
2153 }
2154
2155 case Type::ExtVector:
2156 case Type::Vector: {
2157 const auto *VT = cast<VectorType>(Val: T);
2158 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2159 Width = VT->isPackedVectorBoolType(ctx: *this)
2160 ? VT->getNumElements()
2161 : EltInfo.Width * VT->getNumElements();
2162 // Enforce at least byte size and alignment.
2163 Width = std::max<unsigned>(a: 8, b: Width);
2164 Align = std::max<unsigned>(
2165 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2166
2167 // If the alignment is not a power of 2, round up to the next power of 2.
2168 // This happens for non-power-of-2 length vectors.
2169 if (Align & (Align-1)) {
2170 Align = llvm::bit_ceil(Value: Align);
2171 Width = llvm::alignTo(Value: Width, Align);
2172 }
2173 // Adjust the alignment based on the target max.
2174 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2175 if (TargetVectorAlign && TargetVectorAlign < Align)
2176 Align = TargetVectorAlign;
2177 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2178 // Adjust the alignment for fixed-length SVE vectors. This is important
2179 // for non-power-of-2 vector lengths.
2180 Align = 128;
2181 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2182 // Adjust the alignment for fixed-length SVE predicates.
2183 Align = 16;
2184 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2185 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2188 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2189 // Adjust the alignment for fixed-length RVV vectors.
2190 Align = std::min<unsigned>(a: 64, b: Width);
2191 break;
2192 }
2193
2194 case Type::ConstantMatrix: {
2195 const auto *MT = cast<ConstantMatrixType>(Val: T);
2196 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2197 // The internal layout of a matrix value is implementation defined.
2198 // Initially be ABI compatible with arrays with respect to alignment and
2199 // size.
2200 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2201 Align = ElementInfo.Align;
2202 break;
2203 }
2204
2205 case Type::Builtin:
2206 switch (cast<BuiltinType>(Val: T)->getKind()) {
2207 default: llvm_unreachable("Unknown builtin type!");
2208 case BuiltinType::Void:
2209 // GCC extension: alignof(void) = 8 bits.
2210 Width = 0;
2211 Align = 8;
2212 break;
2213 case BuiltinType::Bool:
2214 Width = Target->getBoolWidth();
2215 Align = Target->getBoolAlign();
2216 break;
2217 case BuiltinType::Char_S:
2218 case BuiltinType::Char_U:
2219 case BuiltinType::UChar:
2220 case BuiltinType::SChar:
2221 case BuiltinType::Char8:
2222 Width = Target->getCharWidth();
2223 Align = Target->getCharAlign();
2224 break;
2225 case BuiltinType::WChar_S:
2226 case BuiltinType::WChar_U:
2227 Width = Target->getWCharWidth();
2228 Align = Target->getWCharAlign();
2229 break;
2230 case BuiltinType::Char16:
2231 Width = Target->getChar16Width();
2232 Align = Target->getChar16Align();
2233 break;
2234 case BuiltinType::Char32:
2235 Width = Target->getChar32Width();
2236 Align = Target->getChar32Align();
2237 break;
2238 case BuiltinType::UShort:
2239 case BuiltinType::Short:
2240 Width = Target->getShortWidth();
2241 Align = Target->getShortAlign();
2242 break;
2243 case BuiltinType::UInt:
2244 case BuiltinType::Int:
2245 Width = Target->getIntWidth();
2246 Align = Target->getIntAlign();
2247 break;
2248 case BuiltinType::ULong:
2249 case BuiltinType::Long:
2250 Width = Target->getLongWidth();
2251 Align = Target->getLongAlign();
2252 break;
2253 case BuiltinType::ULongLong:
2254 case BuiltinType::LongLong:
2255 Width = Target->getLongLongWidth();
2256 Align = Target->getLongLongAlign();
2257 break;
2258 case BuiltinType::Int128:
2259 case BuiltinType::UInt128:
2260 Width = 128;
2261 Align = Target->getInt128Align();
2262 break;
2263 case BuiltinType::ShortAccum:
2264 case BuiltinType::UShortAccum:
2265 case BuiltinType::SatShortAccum:
2266 case BuiltinType::SatUShortAccum:
2267 Width = Target->getShortAccumWidth();
2268 Align = Target->getShortAccumAlign();
2269 break;
2270 case BuiltinType::Accum:
2271 case BuiltinType::UAccum:
2272 case BuiltinType::SatAccum:
2273 case BuiltinType::SatUAccum:
2274 Width = Target->getAccumWidth();
2275 Align = Target->getAccumAlign();
2276 break;
2277 case BuiltinType::LongAccum:
2278 case BuiltinType::ULongAccum:
2279 case BuiltinType::SatLongAccum:
2280 case BuiltinType::SatULongAccum:
2281 Width = Target->getLongAccumWidth();
2282 Align = Target->getLongAccumAlign();
2283 break;
2284 case BuiltinType::ShortFract:
2285 case BuiltinType::UShortFract:
2286 case BuiltinType::SatShortFract:
2287 case BuiltinType::SatUShortFract:
2288 Width = Target->getShortFractWidth();
2289 Align = Target->getShortFractAlign();
2290 break;
2291 case BuiltinType::Fract:
2292 case BuiltinType::UFract:
2293 case BuiltinType::SatFract:
2294 case BuiltinType::SatUFract:
2295 Width = Target->getFractWidth();
2296 Align = Target->getFractAlign();
2297 break;
2298 case BuiltinType::LongFract:
2299 case BuiltinType::ULongFract:
2300 case BuiltinType::SatLongFract:
2301 case BuiltinType::SatULongFract:
2302 Width = Target->getLongFractWidth();
2303 Align = Target->getLongFractAlign();
2304 break;
2305 case BuiltinType::BFloat16:
2306 if (Target->hasBFloat16Type()) {
2307 Width = Target->getBFloat16Width();
2308 Align = Target->getBFloat16Align();
2309 } else if ((getLangOpts().SYCLIsDevice ||
2310 (getLangOpts().OpenMP &&
2311 getLangOpts().OpenMPIsTargetDevice)) &&
2312 AuxTarget->hasBFloat16Type()) {
2313 Width = AuxTarget->getBFloat16Width();
2314 Align = AuxTarget->getBFloat16Align();
2315 }
2316 break;
2317 case BuiltinType::Float16:
2318 case BuiltinType::Half:
2319 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2320 !getLangOpts().OpenMPIsTargetDevice) {
2321 Width = Target->getHalfWidth();
2322 Align = Target->getHalfAlign();
2323 } else {
2324 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2325 "Expected OpenMP device compilation.");
2326 Width = AuxTarget->getHalfWidth();
2327 Align = AuxTarget->getHalfAlign();
2328 }
2329 break;
2330 case BuiltinType::Float:
2331 Width = Target->getFloatWidth();
2332 Align = Target->getFloatAlign();
2333 break;
2334 case BuiltinType::Double:
2335 Width = Target->getDoubleWidth();
2336 Align = Target->getDoubleAlign();
2337 break;
2338 case BuiltinType::Ibm128:
2339 Width = Target->getIbm128Width();
2340 Align = Target->getIbm128Align();
2341 break;
2342 case BuiltinType::LongDouble:
2343 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2344 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2345 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2346 Width = AuxTarget->getLongDoubleWidth();
2347 Align = AuxTarget->getLongDoubleAlign();
2348 } else {
2349 Width = Target->getLongDoubleWidth();
2350 Align = Target->getLongDoubleAlign();
2351 }
2352 break;
2353 case BuiltinType::Float128:
2354 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2355 !getLangOpts().OpenMPIsTargetDevice) {
2356 Width = Target->getFloat128Width();
2357 Align = Target->getFloat128Align();
2358 } else {
2359 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2360 "Expected OpenMP device compilation.");
2361 Width = AuxTarget->getFloat128Width();
2362 Align = AuxTarget->getFloat128Align();
2363 }
2364 break;
2365 case BuiltinType::NullPtr:
2366 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2367 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2368 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2369 break;
2370 case BuiltinType::ObjCId:
2371 case BuiltinType::ObjCClass:
2372 case BuiltinType::ObjCSel:
2373 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2374 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2375 break;
2376 case BuiltinType::OCLSampler:
2377 case BuiltinType::OCLEvent:
2378 case BuiltinType::OCLClkEvent:
2379 case BuiltinType::OCLQueue:
2380 case BuiltinType::OCLReserveID:
2381#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2382 case BuiltinType::Id:
2383#include "clang/Basic/OpenCLImageTypes.def"
2384#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2385 case BuiltinType::Id:
2386#include "clang/Basic/OpenCLExtensionTypes.def"
2387 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2388 Width = Target->getPointerWidth(AddrSpace: AS);
2389 Align = Target->getPointerAlign(AddrSpace: AS);
2390 break;
2391 // The SVE types are effectively target-specific. The length of an
2392 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2393 // of 128 bits. There is one predicate bit for each vector byte, so the
2394 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2395 //
2396 // Because the length is only known at runtime, we use a dummy value
2397 // of 0 for the static length. The alignment values are those defined
2398 // by the Procedure Call Standard for the Arm Architecture.
2399#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2400 case BuiltinType::Id: \
2401 Width = 0; \
2402 Align = 128; \
2403 break;
2404#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2405 case BuiltinType::Id: \
2406 Width = 0; \
2407 Align = 16; \
2408 break;
2409#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2410 case BuiltinType::Id: \
2411 Width = 0; \
2412 Align = 16; \
2413 break;
2414#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2415 case BuiltinType::Id: \
2416 Width = Bits; \
2417 Align = Bits; \
2418 break;
2419#include "clang/Basic/AArch64ACLETypes.def"
2420#define PPC_VECTOR_TYPE(Name, Id, Size) \
2421 case BuiltinType::Id: \
2422 Width = Size; \
2423 Align = Size; \
2424 break;
2425#include "clang/Basic/PPCTypes.def"
2426#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2427 IsFP, IsBF) \
2428 case BuiltinType::Id: \
2429 Width = 0; \
2430 Align = ElBits; \
2431 break;
2432#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2433 case BuiltinType::Id: \
2434 Width = 0; \
2435 Align = 8; \
2436 break;
2437#include "clang/Basic/RISCVVTypes.def"
2438#define WASM_TYPE(Name, Id, SingletonId) \
2439 case BuiltinType::Id: \
2440 Width = 0; \
2441 Align = 8; \
2442 break;
2443#include "clang/Basic/WebAssemblyReferenceTypes.def"
2444#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2445 case BuiltinType::ID: \
2446 Width = WIDTH; \
2447 Align = ALIGN; \
2448 break;
2449#include "clang/Basic/AMDGPUTypes.def"
2450#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2451#include "clang/Basic/HLSLIntangibleTypes.def"
2452 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2453 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2454 break;
2455#define SPIRV_TYPE(Name, Id, SingletonId) \
2456 case BuiltinType::Id: \
2457 Width = Target->getPointerWidth(LangAS::Default); \
2458 Align = Target->getPointerAlign(LangAS::Default); \
2459 break;
2460#include "clang/Basic/SPIRVTypes.def"
2461 }
2462 break;
2463 case Type::ObjCObjectPointer:
2464 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2465 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2466 break;
2467 case Type::BlockPointer:
2468 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2469 Width = Target->getPointerWidth(AddrSpace: AS);
2470 Align = Target->getPointerAlign(AddrSpace: AS);
2471 break;
2472 case Type::LValueReference:
2473 case Type::RValueReference:
2474 // alignof and sizeof should never enter this code path here, so we go
2475 // the pointer route.
2476 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2477 Width = Target->getPointerWidth(AddrSpace: AS);
2478 Align = Target->getPointerAlign(AddrSpace: AS);
2479 break;
2480 case Type::Pointer:
2481 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2482 Width = Target->getPointerWidth(AddrSpace: AS);
2483 Align = Target->getPointerAlign(AddrSpace: AS);
2484 break;
2485 case Type::MemberPointer: {
2486 const auto *MPT = cast<MemberPointerType>(Val: T);
2487 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2488 Width = MPI.Width;
2489 Align = MPI.Align;
2490 break;
2491 }
2492 case Type::Complex: {
2493 // Complex types have the same alignment as their elements, but twice the
2494 // size.
2495 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2496 Width = EltInfo.Width * 2;
2497 Align = EltInfo.Align;
2498 break;
2499 }
2500 case Type::ObjCObject:
2501 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2502 case Type::Adjusted:
2503 case Type::Decayed:
2504 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2505 case Type::ObjCInterface: {
2506 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2507 if (ObjCI->getDecl()->isInvalidDecl()) {
2508 Width = 8;
2509 Align = 8;
2510 break;
2511 }
2512 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2513 Width = toBits(CharSize: Layout.getSize());
2514 Align = toBits(CharSize: Layout.getAlignment());
2515 break;
2516 }
2517 case Type::BitInt: {
2518 const auto *EIT = cast<BitIntType>(Val: T);
2519 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2520 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2521 break;
2522 }
2523 case Type::Record:
2524 case Type::Enum: {
2525 const auto *TT = cast<TagType>(Val: T);
2526 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2527
2528 if (TD->isInvalidDecl()) {
2529 Width = 8;
2530 Align = 8;
2531 break;
2532 }
2533
2534 if (isa<EnumType>(Val: TT)) {
2535 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2536 TypeInfo Info =
2537 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2538 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2539 Info.Align = AttrAlign;
2540 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2541 }
2542 return Info;
2543 }
2544
2545 const auto *RD = cast<RecordDecl>(Val: TD);
2546 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2547 Width = toBits(CharSize: Layout.getSize());
2548 Align = toBits(CharSize: Layout.getAlignment());
2549 AlignRequirement = RD->hasAttr<AlignedAttr>()
2550 ? AlignRequirementKind::RequiredByRecord
2551 : AlignRequirementKind::None;
2552 break;
2553 }
2554
2555 case Type::SubstTemplateTypeParm:
2556 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2557 getReplacementType().getTypePtr());
2558
2559 case Type::Auto:
2560 case Type::DeducedTemplateSpecialization: {
2561 const auto *A = cast<DeducedType>(Val: T);
2562 assert(!A->getDeducedType().isNull() &&
2563 "cannot request the size of an undeduced or dependent auto type");
2564 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2565 }
2566
2567 case Type::Paren:
2568 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2569
2570 case Type::MacroQualified:
2571 return getTypeInfo(
2572 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2573
2574 case Type::ObjCTypeParam:
2575 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2576
2577 case Type::Using:
2578 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2579
2580 case Type::Typedef: {
2581 const auto *TT = cast<TypedefType>(Val: T);
2582 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2583 // If the typedef has an aligned attribute on it, it overrides any computed
2584 // alignment we have. This violates the GCC documentation (which says that
2585 // attribute(aligned) can only round up) but matches its implementation.
2586 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2587 Align = AttrAlign;
2588 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2589 } else {
2590 Align = Info.Align;
2591 AlignRequirement = Info.AlignRequirement;
2592 }
2593 Width = Info.Width;
2594 break;
2595 }
2596
2597 case Type::Attributed:
2598 return getTypeInfo(
2599 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2600
2601 case Type::CountAttributed:
2602 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2603
2604 case Type::LateParsedAttr:
2605 return getTypeInfo(T: cast<LateParsedAttrType>(Val: T)->desugar().getTypePtr());
2606
2607 case Type::BTFTagAttributed:
2608 return getTypeInfo(
2609 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2610
2611 case Type::OverflowBehavior:
2612 return getTypeInfo(
2613 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2614
2615 case Type::HLSLAttributedResource:
2616 return getTypeInfo(
2617 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2618
2619 case Type::HLSLInlineSpirv: {
2620 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2621 // Size is specified in bytes, convert to bits
2622 Width = ST->getSize() * 8;
2623 Align = ST->getAlignment();
2624 if (Width == 0 && Align == 0) {
2625 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2626 Width = 32;
2627 Align = 32;
2628 }
2629 break;
2630 }
2631
2632 case Type::Atomic: {
2633 // Start with the base type information.
2634 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2635 Width = Info.Width;
2636 Align = Info.Align;
2637
2638 if (!Width) {
2639 // An otherwise zero-sized type should still generate an
2640 // atomic operation.
2641 Width = Target->getCharWidth();
2642 assert(Align);
2643 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2644 // If the size of the type doesn't exceed the platform's max
2645 // atomic promotion width, make the size and alignment more
2646 // favorable to atomic operations:
2647
2648 // Round the size up to a power of 2.
2649 Width = llvm::bit_ceil(Value: Width);
2650
2651 // Set the alignment equal to the size.
2652 Align = static_cast<unsigned>(Width);
2653 }
2654 }
2655 break;
2656
2657 case Type::PredefinedSugar:
2658 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2659
2660 case Type::Pipe:
2661 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2662 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2663 break;
2664 }
2665
2666 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2667 return TypeInfo(Width, Align, AlignRequirement);
2668}
2669
2670unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2671 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2672 if (I != MemoizedUnadjustedAlign.end())
2673 return I->second;
2674
2675 unsigned UnadjustedAlign;
2676 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2677 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2678 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2679 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2680 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2681 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2682 } else {
2683 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2684 }
2685
2686 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2687 return UnadjustedAlign;
2688}
2689
2690unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2691 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2692 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2693 return SimdAlign;
2694}
2695
2696/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2697CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2698 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2699}
2700
2701/// toBits - Convert a size in characters to a size in characters.
2702int64_t ASTContext::toBits(CharUnits CharSize) const {
2703 return CharSize.getQuantity() * getCharWidth();
2704}
2705
2706/// getTypeSizeInChars - Return the size of the specified type, in characters.
2707/// This method does not work on incomplete types.
2708CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2709 return getTypeInfoInChars(T).Width;
2710}
2711CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2712 return getTypeInfoInChars(T).Width;
2713}
2714
2715/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2716/// characters. This method does not work on incomplete types.
2717CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2718 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2719}
2720CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2721 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2722}
2723
2724/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2725/// type, in characters, before alignment adjustments. This method does
2726/// not work on incomplete types.
2727CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2728 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2729}
2730CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2731 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2732}
2733
2734/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2735/// type for the current target in bits. This can be different than the ABI
2736/// alignment in cases where it is beneficial for performance or backwards
2737/// compatibility preserving to overalign a data type. (Note: despite the name,
2738/// the preferred alignment is ABI-impacting, and not an optimization.)
2739unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2740 TypeInfo TI = getTypeInfo(T);
2741 unsigned ABIAlign = TI.Align;
2742
2743 T = T->getBaseElementTypeUnsafe();
2744
2745 // The preferred alignment of member pointers is that of a pointer.
2746 if (T->isMemberPointerType())
2747 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2748
2749 if (!Target->allowsLargerPreferedTypeAlignment())
2750 return ABIAlign;
2751
2752 if (const auto *RD = T->getAsRecordDecl()) {
2753 // When used as part of a typedef, or together with a 'packed' attribute,
2754 // the 'aligned' attribute can be used to decrease alignment. Note that the
2755 // 'packed' case is already taken into consideration when computing the
2756 // alignment, we only need to handle the typedef case here.
2757 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2758 RD->isInvalidDecl())
2759 return ABIAlign;
2760
2761 unsigned PreferredAlign = static_cast<unsigned>(
2762 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2763 assert(PreferredAlign >= ABIAlign &&
2764 "PreferredAlign should be at least as large as ABIAlign.");
2765 return PreferredAlign;
2766 }
2767
2768 // Double (and, for targets supporting AIX `power` alignment, long double) and
2769 // long long should be naturally aligned (despite requiring less alignment) if
2770 // possible.
2771 if (const auto *CT = T->getAs<ComplexType>())
2772 T = CT->getElementType().getTypePtr();
2773 if (const auto *ED = T->getAsEnumDecl())
2774 T = ED->getIntegerType().getTypePtr();
2775 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2776 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2777 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2778 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2779 Target->defaultsToAIXPowerAlignment()))
2780 // Don't increase the alignment if an alignment attribute was specified on a
2781 // typedef declaration.
2782 if (!TI.isAlignRequired())
2783 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2784
2785 return ABIAlign;
2786}
2787
2788/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2789/// for __attribute__((aligned)) on this target, to be used if no alignment
2790/// value is specified.
2791unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2792 return getTargetInfo().getDefaultAlignForAttributeAligned();
2793}
2794
2795/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2796/// to a global variable of the specified type.
2797unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2798 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2799 return std::max(a: getPreferredTypeAlign(T),
2800 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2801}
2802
2803/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2804/// should be given to a global variable of the specified type.
2805CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2806 const VarDecl *VD) const {
2807 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2808}
2809
2810unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2811 const VarDecl *VD) const {
2812 // Make the default handling as that of a non-weak definition in the
2813 // current translation unit.
2814 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2815 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2816}
2817
2818CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2819 CharUnits Offset = CharUnits::Zero();
2820 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2821 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2822 Offset += Layout->getBaseClassOffset(Base);
2823 Layout = &getASTRecordLayout(D: Base);
2824 }
2825 return Offset;
2826}
2827
2828CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2829 const ValueDecl *MPD = MP.getMemberPointerDecl();
2830 CharUnits ThisAdjustment = CharUnits::Zero();
2831 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2832 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2833 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2834 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2835 const CXXRecordDecl *Base = RD;
2836 const CXXRecordDecl *Derived = Path[I];
2837 if (DerivedMember)
2838 std::swap(a&: Base, b&: Derived);
2839 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2840 RD = Path[I];
2841 }
2842 if (DerivedMember)
2843 ThisAdjustment = -ThisAdjustment;
2844 return ThisAdjustment;
2845}
2846
2847/// DeepCollectObjCIvars -
2848/// This routine first collects all declared, but not synthesized, ivars in
2849/// super class and then collects all ivars, including those synthesized for
2850/// current class. This routine is used for implementation of current class
2851/// when all ivars, declared and synthesized are known.
2852void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2853 bool leafClass,
2854 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2855 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2856 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2857 if (!leafClass) {
2858 llvm::append_range(C&: Ivars, R: OI->ivars());
2859 } else {
2860 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2861 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2862 Iv= Iv->getNextIvar())
2863 Ivars.push_back(Elt: Iv);
2864 }
2865}
2866
2867/// CollectInheritedProtocols - Collect all protocols in current class and
2868/// those inherited by it.
2869void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2870 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2871 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2872 // We can use protocol_iterator here instead of
2873 // all_referenced_protocol_iterator since we are walking all categories.
2874 for (auto *Proto : OI->all_referenced_protocols()) {
2875 CollectInheritedProtocols(CDecl: Proto, Protocols);
2876 }
2877
2878 // Categories of this Interface.
2879 for (const auto *Cat : OI->visible_categories())
2880 CollectInheritedProtocols(CDecl: Cat, Protocols);
2881
2882 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2883 while (SD) {
2884 CollectInheritedProtocols(CDecl: SD, Protocols);
2885 SD = SD->getSuperClass();
2886 }
2887 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2888 for (auto *Proto : OC->protocols()) {
2889 CollectInheritedProtocols(CDecl: Proto, Protocols);
2890 }
2891 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2892 // Insert the protocol.
2893 if (!Protocols.insert(
2894 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2895 return;
2896
2897 for (auto *Proto : OP->protocols())
2898 CollectInheritedProtocols(CDecl: Proto, Protocols);
2899 }
2900}
2901
2902static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2903 const RecordDecl *RD,
2904 bool CheckIfTriviallyCopyable) {
2905 assert(RD->isUnion() && "Must be union type");
2906 CharUnits UnionSize =
2907 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2908
2909 for (const auto *Field : RD->fields()) {
2910 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2911 CheckIfTriviallyCopyable))
2912 return false;
2913 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2914 if (FieldSize != UnionSize)
2915 return false;
2916 }
2917 return !RD->field_empty();
2918}
2919
2920static int64_t getSubobjectOffset(const FieldDecl *Field,
2921 const ASTContext &Context,
2922 const clang::ASTRecordLayout & /*Layout*/) {
2923 return Context.getFieldOffset(FD: Field);
2924}
2925
2926static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2927 const ASTContext &Context,
2928 const clang::ASTRecordLayout &Layout) {
2929 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2930}
2931
2932static std::optional<int64_t>
2933structHasUniqueObjectRepresentations(const ASTContext &Context,
2934 const RecordDecl *RD,
2935 bool CheckIfTriviallyCopyable);
2936
2937static std::optional<int64_t>
2938getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2939 bool CheckIfTriviallyCopyable) {
2940 if (const auto *RD = Field->getType()->getAsRecordDecl();
2941 RD && !RD->isUnion())
2942 return structHasUniqueObjectRepresentations(Context, RD,
2943 CheckIfTriviallyCopyable);
2944
2945 // A _BitInt type may not be unique if it has padding bits
2946 // but if it is a bitfield the padding bits are not used.
2947 bool IsBitIntType = Field->getType()->isBitIntType();
2948 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2949 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2950 CheckIfTriviallyCopyable))
2951 return std::nullopt;
2952
2953 int64_t FieldSizeInBits =
2954 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2955 if (Field->isBitField()) {
2956 // If we have explicit padding bits, they don't contribute bits
2957 // to the actual object representation, so return 0.
2958 if (Field->isUnnamedBitField())
2959 return 0;
2960
2961 int64_t BitfieldSize = Field->getBitWidthValue();
2962 if (IsBitIntType) {
2963 if ((unsigned)BitfieldSize >
2964 cast<BitIntType>(Val: Field->getType())->getNumBits())
2965 return std::nullopt;
2966 } else if (BitfieldSize > FieldSizeInBits) {
2967 return std::nullopt;
2968 }
2969 FieldSizeInBits = BitfieldSize;
2970 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2971 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2972 return std::nullopt;
2973 }
2974 return FieldSizeInBits;
2975}
2976
2977static std::optional<int64_t>
2978getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2979 bool CheckIfTriviallyCopyable) {
2980 return structHasUniqueObjectRepresentations(Context, RD,
2981 CheckIfTriviallyCopyable);
2982}
2983
2984template <typename RangeT>
2985static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2986 const RangeT &Subobjects, int64_t CurOffsetInBits,
2987 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2988 bool CheckIfTriviallyCopyable) {
2989 for (const auto *Subobject : Subobjects) {
2990 std::optional<int64_t> SizeInBits =
2991 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2992 if (!SizeInBits)
2993 return std::nullopt;
2994 if (*SizeInBits != 0) {
2995 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2996 if (Offset != CurOffsetInBits)
2997 return std::nullopt;
2998 CurOffsetInBits += *SizeInBits;
2999 }
3000 }
3001 return CurOffsetInBits;
3002}
3003
3004static std::optional<int64_t>
3005structHasUniqueObjectRepresentations(const ASTContext &Context,
3006 const RecordDecl *RD,
3007 bool CheckIfTriviallyCopyable) {
3008 assert(!RD->isUnion() && "Must be struct/class type");
3009 const auto &Layout = Context.getASTRecordLayout(D: RD);
3010
3011 int64_t CurOffsetInBits = 0;
3012 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3013 if (ClassDecl->isDynamicClass())
3014 return std::nullopt;
3015
3016 SmallVector<CXXRecordDecl *, 4> Bases;
3017 for (const auto &Base : ClassDecl->bases()) {
3018 // Empty types can be inherited from, and non-empty types can potentially
3019 // have tail padding, so just make sure there isn't an error.
3020 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3021 }
3022
3023 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3024 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3025 });
3026
3027 std::optional<int64_t> OffsetAfterBases =
3028 structSubobjectsHaveUniqueObjectRepresentations(
3029 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3030 if (!OffsetAfterBases)
3031 return std::nullopt;
3032 CurOffsetInBits = *OffsetAfterBases;
3033 }
3034
3035 std::optional<int64_t> OffsetAfterFields =
3036 structSubobjectsHaveUniqueObjectRepresentations(
3037 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3038 CheckIfTriviallyCopyable);
3039 if (!OffsetAfterFields)
3040 return std::nullopt;
3041 CurOffsetInBits = *OffsetAfterFields;
3042
3043 return CurOffsetInBits;
3044}
3045
3046bool ASTContext::hasUniqueObjectRepresentations(
3047 QualType Ty, bool CheckIfTriviallyCopyable) const {
3048 // C++17 [meta.unary.prop]:
3049 // The predicate condition for a template specialization
3050 // has_unique_object_representations<T> shall be satisfied if and only if:
3051 // (9.1) - T is trivially copyable, and
3052 // (9.2) - any two objects of type T with the same value have the same
3053 // object representation, where:
3054 // - two objects of array or non-union class type are considered to have
3055 // the same value if their respective sequences of direct subobjects
3056 // have the same values, and
3057 // - two objects of union type are considered to have the same value if
3058 // they have the same active member and the corresponding members have
3059 // the same value.
3060 // The set of scalar types for which this condition holds is
3061 // implementation-defined. [ Note: If a type has padding bits, the condition
3062 // does not hold; otherwise, the condition holds true for unsigned integral
3063 // types. -- end note ]
3064 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3065
3066 // Arrays are unique only if their element type is unique.
3067 if (Ty->isArrayType())
3068 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3069 CheckIfTriviallyCopyable);
3070
3071 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3072 "hasUniqueObjectRepresentations should not be called with an "
3073 "incomplete type");
3074
3075 // (9.1) - T is trivially copyable...
3076 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3077 return false;
3078
3079 // All integrals and enums are unique.
3080 if (Ty->isIntegralOrEnumerationType()) {
3081 // Address discriminated integer types are not unique.
3082 if (Ty.hasAddressDiscriminatedPointerAuth())
3083 return false;
3084 // Except _BitInt types that have padding bits.
3085 if (const auto *BIT = Ty->getAs<BitIntType>())
3086 return getTypeSize(T: BIT) == BIT->getNumBits();
3087
3088 return true;
3089 }
3090
3091 // All other pointers are unique.
3092 if (Ty->isPointerType())
3093 return !Ty.hasAddressDiscriminatedPointerAuth();
3094
3095 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3096 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3097
3098 if (const auto *Record = Ty->getAsRecordDecl()) {
3099 if (Record->isInvalidDecl())
3100 return false;
3101
3102 if (Record->isUnion())
3103 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3104 CheckIfTriviallyCopyable);
3105
3106 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3107 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3108
3109 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3110 }
3111
3112 // FIXME: More cases to handle here (list by rsmith):
3113 // vectors (careful about, eg, vector of 3 foo)
3114 // _Complex int and friends
3115 // _Atomic T
3116 // Obj-C block pointers
3117 // Obj-C object pointers
3118 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3119 // clk_event_t, queue_t, reserve_id_t)
3120 // There're also Obj-C class types and the Obj-C selector type, but I think it
3121 // makes sense for those to return false here.
3122
3123 return false;
3124}
3125
3126unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3127 unsigned count = 0;
3128 // Count ivars declared in class extension.
3129 for (const auto *Ext : OI->known_extensions())
3130 count += Ext->ivar_size();
3131
3132 // Count ivar defined in this class's implementation. This
3133 // includes synthesized ivars.
3134 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3135 count += ImplDecl->ivar_size();
3136
3137 return count;
3138}
3139
3140bool ASTContext::isSentinelNullExpr(const Expr *E) {
3141 if (!E)
3142 return false;
3143
3144 // nullptr_t is always treated as null.
3145 if (E->getType()->isNullPtrType()) return true;
3146
3147 if (E->getType()->isAnyPointerType() &&
3148 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3149 NPC: Expr::NPC_ValueDependentIsNull))
3150 return true;
3151
3152 // Unfortunately, __null has type 'int'.
3153 if (isa<GNUNullExpr>(Val: E)) return true;
3154
3155 return false;
3156}
3157
3158/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3159/// exists.
3160ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3162 I = ObjCImpls.find(Val: D);
3163 if (I != ObjCImpls.end())
3164 return cast<ObjCImplementationDecl>(Val: I->second);
3165 return nullptr;
3166}
3167
3168/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3169/// exists.
3170ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3171 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3172 I = ObjCImpls.find(Val: D);
3173 if (I != ObjCImpls.end())
3174 return cast<ObjCCategoryImplDecl>(Val: I->second);
3175 return nullptr;
3176}
3177
3178/// Set the implementation of ObjCInterfaceDecl.
3179void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3180 ObjCImplementationDecl *ImplD) {
3181 assert(IFaceD && ImplD && "Passed null params");
3182 ObjCImpls[IFaceD] = ImplD;
3183}
3184
3185/// Set the implementation of ObjCCategoryDecl.
3186void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3187 ObjCCategoryImplDecl *ImplD) {
3188 assert(CatD && ImplD && "Passed null params");
3189 ObjCImpls[CatD] = ImplD;
3190}
3191
3192const ObjCMethodDecl *
3193ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3194 return ObjCMethodRedecls.lookup(Val: MD);
3195}
3196
3197void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3198 const ObjCMethodDecl *Redecl) {
3199 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3200 ObjCMethodRedecls[MD] = Redecl;
3201}
3202
3203const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3204 const NamedDecl *ND) const {
3205 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3206 return ID;
3207 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3208 return CD->getClassInterface();
3209 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3210 return IMD->getClassInterface();
3211
3212 return nullptr;
3213}
3214
3215/// Get the copy initialization expression of VarDecl, or nullptr if
3216/// none exists.
3217BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3218 assert(VD && "Passed null params");
3219 assert(VD->hasAttr<BlocksAttr>() &&
3220 "getBlockVarCopyInits - not __block var");
3221 auto I = BlockVarCopyInits.find(Val: VD);
3222 if (I != BlockVarCopyInits.end())
3223 return I->second;
3224 return {nullptr, false};
3225}
3226
3227/// Set the copy initialization expression of a block var decl.
3228void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3229 bool CanThrow) {
3230 assert(VD && CopyExpr && "Passed null params");
3231 assert(VD->hasAttr<BlocksAttr>() &&
3232 "setBlockVarCopyInits - not __block var");
3233 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3234}
3235
3236TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3237 unsigned DataSize) const {
3238 if (!DataSize)
3239 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3240 else
3241 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3242 "incorrect data size provided to CreateTypeSourceInfo!");
3243
3244 auto *TInfo =
3245 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3246 new (TInfo) TypeSourceInfo(T, DataSize);
3247 return TInfo;
3248}
3249
3250TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3251 SourceLocation L) const {
3252 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3253 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3254 return TSI;
3255}
3256
3257const ASTRecordLayout &
3258ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3259 return getObjCLayout(D);
3260}
3261
3262static auto getCanonicalTemplateArguments(const ASTContext &C,
3263 ArrayRef<TemplateArgument> Args,
3264 bool &AnyNonCanonArgs) {
3265 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3266 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3267 return CanonArgs;
3268}
3269
3270bool ASTContext::canonicalizeTemplateArguments(
3271 MutableArrayRef<TemplateArgument> Args) const {
3272 bool AnyNonCanonArgs = false;
3273 for (auto &Arg : Args) {
3274 TemplateArgument OrigArg = Arg;
3275 Arg = getCanonicalTemplateArgument(Arg);
3276 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3277 }
3278 return AnyNonCanonArgs;
3279}
3280
3281//===----------------------------------------------------------------------===//
3282// Type creation/memoization methods
3283//===----------------------------------------------------------------------===//
3284
3285QualType
3286ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3287 unsigned fastQuals = quals.getFastQualifiers();
3288 quals.removeFastQualifiers();
3289
3290 // Check if we've already instantiated this type.
3291 llvm::FoldingSetNodeID ID;
3292 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3293 llvm::FoldingSetInsertToken Token;
3294 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3295 assert(eq->getQualifiers() == quals);
3296 return QualType(eq, fastQuals);
3297 }
3298
3299 // If the base type is not canonical, make the appropriate canonical type.
3300 QualType canon;
3301 if (!baseType->isCanonicalUnqualified()) {
3302 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3303 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3304 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3305
3306 // Re-find the insert position.
3307 (void)ExtQualNodes.lookup(ID, Token);
3308 }
3309
3310 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3311 ExtQualNodes.insert(N: eq, Token);
3312 return QualType(eq, fastQuals);
3313}
3314
3315QualType ASTContext::getAddrSpaceQualType(QualType T,
3316 LangAS AddressSpace) const {
3317 QualType CanT = getCanonicalType(T);
3318 if (CanT.getAddressSpace() == AddressSpace)
3319 return T;
3320
3321 // If we are composing extended qualifiers together, merge together
3322 // into one ExtQuals node.
3323 QualifierCollector Quals;
3324 const Type *TypeNode = Quals.strip(type: T);
3325
3326 // If this type already has an address space specified, it cannot get
3327 // another one.
3328 assert(!Quals.hasAddressSpace() &&
3329 "Type cannot be in multiple addr spaces!");
3330 Quals.addAddressSpace(space: AddressSpace);
3331
3332 return getExtQualType(baseType: TypeNode, quals: Quals);
3333}
3334
3335QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3336 // If the type is not qualified with an address space, just return it
3337 // immediately.
3338 if (!T.hasAddressSpace())
3339 return T;
3340
3341 QualifierCollector Quals;
3342 const Type *TypeNode;
3343 // For arrays, strip the qualifier off the element type, then reconstruct the
3344 // array type
3345 if (T.getTypePtr()->isArrayType()) {
3346 T = getUnqualifiedArrayType(T, Quals);
3347 TypeNode = T.getTypePtr();
3348 } else {
3349 // If we are composing extended qualifiers together, merge together
3350 // into one ExtQuals node.
3351 while (T.hasAddressSpace()) {
3352 TypeNode = Quals.strip(type: T);
3353
3354 // If the type no longer has an address space after stripping qualifiers,
3355 // jump out.
3356 if (!QualType(TypeNode, 0).hasAddressSpace())
3357 break;
3358
3359 // There might be sugar in the way. Strip it and try again.
3360 T = T.getSingleStepDesugaredType(Context: *this);
3361 }
3362 }
3363
3364 Quals.removeAddressSpace();
3365
3366 // Removal of the address space can mean there are no longer any
3367 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3368 // or required.
3369 if (Quals.hasNonFastQualifiers())
3370 return getExtQualType(baseType: TypeNode, quals: Quals);
3371 else
3372 return QualType(TypeNode, Quals.getFastQualifiers());
3373}
3374
3375uint16_t
3376ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD,
3377 bool IsVTTEntry) {
3378 assert(RD->isPolymorphic() &&
3379 "Attempted to get vtable pointer discriminator on a monomorphic type");
3380
3381 std::unique_ptr<MangleContext> MC(createMangleContext());
3382 SmallString<256> Str;
3383 llvm::raw_svector_ostream Out(Str);
3384 MC->mangleCXXVTable(RD, Out);
3385 if (IsVTTEntry)
3386 Out << VTTVTablePointerDiscriminatorSuffix;
3387 return llvm::getPointerAuthStableSipHash(S: Str);
3388}
3389
3390/// Encode a function type for use in the discriminator of a function pointer
3391/// type. We can't use the itanium scheme for this since C has quite permissive
3392/// rules for type compatibility that we need to be compatible with.
3393///
3394/// Formally, this function associates every function pointer type T with an
3395/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3396/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3397/// compatibility requires equivalent treatment under the ABI, so
3398/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3399/// a subset of ~. Crucially, however, it must be a proper subset because
3400/// CCompatible is not an equivalence relation: for example, int[] is compatible
3401/// with both int[1] and int[2], but the latter are not compatible with each
3402/// other. Therefore this encoding function must be careful to only distinguish
3403/// types if there is no third type with which they are both required to be
3404/// compatible.
3405static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3406 raw_ostream &OS, QualType QT) {
3407 // FIXME: Consider address space qualifiers.
3408 const Type *T = QT.getCanonicalType().getTypePtr();
3409
3410 // FIXME: Consider using the C++ type mangling when we encounter a construct
3411 // that is incompatible with C.
3412
3413 switch (T->getTypeClass()) {
3414 case Type::Atomic:
3415 return encodeTypeForFunctionPointerAuth(
3416 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3417
3418 case Type::LValueReference:
3419 OS << "R";
3420 encodeTypeForFunctionPointerAuth(Ctx, OS,
3421 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3422 return;
3423 case Type::RValueReference:
3424 OS << "O";
3425 encodeTypeForFunctionPointerAuth(Ctx, OS,
3426 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3427 return;
3428
3429 case Type::Pointer:
3430 // C11 6.7.6.1p2:
3431 // For two pointer types to be compatible, both shall be identically
3432 // qualified and both shall be pointers to compatible types.
3433 // FIXME: we should also consider pointee types.
3434 OS << "P";
3435 return;
3436
3437 case Type::ObjCObjectPointer:
3438 case Type::BlockPointer:
3439 OS << "P";
3440 return;
3441
3442 case Type::Complex:
3443 OS << "C";
3444 return encodeTypeForFunctionPointerAuth(
3445 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3446
3447 case Type::VariableArray:
3448 case Type::ConstantArray:
3449 case Type::IncompleteArray:
3450 case Type::ArrayParameter:
3451 // C11 6.7.6.2p6:
3452 // For two array types to be compatible, both shall have compatible
3453 // element types, and if both size specifiers are present, and are integer
3454 // constant expressions, then both size specifiers shall have the same
3455 // constant value [...]
3456 //
3457 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3458 // width of the array.
3459 OS << "A";
3460 return encodeTypeForFunctionPointerAuth(
3461 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3462
3463 case Type::ObjCInterface:
3464 case Type::ObjCObject:
3465 OS << "<objc_object>";
3466 return;
3467
3468 case Type::Enum: {
3469 // C11 6.7.2.2p4:
3470 // Each enumerated type shall be compatible with char, a signed integer
3471 // type, or an unsigned integer type.
3472 //
3473 // So we have to treat enum types as integers.
3474 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3475 return encodeTypeForFunctionPointerAuth(
3476 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3477 }
3478
3479 case Type::FunctionNoProto:
3480 case Type::FunctionProto: {
3481 // C11 6.7.6.3p15:
3482 // For two function types to be compatible, both shall specify compatible
3483 // return types. Moreover, the parameter type lists, if both are present,
3484 // shall agree in the number of parameters and in the use of the ellipsis
3485 // terminator; corresponding parameters shall have compatible types.
3486 //
3487 // That paragraph goes on to describe how unprototyped functions are to be
3488 // handled, which we ignore here. Unprototyped function pointers are hashed
3489 // as though they were prototyped nullary functions since thats probably
3490 // what the user meant. This behavior is non-conforming.
3491 // FIXME: If we add a "custom discriminator" function type attribute we
3492 // should encode functions as their discriminators.
3493 OS << "F";
3494 const auto *FuncType = cast<FunctionType>(Val: T);
3495 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3496 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3497 for (QualType Param : FPT->param_types()) {
3498 Param = Ctx.getSignatureParameterType(T: Param);
3499 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3500 }
3501 if (FPT->isVariadic())
3502 OS << "z";
3503 }
3504 OS << "E";
3505 return;
3506 }
3507
3508 case Type::MemberPointer: {
3509 OS << "M";
3510 const auto *MPT = T->castAs<MemberPointerType>();
3511 encodeTypeForFunctionPointerAuth(
3512 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3513 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3514 return;
3515 }
3516 case Type::ExtVector:
3517 case Type::Vector:
3518 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3519 break;
3520
3521 // Don't bother discriminating based on these types.
3522 case Type::Pipe:
3523 case Type::BitInt:
3524 case Type::ConstantMatrix:
3525 OS << "?";
3526 return;
3527
3528 case Type::Builtin: {
3529 const auto *BTy = T->castAs<BuiltinType>();
3530 switch (BTy->getKind()) {
3531#define SIGNED_TYPE(Id, SingletonId) \
3532 case BuiltinType::Id: \
3533 OS << "i"; \
3534 return;
3535#define UNSIGNED_TYPE(Id, SingletonId) \
3536 case BuiltinType::Id: \
3537 OS << "i"; \
3538 return;
3539#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3540#define BUILTIN_TYPE(Id, SingletonId)
3541#include "clang/AST/BuiltinTypes.def"
3542 llvm_unreachable("placeholder types should not appear here.");
3543
3544 case BuiltinType::Half:
3545 OS << "Dh";
3546 return;
3547 case BuiltinType::Float:
3548 OS << "f";
3549 return;
3550 case BuiltinType::Double:
3551 OS << "d";
3552 return;
3553 case BuiltinType::LongDouble:
3554 OS << "e";
3555 return;
3556 case BuiltinType::Float16:
3557 OS << "DF16_";
3558 return;
3559 case BuiltinType::Float128:
3560 OS << "g";
3561 return;
3562
3563 case BuiltinType::Void:
3564 OS << "v";
3565 return;
3566
3567 case BuiltinType::ObjCId:
3568 case BuiltinType::ObjCClass:
3569 case BuiltinType::ObjCSel:
3570 case BuiltinType::NullPtr:
3571 OS << "P";
3572 return;
3573
3574 // Don't bother discriminating based on OpenCL types.
3575 case BuiltinType::OCLSampler:
3576 case BuiltinType::OCLEvent:
3577 case BuiltinType::OCLClkEvent:
3578 case BuiltinType::OCLQueue:
3579 case BuiltinType::OCLReserveID:
3580 case BuiltinType::BFloat16:
3581 case BuiltinType::VectorQuad:
3582 case BuiltinType::VectorPair:
3583 case BuiltinType::DMR1024:
3584 case BuiltinType::DMR2048:
3585 OS << "?";
3586 return;
3587
3588 // Don't bother discriminating based on these seldom-used types.
3589 case BuiltinType::Ibm128:
3590 return;
3591#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3592 case BuiltinType::Id: \
3593 return;
3594#include "clang/Basic/OpenCLImageTypes.def"
3595#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3596 case BuiltinType::Id: \
3597 return;
3598#include "clang/Basic/OpenCLExtensionTypes.def"
3599#define SVE_TYPE(Name, Id, SingletonId) \
3600 case BuiltinType::Id: \
3601 return;
3602#include "clang/Basic/AArch64ACLETypes.def"
3603#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3604 case BuiltinType::Id: \
3605 return;
3606#include "clang/Basic/HLSLIntangibleTypes.def"
3607 case BuiltinType::Dependent:
3608 llvm_unreachable("should never get here");
3609#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3610#include "clang/Basic/AMDGPUTypes.def"
3611 case BuiltinType::WasmExternRef:
3612#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3613#include "clang/Basic/RISCVVTypes.def"
3614#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3615#include "clang/Basic/SPIRVTypes.def"
3616 llvm_unreachable("not yet implemented");
3617 }
3618 llvm_unreachable("should never get here");
3619 }
3620 case Type::Record: {
3621 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3622 const IdentifierInfo *II = RD->getIdentifier();
3623
3624 // In C++, an immediate typedef of an anonymous struct or union
3625 // is considered to name it for ODR purposes, but C's specification
3626 // of type compatibility does not have a similar rule. Using the typedef
3627 // name in function type discriminators anyway, as we do here,
3628 // therefore technically violates the C standard: two function pointer
3629 // types defined in terms of two typedef'd anonymous structs with
3630 // different names are formally still compatible, but we are assigning
3631 // them different discriminators and therefore incompatible ABIs.
3632 //
3633 // This is a relatively minor violation that significantly improves
3634 // discrimination in some cases and has not caused problems in
3635 // practice. Regardless, it is now part of the ABI in places where
3636 // function type discrimination is used, and it can no longer be
3637 // changed except on new platforms.
3638
3639 if (!II)
3640 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3641 II = Typedef->getDeclName().getAsIdentifierInfo();
3642
3643 if (!II) {
3644 OS << "<anonymous_record>";
3645 return;
3646 }
3647 OS << II->getLength() << II->getName();
3648 return;
3649 }
3650 case Type::HLSLAttributedResource:
3651 case Type::HLSLInlineSpirv:
3652 llvm_unreachable("should never get here");
3653 break;
3654 case Type::OverflowBehavior:
3655 llvm_unreachable("should never get here");
3656 break;
3657 case Type::DeducedTemplateSpecialization:
3658 case Type::Auto:
3659#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3660#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3661#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3662#define ABSTRACT_TYPE(Class, Base)
3663#define TYPE(Class, Base)
3664#include "clang/AST/TypeNodes.inc"
3665 llvm_unreachable("unexpected non-canonical or dependent type!");
3666 return;
3667 }
3668}
3669
3670uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3671 assert(!T->isDependentType() &&
3672 "cannot compute type discriminator of a dependent type");
3673 SmallString<256> Str;
3674 llvm::raw_svector_ostream Out(Str);
3675
3676 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3677 T = T->getPointeeType();
3678
3679 if (T->isFunctionType()) {
3680 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3681 } else {
3682 T = T.getUnqualifiedType();
3683 // Calls to member function pointers don't need to worry about
3684 // language interop or the laxness of the C type compatibility rules.
3685 // We just mangle the member pointer type directly, which is
3686 // implicitly much stricter about type matching. However, we do
3687 // strip any top-level exception specification before this mangling.
3688 // C++23 requires calls to work when the function type is convertible
3689 // to the pointer type by a function pointer conversion, which can
3690 // change the exception specification. This does not technically
3691 // require the exception specification to not affect representation,
3692 // because the function pointer conversion is still always a direct
3693 // value conversion and therefore an opportunity to resign the
3694 // pointer. (This is in contrast to e.g. qualification conversions,
3695 // which can be applied in nested pointer positions, effectively
3696 // requiring qualified and unqualified representations to match.)
3697 // However, it is pragmatic to ignore exception specifications
3698 // because it allows a certain amount of `noexcept` mismatching
3699 // to not become a visible ODR problem. This also leaves some
3700 // room for the committee to add laxness to function pointer
3701 // conversions in future standards.
3702 if (auto *MPT = T->getAs<MemberPointerType>())
3703 if (MPT->isMemberFunctionPointer()) {
3704 QualType PointeeType = MPT->getPointeeType();
3705 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3706 EST_None) {
3707 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3708 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3709 Cls: MPT->getMostRecentCXXRecordDecl());
3710 }
3711 }
3712 std::unique_ptr<MangleContext> MC(createMangleContext());
3713 MC->mangleCanonicalTypeName(T, Out);
3714 }
3715
3716 return llvm::getPointerAuthStableSipHash(S: Str);
3717}
3718
3719QualType ASTContext::getObjCGCQualType(QualType T,
3720 Qualifiers::GC GCAttr) const {
3721 QualType CanT = getCanonicalType(T);
3722 if (CanT.getObjCGCAttr() == GCAttr)
3723 return T;
3724
3725 if (const auto *ptr = T->getAs<PointerType>()) {
3726 QualType Pointee = ptr->getPointeeType();
3727 if (Pointee->isAnyPointerType()) {
3728 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3729 return getPointerType(T: ResultType);
3730 }
3731 }
3732
3733 // If we are composing extended qualifiers together, merge together
3734 // into one ExtQuals node.
3735 QualifierCollector Quals;
3736 const Type *TypeNode = Quals.strip(type: T);
3737
3738 // If this type already has an ObjCGC specified, it cannot get
3739 // another one.
3740 assert(!Quals.hasObjCGCAttr() &&
3741 "Type cannot have multiple ObjCGCs!");
3742 Quals.addObjCGCAttr(type: GCAttr);
3743
3744 return getExtQualType(baseType: TypeNode, quals: Quals);
3745}
3746
3747QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3748 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3749 QualType Pointee = Ptr->getPointeeType();
3750 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3751 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3752 }
3753 }
3754 return T;
3755}
3756
3757QualType ASTContext::getCountAttributedType(
3758 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3759 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3760 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3761 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3762
3763 // Complete (non-late-parsed) path: the count expression is known up front.
3764 // This deliberately preserves the pre-existing uniquing behavior -- the
3765 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3766 // getIncompleteCountAttributedType (count filled in later) opts out of
3767 // uniquing.
3768 llvm::FoldingSetNodeID ID;
3769 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3770
3771 llvm::FoldingSetInsertToken Token;
3772 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3773 if (CATy)
3774 return QualType(CATy, 0);
3775
3776 QualType CanonTy = getCanonicalType(T: WrappedTy);
3777 CATy = CountAttributedType::Create(Ctx: *this, Wrapped: WrappedTy, Canon: CanonTy, CountExpr,
3778 CountInBytes, OrNull, CoupledDecls: DependentDecls);
3779 Types.push_back(Elt: CATy);
3780 CountAttributedTypes.insert(N: CATy, Token);
3781
3782 return QualType(CATy, 0);
3783}
3784
3785CountAttributedType *ASTContext::getIncompleteCountAttributedType(
3786 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3787 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3788
3789 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3790 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3791 // null here, so every incomplete node would profile identically as
3792 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3793 // collide. The node stays un-uniqued even after completion; see
3794 // `completeCountAttributedType`.
3795 //
3796 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3797 // without ever being completed (a nested counted_by, or an argument that
3798 // fails to parse), and a null-count node must not be reachable by anything
3799 // that scans `Types`. `completeCountAttributedType` registers it once the
3800 // count is in place.
3801 return CountAttributedType::Create(
3802 Ctx: *this, Wrapped: WrappedTy, Canon: getCanonicalType(T: WrappedTy),
3803 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3804 /*CoupledDecls=*/{});
3805}
3806
3807void ASTContext::completeCountAttributedType(
3808 CountAttributedType *CATy, Expr *CountExpr,
3809 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3810 CATy->complete(Ctx: *this, E: CountExpr, CoupledDecls: DependentDecls);
3811 // Safe for `Types` scanners now that the count is in place; see
3812 // `getIncompleteCountAttributedType` for why it was held back.
3813 //
3814 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3815 // an eagerly built node: this pointer is already embedded in the enclosing
3816 // types and handed out, so an equal node that happens to exist cannot be
3817 // merged into. The only cost is that a completed node is never
3818 // pointer-shared with an equal eager one, which does not affect semantic
3819 // type equality -- `hasSameType` compares canonical types, and this sugar's
3820 // canonical type is the wrapped type's.
3821 Types.push_back(Elt: CATy);
3822}
3823
3824QualType ASTContext::getLateParsedAttrType(
3825 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3826 QualType CanonTy = getCanonicalType(T: WrappedTy);
3827
3828 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3829 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3830
3831 Types.push_back(Elt: LPATy);
3832 return QualType(LPATy, 0);
3833}
3834
3835QualType
3836ASTContext::adjustType(QualType Orig,
3837 llvm::function_ref<QualType(QualType)> Adjust) const {
3838 switch (Orig->getTypeClass()) {
3839 case Type::Attributed: {
3840 const auto *AT = cast<AttributedType>(Val&: Orig);
3841 return getAttributedType(attrKind: AT->getAttrKind(),
3842 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3843 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3844 attr: AT->getAttr());
3845 }
3846
3847 case Type::BTFTagAttributed: {
3848 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3849 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3850 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3851 }
3852
3853 case Type::OverflowBehavior: {
3854 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3855 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3856 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3857 }
3858
3859 case Type::Paren:
3860 return getParenType(
3861 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3862
3863 case Type::Adjusted: {
3864 const auto *AT = cast<AdjustedType>(Val&: Orig);
3865 return getAdjustedType(Orig: AT->getOriginalType(),
3866 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3867 }
3868
3869 case Type::MacroQualified: {
3870 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3871 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3872 MacroII: MQT->getMacroIdentifier());
3873 }
3874
3875 default:
3876 return Adjust(Orig);
3877 }
3878}
3879
3880const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3881 FunctionType::ExtInfo Info) {
3882 if (T->getExtInfo() == Info)
3883 return T;
3884
3885 QualType Result;
3886 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3887 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3888 } else {
3889 const auto *FPT = cast<FunctionProtoType>(Val: T);
3890 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3891 EPI.ExtInfo = Info;
3892 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3893 }
3894
3895 return cast<FunctionType>(Val: Result.getTypePtr());
3896}
3897
3898QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3899 QualType ResultType) {
3900 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3901 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3902 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3903
3904 const auto *FPT = Orig->castAs<FunctionProtoType>();
3905 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3906 EPI: FPT->getExtProtoInfo());
3907 });
3908}
3909
3910void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3911 QualType ResultType) {
3912 FD = FD->getMostRecentDecl();
3913 while (true) {
3914 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3915 if (FunctionDecl *Next = FD->getPreviousDecl())
3916 FD = Next;
3917 else
3918 break;
3919 }
3920 if (ASTMutationListener *L = getASTMutationListener())
3921 L->DeducedReturnType(FD, ReturnType: ResultType);
3922}
3923
3924/// Get a function type and produce the equivalent function type with the
3925/// specified exception specification. Type sugar that can be present on a
3926/// declaration of a function with an exception specification is permitted
3927/// and preserved. Other type sugar (for instance, typedefs) is not.
3928QualType ASTContext::getFunctionTypeWithExceptionSpec(
3929 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3930 return adjustType(Orig, Adjust: [&](QualType Ty) {
3931 const auto *Proto = Ty->castAs<FunctionProtoType>();
3932 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3933 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3934 });
3935}
3936
3937bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3938 QualType U) const {
3939 return hasSameType(T1: T, T2: U) ||
3940 (getLangOpts().CPlusPlus17 &&
3941 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3942 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3943}
3944
3945QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3946 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3947 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3948 SmallVector<QualType, 16> Args(Proto->param_types().size());
3949 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3950 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3951 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3952 }
3953
3954 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3955 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3956 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3957 }
3958
3959 return T;
3960}
3961
3962bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3963 return hasSameType(T1: T, T2: U) ||
3964 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3965 T2: getFunctionTypeWithoutPtrSizes(T: U));
3966}
3967
3968QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3969 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3970 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3971 EPI.ExtParameterInfos = nullptr;
3972 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3973 }
3974 return T;
3975}
3976
3977bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3978 QualType U) const {
3979 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3980 T2: getFunctionTypeWithoutParamABIs(T: U));
3981}
3982
3983void ASTContext::adjustExceptionSpec(
3984 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3985 bool AsWritten) {
3986 // Update the type.
3987 QualType Updated =
3988 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
3989 FD->setType(Updated);
3990
3991 if (!AsWritten)
3992 return;
3993
3994 // Update the type in the type source information too.
3995 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3996 // If the type and the type-as-written differ, we may need to update
3997 // the type-as-written too.
3998 if (TSInfo->getType() != FD->getType())
3999 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
4000
4001 // FIXME: When we get proper type location information for exceptions,
4002 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4003 // up the TypeSourceInfo;
4004 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4005 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4006 "TypeLoc size mismatch from updating exception specification");
4007 TSInfo->overrideType(T: Updated);
4008 }
4009}
4010
4011/// getComplexType - Return the uniqued reference to the type for a complex
4012/// number with the specified element type.
4013QualType ASTContext::getComplexType(QualType T) const {
4014 // Unique pointers, to guarantee there is only one pointer of a particular
4015 // structure.
4016 llvm::FoldingSetInsertToken Token;
4017 if (ComplexType *CT = ComplexTypes.lookup(Key: T, Token))
4018 return QualType(CT, 0);
4019
4020 // If the pointee type isn't canonical, this won't be a canonical type either,
4021 // so fill in the canonical type field.
4022 QualType Canonical;
4023 if (!T.isCanonical()) {
4024 Canonical = getComplexType(T: getCanonicalType(T));
4025
4026 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4027 }
4028 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4029 Types.push_back(Elt: New);
4030 ComplexTypes.insert(N: New, Token);
4031 return QualType(New, 0);
4032}
4033
4034/// getPointerType - Return the uniqued reference to the type for a pointer to
4035/// the specified type.
4036QualType ASTContext::getPointerType(QualType T) const {
4037 // Unique pointers, to guarantee there is only one pointer of a particular
4038 // structure.
4039 llvm::FoldingSetInsertToken Token;
4040 if (PointerType *PT = PointerTypes.lookup(Key: T, Token))
4041 return QualType(PT, 0);
4042
4043 // If the pointee type isn't canonical, this won't be a canonical type either,
4044 // so fill in the canonical type field.
4045 QualType Canonical;
4046 if (!T.isCanonical()) {
4047 Canonical = getPointerType(T: getCanonicalType(T));
4048
4049 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4050 }
4051 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4052 Types.push_back(Elt: New);
4053 PointerTypes.insert(N: New, Token);
4054 return QualType(New, 0);
4055}
4056
4057QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4058 llvm::FoldingSetInsertToken Token;
4059 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, New}, Token);
4060 if (AT)
4061 return QualType(AT, 0);
4062
4063 QualType Canonical = getCanonicalType(T: New);
4064
4065 AT = new (*this, alignof(AdjustedType))
4066 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4067 Types.push_back(Elt: AT);
4068 AdjustedTypes.insert(N: AT, Token);
4069 return QualType(AT, 0);
4070}
4071
4072QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4073 llvm::FoldingSetInsertToken Token;
4074 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, Decayed}, Token);
4075 if (AT)
4076 return QualType(AT, 0);
4077
4078 QualType Canonical = getCanonicalType(T: Decayed);
4079
4080 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4081 Types.push_back(Elt: AT);
4082 AdjustedTypes.insert(N: AT, Token);
4083 return QualType(AT, 0);
4084}
4085
4086QualType ASTContext::getDecayedType(QualType T) const {
4087 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4088
4089 QualType Decayed;
4090
4091 // C99 6.7.5.3p7:
4092 // A declaration of a parameter as "array of type" shall be
4093 // adjusted to "qualified pointer to type", where the type
4094 // qualifiers (if any) are those specified within the [ and ] of
4095 // the array type derivation.
4096 if (T->isArrayType())
4097 Decayed = getArrayDecayedType(T);
4098
4099 // C99 6.7.5.3p8:
4100 // A declaration of a parameter as "function returning type"
4101 // shall be adjusted to "pointer to function returning type", as
4102 // in 6.3.2.1.
4103 if (T->isFunctionType())
4104 Decayed = getPointerType(T);
4105
4106 return getDecayedType(Orig: T, Decayed);
4107}
4108
4109QualType ASTContext::getArrayParameterType(QualType Ty) const {
4110 if (Ty->isArrayParameterType())
4111 return Ty;
4112 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4113 QualType DTy = Ty.getDesugaredType(Context: *this);
4114 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4115 llvm::FoldingSetNodeID ID;
4116 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4117 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4118 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4119 llvm::FoldingSetInsertToken Token;
4120 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4121 if (AT)
4122 return QualType(AT, 0);
4123
4124 QualType Canonical;
4125 if (!DTy.isCanonical()) {
4126 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4127
4128 // Get the new insert position for the node we care about.
4129 AT = ArrayParameterTypes.lookup(ID, Token);
4130 assert(!AT && "Shouldn't be in the map!");
4131 }
4132
4133 AT = new (*this, alignof(ArrayParameterType))
4134 ArrayParameterType(ATy, Canonical);
4135 Types.push_back(Elt: AT);
4136 ArrayParameterTypes.insert(N: AT, Token);
4137 return QualType(AT, 0);
4138}
4139
4140/// getBlockPointerType - Return the uniqued reference to the type for
4141/// a pointer to the specified block.
4142QualType ASTContext::getBlockPointerType(QualType T) const {
4143 assert(T->isFunctionType() && "block of function types only");
4144 // Unique pointers, to guarantee there is only one block of a particular
4145 // structure.
4146 llvm::FoldingSetInsertToken Token;
4147 if (BlockPointerType *PT = BlockPointerTypes.lookup(Key: T, Token))
4148 return QualType(PT, 0);
4149
4150 // If the block pointee type isn't canonical, this won't be a canonical
4151 // type either so fill in the canonical type field.
4152 QualType Canonical;
4153 if (!T.isCanonical()) {
4154 Canonical = getBlockPointerType(T: getCanonicalType(T));
4155
4156 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4157 }
4158 auto *New =
4159 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4160 Types.push_back(Elt: New);
4161 BlockPointerTypes.insert(N: New, Token);
4162 return QualType(New, 0);
4163}
4164
4165/// getLValueReferenceType - Return the uniqued reference to the type for an
4166/// lvalue reference to the specified type.
4167QualType
4168ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4169 assert((!T->isPlaceholderType() ||
4170 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4171 "Unresolved placeholder type");
4172
4173 // Unique pointers, to guarantee there is only one pointer of a particular
4174 // structure.
4175 llvm::FoldingSetInsertToken Token;
4176 if (LValueReferenceType *RT =
4177 LValueReferenceTypes.lookup(Key: {T, SpelledAsLValue}, Token))
4178 return QualType(RT, 0);
4179
4180 const auto *InnerRef = T->getAs<ReferenceType>();
4181
4182 // If the referencee type isn't canonical, this won't be a canonical type
4183 // either, so fill in the canonical type field.
4184 QualType Canonical;
4185 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4186 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4187 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4188
4189 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4190 "Shouldn't be in the map!");
4191 }
4192
4193 auto *New = new (*this, alignof(LValueReferenceType))
4194 LValueReferenceType(T, Canonical, SpelledAsLValue);
4195 Types.push_back(Elt: New);
4196 LValueReferenceTypes.insert(N: New, Token);
4197
4198 return QualType(New, 0);
4199}
4200
4201/// getRValueReferenceType - Return the uniqued reference to the type for an
4202/// rvalue reference to the specified type.
4203QualType ASTContext::getRValueReferenceType(QualType T) const {
4204 assert((!T->isPlaceholderType() ||
4205 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4206 "Unresolved placeholder type");
4207
4208 // Unique pointers, to guarantee there is only one pointer of a particular
4209 // structure.
4210 llvm::FoldingSetInsertToken Token;
4211 if (RValueReferenceType *RT = RValueReferenceTypes.lookup(Key: {T, false}, Token))
4212 return QualType(RT, 0);
4213
4214 const auto *InnerRef = T->getAs<ReferenceType>();
4215
4216 // If the referencee type isn't canonical, this won't be a canonical type
4217 // either, so fill in the canonical type field.
4218 QualType Canonical;
4219 if (InnerRef || !T.isCanonical()) {
4220 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4221 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4222
4223 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4224 "Shouldn't be in the map!");
4225 }
4226
4227 auto *New = new (*this, alignof(RValueReferenceType))
4228 RValueReferenceType(T, Canonical);
4229 Types.push_back(Elt: New);
4230 RValueReferenceTypes.insert(N: New, Token);
4231 return QualType(New, 0);
4232}
4233
4234QualType ASTContext::getMemberPointerType(QualType T,
4235 NestedNameSpecifier Qualifier,
4236 const CXXRecordDecl *Cls) const {
4237 if (!Qualifier) {
4238 assert(Cls && "At least one of Qualifier or Cls must be provided");
4239 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4240 } else if (!Cls) {
4241 Cls = Qualifier.getAsRecordDecl();
4242 }
4243 // Unique pointers, to guarantee there is only one pointer of a particular
4244 // structure.
4245 llvm::FoldingSetNodeID ID;
4246 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4247
4248 llvm::FoldingSetInsertToken Token;
4249 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4250 return QualType(PT, 0);
4251
4252 NestedNameSpecifier CanonicalQualifier = [&] {
4253 if (!Cls)
4254 return Qualifier.getCanonical();
4255 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4256 assert(R.isCanonical());
4257 return R;
4258 }();
4259 // If the pointee or class type isn't canonical, this won't be a canonical
4260 // type either, so fill in the canonical type field.
4261 QualType Canonical;
4262 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4263 Canonical =
4264 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4265 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4266 // Get the new insert position for the node we care about.
4267 [[maybe_unused]] MemberPointerType *NewIP =
4268 MemberPointerTypes.lookup(ID, Token);
4269 assert(!NewIP && "Shouldn't be in the map!");
4270 }
4271 auto *New = new (*this, alignof(MemberPointerType))
4272 MemberPointerType(T, Qualifier, Canonical);
4273 Types.push_back(Elt: New);
4274 MemberPointerTypes.insert(N: New, Token);
4275 return QualType(New, 0);
4276}
4277
4278/// getConstantArrayType - Return the unique reference to the type for an
4279/// array of the specified element type.
4280QualType ASTContext::getConstantArrayType(QualType EltTy,
4281 const llvm::APInt &ArySizeIn,
4282 const Expr *SizeExpr,
4283 ArraySizeModifier ASM,
4284 unsigned IndexTypeQuals) const {
4285 assert((EltTy->isDependentType() ||
4286 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4287 "Constant array of VLAs is illegal!");
4288
4289 // We only need the size as part of the type if it's instantiation-dependent.
4290 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4291 SizeExpr = nullptr;
4292
4293 // Convert the array size into a canonical width matching the pointer size for
4294 // the target.
4295 llvm::APInt ArySize(ArySizeIn);
4296 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4297
4298 // The type stores only the CVR bits of the index qualifiers, so key on
4299 // those.
4300 IndexTypeQuals &= Qualifiers::CVRMask;
4301
4302 llvm::FoldingSetNodeID ID;
4303 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4304 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4305
4306 llvm::FoldingSetInsertToken Token;
4307 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4308 return QualType(ATP, 0);
4309
4310 // If the element type isn't canonical or has qualifiers, or the array bound
4311 // is instantiation-dependent, this won't be a canonical type either, so fill
4312 // in the canonical type field.
4313 QualType Canon;
4314 // FIXME: Check below should look for qualifiers behind sugar.
4315 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4316 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4317 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4318 ASM, IndexTypeQuals);
4319 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4320
4321 // Get the new insert position for the node we care about.
4322 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4323 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4324 }
4325
4326 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4327 SzMod: ASM, Qual: IndexTypeQuals);
4328 ConstantArrayTypes.insert(N: New, Token);
4329 Types.push_back(Elt: New);
4330 return QualType(New, 0);
4331}
4332
4333/// getVariableArrayDecayedType - Turns the given type, which may be
4334/// variably-modified, into the corresponding type with all the known
4335/// sizes replaced with [*].
4336QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4337 // Vastly most common case.
4338 if (!type->isVariablyModifiedType()) return type;
4339
4340 QualType result;
4341
4342 SplitQualType split = type.getSplitDesugaredType();
4343 const Type *ty = split.Ty;
4344 switch (ty->getTypeClass()) {
4345#define TYPE(Class, Base)
4346#define ABSTRACT_TYPE(Class, Base)
4347#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4348#include "clang/AST/TypeNodes.inc"
4349 llvm_unreachable("didn't desugar past all non-canonical types?");
4350
4351 // These types should never be variably-modified.
4352 case Type::Builtin:
4353 case Type::Complex:
4354 case Type::Vector:
4355 case Type::DependentVector:
4356 case Type::ExtVector:
4357 case Type::DependentSizedExtVector:
4358 case Type::ConstantMatrix:
4359 case Type::DependentSizedMatrix:
4360 case Type::DependentAddressSpace:
4361 case Type::ObjCObject:
4362 case Type::ObjCInterface:
4363 case Type::ObjCObjectPointer:
4364 case Type::Record:
4365 case Type::Enum:
4366 case Type::UnresolvedUsing:
4367 case Type::TypeOfExpr:
4368 case Type::TypeOf:
4369 case Type::Decltype:
4370 case Type::UnaryTransform:
4371 case Type::DependentName:
4372 case Type::InjectedClassName:
4373 case Type::TemplateSpecialization:
4374 case Type::TemplateTypeParm:
4375 case Type::SubstTemplateTypeParmPack:
4376 case Type::SubstBuiltinTemplatePack:
4377 case Type::Auto:
4378 case Type::DeducedTemplateSpecialization:
4379 case Type::PackExpansion:
4380 case Type::PackIndexing:
4381 case Type::BitInt:
4382 case Type::DependentBitInt:
4383 case Type::ArrayParameter:
4384 case Type::HLSLAttributedResource:
4385 case Type::HLSLInlineSpirv:
4386 case Type::OverflowBehavior:
4387 llvm_unreachable("type should never be variably-modified");
4388
4389 // These types can be variably-modified but should never need to
4390 // further decay.
4391 case Type::FunctionNoProto:
4392 case Type::FunctionProto:
4393 case Type::BlockPointer:
4394 case Type::MemberPointer:
4395 case Type::Pipe:
4396 return type;
4397
4398 // These types can be variably-modified. All these modifications
4399 // preserve structure except as noted by comments.
4400 // TODO: if we ever care about optimizing VLAs, there are no-op
4401 // optimizations available here.
4402 case Type::Pointer:
4403 result = getPointerType(T: getVariableArrayDecayedType(
4404 type: cast<PointerType>(Val: ty)->getPointeeType()));
4405 break;
4406
4407 case Type::LValueReference: {
4408 const auto *lv = cast<LValueReferenceType>(Val: ty);
4409 result = getLValueReferenceType(
4410 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4411 SpelledAsLValue: lv->isSpelledAsLValue());
4412 break;
4413 }
4414
4415 case Type::RValueReference: {
4416 const auto *lv = cast<RValueReferenceType>(Val: ty);
4417 result = getRValueReferenceType(
4418 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4419 break;
4420 }
4421
4422 case Type::Atomic: {
4423 const auto *at = cast<AtomicType>(Val: ty);
4424 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4425 break;
4426 }
4427
4428 case Type::ConstantArray: {
4429 const auto *cat = cast<ConstantArrayType>(Val: ty);
4430 result = getConstantArrayType(
4431 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4432 ArySizeIn: cat->getSize(),
4433 SizeExpr: cat->getSizeExpr(),
4434 ASM: cat->getSizeModifier(),
4435 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4436 break;
4437 }
4438
4439 case Type::DependentSizedArray: {
4440 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4441 result = getDependentSizedArrayType(
4442 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4443 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4444 break;
4445 }
4446
4447 // Turn incomplete types into [*] types.
4448 case Type::IncompleteArray: {
4449 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4450 result =
4451 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4452 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4453 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4454 break;
4455 }
4456
4457 // Turn VLA types into [*] types.
4458 case Type::VariableArray: {
4459 const auto *vat = cast<VariableArrayType>(Val: ty);
4460 result =
4461 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4462 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4463 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4464 break;
4465 }
4466 }
4467
4468 // Apply the top-level qualifiers from the original.
4469 return getQualifiedType(T: result, Qs: split.Quals);
4470}
4471
4472/// getVariableArrayType - Returns a non-unique reference to the type for a
4473/// variable array of the specified element type.
4474QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4475 ArraySizeModifier ASM,
4476 unsigned IndexTypeQuals) const {
4477 // Since we don't unique expressions, it isn't possible to unique VLA's
4478 // that have an expression provided for their size.
4479 QualType Canon;
4480
4481 // Be sure to pull qualifiers off the element type.
4482 // FIXME: Check below should look for qualifiers behind sugar.
4483 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4484 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4485 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4486 IndexTypeQuals);
4487 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4488 }
4489
4490 auto *New = new (*this, alignof(VariableArrayType))
4491 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4492
4493 VariableArrayTypes.push_back(x: New);
4494 Types.push_back(Elt: New);
4495 return QualType(New, 0);
4496}
4497
4498/// getDependentSizedArrayType - Returns a non-unique reference to
4499/// the type for a dependently-sized array of the specified element
4500/// type.
4501QualType
4502ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4503 ArraySizeModifier ASM,
4504 unsigned elementTypeQuals) const {
4505 assert((!numElements || numElements->isTypeDependent() ||
4506 numElements->isValueDependent()) &&
4507 "Size must be type- or value-dependent!");
4508
4509 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4510
4511 llvm::FoldingSetInsertToken Token;
4512 llvm::FoldingSetNodeID ID;
4513 DependentSizedArrayType::Profile(
4514 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4515 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4516
4517 // Look for an existing type with these properties.
4518 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4519
4520 // Dependently-sized array types that do not have a specified number
4521 // of elements will have their sizes deduced from a dependent
4522 // initializer.
4523 if (!numElements) {
4524 if (canonTy)
4525 return QualType(canonTy, 0);
4526
4527 auto *newType = new (*this, alignof(DependentSizedArrayType))
4528 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4529 elementTypeQuals);
4530 DependentSizedArrayTypes.insert(N: newType, Token);
4531 Types.push_back(Elt: newType);
4532 return QualType(newType, 0);
4533 }
4534
4535 // If we don't have one, build one.
4536 if (!canonTy) {
4537 canonTy = new (*this, alignof(DependentSizedArrayType))
4538 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4539 numElements, ASM, elementTypeQuals);
4540 DependentSizedArrayTypes.insert(N: canonTy, Token);
4541 Types.push_back(Elt: canonTy);
4542 }
4543
4544 // Apply qualifiers from the element type to the array.
4545 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4546 Qs: canonElementType.Quals);
4547
4548 // If we didn't need extra canonicalization for the element type or the size
4549 // expression, then just use that as our result.
4550 if (QualType(canonElementType.Ty, 0) == elementType &&
4551 canonTy->getSizeExpr() == numElements)
4552 return canon;
4553
4554 // Otherwise, we need to build a type which follows the spelling
4555 // of the element type.
4556 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4557 DependentSizedArrayType(elementType, canon, numElements, ASM,
4558 elementTypeQuals);
4559 Types.push_back(Elt: sugaredType);
4560 return QualType(sugaredType, 0);
4561}
4562
4563QualType ASTContext::getIncompleteArrayType(QualType elementType,
4564 ArraySizeModifier ASM,
4565 unsigned elementTypeQuals) const {
4566 llvm::FoldingSetNodeID ID;
4567 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4568
4569 llvm::FoldingSetInsertToken Token;
4570 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4571 return QualType(iat, 0);
4572
4573 // If the element type isn't canonical, this won't be a canonical type
4574 // either, so fill in the canonical type field. We also have to pull
4575 // qualifiers off the element type.
4576 QualType canon;
4577
4578 // FIXME: Check below should look for qualifiers behind sugar.
4579 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4580 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4581 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4582 ASM, elementTypeQuals);
4583 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4584
4585 // Get the new insert position for the node we care about.
4586 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4587 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4588 }
4589
4590 auto *newType = new (*this, alignof(IncompleteArrayType))
4591 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4592
4593 IncompleteArrayTypes.insert(N: newType, Token);
4594 Types.push_back(Elt: newType);
4595 return QualType(newType, 0);
4596}
4597
4598ASTContext::BuiltinVectorTypeInfo
4599ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4600#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4601 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4602 NUMVECTORS};
4603
4604#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4605 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4606
4607 switch (Ty->getKind()) {
4608 default:
4609 llvm_unreachable("Unsupported builtin vector type");
4610
4611#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4612 ElBits, NF, IsSigned) \
4613 case BuiltinType::Id: \
4614 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4615 llvm::ElementCount::getScalable(NumEls), NF};
4616#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4617 ElBits, NF) \
4618 case BuiltinType::Id: \
4619 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4620 llvm::ElementCount::getScalable(NumEls), NF};
4621#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4622 ElBits, NF) \
4623 case BuiltinType::Id: \
4624 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4625#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4626 ElBits, NF) \
4627 case BuiltinType::Id: \
4628 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4629#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4630 case BuiltinType::Id: \
4631 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4632#include "clang/Basic/AArch64ACLETypes.def"
4633
4634#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4635 IsSigned) \
4636 case BuiltinType::Id: \
4637 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4638 llvm::ElementCount::getScalable(NumEls), NF};
4639#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4640 case BuiltinType::Id: \
4641 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4642 llvm::ElementCount::getScalable(NumEls), NF};
4643#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4644 case BuiltinType::Id: \
4645 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4646#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4647 case BuiltinType::Id: \
4648 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4649#include "clang/Basic/RISCVVTypes.def"
4650 }
4651}
4652
4653/// getExternrefType - Return a WebAssembly externref type, which represents an
4654/// opaque reference to a host value.
4655QualType ASTContext::getWebAssemblyExternrefType() const {
4656 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4657#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4658 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4659 return SingletonId;
4660#include "clang/Basic/WebAssemblyReferenceTypes.def"
4661 }
4662 llvm_unreachable(
4663 "shouldn't try to generate type externref outside WebAssembly target");
4664}
4665
4666/// getScalableVectorType - Return the unique reference to a scalable vector
4667/// type of the specified element type and size. VectorType must be a built-in
4668/// type.
4669QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4670 unsigned NumFields) const {
4671 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4672 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4673 return It->second;
4674
4675 if (Target->hasAArch64ACLETypes()) {
4676 uint64_t EltTySize = getTypeSize(T: EltTy);
4677
4678#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4679 ElBits, NF, IsSigned) \
4680 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4681 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4682 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4683 return ScalableVecTyMap[K] = SingletonId; \
4684 }
4685#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4686 ElBits, NF) \
4687 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4688 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4689 return ScalableVecTyMap[K] = SingletonId; \
4690 }
4691#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4692 ElBits, NF) \
4693 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4694 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4695 return ScalableVecTyMap[K] = SingletonId; \
4696 }
4697#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4698 ElBits, NF) \
4699 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4700 NumElts == (NumEls * NF) && NumFields == 1) { \
4701 return ScalableVecTyMap[K] = SingletonId; \
4702 }
4703#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4704 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4705 return ScalableVecTyMap[K] = SingletonId;
4706#include "clang/Basic/AArch64ACLETypes.def"
4707 } else if (Target->hasRISCVVTypes()) {
4708 uint64_t EltTySize = getTypeSize(T: EltTy);
4709#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4710 IsFP, IsBF) \
4711 if (!EltTy->isBooleanType() && \
4712 ((EltTy->hasIntegerRepresentation() && \
4713 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4714 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4715 IsFP && !IsBF) || \
4716 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4717 IsBF && !IsFP)) && \
4718 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4719 return ScalableVecTyMap[K] = SingletonId;
4720#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4721 if (EltTy->isBooleanType() && NumElts == NumEls) \
4722 return ScalableVecTyMap[K] = SingletonId;
4723#include "clang/Basic/RISCVVTypes.def"
4724 }
4725 return QualType();
4726}
4727
4728/// getVectorType - Return the unique reference to a vector type of
4729/// the specified element type and size. VectorType must be a built-in type.
4730QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4731 VectorKind VecKind) const {
4732 assert(vecType->isBuiltinType() ||
4733 (vecType->isBitIntType() &&
4734 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4735 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4736
4737 // Check if we've already instantiated a vector of this type.
4738 llvm::FoldingSetNodeID ID;
4739 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4740
4741 llvm::FoldingSetInsertToken Token;
4742 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4743 return QualType(VTP, 0);
4744
4745 // If the element type isn't canonical, this won't be a canonical type either,
4746 // so fill in the canonical type field.
4747 QualType Canonical;
4748 if (!vecType.isCanonical()) {
4749 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4750
4751 // Get the new insert position for the node we care about.
4752 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4753 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4754 }
4755 auto *New = new (*this, alignof(VectorType))
4756 VectorType(vecType, NumElts, Canonical, VecKind);
4757 VectorTypes.insert(N: New, Token);
4758 Types.push_back(Elt: New);
4759 return QualType(New, 0);
4760}
4761
4762QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4763 SourceLocation AttrLoc,
4764 VectorKind VecKind) const {
4765 llvm::FoldingSetNodeID ID;
4766 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4767 VecKind);
4768 llvm::FoldingSetInsertToken Token;
4769 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4770 DependentVectorType *New;
4771
4772 if (Canon) {
4773 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4774 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4775 } else {
4776 QualType CanonVecTy = getCanonicalType(T: VecType);
4777 if (CanonVecTy == VecType) {
4778 New = new (*this, alignof(DependentVectorType))
4779 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4780
4781 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4782 assert(!CanonCheck &&
4783 "Dependent-sized vector_size canonical type broken");
4784 (void)CanonCheck;
4785 DependentVectorTypes.insert(N: New, Token);
4786 } else {
4787 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4788 AttrLoc: SourceLocation(), VecKind);
4789 New = new (*this, alignof(DependentVectorType))
4790 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4791 }
4792 }
4793
4794 Types.push_back(Elt: New);
4795 return QualType(New, 0);
4796}
4797
4798/// getExtVectorType - Return the unique reference to an extended vector type of
4799/// the specified element type and size. VectorType must be a built-in type.
4800QualType ASTContext::getExtVectorType(QualType vecType,
4801 unsigned NumElts) const {
4802 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4803 (vecType->isBitIntType() &&
4804 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4805 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4806
4807 // Check if we've already instantiated a vector of this type.
4808 llvm::FoldingSetNodeID ID;
4809 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4810 VecKind: VectorKind::Generic);
4811 llvm::FoldingSetInsertToken Token;
4812 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4813 return QualType(VTP, 0);
4814
4815 // If the element type isn't canonical, this won't be a canonical type either,
4816 // so fill in the canonical type field.
4817 QualType Canonical;
4818 if (!vecType.isCanonical()) {
4819 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4820
4821 // Get the new insert position for the node we care about.
4822 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4823 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4824 }
4825 auto *New = new (*this, alignof(ExtVectorType))
4826 ExtVectorType(vecType, NumElts, Canonical);
4827 VectorTypes.insert(N: New, Token);
4828 Types.push_back(Elt: New);
4829 return QualType(New, 0);
4830}
4831
4832QualType
4833ASTContext::getDependentSizedExtVectorType(QualType vecType,
4834 Expr *SizeExpr,
4835 SourceLocation AttrLoc) const {
4836 llvm::FoldingSetNodeID ID;
4837 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4838 SizeExpr);
4839
4840 llvm::FoldingSetInsertToken Token;
4841 DependentSizedExtVectorType *Canon =
4842 DependentSizedExtVectorTypes.lookup(ID, Token);
4843 DependentSizedExtVectorType *New;
4844 if (Canon) {
4845 // We already have a canonical version of this array type; use it as
4846 // the canonical type for a newly-built type.
4847 New = new (*this, alignof(DependentSizedExtVectorType))
4848 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4849 AttrLoc);
4850 } else {
4851 QualType CanonVecTy = getCanonicalType(T: vecType);
4852 if (CanonVecTy == vecType) {
4853 New = new (*this, alignof(DependentSizedExtVectorType))
4854 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4855
4856 DependentSizedExtVectorType *CanonCheck =
4857 DependentSizedExtVectorTypes.lookup(ID, Token);
4858 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4859 (void)CanonCheck;
4860 DependentSizedExtVectorTypes.insert(N: New, Token);
4861 } else {
4862 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4863 AttrLoc: SourceLocation());
4864 New = new (*this, alignof(DependentSizedExtVectorType))
4865 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4866 }
4867 }
4868
4869 Types.push_back(Elt: New);
4870 return QualType(New, 0);
4871}
4872
4873QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4874 unsigned NumColumns) const {
4875 llvm::FoldingSetNodeID ID;
4876 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns,
4877 TypeClass: Type::ConstantMatrix);
4878
4879 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4880 "need a valid element type");
4881 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4882 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4883 "need valid matrix dimensions");
4884 llvm::FoldingSetInsertToken Token;
4885 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4886 return QualType(MTP, 0);
4887
4888 QualType Canonical;
4889 if (!ElementTy.isCanonical()) {
4890 Canonical =
4891 getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows, NumColumns);
4892
4893 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4894 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4895 (void)NewIP;
4896 }
4897
4898 auto *New = new (*this, alignof(ConstantMatrixType))
4899 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4900 MatrixTypes.insert(N: New, Token);
4901 Types.push_back(Elt: New);
4902 return QualType(New, 0);
4903}
4904
4905QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4906 Expr *RowExpr,
4907 Expr *ColumnExpr,
4908 SourceLocation AttrLoc) const {
4909 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4910 llvm::FoldingSetNodeID ID;
4911 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4912 ColumnExpr);
4913
4914 llvm::FoldingSetInsertToken Token;
4915 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4916
4917 if (!Canon) {
4918 Canon = new (*this, alignof(DependentSizedMatrixType))
4919 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4920 ColumnExpr, AttrLoc);
4921#ifndef NDEBUG
4922 DependentSizedMatrixType *CanonCheck =
4923 DependentSizedMatrixTypes.lookup(ID, Token);
4924 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4925#endif
4926 DependentSizedMatrixTypes.insert(N: Canon, Token);
4927 Types.push_back(Elt: Canon);
4928 }
4929
4930 // Already have a canonical version of the matrix type
4931 //
4932 // If it exactly matches the requested type, use it directly.
4933 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4934 Canon->getRowExpr() == ColumnExpr)
4935 return QualType(Canon, 0);
4936
4937 // Use Canon as the canonical type for newly-built type.
4938 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4939 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4940 ColumnExpr, AttrLoc);
4941 Types.push_back(Elt: New);
4942 return QualType(New, 0);
4943}
4944
4945QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4946 Expr *AddrSpaceExpr,
4947 SourceLocation AttrLoc) const {
4948 assert(AddrSpaceExpr->isInstantiationDependent());
4949
4950 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4951
4952 llvm::FoldingSetInsertToken Token;
4953 llvm::FoldingSetNodeID ID;
4954 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4955 AddrSpaceExpr);
4956
4957 DependentAddressSpaceType *canonTy =
4958 DependentAddressSpaceTypes.lookup(ID, Token);
4959
4960 if (!canonTy) {
4961 canonTy = new (*this, alignof(DependentAddressSpaceType))
4962 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4963 AttrLoc);
4964 DependentAddressSpaceTypes.insert(N: canonTy, Token);
4965 Types.push_back(Elt: canonTy);
4966 }
4967
4968 if (canonPointeeType == PointeeType &&
4969 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4970 return QualType(canonTy, 0);
4971
4972 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4973 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4974 AddrSpaceExpr, AttrLoc);
4975 Types.push_back(Elt: sugaredType);
4976 return QualType(sugaredType, 0);
4977}
4978
4979/// Determine whether \p T is canonical as the result type of a function.
4980static bool isCanonicalResultType(QualType T) {
4981 return T.isCanonical() &&
4982 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4983 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4984}
4985
4986/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4987QualType
4988ASTContext::getFunctionNoProtoType(QualType ResultTy,
4989 const FunctionType::ExtInfo &Info) const {
4990 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4991 // functionality creates a function without a prototype regardless of
4992 // language mode (so it makes them even in C++). Once the rewriter has been
4993 // fixed, this assertion can be enabled again.
4994 //assert(!LangOpts.requiresStrictPrototypes() &&
4995 // "strict prototypes are disabled");
4996
4997 // Unique functions, to guarantee there is only one function of a particular
4998 // structure.
4999 llvm::FoldingSetNodeID ID;
5000 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
5001
5002 llvm::FoldingSetInsertToken Token;
5003 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5004 return QualType(FT, 0);
5005
5006 QualType Canonical;
5007 if (!isCanonicalResultType(T: ResultTy)) {
5008 Canonical =
5009 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
5010
5011 // Get the new insert position for the node we care about.
5012 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5013 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5014 }
5015
5016 auto *New = new (*this, alignof(FunctionNoProtoType))
5017 FunctionNoProtoType(ResultTy, Canonical, Info);
5018 Types.push_back(Elt: New);
5019 FunctionNoProtoTypes.insert(N: New, Token);
5020 return QualType(New, 0);
5021}
5022
5023CanQualType
5024ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5025 CanQualType CanResultType = getCanonicalType(T: ResultType);
5026
5027 // Canonical result types do not have ARC lifetime qualifiers.
5028 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5029 Qualifiers Qs = CanResultType.getQualifiers();
5030 Qs.removeObjCLifetime();
5031 return CanQualType::CreateUnsafe(
5032 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5033 }
5034
5035 return CanResultType;
5036}
5037
5038static bool isCanonicalExceptionSpecification(
5039 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5040 if (ESI.Type == EST_None)
5041 return true;
5042 if (!NoexceptInType)
5043 return false;
5044
5045 // C++17 onwards: exception specification is part of the type, as a simple
5046 // boolean "can this function type throw".
5047 if (ESI.Type == EST_BasicNoexcept)
5048 return true;
5049
5050 // A noexcept(expr) specification is (possibly) canonical if expr is
5051 // value-dependent.
5052 if (ESI.Type == EST_DependentNoexcept)
5053 return true;
5054
5055 // A dynamic exception specification is canonical if it only contains pack
5056 // expansions (so we can't tell whether it's non-throwing) and all its
5057 // contained types are canonical.
5058 if (ESI.Type == EST_Dynamic) {
5059 bool AnyPackExpansions = false;
5060 for (QualType ET : ESI.Exceptions) {
5061 if (!ET.isCanonical())
5062 return false;
5063 if (ET->getAs<PackExpansionType>())
5064 AnyPackExpansions = true;
5065 }
5066 return AnyPackExpansions;
5067 }
5068
5069 return false;
5070}
5071
5072QualType ASTContext::getFunctionTypeInternal(
5073 QualType ResultTy, ArrayRef<QualType> ArgArray,
5074 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5075 size_t NumArgs = ArgArray.size();
5076
5077 // Unique functions, to guarantee there is only one function of a particular
5078 // structure.
5079 llvm::FoldingSetNodeID ID;
5080 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5081 Context: *this);
5082
5083 QualType Canonical;
5084 bool Unique = false;
5085
5086 llvm::FoldingSetInsertToken Token;
5087 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5088 QualType Existing = QualType(FPT, 0);
5089
5090 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5091 // it so long as our exception specification doesn't contain a dependent
5092 // noexcept expression, or we're just looking for a canonical type.
5093 // Otherwise, we're going to need to create a type
5094 // sugar node to hold the concrete expression.
5095 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5096 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5097 return Existing;
5098
5099 // We need a new type sugar node for this one, to hold the new noexcept
5100 // expression. We do no canonicalization here, but that's OK since we don't
5101 // expect to see the same noexcept expression much more than once.
5102 Canonical = getCanonicalType(T: Existing);
5103 Unique = true;
5104 }
5105
5106 bool NoexceptInType = getLangOpts().CPlusPlus17;
5107 bool IsCanonicalExceptionSpec =
5108 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5109
5110 // Determine whether the type being created is already canonical or not.
5111 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5112 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5113 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5114 if (!ArgArray[i].isCanonicalAsParam())
5115 isCanonical = false;
5116
5117 if (OnlyWantCanonical)
5118 assert(isCanonical &&
5119 "given non-canonical parameters constructing canonical type");
5120
5121 // If this type isn't canonical, get the canonical version of it if we don't
5122 // already have it. The exception spec is only partially part of the
5123 // canonical type, and only in C++17 onwards.
5124 if (!isCanonical && Canonical.isNull()) {
5125 SmallVector<QualType, 16> CanonicalArgs;
5126 CanonicalArgs.reserve(N: NumArgs);
5127 for (unsigned i = 0; i != NumArgs; ++i)
5128 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5129
5130 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5131 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5132 CanonicalEPI.HasTrailingReturn = false;
5133
5134 if (IsCanonicalExceptionSpec) {
5135 // Exception spec is already OK.
5136 } else if (NoexceptInType) {
5137 switch (EPI.ExceptionSpec.Type) {
5138 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5139 // We don't know yet. It shouldn't matter what we pick here; no-one
5140 // should ever look at this.
5141 [[fallthrough]];
5142 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5143 CanonicalEPI.ExceptionSpec.Type = EST_None;
5144 break;
5145
5146 // A dynamic exception specification is almost always "not noexcept",
5147 // with the exception that a pack expansion might expand to no types.
5148 case EST_Dynamic: {
5149 bool AnyPacks = false;
5150 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5151 if (ET->getAs<PackExpansionType>())
5152 AnyPacks = true;
5153 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5154 }
5155 if (!AnyPacks)
5156 CanonicalEPI.ExceptionSpec.Type = EST_None;
5157 else {
5158 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5159 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5160 }
5161 break;
5162 }
5163
5164 case EST_DynamicNone:
5165 case EST_BasicNoexcept:
5166 case EST_NoexceptTrue:
5167 case EST_NoThrow:
5168 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5169 break;
5170
5171 case EST_DependentNoexcept:
5172 llvm_unreachable("dependent noexcept is already canonical");
5173 }
5174 } else {
5175 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5176 }
5177
5178 // Adjust the canonical function result type.
5179 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5180 Canonical =
5181 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5182
5183 // Get the new insert position for the node we care about.
5184 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5185 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5186 }
5187
5188 // Compute the needed size to hold this FunctionProtoType and the
5189 // various trailing objects.
5190 auto ESH = FunctionProtoType::getExceptionSpecSize(
5191 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5192 size_t Size = FunctionProtoType::totalSizeToAlloc<
5193 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5194 FunctionType::FunctionTypeExtraAttributeInfo,
5195 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5196 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5197 FunctionEffect, EffectConditionExpr>(
5198 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5199 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5200 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5201 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5202 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5203 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5204 Counts: EPI.FunctionEffects.conditions().size());
5205
5206 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5207 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5208 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5209 Types.push_back(Elt: FTP);
5210 if (!Unique)
5211 FunctionProtoTypes.insert(N: FTP, Token);
5212 if (!EPI.FunctionEffects.empty())
5213 AnyFunctionEffects = true;
5214 return QualType(FTP, 0);
5215}
5216
5217QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5218 llvm::FoldingSetInsertToken Token;
5219 if (PipeType *PT = PipeTypes.lookup(Key: {T, ReadOnly}, Token))
5220 return QualType(PT, 0);
5221
5222 // If the pipe element type isn't canonical, this won't be a canonical type
5223 // either, so fill in the canonical type field.
5224 QualType Canonical;
5225 if (!T.isCanonical()) {
5226 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5227
5228 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5229 "Shouldn't be in the map!");
5230 }
5231 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5232 Types.push_back(Elt: New);
5233 PipeTypes.insert(N: New, Token);
5234 return QualType(New, 0);
5235}
5236
5237QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5238 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5239 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5240 : Ty;
5241}
5242
5243QualType ASTContext::getReadPipeType(QualType T) const {
5244 return getPipeType(T, ReadOnly: true);
5245}
5246
5247QualType ASTContext::getWritePipeType(QualType T) const {
5248 return getPipeType(T, ReadOnly: false);
5249}
5250
5251QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5252 auto Key = std::make_pair(x: unsigned(IsUnsigned), y&: NumBits);
5253
5254 llvm::FoldingSetInsertToken Token;
5255 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5256 return QualType(EIT, 0);
5257
5258 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5259 BitIntTypes.insert(N: New, Token);
5260 Types.push_back(Elt: New);
5261 return QualType(New, 0);
5262}
5263
5264QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5265 Expr *NumBitsExpr) const {
5266 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5267 llvm::FoldingSetNodeID ID;
5268 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5269
5270 llvm::FoldingSetInsertToken Token;
5271 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5272 return QualType(Existing, 0);
5273
5274 auto *New = new (*this, alignof(DependentBitIntType))
5275 DependentBitIntType(IsUnsigned, NumBitsExpr);
5276 DependentBitIntTypes.insert(N: New, Token);
5277
5278 Types.push_back(Elt: New);
5279 return QualType(New, 0);
5280}
5281
5282QualType
5283ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5284 using Kind = PredefinedSugarType::Kind;
5285
5286 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5287 Target != nullptr)
5288 return QualType(Target, 0);
5289
5290 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5291 switch (KDI) {
5292 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5293 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5294 // are part of the core language and are widely used. Using
5295 // PredefinedSugarType makes these types as named sugar types rather than
5296 // standard integer types, enabling better hints and diagnostics.
5297 case Kind::SizeT:
5298 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5299 case Kind::SignedSizeT:
5300 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5301 case Kind::PtrdiffT:
5302 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5303 }
5304 llvm_unreachable("unexpected kind");
5305 };
5306 auto *New = new (*this, alignof(PredefinedSugarType))
5307 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5308 getCanonicalType(*this, static_cast<Kind>(KD)));
5309 Types.push_back(Elt: New);
5310 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5311 return QualType(New, 0);
5312}
5313
5314QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5315 NestedNameSpecifier Qualifier,
5316 const TypeDecl *Decl) const {
5317 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5318 return getTagType(Keyword, Qualifier, TD: Tag,
5319 /*OwnsTag=*/false);
5320 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5321 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5322 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5323 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5324
5325 assert(Keyword == ElaboratedTypeKeyword::None);
5326 assert(!Qualifier);
5327 return QualType(Decl->TypeForDecl, 0);
5328}
5329
5330CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5331 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5332 return getCanonicalTagType(TD: Tag);
5333 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5334 return getCanonicalType(T: TN->getUnderlyingType());
5335 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5336 return getCanonicalUnresolvedUsingType(D: UD);
5337 assert(TD->TypeForDecl);
5338 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5339}
5340
5341QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5342 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5343 return getCanonicalTagType(TD);
5344 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5345 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5346 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5347 /*Qualifier=*/std::nullopt, Decl: TD);
5348 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5349 return getCanonicalUnresolvedUsingType(D: Using);
5350
5351 assert(Decl->TypeForDecl);
5352 return QualType(Decl->TypeForDecl, 0);
5353}
5354
5355/// getTypedefType - Return the unique reference to the type for the
5356/// specified typedef name decl.
5357QualType
5358ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5359 NestedNameSpecifier Qualifier,
5360 const TypedefNameDecl *Decl, QualType UnderlyingType,
5361 std::optional<bool> TypeMatchesDeclOrNone) const {
5362 if (!TypeMatchesDeclOrNone) {
5363 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5364 assert(!DeclUnderlyingType.isNull());
5365 if (UnderlyingType.isNull())
5366 UnderlyingType = DeclUnderlyingType;
5367 else
5368 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5369 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5370 } else {
5371 // FIXME: This is a workaround for a serialization cycle: assume the decl
5372 // underlying type is not available; don't touch it.
5373 assert(!UnderlyingType.isNull());
5374 }
5375
5376 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5377 *TypeMatchesDeclOrNone) {
5378 if (Decl->TypeForDecl)
5379 return QualType(Decl->TypeForDecl, 0);
5380
5381 auto *NewType = new (*this, alignof(TypedefType))
5382 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5383 !*TypeMatchesDeclOrNone);
5384
5385 Types.push_back(Elt: NewType);
5386 Decl->TypeForDecl = NewType;
5387 return QualType(NewType, 0);
5388 }
5389
5390 llvm::FoldingSetNodeID ID;
5391 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5392 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5393
5394 llvm::FoldingSetInsertToken Token;
5395 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5396 TypedefTypes.lookup(ID, Token))
5397 return QualType(Placeholder->getType(), 0);
5398
5399 void *Mem =
5400 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5401 NestedNameSpecifier, QualType>(
5402 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5403 Align: alignof(TypedefType));
5404 auto *NewType =
5405 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5406 UnderlyingType, !*TypeMatchesDeclOrNone);
5407 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5408 FoldingSetPlaceholder<TypedefType>();
5409 TypedefTypes.insert(N: Placeholder, Token);
5410 Types.push_back(Elt: NewType);
5411 return QualType(NewType, 0);
5412}
5413
5414QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5415 NestedNameSpecifier Qualifier,
5416 const UsingShadowDecl *D,
5417 QualType UnderlyingType) const {
5418 // FIXME: This is expensive to compute every time!
5419 if (UnderlyingType.isNull()) {
5420 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5421 UnderlyingType =
5422 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5423 : ElaboratedTypeKeyword::None,
5424 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5425 }
5426
5427 llvm::FoldingSetNodeID ID;
5428 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5429
5430 llvm::FoldingSetInsertToken Token;
5431 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5432 return QualType(T, 0);
5433
5434 assert(!UnderlyingType.hasLocalQualifiers());
5435
5436 assert(
5437 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5438 UnderlyingType));
5439
5440 void *Mem =
5441 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5442 Align: alignof(UsingType));
5443 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5444 Types.push_back(Elt: T);
5445 UsingTypes.insert(N: T, Token);
5446 return QualType(T, 0);
5447}
5448
5449TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5450 NestedNameSpecifier Qualifier,
5451 const TagDecl *TD, bool OwnsTag,
5452 bool IsInjected,
5453 const Type *CanonicalType,
5454 bool WithFoldingSetNode) const {
5455 auto [TC, Size] = [&] {
5456 switch (TD->getDeclKind()) {
5457 case Decl::Enum:
5458 static_assert(alignof(EnumType) == alignof(TagType));
5459 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5460 case Decl::ClassTemplatePartialSpecialization:
5461 case Decl::ClassTemplateSpecialization:
5462 case Decl::CXXRecord:
5463 static_assert(alignof(RecordType) == alignof(TagType));
5464 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5465 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5466 return std::make_tuple(args: Type::InjectedClassName,
5467 args: sizeof(InjectedClassNameType));
5468 [[fallthrough]];
5469 case Decl::Record:
5470 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5471 default:
5472 llvm_unreachable("unexpected decl kind");
5473 }
5474 }();
5475
5476 if (Qualifier) {
5477 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5478 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5479 sizeof(NestedNameSpecifier);
5480 }
5481 void *Mem;
5482 if (WithFoldingSetNode) {
5483 // FIXME: It would be more profitable to tail allocate the folding set node
5484 // from the type, instead of the other way around, due to the greater
5485 // alignment requirements of the type. But this makes it harder to deal with
5486 // the different type node sizes. This would require either uniquing from
5487 // different folding sets, or having the folding setaccept a
5488 // contextual parameter which is not fixed at construction.
5489 Mem = Allocate(
5490 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5491 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5492 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5493 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5494 Mem = T->getTagType();
5495 } else {
5496 Mem = Allocate(Size, Align: alignof(TagType));
5497 }
5498
5499 auto *T = [&, TC = TC]() -> TagType * {
5500 switch (TC) {
5501 case Type::Enum: {
5502 assert(isa<EnumDecl>(TD));
5503 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5504 IsInjected, CanonicalType);
5505 assert(reinterpret_cast<void *>(T) ==
5506 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5507 "TagType must be the first base of EnumType");
5508 return T;
5509 }
5510 case Type::Record: {
5511 assert(isa<RecordDecl>(TD));
5512 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5513 IsInjected, CanonicalType);
5514 assert(reinterpret_cast<void *>(T) ==
5515 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5516 "TagType must be the first base of RecordType");
5517 return T;
5518 }
5519 case Type::InjectedClassName: {
5520 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5521 IsInjected, CanonicalType);
5522 assert(reinterpret_cast<void *>(T) ==
5523 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5524 "TagType must be the first base of InjectedClassNameType");
5525 return T;
5526 }
5527 default:
5528 llvm_unreachable("unexpected type class");
5529 }
5530 }();
5531 assert(T->getKeyword() == Keyword);
5532 assert(T->getQualifier() == Qualifier);
5533 assert(T->getDecl() == TD);
5534 assert(T->isInjected() == IsInjected);
5535 assert(T->isTagOwned() == OwnsTag);
5536 assert((T->isCanonicalUnqualified()
5537 ? QualType()
5538 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5539 Types.push_back(Elt: T);
5540 return T;
5541}
5542
5543static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5544 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5545 RD && RD->isInjectedClassName())
5546 return cast<TagDecl>(Val: RD->getDeclContext());
5547 return TD;
5548}
5549
5550CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5551 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5552 if (TD->TypeForDecl)
5553 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5554
5555 const Type *CanonicalType = getTagTypeInternal(
5556 Keyword: ElaboratedTypeKeyword::None,
5557 /*Qualifier=*/std::nullopt, TD,
5558 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5559 /*WithFoldingSetNode=*/false);
5560 TD->TypeForDecl = CanonicalType;
5561 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5562}
5563
5564QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5565 NestedNameSpecifier Qualifier,
5566 const TagDecl *TD, bool OwnsTag) const {
5567
5568 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5569 bool IsInjected = TD != NonInjectedTD;
5570
5571 ElaboratedTypeKeyword PreferredKeyword =
5572 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5573 : KeywordHelpers::getKeywordForTagTypeKind(
5574 Tag: NonInjectedTD->getTagKind());
5575
5576 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5577 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5578 return QualType(T, 0);
5579
5580 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5581 const Type *T =
5582 getTagTypeInternal(Keyword,
5583 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5584 /*OwnsTag=*/false, IsInjected, CanonicalType,
5585 /*WithFoldingSetNode=*/false);
5586 TD->TypeForDecl = T;
5587 return QualType(T, 0);
5588 }
5589
5590 llvm::FoldingSetNodeID ID;
5591 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5592 OwnsTag, IsInjected);
5593
5594 llvm::FoldingSetInsertToken Token;
5595 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5596 return QualType(T->getTagType(), 0);
5597
5598 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5599 TagType *T =
5600 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5601 CanonicalType, /*WithFoldingSetNode=*/true);
5602 TagTypes.insert(N: TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5603 return QualType(T, 0);
5604}
5605
5606bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5607 unsigned NumPositiveBits,
5608 QualType &BestType,
5609 QualType &BestPromotionType) {
5610 unsigned IntWidth = Target->getIntWidth();
5611 unsigned CharWidth = Target->getCharWidth();
5612 unsigned ShortWidth = Target->getShortWidth();
5613 bool EnumTooLarge = false;
5614 unsigned BestWidth;
5615 if (NumNegativeBits) {
5616 // If there is a negative value, figure out the smallest integer type (of
5617 // int/long/longlong) that fits.
5618 // If it's packed, check also if it fits a char or a short.
5619 if (IsPacked && NumNegativeBits <= CharWidth &&
5620 NumPositiveBits < CharWidth) {
5621 BestType = SignedCharTy;
5622 BestWidth = CharWidth;
5623 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5624 NumPositiveBits < ShortWidth) {
5625 BestType = ShortTy;
5626 BestWidth = ShortWidth;
5627 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5628 BestType = IntTy;
5629 BestWidth = IntWidth;
5630 } else {
5631 BestWidth = Target->getLongWidth();
5632
5633 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5634 BestType = LongTy;
5635 } else {
5636 BestWidth = Target->getLongLongWidth();
5637
5638 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5639 EnumTooLarge = true;
5640 BestType = LongLongTy;
5641 }
5642 }
5643 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5644 } else {
5645 // If there is no negative value, figure out the smallest type that fits
5646 // all of the enumerator values.
5647 // If it's packed, check also if it fits a char or a short.
5648 if (IsPacked && NumPositiveBits <= CharWidth) {
5649 BestType = UnsignedCharTy;
5650 BestPromotionType = IntTy;
5651 BestWidth = CharWidth;
5652 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5653 BestType = UnsignedShortTy;
5654 BestPromotionType = IntTy;
5655 BestWidth = ShortWidth;
5656 } else if (NumPositiveBits <= IntWidth) {
5657 BestType = UnsignedIntTy;
5658 BestWidth = IntWidth;
5659 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5660 ? UnsignedIntTy
5661 : IntTy;
5662 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5663 BestType = UnsignedLongTy;
5664 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5665 ? UnsignedLongTy
5666 : LongTy;
5667 } else {
5668 BestWidth = Target->getLongLongWidth();
5669 if (NumPositiveBits > BestWidth) {
5670 // This can happen with bit-precise integer types, but those are not
5671 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5672 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5673 // a 128-bit integer, we should consider doing the same.
5674 EnumTooLarge = true;
5675 }
5676 BestType = UnsignedLongLongTy;
5677 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5678 ? UnsignedLongLongTy
5679 : LongLongTy;
5680 }
5681 }
5682 return EnumTooLarge;
5683}
5684
5685bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5686 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5687 "Integral type required!");
5688 unsigned BitWidth = getIntWidth(T);
5689
5690 if (Value.isUnsigned() || Value.isNonNegative()) {
5691 if (T->isSignedIntegerOrEnumerationType())
5692 --BitWidth;
5693 return Value.getActiveBits() <= BitWidth;
5694 }
5695 return Value.getSignificantBits() <= BitWidth;
5696}
5697
5698UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5699 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5700 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5701 const Type *CanonicalType) const {
5702 void *Mem = Allocate(
5703 Size: UnresolvedUsingType::totalSizeToAlloc<
5704 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5705 Counts: !!Token, Counts: !!Qualifier),
5706 Align: alignof(UnresolvedUsingType));
5707 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5708 if (Token) {
5709 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5710 FoldingSetPlaceholder<UnresolvedUsingType>();
5711 UnresolvedUsingTypes.insert(N: Placeholder, Token);
5712 }
5713 Types.push_back(Elt: T);
5714 return T;
5715}
5716
5717CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5718 const UnresolvedUsingTypenameDecl *D) const {
5719 D = D->getCanonicalDecl();
5720 if (D->TypeForDecl)
5721 return D->TypeForDecl->getCanonicalTypeUnqualified();
5722
5723 const Type *CanonicalType =
5724 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5725 /*Qualifier=*/std::nullopt, D,
5726 /*Token=*/{}, /*CanonicalType=*/nullptr);
5727 D->TypeForDecl = CanonicalType;
5728 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5729}
5730
5731QualType
5732ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5733 NestedNameSpecifier Qualifier,
5734 const UnresolvedUsingTypenameDecl *D) const {
5735 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5736 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5737 return QualType(T, 0);
5738
5739 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5740 const Type *T =
5741 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5742 /*Qualifier=*/std::nullopt, D,
5743 /*Token=*/{}, CanonicalType);
5744 D->TypeForDecl = T;
5745 return QualType(T, 0);
5746 }
5747
5748 llvm::FoldingSetNodeID ID;
5749 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5750
5751 llvm::FoldingSetInsertToken Token;
5752 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5753 UnresolvedUsingTypes.lookup(ID, Token))
5754 return QualType(Placeholder->getType(), 0);
5755 assert(Token);
5756
5757 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5758 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5759 CanonicalType);
5760 return QualType(T, 0);
5761}
5762
5763QualType ASTContext::getAttributedType(attr::Kind attrKind,
5764 QualType modifiedType,
5765 QualType equivalentType,
5766 const Attr *attr) const {
5767 llvm::FoldingSetNodeID id;
5768 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5769 attr);
5770
5771 llvm::FoldingSetInsertToken Token;
5772 AttributedType *type = AttributedTypes.lookup(ID: id, Token);
5773 if (type) return QualType(type, 0);
5774
5775 assert(!attr || attr->getKind() == attrKind);
5776
5777 QualType canon = getCanonicalType(T: equivalentType);
5778 type = new (*this, alignof(AttributedType))
5779 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5780
5781 Types.push_back(Elt: type);
5782 AttributedTypes.insert(N: type, Token);
5783
5784 return QualType(type, 0);
5785}
5786
5787QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5788 QualType equivalentType) const {
5789 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5790}
5791
5792QualType ASTContext::getAttributedType(NullabilityKind nullability,
5793 QualType modifiedType,
5794 QualType equivalentType) const {
5795 switch (nullability) {
5796 case NullabilityKind::NonNull:
5797 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5798
5799 case NullabilityKind::Nullable:
5800 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5801
5802 case NullabilityKind::NullableResult:
5803 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5804 equivalentType);
5805
5806 case NullabilityKind::Unspecified:
5807 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5808 equivalentType);
5809 }
5810
5811 llvm_unreachable("Unknown nullability kind");
5812}
5813
5814QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5815 QualType Wrapped) const {
5816 llvm::FoldingSetNodeID ID;
5817 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5818
5819 llvm::FoldingSetInsertToken Token;
5820 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5821 if (Ty)
5822 return QualType(Ty, 0);
5823
5824 QualType Canon = getCanonicalType(T: Wrapped);
5825 Ty = new (*this, alignof(BTFTagAttributedType))
5826 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5827
5828 Types.push_back(Elt: Ty);
5829 BTFTagAttributedTypes.insert(N: Ty, Token);
5830
5831 return QualType(Ty, 0);
5832}
5833
5834QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5835 QualType Underlying) const {
5836 const IdentifierInfo *II = Attr->getBehaviorKind();
5837 StringRef IdentName = II->getName();
5838 OverflowBehaviorType::OverflowBehaviorKind Kind;
5839 if (IdentName == "wrap") {
5840 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5841 } else if (IdentName == "trap") {
5842 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5843 } else {
5844 return Underlying;
5845 }
5846
5847 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5848}
5849
5850QualType ASTContext::getOverflowBehaviorType(
5851 OverflowBehaviorType::OverflowBehaviorKind Kind,
5852 QualType Underlying) const {
5853 assert(!Underlying->isOverflowBehaviorType() &&
5854 "Cannot have underlying types that are themselves OBTs");
5855
5856 llvm::FoldingSetInsertToken Token;
5857 if (OverflowBehaviorType *OBT =
5858 OverflowBehaviorTypes.lookup(Key: {Underlying, Kind}, Token)) {
5859 return QualType(OBT, 0);
5860 }
5861
5862 QualType Canonical;
5863 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5864 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5865 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5866 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5867 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5868 "Shouldn't be in the map");
5869 }
5870
5871 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5872 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5873
5874 Types.push_back(Elt: Ty);
5875 OverflowBehaviorTypes.insert(N: Ty, Token);
5876 return QualType(Ty, 0);
5877}
5878
5879QualType ASTContext::getHLSLAttributedResourceType(
5880 QualType Wrapped, QualType Contained,
5881 const HLSLAttributedResourceType::Attributes &Attrs) {
5882
5883 llvm::FoldingSetNodeID ID;
5884 HLSLAttributedResourceType::Profile(ID, Ctx: *this, Wrapped, Contained, Attrs);
5885
5886 llvm::FoldingSetInsertToken Token;
5887 HLSLAttributedResourceType *Ty =
5888 HLSLAttributedResourceTypes.lookup(ID, Token);
5889 if (Ty)
5890 return QualType(Ty, 0);
5891
5892 Ty = new (*this, alignof(HLSLAttributedResourceType))
5893 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5894
5895 Types.push_back(Elt: Ty);
5896 HLSLAttributedResourceTypes.insert(N: Ty, Token);
5897
5898 return QualType(Ty, 0);
5899}
5900
5901QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5902 uint32_t Alignment,
5903 ArrayRef<SpirvOperand> Operands) {
5904 llvm::FoldingSetNodeID ID;
5905 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5906
5907 llvm::FoldingSetInsertToken Token;
5908 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5909 if (Ty)
5910 return QualType(Ty, 0);
5911
5912 void *Mem = Allocate(
5913 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5914 Align: alignof(HLSLInlineSpirvType));
5915
5916 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5917
5918 Types.push_back(Elt: Ty);
5919 HLSLInlineSpirvTypes.insert(N: Ty, Token);
5920
5921 return QualType(Ty, 0);
5922}
5923
5924/// Retrieve a substitution-result type.
5925QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5926 Decl *AssociatedDecl,
5927 unsigned Index,
5928 UnsignedOrNone PackIndex,
5929 bool Final) const {
5930 auto Key =
5931 std::make_tuple(args&: Replacement, args&: AssociatedDecl, args&: Index,
5932 args: PackIndex.toInternalRepresentation(), args: unsigned(Final));
5933 llvm::FoldingSetInsertToken Token;
5934 SubstTemplateTypeParmType *SubstParm =
5935 SubstTemplateTypeParmTypes.lookup(Key, Token);
5936
5937 if (!SubstParm) {
5938 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5939 Counts: !Replacement.isCanonical()),
5940 Align: alignof(SubstTemplateTypeParmType));
5941 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5942 Index, PackIndex, Final);
5943 Types.push_back(Elt: SubstParm);
5944 SubstTemplateTypeParmTypes.insert(N: SubstParm, Token);
5945 }
5946
5947 return QualType(SubstParm, 0);
5948}
5949
5950QualType
5951ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5952 unsigned Index, bool Final,
5953 const TemplateArgument &ArgPack) {
5954#ifndef NDEBUG
5955 for (const auto &P : ArgPack.pack_elements())
5956 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5957#endif
5958
5959 llvm::FoldingSetNodeID ID;
5960 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5961 ArgPack);
5962 llvm::FoldingSetInsertToken Token;
5963 if (SubstTemplateTypeParmPackType *SubstParm =
5964 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
5965 return QualType(SubstParm, 0);
5966
5967 QualType Canon;
5968 {
5969 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5970 if (!AssociatedDecl->isCanonicalDecl() ||
5971 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
5972 Canon = getSubstTemplateTypeParmPackType(
5973 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
5974 [[maybe_unused]] const auto *Nothing =
5975 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
5976 assert(!Nothing);
5977 }
5978 }
5979
5980 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5981 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5982 ArgPack);
5983 Types.push_back(Elt: SubstParm);
5984 SubstTemplateTypeParmPackTypes.insert(N: SubstParm, Token);
5985 return QualType(SubstParm, 0);
5986}
5987
5988QualType
5989ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
5990 assert(llvm::all_of(ArgPack.pack_elements(),
5991 [](const auto &P) {
5992 return P.getKind() == TemplateArgument::Type;
5993 }) &&
5994 "Pack contains a non-type");
5995
5996 llvm::FoldingSetNodeID ID;
5997 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5998
5999 llvm::FoldingSetInsertToken Token;
6000 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6001 return QualType(T, 0);
6002
6003 QualType Canon;
6004 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6005 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6006 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6007 // Refresh Token, in case the recursive call above caused rehashing,
6008 // which would invalidate the bucket pointer.
6009 [[maybe_unused]] const auto *Nothing =
6010 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6011 assert(!Nothing);
6012 }
6013
6014 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6015 SubstBuiltinTemplatePackType(Canon, ArgPack);
6016 Types.push_back(Elt: PackType);
6017 SubstBuiltinTemplatePackTypes.insert(N: PackType, Token);
6018 return QualType(PackType, 0);
6019}
6020
6021/// Retrieve the template type parameter type for a template
6022/// parameter or parameter pack with the given depth, index, and (optionally)
6023/// name.
6024QualType
6025ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6026 TemplateTypeParmDecl *TTPDecl) const {
6027 assert(Depth >= 0 && "Depth must be non-negative");
6028 assert(Index >= 0 && "Index must be non-negative");
6029
6030 auto Key = std::make_tuple(args: unsigned(Depth), args: unsigned(Index),
6031 args: unsigned(ParameterPack), args&: TTPDecl);
6032 llvm::FoldingSetInsertToken Token;
6033 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6034
6035 if (TypeParm)
6036 return QualType(TypeParm, 0);
6037
6038 if (TTPDecl) {
6039 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6040 TypeParm = new (*this, alignof(TemplateTypeParmType))
6041 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6042 } else
6043 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6044 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6045
6046 Types.push_back(Elt: TypeParm);
6047 TemplateTypeParmTypes.insert(N: TypeParm, Token);
6048
6049 return QualType(TypeParm, 0);
6050}
6051
6052static ElaboratedTypeKeyword
6053getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6054 switch (Keyword) {
6055 // These are just themselves.
6056 case ElaboratedTypeKeyword::None:
6057 case ElaboratedTypeKeyword::Struct:
6058 case ElaboratedTypeKeyword::Union:
6059 case ElaboratedTypeKeyword::Enum:
6060 case ElaboratedTypeKeyword::Interface:
6061 return Keyword;
6062
6063 // These are equivalent.
6064 case ElaboratedTypeKeyword::Typename:
6065 return ElaboratedTypeKeyword::None;
6066
6067 // These are functionally equivalent, so relying on their equivalence is
6068 // IFNDR. By making them equivalent, we disallow overloading, which at least
6069 // can produce a diagnostic.
6070 case ElaboratedTypeKeyword::Class:
6071 return ElaboratedTypeKeyword::Struct;
6072 }
6073 llvm_unreachable("unexpected keyword kind");
6074}
6075
6076TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6077 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6078 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6079 TemplateName Name, SourceLocation NameLoc,
6080 const TemplateArgumentListInfo &SpecifiedArgs,
6081 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6082 QualType TST = getTemplateSpecializationType(
6083 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6084
6085 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6086 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6087 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6088 TAL: SpecifiedArgs);
6089 return TSI;
6090}
6091
6092QualType ASTContext::getTemplateSpecializationType(
6093 ElaboratedTypeKeyword Keyword, TemplateName Template,
6094 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6095 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6096 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6097 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6098 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6099 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6100
6101 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6102 CanonicalArgs, Underlying);
6103}
6104
6105[[maybe_unused]] static bool
6106hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6107 for (const TemplateArgument &Arg : Args)
6108 if (Arg.isPackExpansion())
6109 return true;
6110 return false;
6111}
6112
6113QualType ASTContext::getCanonicalTemplateSpecializationType(
6114 ElaboratedTypeKeyword Keyword, TemplateName Template,
6115 ArrayRef<TemplateArgument> Args) const {
6116 assert(Template ==
6117 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6118 assert((Keyword == ElaboratedTypeKeyword::None ||
6119 Template.getAsDependentTemplateName()));
6120#ifndef NDEBUG
6121 for (const auto &Arg : Args)
6122 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6123#endif
6124
6125 llvm::FoldingSetNodeID ID;
6126 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6127 Context: *this);
6128 llvm::FoldingSetInsertToken Token;
6129 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6130 return QualType(T, 0);
6131
6132 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6133 sizeof(TemplateArgument) * Args.size(),
6134 Align: alignof(TemplateSpecializationType));
6135 auto *Spec =
6136 new (Mem) TemplateSpecializationType(Keyword, Template,
6137 /*IsAlias=*/false, Args, QualType());
6138 assert(Spec->isDependentType() &&
6139 "canonical template specialization must be dependent");
6140 Types.push_back(Elt: Spec);
6141 TemplateSpecializationTypes.insert(N: Spec, Token);
6142 return QualType(Spec, 0);
6143}
6144
6145QualType ASTContext::getTemplateSpecializationType(
6146 ElaboratedTypeKeyword Keyword, TemplateName Template,
6147 ArrayRef<TemplateArgument> SpecifiedArgs,
6148 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6149 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6150 bool IsTypeAlias = TD && TD->isTypeAlias();
6151 if (Underlying.isNull()) {
6152 TemplateName CanonTemplate =
6153 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6154 ElaboratedTypeKeyword CanonKeyword =
6155 CanonTemplate.getAsDependentTemplateName()
6156 ? getCanonicalElaboratedTypeKeyword(Keyword)
6157 : ElaboratedTypeKeyword::None;
6158 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6159 SmallVector<TemplateArgument, 4> CanonArgsVec;
6160 if (CanonicalArgs.empty()) {
6161 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6162 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6163 CanonicalArgs = CanonArgsVec;
6164 } else {
6165 NonCanonical |= !llvm::equal(
6166 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6167 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6168 return A.structurallyEquals(Other: B);
6169 });
6170 }
6171
6172 // We can get here with an alias template when the specialization
6173 // contains a pack expansion that does not match up with a parameter
6174 // pack, or a builtin template which cannot be resolved due to dependency.
6175 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6176 hasAnyPackExpansions(CanonicalArgs)) &&
6177 "Caller must compute aliased type");
6178 IsTypeAlias = false;
6179
6180 Underlying = getCanonicalTemplateSpecializationType(
6181 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6182 if (!NonCanonical)
6183 return Underlying;
6184 }
6185 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6186 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6187 (IsTypeAlias ? sizeof(QualType) : 0),
6188 Align: alignof(TemplateSpecializationType));
6189 auto *Spec = new (Mem) TemplateSpecializationType(
6190 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6191 Types.push_back(Elt: Spec);
6192 return QualType(Spec, 0);
6193}
6194
6195QualType
6196ASTContext::getParenType(QualType InnerType) const {
6197 llvm::FoldingSetInsertToken Token;
6198 ParenType *T = ParenTypes.lookup(Key: InnerType, Token);
6199 if (T)
6200 return QualType(T, 0);
6201
6202 QualType Canon = InnerType;
6203 if (!Canon.isCanonical()) {
6204 Canon = getCanonicalType(T: InnerType);
6205 assert(!ParenTypes.lookup(InnerType, Token) &&
6206 "Paren canonical type broken");
6207 }
6208
6209 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6210 Types.push_back(Elt: T);
6211 ParenTypes.insert(N: T, Token);
6212 return QualType(T, 0);
6213}
6214
6215QualType
6216ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6217 const IdentifierInfo *MacroII) const {
6218 QualType Canon = UnderlyingTy;
6219 if (!Canon.isCanonical())
6220 Canon = getCanonicalType(T: UnderlyingTy);
6221
6222 auto *newType = new (*this, alignof(MacroQualifiedType))
6223 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6224 Types.push_back(Elt: newType);
6225 return QualType(newType, 0);
6226}
6227
6228QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6229 NestedNameSpecifier NNS,
6230 const IdentifierInfo *Name) const {
6231 llvm::FoldingSetNodeID ID;
6232 DependentNameType::Profile(ID, Keyword, NNS, Name);
6233
6234 llvm::FoldingSetInsertToken Token;
6235 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6236 return QualType(T, 0);
6237
6238 ElaboratedTypeKeyword CanonKeyword =
6239 getCanonicalElaboratedTypeKeyword(Keyword);
6240 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6241
6242 QualType Canon;
6243 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6244 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6245 [[maybe_unused]] DependentNameType *T =
6246 DependentNameTypes.lookup(ID, Token);
6247 assert(!T && "broken canonicalization");
6248 assert(Canon.isCanonical());
6249 }
6250
6251 DependentNameType *T = new (*this, alignof(DependentNameType))
6252 DependentNameType(Keyword, NNS, Name, Canon);
6253 Types.push_back(Elt: T);
6254 DependentNameTypes.insert(N: T, Token);
6255 return QualType(T, 0);
6256}
6257
6258TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6259 TemplateArgument Arg;
6260 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6261 QualType ArgType = getTypeDeclType(Decl: TTP);
6262 if (TTP->isParameterPack())
6263 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6264
6265 Arg = TemplateArgument(ArgType);
6266 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6267 QualType T =
6268 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6269 // For class NTTPs, ensure we include the 'const' so the type matches that
6270 // of a real template argument.
6271 // FIXME: It would be more faithful to model this as something like an
6272 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6273 ExprValueKind VK;
6274 if (T->isRecordType()) {
6275 // C++ [temp.param]p8: An id-expression naming a non-type
6276 // template-parameter of class type T denotes a static storage duration
6277 // object of type const T.
6278 T.addConst();
6279 VK = VK_LValue;
6280 } else {
6281 VK = Expr::getValueKindForType(T: NTTP->getType());
6282 }
6283 Expr *E = new (*this)
6284 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6285 T, VK, NTTP->getLocation());
6286
6287 if (NTTP->isParameterPack())
6288 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6289 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6290 } else {
6291 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6292 TemplateName Name = getQualifiedTemplateName(
6293 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6294 Template: TemplateName(TTP));
6295 if (TTP->isParameterPack())
6296 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6297 else
6298 Arg = TemplateArgument(Name);
6299 }
6300
6301 if (Param->isTemplateParameterPack())
6302 Arg =
6303 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6304
6305 return Arg;
6306}
6307
6308QualType ASTContext::getPackExpansionType(QualType Pattern,
6309 UnsignedOrNone NumExpansions,
6310 bool ExpectPackInType) const {
6311 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6312 "Pack expansions must expand one or more parameter packs");
6313
6314 auto Key = std::make_pair(x&: Pattern, y: NumExpansions.toInternalRepresentation());
6315
6316 llvm::FoldingSetInsertToken Token;
6317 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6318 if (T)
6319 return QualType(T, 0);
6320
6321 QualType Canon;
6322 if (!Pattern.isCanonical()) {
6323 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6324 /*ExpectPackInType=*/false);
6325
6326 // Find the insert position again, in case we inserted an element into
6327 // PackExpansionTypes and invalidated our insert position.
6328 PackExpansionTypes.lookup(Key, Token);
6329 }
6330
6331 T = new (*this, alignof(PackExpansionType))
6332 PackExpansionType(Pattern, Canon, NumExpansions);
6333 Types.push_back(Elt: T);
6334 PackExpansionTypes.insert(N: T, Token);
6335 return QualType(T, 0);
6336}
6337
6338/// CmpProtocolNames - Comparison predicate for sorting protocols
6339/// alphabetically.
6340static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6341 ObjCProtocolDecl *const *RHS) {
6342 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6343}
6344
6345static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6346 if (Protocols.empty()) return true;
6347
6348 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6349 return false;
6350
6351 for (unsigned i = 1; i != Protocols.size(); ++i)
6352 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6353 Protocols[i]->getCanonicalDecl() != Protocols[i])
6354 return false;
6355 return true;
6356}
6357
6358static void
6359SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6360 // Sort protocols, keyed by name.
6361 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6362
6363 // Canonicalize.
6364 for (ObjCProtocolDecl *&P : Protocols)
6365 P = P->getCanonicalDecl();
6366
6367 // Remove duplicates.
6368 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6369 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6370}
6371
6372QualType ASTContext::getObjCObjectType(QualType BaseType,
6373 ObjCProtocolDecl * const *Protocols,
6374 unsigned NumProtocols) const {
6375 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6376 /*isKindOf=*/false);
6377}
6378
6379QualType ASTContext::getObjCObjectType(
6380 QualType baseType,
6381 ArrayRef<QualType> typeArgs,
6382 ArrayRef<ObjCProtocolDecl *> protocols,
6383 bool isKindOf) const {
6384 // If the base type is an interface and there aren't any protocols or
6385 // type arguments to add, then the interface type will do just fine.
6386 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6387 isa<ObjCInterfaceType>(Val: baseType))
6388 return baseType;
6389
6390 // Look in the folding set for an existing type.
6391 llvm::FoldingSetNodeID ID;
6392 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6393 llvm::FoldingSetInsertToken Token;
6394 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6395 return QualType(QT, 0);
6396
6397 // Determine the type arguments to be used for canonicalization,
6398 // which may be explicitly specified here or written on the base
6399 // type.
6400 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6401 if (effectiveTypeArgs.empty()) {
6402 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6403 effectiveTypeArgs = baseObject->getTypeArgs();
6404 }
6405
6406 // Build the canonical type, which has the canonical base type and a
6407 // sorted-and-uniqued list of protocols and the type arguments
6408 // canonicalized.
6409 QualType canonical;
6410 bool typeArgsAreCanonical = llvm::all_of(
6411 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6412 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6413 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6414 // Determine the canonical type arguments.
6415 ArrayRef<QualType> canonTypeArgs;
6416 SmallVector<QualType, 4> canonTypeArgsVec;
6417 if (!typeArgsAreCanonical) {
6418 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6419 for (auto typeArg : effectiveTypeArgs)
6420 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6421 canonTypeArgs = canonTypeArgsVec;
6422 } else {
6423 canonTypeArgs = effectiveTypeArgs;
6424 }
6425
6426 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6427 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6428 if (!protocolsSorted) {
6429 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6430 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6431 canonProtocols = canonProtocolsVec;
6432 } else {
6433 canonProtocols = protocols;
6434 }
6435
6436 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6437 protocols: canonProtocols, isKindOf);
6438
6439 // Regenerate Token.
6440 ObjCObjectTypes.lookup(ID, Token);
6441 }
6442
6443 unsigned size = sizeof(ObjCObjectTypeImpl);
6444 size += typeArgs.size() * sizeof(QualType);
6445 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6446 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6447 auto *T =
6448 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6449 isKindOf);
6450
6451 Types.push_back(Elt: T);
6452 ObjCObjectTypes.insert(N: T, Token);
6453 return QualType(T, 0);
6454}
6455
6456/// Apply Objective-C protocol qualifiers to the given type.
6457/// If this is for the canonical type of a type parameter, we can apply
6458/// protocol qualifiers on the ObjCObjectPointerType.
6459QualType
6460ASTContext::applyObjCProtocolQualifiers(QualType type,
6461 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6462 bool allowOnPointerType) const {
6463 hasError = false;
6464
6465 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6466 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6467 }
6468
6469 // Apply protocol qualifiers to ObjCObjectPointerType.
6470 if (allowOnPointerType) {
6471 if (const auto *objPtr =
6472 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6473 const ObjCObjectType *objT = objPtr->getObjectType();
6474 // Merge protocol lists and construct ObjCObjectType.
6475 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6476 protocolsVec.append(in_start: objT->qual_begin(),
6477 in_end: objT->qual_end());
6478 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6479 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6480 type = getObjCObjectType(
6481 baseType: objT->getBaseType(),
6482 typeArgs: objT->getTypeArgsAsWritten(),
6483 protocols,
6484 isKindOf: objT->isKindOfTypeAsWritten());
6485 return getObjCObjectPointerType(OIT: type);
6486 }
6487 }
6488
6489 // Apply protocol qualifiers to ObjCObjectType.
6490 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6491 // FIXME: Check for protocols to which the class type is already
6492 // known to conform.
6493
6494 return getObjCObjectType(baseType: objT->getBaseType(),
6495 typeArgs: objT->getTypeArgsAsWritten(),
6496 protocols,
6497 isKindOf: objT->isKindOfTypeAsWritten());
6498 }
6499
6500 // If the canonical type is ObjCObjectType, ...
6501 if (type->isObjCObjectType()) {
6502 // Silently overwrite any existing protocol qualifiers.
6503 // TODO: determine whether that's the right thing to do.
6504
6505 // FIXME: Check for protocols to which the class type is already
6506 // known to conform.
6507 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6508 }
6509
6510 // id<protocol-list>
6511 if (type->isObjCIdType()) {
6512 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6513 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6514 isKindOf: objPtr->isKindOfType());
6515 return getObjCObjectPointerType(OIT: type);
6516 }
6517
6518 // Class<protocol-list>
6519 if (type->isObjCClassType()) {
6520 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6521 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6522 isKindOf: objPtr->isKindOfType());
6523 return getObjCObjectPointerType(OIT: type);
6524 }
6525
6526 hasError = true;
6527 return type;
6528}
6529
6530QualType
6531ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6532 ArrayRef<ObjCProtocolDecl *> protocols) const {
6533 // We canonicalize to the underlying type.
6534 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6535 if (!protocols.empty()) {
6536 // Apply the protocol qualifers.
6537 bool hasError;
6538 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6539 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6540 assert(!hasError && "Error when apply protocol qualifier to bound type");
6541 }
6542
6543 // Key on the canonical type the node is constructed with, which is what
6544 // Profile() reports; the decl's underlying type can be updated later.
6545 auto Key = std::make_tuple(args&: Decl, args&: Canonical, args&: protocols);
6546 llvm::FoldingSetInsertToken Token;
6547 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6548 return QualType(TypeParam, 0);
6549
6550 unsigned size = sizeof(ObjCTypeParamType);
6551 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6552 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6553 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6554
6555 Types.push_back(Elt: newType);
6556 ObjCTypeParamTypes.insert(N: newType, Token);
6557 return QualType(newType, 0);
6558}
6559
6560void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6561 ObjCTypeParamDecl *New) const {
6562 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6563 // Update TypeForDecl after updating TypeSourceInfo.
6564 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6565 SmallVector<ObjCProtocolDecl *, 8> protocols;
6566 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6567 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6568 New->TypeForDecl = UpdatedTy.getTypePtr();
6569}
6570
6571/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6572/// protocol list adopt all protocols in QT's qualified-id protocol
6573/// list.
6574bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6575 ObjCInterfaceDecl *IC) {
6576 if (!QT->isObjCQualifiedIdType())
6577 return false;
6578
6579 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6580 // If both the right and left sides have qualifiers.
6581 for (auto *Proto : OPT->quals()) {
6582 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6583 return false;
6584 }
6585 return true;
6586 }
6587 return false;
6588}
6589
6590/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6591/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6592/// of protocols.
6593bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6594 ObjCInterfaceDecl *IDecl) {
6595 if (!QT->isObjCQualifiedIdType())
6596 return false;
6597 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6598 if (!OPT)
6599 return false;
6600 if (!IDecl->hasDefinition())
6601 return false;
6602 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6603 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6604 if (InheritedProtocols.empty())
6605 return false;
6606 // Check that if every protocol in list of id<plist> conforms to a protocol
6607 // of IDecl's, then bridge casting is ok.
6608 bool Conforms = false;
6609 for (auto *Proto : OPT->quals()) {
6610 Conforms = false;
6611 for (auto *PI : InheritedProtocols) {
6612 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6613 Conforms = true;
6614 break;
6615 }
6616 }
6617 if (!Conforms)
6618 break;
6619 }
6620 if (Conforms)
6621 return true;
6622
6623 for (auto *PI : InheritedProtocols) {
6624 // If both the right and left sides have qualifiers.
6625 bool Adopts = false;
6626 for (auto *Proto : OPT->quals()) {
6627 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6628 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6629 break;
6630 }
6631 if (!Adopts)
6632 return false;
6633 }
6634 return true;
6635}
6636
6637/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6638/// the given object type.
6639QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6640 llvm::FoldingSetInsertToken Token;
6641 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(Key: ObjectT, Token))
6642 return QualType(QT, 0);
6643
6644 // Find the canonical object type.
6645 QualType Canonical;
6646 if (!ObjectT.isCanonical())
6647 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6648
6649 // No match.
6650 void *Mem =
6651 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6652 auto *QType =
6653 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6654
6655 Types.push_back(Elt: QType);
6656 ObjCObjectPointerTypes.insert(N: QType, Token);
6657 return QualType(QType, 0);
6658}
6659
6660/// getObjCInterfaceType - Return the unique reference to the type for the
6661/// specified ObjC interface decl. The list of protocols is optional.
6662QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6663 ObjCInterfaceDecl *PrevDecl) const {
6664 if (Decl->TypeForDecl)
6665 return QualType(Decl->TypeForDecl, 0);
6666
6667 if (PrevDecl) {
6668 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6669 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6670 return QualType(PrevDecl->TypeForDecl, 0);
6671 }
6672
6673 // Prefer the definition, if there is one.
6674 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6675 Decl = Def;
6676
6677 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6678 auto *T = new (Mem) ObjCInterfaceType(Decl);
6679 Decl->TypeForDecl = T;
6680 Types.push_back(Elt: T);
6681 return QualType(T, 0);
6682}
6683
6684/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6685/// TypeOfExprType AST's (since expression's are never shared). For example,
6686/// multiple declarations that refer to "typeof(x)" all contain different
6687/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6688/// on canonical type's (which are always unique).
6689QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6690 TypeOfExprType *toe;
6691 if (tofExpr->isTypeDependent()) {
6692 llvm::FoldingSetNodeID ID;
6693 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6694 IsUnqual: Kind == TypeOfKind::Unqualified);
6695
6696 llvm::FoldingSetInsertToken Token;
6697 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6698 if (Canon) {
6699 // We already have a "canonical" version of an identical, dependent
6700 // typeof(expr) type. Use that as our canonical type.
6701 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6702 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6703 } else {
6704 // Build a new, canonical typeof(expr) type.
6705 Canon = new (*this, alignof(DependentTypeOfExprType))
6706 DependentTypeOfExprType(*this, tofExpr, Kind);
6707 DependentTypeOfExprTypes.insert(N: Canon, Token);
6708 toe = Canon;
6709 }
6710 } else {
6711 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6712 toe = new (*this, alignof(TypeOfExprType))
6713 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6714 }
6715 Types.push_back(Elt: toe);
6716 return QualType(toe, 0);
6717}
6718
6719/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6720/// TypeOfType nodes. The only motivation to unique these nodes would be
6721/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6722/// an issue. This doesn't affect the type checker, since it operates
6723/// on canonical types (which are always unique).
6724QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6725 QualType Canonical = getCanonicalType(T: tofType);
6726 auto *tot = new (*this, alignof(TypeOfType))
6727 TypeOfType(*this, tofType, Canonical, Kind);
6728 Types.push_back(Elt: tot);
6729 return QualType(tot, 0);
6730}
6731
6732/// getReferenceQualifiedType - Given an expr, will return the type for
6733/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6734/// and class member access into account.
6735QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6736 // C++11 [dcl.type.simple]p4:
6737 // [...]
6738 QualType T = E->getType();
6739 switch (E->getValueKind()) {
6740 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6741 // type of e;
6742 case VK_XValue:
6743 return getRValueReferenceType(T);
6744 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6745 // type of e;
6746 case VK_LValue:
6747 return getLValueReferenceType(T);
6748 // - otherwise, decltype(e) is the type of e.
6749 case VK_PRValue:
6750 return T;
6751 }
6752 llvm_unreachable("Unknown value kind");
6753}
6754
6755/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6756/// nodes. This would never be helpful, since each such type has its own
6757/// expression, and would not give a significant memory saving, since there
6758/// is an Expr tree under each such type.
6759QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6760 // C++11 [temp.type]p2:
6761 // If an expression e involves a template parameter, decltype(e) denotes a
6762 // unique dependent type. Two such decltype-specifiers refer to the same
6763 // type only if their expressions are equivalent (14.5.6.1).
6764 QualType CanonType;
6765 if (!E->isInstantiationDependent()) {
6766 CanonType = getCanonicalType(T: UnderlyingType);
6767 } else if (!UnderlyingType.isNull()) {
6768 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6769 } else {
6770 llvm::FoldingSetNodeID ID;
6771 DependentDecltypeType::Profile(ID, Context: *this, E);
6772
6773 llvm::FoldingSetInsertToken Token;
6774 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6775 return QualType(Canon, 0);
6776
6777 // Build a new, canonical decltype(expr) type.
6778 auto *DT =
6779 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6780 DependentDecltypeTypes.insert(N: DT, Token);
6781 Types.push_back(Elt: DT);
6782 return QualType(DT, 0);
6783 }
6784 auto *DT = new (*this, alignof(DecltypeType))
6785 DecltypeType(E, UnderlyingType, CanonType);
6786 Types.push_back(Elt: DT);
6787 return QualType(DT, 0);
6788}
6789
6790QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6791 bool FullySubstituted,
6792 ArrayRef<QualType> Expansions,
6793 UnsignedOrNone Index) const {
6794 QualType Canonical;
6795 if (FullySubstituted && Index) {
6796 Canonical = getCanonicalType(T: Expansions[*Index]);
6797 } else {
6798 llvm::FoldingSetNodeID ID;
6799 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6800 FullySubstituted, Expansions);
6801 llvm::FoldingSetInsertToken Token;
6802 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6803 if (!Canon) {
6804 void *Mem = Allocate(
6805 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6806 Align: TypeAlignment);
6807 Canon =
6808 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6809 IndexExpr, FullySubstituted, Expansions);
6810 DependentPackIndexingTypes.insert(N: Canon, Token);
6811 }
6812 Canonical = QualType(Canon, 0);
6813 }
6814
6815 void *Mem =
6816 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6817 Align: TypeAlignment);
6818 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6819 FullySubstituted, Expansions);
6820 Types.push_back(Elt: T);
6821 return QualType(T, 0);
6822}
6823
6824/// getUnaryTransformationType - We don't unique these, since the memory
6825/// savings are minimal and these are rare.
6826QualType
6827ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6828 UnaryTransformType::UTTKind Kind) const {
6829 // Clear UnderlyingType for a dependent base before building the ID: that is
6830 // what the node is constructed with, and what Profile() reports.
6831 if (BaseType->isDependentType()) {
6832 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6833 UnderlyingType = QualType();
6834 }
6835
6836 auto Key = std::make_tuple(args&: BaseType, args&: UnderlyingType, args&: Kind);
6837
6838 llvm::FoldingSetInsertToken Token;
6839 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6840 return QualType(UT, 0);
6841
6842 QualType CanonType;
6843 if (!BaseType->isDependentType()) {
6844 CanonType = UnderlyingType.getCanonicalType();
6845 } else {
6846 if (QualType CanonBase = BaseType.getCanonicalType();
6847 BaseType != CanonBase) {
6848 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6849 assert(CanonType.isCanonical());
6850 }
6851 }
6852
6853 auto *UT = new (*this, alignof(UnaryTransformType))
6854 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6855 UnaryTransformTypes.insert(N: UT, Token);
6856 Types.push_back(Elt: UT);
6857 return QualType(UT, 0);
6858}
6859
6860/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6861/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6862/// canonical deduced-but-dependent 'auto' type.
6863QualType
6864ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6865 AutoTypeKeyword Keyword,
6866 TemplateName TypeConstraintConcept,
6867 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6868 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6869 TypeConstraintConcept.isNull()) {
6870 assert(DeducedAsType.isNull() && "");
6871 assert(TypeConstraintArgs.empty() && "");
6872 return getAutoDeductType();
6873 }
6874
6875 // Look in the folding set for an existing type.
6876 llvm::FoldingSetNodeID ID;
6877 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6878 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6879 if (auto const AT_iter = AutoTypes.find_as(Val: ID); AT_iter != AutoTypes.end())
6880 return QualType(AT_iter->getSecond(), 0);
6881
6882 if (DK == DeducedKind::Deduced) {
6883 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6884 } else {
6885 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6886 if (!TypeConstraintConcept.isNull()) {
6887 bool AnyNonCanonArgs = false;
6888 TemplateName CanonicalConcept =
6889 getCanonicalTemplateName(Name: TypeConstraintConcept);
6890 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6891 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6892 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6893 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6894 TypeConstraintArgs: CanonicalConceptArgs);
6895 }
6896 }
6897
6898 void *Mem = Allocate(Size: sizeof(AutoType) +
6899 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6900 Align: alignof(AutoType));
6901 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6902 TypeConstraintConcept, TypeConstraintArgs);
6903#ifndef NDEBUG
6904 llvm::FoldingSetNodeID InsertedID;
6905 AT->Profile(InsertedID, *this);
6906 assert(InsertedID == ID && "ID does not match");
6907#endif
6908 Types.push_back(Elt: AT);
6909 AutoTypes.try_emplace(Key: ID.Intern(Allocator&: BumpAlloc), Args&: AT);
6910 return QualType(AT, 0);
6911}
6912
6913QualType ASTContext::getUnconstrainedType(QualType T) const {
6914 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6915
6916 // Remove a type-constraint from a top-level auto or decltype(auto).
6917 if (auto *AT = CanonT->getAs<AutoType>()) {
6918 if (!AT->isConstrained())
6919 return T;
6920 return getQualifiedType(
6921 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6922 Qs: T.getQualifiers());
6923 }
6924
6925 // FIXME: We only support constrained auto at the top level in the type of a
6926 // non-type template parameter at the moment. Once we lift that restriction,
6927 // we'll need to recursively build types containing auto here.
6928 assert(!CanonT->getContainedAutoType() ||
6929 !CanonT->getContainedAutoType()->isConstrained());
6930 return T;
6931}
6932
6933/// Return the uniqued reference to the deduced template specialization type
6934/// which has been deduced to the given type, or to the canonical undeduced
6935/// such type, or the canonical deduced-but-dependent such type.
6936QualType ASTContext::getDeducedTemplateSpecializationType(
6937 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6938 TemplateName Template) const {
6939 // Look in the folding set for an existing type.
6940 llvm::FoldingSetInsertToken Token;
6941 llvm::FoldingSetNodeID ID;
6942 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6943 Template);
6944 if (DeducedTemplateSpecializationType *DTST =
6945 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6946 return QualType(DTST, 0);
6947
6948 if (DK == DeducedKind::Deduced) {
6949 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6950 } else {
6951 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6952 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
6953 // FIXME: Can this be formed from a DependentTemplateName, such that the
6954 // keyword should be part of the canonical type?
6955 if (Keyword != ElaboratedTypeKeyword::None ||
6956 Template != CanonTemplateName) {
6957 DeducedAsType = getDeducedTemplateSpecializationType(
6958 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
6959 // Find the insertion position again.
6960 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6961 DeducedTemplateSpecializationTypes.lookup(ID, Token);
6962 assert(!DTST && "broken canonicalization");
6963 }
6964 }
6965
6966 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6967 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6968
6969#ifndef NDEBUG
6970 llvm::FoldingSetNodeID TempID;
6971 DTST->Profile(TempID);
6972 assert(ID == TempID && "ID does not match");
6973#endif
6974 Types.push_back(Elt: DTST);
6975 DeducedTemplateSpecializationTypes.insert(N: DTST, Token);
6976 return QualType(DTST, 0);
6977}
6978
6979/// getAtomicType - Return the uniqued reference to the atomic type for
6980/// the given value type.
6981QualType ASTContext::getAtomicType(QualType T) const {
6982 // Unique pointers, to guarantee there is only one pointer of a particular
6983 // structure.
6984 llvm::FoldingSetInsertToken Token;
6985 if (AtomicType *AT = AtomicTypes.lookup(Key: T, Token))
6986 return QualType(AT, 0);
6987
6988 // If the atomic value type isn't canonical, this won't be a canonical type
6989 // either, so fill in the canonical type field.
6990 QualType Canonical;
6991 if (!T.isCanonical()) {
6992 Canonical = getAtomicType(T: getCanonicalType(T));
6993
6994 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
6995 }
6996 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6997 Types.push_back(Elt: New);
6998 AtomicTypes.insert(N: New, Token);
6999 return QualType(New, 0);
7000}
7001
7002/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7003QualType ASTContext::getAutoDeductType() const {
7004 if (AutoDeductTy.isNull())
7005 AutoDeductTy = QualType(
7006 new (*this, alignof(AutoType))
7007 AutoType(DeducedKind::Undeduced, QualType(), AutoTypeKeyword::Auto,
7008 /*TypeConstraintConcept=*/TemplateName(),
7009 /*TypeConstraintArgs=*/{}),
7010 0);
7011 return AutoDeductTy;
7012}
7013
7014/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7015QualType ASTContext::getAutoRRefDeductType() const {
7016 if (AutoRRefDeductTy.isNull())
7017 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7018 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7019 return AutoRRefDeductTy;
7020}
7021
7022/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7023/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7024/// needs to agree with the definition in <stddef.h>.
7025QualType ASTContext::getSizeType() const {
7026 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7027}
7028
7029CanQualType ASTContext::getCanonicalSizeType() const {
7030 return getFromTargetType(Type: Target->getSizeType());
7031}
7032
7033/// Return the unique signed counterpart of the integer type
7034/// corresponding to size_t.
7035QualType ASTContext::getSignedSizeType() const {
7036 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7037}
7038
7039/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7040/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7041QualType ASTContext::getPointerDiffType() const {
7042 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7043}
7044
7045/// Return the unique unsigned counterpart of "ptrdiff_t"
7046/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7047/// in the definition of %tu format specifier.
7048QualType ASTContext::getUnsignedPointerDiffType() const {
7049 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7050}
7051
7052/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7053CanQualType ASTContext::getIntMaxType() const {
7054 return getFromTargetType(Type: Target->getIntMaxType());
7055}
7056
7057/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7058CanQualType ASTContext::getUIntMaxType() const {
7059 return getFromTargetType(Type: Target->getUIntMaxType());
7060}
7061
7062/// getSignedWCharType - Return the type of "signed wchar_t".
7063/// Used when in C++, as a GCC extension.
7064QualType ASTContext::getSignedWCharType() const {
7065 // FIXME: derive from "Target" ?
7066 return WCharTy;
7067}
7068
7069/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7070/// Used when in C++, as a GCC extension.
7071QualType ASTContext::getUnsignedWCharType() const {
7072 // FIXME: derive from "Target" ?
7073 return UnsignedIntTy;
7074}
7075
7076QualType ASTContext::getIntPtrType() const {
7077 return getFromTargetType(Type: Target->getIntPtrType());
7078}
7079
7080QualType ASTContext::getUIntPtrType() const {
7081 return getCorrespondingUnsignedType(T: getIntPtrType());
7082}
7083
7084/// Return the unique type for "pid_t" defined in
7085/// <sys/types.h>. We need this to compute the correct type for vfork().
7086QualType ASTContext::getProcessIDType() const {
7087 return getFromTargetType(Type: Target->getProcessIDType());
7088}
7089
7090//===----------------------------------------------------------------------===//
7091// Type Operators
7092//===----------------------------------------------------------------------===//
7093
7094CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7095 // Push qualifiers into arrays, and then discard any remaining
7096 // qualifiers.
7097 T = getCanonicalType(T);
7098 T = getVariableArrayDecayedType(type: T);
7099 const Type *Ty = T.getTypePtr();
7100 QualType Result;
7101 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7102 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7103 } else if (isa<ArrayType>(Val: Ty)) {
7104 Result = getArrayDecayedType(T: QualType(Ty,0));
7105 } else if (isa<FunctionType>(Val: Ty)) {
7106 Result = getPointerType(T: QualType(Ty, 0));
7107 } else {
7108 Result = QualType(Ty, 0);
7109 }
7110
7111 return CanQualType::CreateUnsafe(Other: Result);
7112}
7113
7114QualType ASTContext::getUnqualifiedArrayType(QualType type,
7115 Qualifiers &quals) const {
7116 SplitQualType splitType = type.getSplitUnqualifiedType();
7117
7118 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7119 // the unqualified desugared type and then drops it on the floor.
7120 // We then have to strip that sugar back off with
7121 // getUnqualifiedDesugaredType(), which is silly.
7122 const auto *AT =
7123 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7124
7125 // If we don't have an array, just use the results in splitType.
7126 if (!AT) {
7127 quals = splitType.Quals;
7128 return QualType(splitType.Ty, 0);
7129 }
7130
7131 // Otherwise, recurse on the array's element type.
7132 QualType elementType = AT->getElementType();
7133 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7134
7135 // If that didn't change the element type, AT has no qualifiers, so we
7136 // can just use the results in splitType.
7137 if (elementType == unqualElementType) {
7138 assert(quals.empty()); // from the recursive call
7139 quals = splitType.Quals;
7140 return QualType(splitType.Ty, 0);
7141 }
7142
7143 // Otherwise, add in the qualifiers from the outermost type, then
7144 // build the type back up.
7145 quals.addConsistentQualifiers(qs: splitType.Quals);
7146
7147 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7148 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7149 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7150 }
7151
7152 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7153 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7154 }
7155
7156 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7157 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7158 ASM: VAT->getSizeModifier(),
7159 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7160 }
7161
7162 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7163 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7164 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7165}
7166
7167/// Attempt to unwrap two types that may both be array types with the same bound
7168/// (or both be array types of unknown bound) for the purpose of comparing the
7169/// cv-decomposition of two types per C++ [conv.qual].
7170///
7171/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7172/// C++20 [conv.qual], if permitted by the current language mode.
7173void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7174 bool AllowPiMismatch) const {
7175 while (true) {
7176 auto *AT1 = getAsArrayType(T: T1);
7177 if (!AT1)
7178 return;
7179
7180 auto *AT2 = getAsArrayType(T: T2);
7181 if (!AT2)
7182 return;
7183
7184 // If we don't have two array types with the same constant bound nor two
7185 // incomplete array types, we've unwrapped everything we can.
7186 // C++20 also permits one type to be a constant array type and the other
7187 // to be an incomplete array type.
7188 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7189 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7190 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7191 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7192 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7193 isa<IncompleteArrayType>(Val: AT2))))
7194 return;
7195 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7196 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7197 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7198 isa<ConstantArrayType>(Val: AT2))))
7199 return;
7200 } else {
7201 return;
7202 }
7203
7204 T1 = AT1->getElementType();
7205 T2 = AT2->getElementType();
7206 }
7207}
7208
7209/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7210///
7211/// If T1 and T2 are both pointer types of the same kind, or both array types
7212/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7213/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7214///
7215/// This function will typically be called in a loop that successively
7216/// "unwraps" pointer and pointer-to-member types to compare them at each
7217/// level.
7218///
7219/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7220/// C++20 [conv.qual], if permitted by the current language mode.
7221///
7222/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7223/// pair of types that can't be unwrapped further.
7224bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7225 bool AllowPiMismatch) const {
7226 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7227
7228 const auto *T1PtrType = T1->getAs<PointerType>();
7229 const auto *T2PtrType = T2->getAs<PointerType>();
7230 if (T1PtrType && T2PtrType) {
7231 T1 = T1PtrType->getPointeeType();
7232 T2 = T2PtrType->getPointeeType();
7233 return true;
7234 }
7235
7236 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7237 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7238 T1MPType && T2MPType) {
7239 // Compare the qualifiers of the canonical type, as the non-canonical type
7240 // may have qualifiers pointing to a base or derived class.
7241 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7242 return false;
7243 // Get the pointee types of the non-canonical type, in order to preserve
7244 // their sugar.
7245 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7246 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7247 return true;
7248 }
7249
7250 if (getLangOpts().ObjC) {
7251 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7252 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7253 if (T1OPType && T2OPType) {
7254 T1 = T1OPType->getPointeeType();
7255 T2 = T2OPType->getPointeeType();
7256 return true;
7257 }
7258 }
7259
7260 // FIXME: Block pointers, too?
7261
7262 return false;
7263}
7264
7265bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7266 while (true) {
7267 Qualifiers Quals;
7268 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7269 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7270 if (hasSameType(T1, T2))
7271 return true;
7272 if (!UnwrapSimilarTypes(T1, T2))
7273 return false;
7274 }
7275}
7276
7277bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7278 while (true) {
7279 Qualifiers Quals1, Quals2;
7280 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7281 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7282
7283 Quals1.removeCVRQualifiers();
7284 Quals2.removeCVRQualifiers();
7285 if (Quals1 != Quals2)
7286 return false;
7287
7288 if (hasSameType(T1, T2))
7289 return true;
7290
7291 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7292 return false;
7293 }
7294}
7295
7296DeclarationNameInfo
7297ASTContext::getNameForTemplate(TemplateName Name,
7298 SourceLocation NameLoc) const {
7299 switch (Name.getKind()) {
7300 case TemplateName::QualifiedTemplate:
7301 case TemplateName::Template:
7302 // DNInfo work in progress: CHECKME: what about DNLoc?
7303 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7304 NameLoc);
7305
7306 case TemplateName::OverloadedTemplate: {
7307 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7308 // DNInfo work in progress: CHECKME: what about DNLoc?
7309 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7310 }
7311
7312 case TemplateName::AssumedTemplate: {
7313 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7314 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7315 }
7316
7317 case TemplateName::DependentTemplate: {
7318 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7319 IdentifierOrOverloadedOperator TN = DTN->getName();
7320 DeclarationName DName;
7321 if (const IdentifierInfo *II = TN.getIdentifier()) {
7322 DName = DeclarationNames.getIdentifier(ID: II);
7323 return DeclarationNameInfo(DName, NameLoc);
7324 } else {
7325 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7326 // DNInfo work in progress: FIXME: source locations?
7327 DeclarationNameLoc DNLoc =
7328 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7329 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7330 }
7331 }
7332
7333 case TemplateName::SubstTemplateTemplateParm: {
7334 SubstTemplateTemplateParmStorage *subst
7335 = Name.getAsSubstTemplateTemplateParm();
7336 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7337 NameLoc);
7338 }
7339
7340 case TemplateName::SubstTemplateTemplateParmPack: {
7341 SubstTemplateTemplateParmPackStorage *subst
7342 = Name.getAsSubstTemplateTemplateParmPack();
7343 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7344 NameLoc);
7345 }
7346 case TemplateName::UsingTemplate:
7347 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7348 NameLoc);
7349 case TemplateName::DeducedTemplate: {
7350 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7351 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7352 }
7353 case TemplateName::PackIndexingTemplate: {
7354 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7355 return getNameForTemplate(Name: PI->getPattern(), NameLoc);
7356 }
7357 }
7358
7359 llvm_unreachable("bad template name kind!");
7360}
7361
7362const TemplateArgument *
7363ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7364 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7365 if (!TP->hasDefaultArgument())
7366 return nullptr;
7367 return &TP->getDefaultArgument().getArgument();
7368 };
7369 switch (P->getKind()) {
7370 case NamedDecl::TemplateTypeParm:
7371 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7372 case NamedDecl::NonTypeTemplateParm:
7373 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7374 case NamedDecl::TemplateTemplateParm:
7375 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7376 default:
7377 llvm_unreachable("Unexpected template parameter kind");
7378 }
7379}
7380
7381TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7382 bool IgnoreDeduced) const {
7383 while (std::optional<TemplateName> UnderlyingOrNone =
7384 Name.desugar(IgnoreDeduced))
7385 Name = *UnderlyingOrNone;
7386
7387 switch (Name.getKind()) {
7388 case TemplateName::Template: {
7389 TemplateDecl *Template = Name.getAsTemplateDecl();
7390 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7391 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7392
7393 // The canonical template name is the canonical template declaration.
7394 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7395 }
7396
7397 case TemplateName::AssumedTemplate:
7398 // An assumed template is just a name, so it is already canonical.
7399 return Name;
7400
7401 case TemplateName::OverloadedTemplate:
7402 llvm_unreachable("cannot canonicalize overloaded template");
7403
7404 case TemplateName::DependentTemplate: {
7405 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7406 assert(DTN && "Non-dependent template names must refer to template decls.");
7407 NestedNameSpecifier Qualifier = DTN->getQualifier();
7408 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7409 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7410 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7411 /*HasTemplateKeyword=*/true});
7412 return Name;
7413 }
7414
7415 case TemplateName::SubstTemplateTemplateParmPack: {
7416 SubstTemplateTemplateParmPackStorage *subst =
7417 Name.getAsSubstTemplateTemplateParmPack();
7418 TemplateArgument canonArgPack =
7419 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7420 return getSubstTemplateTemplateParmPack(
7421 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7422 Index: subst->getIndex(), Final: subst->getFinal());
7423 }
7424
7425 case TemplateName::PackIndexingTemplate: {
7426 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7427 SmallVector<TemplateName, 4> CanonExpansions;
7428 for (TemplateName T : PI->getExpansions())
7429 CanonExpansions.push_back(Elt: getCanonicalTemplateName(Name: T, IgnoreDeduced));
7430 return getPackIndexingTemplateName(
7431 Pattern: getCanonicalTemplateName(Name: PI->getPattern(), IgnoreDeduced),
7432 IndexExpr: PI->getIndexExpr(), FullySubstituted: PI->isFullySubstituted(), Expansions: CanonExpansions);
7433 }
7434 case TemplateName::DeducedTemplate: {
7435 assert(IgnoreDeduced == false);
7436 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7437 DefaultArguments DefArgs = DTS->getDefaultArguments();
7438 TemplateName Underlying = DTS->getUnderlying();
7439
7440 TemplateName CanonUnderlying =
7441 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7442 bool NonCanonical = CanonUnderlying != Underlying;
7443 auto CanonArgs =
7444 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7445
7446 ArrayRef<NamedDecl *> Params =
7447 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7448 assert(CanonArgs.size() <= Params.size());
7449 // A deduced template name which deduces the same default arguments already
7450 // declared in the underlying template is the same template as the
7451 // underlying template. We need need to note any arguments which differ from
7452 // the corresponding declaration. If any argument differs, we must build a
7453 // deduced template name.
7454 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7455 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7456 if (!A)
7457 break;
7458 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7459 TemplateArgument &CanonDefArg = CanonArgs[I];
7460 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7461 continue;
7462 // Keep popping from the back any deault arguments which are the same.
7463 if (I == int(CanonArgs.size() - 1))
7464 CanonArgs.pop_back();
7465 NonCanonical = true;
7466 }
7467 return NonCanonical ? getDeducedTemplateName(
7468 Underlying: CanonUnderlying,
7469 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7470 : Name;
7471 }
7472 case TemplateName::UsingTemplate:
7473 case TemplateName::QualifiedTemplate:
7474 case TemplateName::SubstTemplateTemplateParm:
7475 llvm_unreachable("always sugar node");
7476 }
7477
7478 llvm_unreachable("bad template name!");
7479}
7480
7481bool ASTContext::hasSameTemplateName(const TemplateName &X,
7482 const TemplateName &Y,
7483 bool IgnoreDeduced) const {
7484 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7485 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7486}
7487
7488bool ASTContext::isSameAssociatedConstraint(
7489 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7490 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7491 return false;
7492 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7493 return false;
7494 return true;
7495}
7496
7497bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7498 if (!XCE != !YCE)
7499 return false;
7500
7501 if (!XCE)
7502 return true;
7503
7504 llvm::FoldingSetNodeID XCEID, YCEID;
7505 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7506 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7507 return XCEID == YCEID;
7508}
7509
7510bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7511 const TypeConstraint *YTC) const {
7512 if (!XTC != !YTC)
7513 return false;
7514
7515 if (!XTC)
7516 return true;
7517
7518 TemplateDecl *NCX = XTC->getNamedConcept().getAsTemplateDecl();
7519 TemplateDecl *NCY = YTC->getNamedConcept().getAsTemplateDecl();
7520 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7521 return false;
7522 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7523 YTC->getConceptReference()->hasExplicitTemplateArgs())
7524 return false;
7525 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7526 if (XTC->getConceptReference()
7527 ->getTemplateArgsAsWritten()
7528 ->NumTemplateArgs !=
7529 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7530 return false;
7531
7532 // Compare slowly by profiling.
7533 //
7534 // We couldn't compare the profiling result for the template
7535 // args here. Consider the following example in different modules:
7536 //
7537 // template <__integer_like _Tp, C<_Tp> Sentinel>
7538 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7539 // return __t;
7540 // }
7541 //
7542 // When we compare the profiling result for `C<_Tp>` in different
7543 // modules, it will compare the type of `_Tp` in different modules.
7544 // However, the type of `_Tp` in different modules refer to different
7545 // types here naturally. So we couldn't compare the profiling result
7546 // for the template args directly.
7547 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7548 YCE: YTC->getImmediatelyDeclaredConstraint());
7549}
7550
7551bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7552 const NamedDecl *Y) const {
7553 if (X->getKind() != Y->getKind())
7554 return false;
7555
7556 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7557 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7558 if (TX->isParameterPack() != TY->isParameterPack())
7559 return false;
7560 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7561 return false;
7562 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7563 YTC: TY->getTypeConstraint());
7564 }
7565
7566 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7567 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7568 return TX->isParameterPack() == TY->isParameterPack() &&
7569 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7570 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7571 YCE: TY->getPlaceholderTypeConstraint());
7572 }
7573
7574 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7575 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7576 return TX->isParameterPack() == TY->isParameterPack() &&
7577 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7578 Y: TY->getTemplateParameters());
7579}
7580
7581bool ASTContext::isSameTemplateParameterList(
7582 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7583 if (X->size() != Y->size())
7584 return false;
7585
7586 for (unsigned I = 0, N = X->size(); I != N; ++I)
7587 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7588 return false;
7589
7590 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7591}
7592
7593bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7594 const NamedDecl *Y) const {
7595 // If the type parameter isn't the same already, we don't need to check the
7596 // default argument further.
7597 if (!isSameTemplateParameter(X, Y))
7598 return false;
7599
7600 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7601 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7602 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7603 return false;
7604
7605 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7606 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7607 }
7608
7609 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7610 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7611 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7612 return false;
7613
7614 Expr *DefaultArgumentX =
7615 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7616 Expr *DefaultArgumentY =
7617 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7618 llvm::FoldingSetNodeID XID, YID;
7619 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7620 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7621 return XID == YID;
7622 }
7623
7624 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7625 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7626
7627 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7628 return false;
7629
7630 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7631 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7632 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7633}
7634
7635static bool isSameQualifier(const NestedNameSpecifier X,
7636 const NestedNameSpecifier Y) {
7637 if (X == Y)
7638 return true;
7639 if (!X || !Y)
7640 return false;
7641
7642 auto Kind = X.getKind();
7643 if (Kind != Y.getKind())
7644 return false;
7645
7646 // FIXME: For namespaces and types, we're permitted to check that the entity
7647 // is named via the same tokens. We should probably do so.
7648 switch (Kind) {
7649 case NestedNameSpecifier::Kind::Namespace: {
7650 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7651 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7652 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7653 D2: NamespaceY->getNamespace()))
7654 return false;
7655 return isSameQualifier(X: PrefixX, Y: PrefixY);
7656 }
7657 case NestedNameSpecifier::Kind::Type: {
7658 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7659 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7660 return false;
7661 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7662 }
7663 case NestedNameSpecifier::Kind::Null:
7664 case NestedNameSpecifier::Kind::Global:
7665 case NestedNameSpecifier::Kind::MicrosoftSuper:
7666 return true;
7667 }
7668 llvm_unreachable("unhandled qualifier kind");
7669}
7670
7671static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7672 if (!A->getASTContext().getLangOpts().CUDA)
7673 return true; // Target attributes are overloadable in CUDA compilation only.
7674 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7675 return false;
7676 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7677 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7678 return true; // unattributed and __host__ functions are the same.
7679}
7680
7681/// Determine whether the attributes we can overload on are identical for A and
7682/// B. Will ignore any overloadable attrs represented in the type of A and B.
7683static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7684 const FunctionDecl *B) {
7685 // Note that pass_object_size attributes are represented in the function's
7686 // ExtParameterInfo, so we don't need to check them here.
7687
7688 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7689 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7690 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7691
7692 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7693 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7694 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7695
7696 // Return false if the number of enable_if attributes is different.
7697 if (!Cand1A || !Cand2A)
7698 return false;
7699
7700 Cand1ID.clear();
7701 Cand2ID.clear();
7702
7703 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7704 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7705
7706 // Return false if any of the enable_if expressions of A and B are
7707 // different.
7708 if (Cand1ID != Cand2ID)
7709 return false;
7710 }
7711 return hasSameCudaAttrs(A, B);
7712}
7713
7714bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7715 // Caution: this function is called by the AST reader during deserialization,
7716 // so it cannot rely on AST invariants being met. Non-trivial accessors
7717 // should be avoided, along with any traversal of redeclaration chains.
7718
7719 if (X == Y)
7720 return true;
7721
7722 if (X->getDeclName() != Y->getDeclName())
7723 return false;
7724
7725 // Must be in the same context.
7726 //
7727 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7728 // could be two different declarations of the same function. (We will fix the
7729 // semantic DC to refer to the primary definition after merging.)
7730 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7731 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7732 return false;
7733
7734 // If either X or Y are local to the owning module, they are only possible to
7735 // be the same entity if they are in the same module.
7736 if (X->isModuleLocal() || Y->isModuleLocal())
7737 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7738 return false;
7739
7740 // Two typedefs refer to the same entity if they have the same underlying
7741 // type.
7742 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7743 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7744 return hasSameType(T1: TypedefX->getUnderlyingType(),
7745 T2: TypedefY->getUnderlyingType());
7746
7747 // Must have the same kind.
7748 if (X->getKind() != Y->getKind())
7749 return false;
7750
7751 // Objective-C classes and protocols with the same name always match.
7752 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7753 return true;
7754
7755 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7756 // No need to handle these here: we merge them when adding them to the
7757 // template.
7758 return false;
7759 }
7760
7761 // Compatible tags match.
7762 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7763 const auto *TagY = cast<TagDecl>(Val: Y);
7764 return (TagX->getTagKind() == TagY->getTagKind()) ||
7765 ((TagX->getTagKind() == TagTypeKind::Struct ||
7766 TagX->getTagKind() == TagTypeKind::Class ||
7767 TagX->getTagKind() == TagTypeKind::Interface) &&
7768 (TagY->getTagKind() == TagTypeKind::Struct ||
7769 TagY->getTagKind() == TagTypeKind::Class ||
7770 TagY->getTagKind() == TagTypeKind::Interface));
7771 }
7772
7773 // Functions with the same type and linkage match.
7774 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7775 // functions, etc.
7776 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7777 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7778 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7779 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7780 if (CtorX->getInheritedConstructor() &&
7781 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7782 Y: CtorY->getInheritedConstructor().getConstructor()))
7783 return false;
7784 }
7785
7786 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7787 return false;
7788
7789 // Multiversioned functions with different feature strings are represented
7790 // as separate declarations.
7791 if (FuncX->isMultiVersion()) {
7792 const auto *TAX = FuncX->getAttr<TargetAttr>();
7793 const auto *TAY = FuncY->getAttr<TargetAttr>();
7794 assert(TAX && TAY && "Multiversion Function without target attribute");
7795
7796 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7797 return false;
7798 }
7799
7800 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7801 // not the same entity if they are constrained.
7802 if ((FuncX->isMemberLikeConstrainedFriend() ||
7803 FuncY->isMemberLikeConstrainedFriend()) &&
7804 !FuncX->getLexicalDeclContext()->Equals(
7805 DC: FuncY->getLexicalDeclContext())) {
7806 return false;
7807 }
7808
7809 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7810 ACY: FuncY->getTrailingRequiresClause()))
7811 return false;
7812
7813 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7814 // Map to the first declaration that we've already merged into this one.
7815 // The TSI of redeclarations might not match (due to calling conventions
7816 // being inherited onto the type but not the TSI), but the TSI type of
7817 // the first declaration of the function should match across modules.
7818 FD = FD->getCanonicalDecl();
7819 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7820 : FD->getType();
7821 };
7822 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7823 if (!hasSameType(T1: XT, T2: YT)) {
7824 // We can get functions with different types on the redecl chain in C++17
7825 // if they have differing exception specifications and at least one of
7826 // the excpetion specs is unresolved.
7827 auto *XFPT = XT->getAs<FunctionProtoType>();
7828 auto *YFPT = YT->getAs<FunctionProtoType>();
7829 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7830 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7831 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7832 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7833 return true;
7834 return false;
7835 }
7836
7837 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7838 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7839 }
7840
7841 // Variables with the same type and linkage match.
7842 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7843 const auto *VarY = cast<VarDecl>(Val: Y);
7844 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7845 // During deserialization, we might compare variables before we load
7846 // their types. Assume the types will end up being the same.
7847 if (VarX->getType().isNull() || VarY->getType().isNull())
7848 return true;
7849
7850 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7851 return true;
7852
7853 // We can get decls with different types on the redecl chain. Eg.
7854 // template <typename T> struct S { static T Var[]; }; // #1
7855 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7856 // Only? happens when completing an incomplete array type. In this case
7857 // when comparing #1 and #2 we should go through their element type.
7858 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7859 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7860 if (!VarXTy || !VarYTy)
7861 return false;
7862 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7863 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7864 }
7865 return false;
7866 }
7867
7868 // Namespaces with the same name and inlinedness match.
7869 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7870 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7871 return NamespaceX->isInline() == NamespaceY->isInline();
7872 }
7873
7874 // Identical template names and kinds match if their template parameter lists
7875 // and patterns match.
7876 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7877 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7878
7879 // ConceptDecl wouldn't be the same if their constraint expression differs.
7880 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7881 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7882 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7883 YCE: ConceptY->getConstraintExpr()))
7884 return false;
7885 }
7886
7887 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7888 Y: TemplateY->getTemplatedDecl()) &&
7889 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7890 Y: TemplateY->getTemplateParameters());
7891 }
7892
7893 // Fields with the same name and the same type match.
7894 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7895 const auto *FDY = cast<FieldDecl>(Val: Y);
7896 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7897 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7898 }
7899
7900 // Indirect fields with the same target field match.
7901 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7902 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7903 return IFDX->getAnonField()->getCanonicalDecl() ==
7904 IFDY->getAnonField()->getCanonicalDecl();
7905 }
7906
7907 // Enumerators with the same name match.
7908 if (isa<EnumConstantDecl>(Val: X))
7909 // FIXME: Also check the value is odr-equivalent.
7910 return true;
7911
7912 // Using shadow declarations with the same target match.
7913 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7914 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7915 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7916 }
7917
7918 // Using declarations with the same qualifier match. (We already know that
7919 // the name matches.)
7920 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7921 const auto *UY = cast<UsingDecl>(Val: Y);
7922 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7923 UX->hasTypename() == UY->hasTypename() &&
7924 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7925 }
7926 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7927 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7928 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7929 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7930 }
7931 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7932 return isSameQualifier(
7933 X: UX->getQualifier(),
7934 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7935 }
7936
7937 // Using-pack declarations are only created by instantiation, and match if
7938 // they're instantiated from matching UnresolvedUsing...Decls.
7939 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7940 return declaresSameEntity(
7941 D1: UX->getInstantiatedFromUsingDecl(),
7942 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7943 }
7944
7945 // Namespace alias definitions with the same target match.
7946 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7947 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
7948 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
7949 }
7950
7951 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
7952 const auto *UY = cast<UsingEnumDecl>(Val: Y);
7953 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7954 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
7955 }
7956
7957 return false;
7958}
7959
7960TemplateArgument
7961ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
7962 switch (Arg.getKind()) {
7963 case TemplateArgument::Null:
7964 return Arg;
7965
7966 case TemplateArgument::Expression:
7967 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7968 Arg.getIsDefaulted());
7969
7970 case TemplateArgument::Declaration: {
7971 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
7972 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
7973 Arg.getIsDefaulted());
7974 }
7975
7976 case TemplateArgument::NullPtr:
7977 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
7978 /*isNullPtr*/ true, Arg.getIsDefaulted());
7979
7980 case TemplateArgument::Template:
7981 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
7982 Arg.getIsDefaulted());
7983
7984 case TemplateArgument::TemplateExpansion:
7985 return TemplateArgument(
7986 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
7987 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
7988
7989 case TemplateArgument::Integral:
7990 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
7991
7992 case TemplateArgument::StructuralValue:
7993 return TemplateArgument(*this,
7994 getCanonicalType(T: Arg.getStructuralValueType()),
7995 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
7996
7997 case TemplateArgument::Type:
7998 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
7999 /*isNullPtr*/ false, Arg.getIsDefaulted());
8000
8001 case TemplateArgument::Pack: {
8002 bool AnyNonCanonArgs = false;
8003 auto CanonArgs = ::getCanonicalTemplateArguments(
8004 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8005 if (!AnyNonCanonArgs)
8006 return Arg;
8007 auto NewArg = TemplateArgument::CreatePackCopy(
8008 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8009 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8010 return NewArg;
8011 }
8012 }
8013
8014 // Silence GCC warning
8015 llvm_unreachable("Unhandled template argument kind");
8016}
8017
8018bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8019 const TemplateArgument &Arg2) const {
8020 if (Arg1.getKind() != Arg2.getKind())
8021 return false;
8022
8023 switch (Arg1.getKind()) {
8024 case TemplateArgument::Null:
8025 llvm_unreachable("Comparing NULL template argument");
8026
8027 case TemplateArgument::Type:
8028 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8029
8030 case TemplateArgument::Declaration:
8031 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8032 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8033
8034 case TemplateArgument::NullPtr:
8035 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8036
8037 case TemplateArgument::Template:
8038 case TemplateArgument::TemplateExpansion:
8039 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8040 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8041
8042 case TemplateArgument::Integral:
8043 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8044 I2: Arg2.getAsIntegral());
8045
8046 case TemplateArgument::StructuralValue:
8047 return Arg1.structurallyEquals(Other: Arg2);
8048
8049 case TemplateArgument::Expression: {
8050 llvm::FoldingSetNodeID ID1, ID2;
8051 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8052 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8053 return ID1 == ID2;
8054 }
8055
8056 case TemplateArgument::Pack:
8057 return llvm::equal(
8058 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8059 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8060 return isSameTemplateArgument(Arg1, Arg2);
8061 });
8062 }
8063
8064 llvm_unreachable("Unhandled template argument kind");
8065}
8066
8067const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8068 // Handle the non-qualified case efficiently.
8069 if (!T.hasLocalQualifiers()) {
8070 // Handle the common positive case fast.
8071 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8072 return AT;
8073 }
8074
8075 // Handle the common negative case fast.
8076 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8077 return nullptr;
8078
8079 // Apply any qualifiers from the array type to the element type. This
8080 // implements C99 6.7.3p8: "If the specification of an array type includes
8081 // any type qualifiers, the element type is so qualified, not the array type."
8082
8083 // If we get here, we either have type qualifiers on the type, or we have
8084 // sugar such as a typedef in the way. If we have type qualifiers on the type
8085 // we must propagate them down into the element type.
8086
8087 SplitQualType split = T.getSplitDesugaredType();
8088 Qualifiers qs = split.Quals;
8089
8090 // If we have a simple case, just return now.
8091 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8092 if (!ATy || qs.empty())
8093 return ATy;
8094
8095 // Otherwise, we have an array and we have qualifiers on it. Push the
8096 // qualifiers into the array element type and return a new array type.
8097 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8098
8099 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8100 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8101 SizeExpr: CAT->getSizeExpr(),
8102 ASM: CAT->getSizeModifier(),
8103 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8104 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8105 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8106 ASM: IAT->getSizeModifier(),
8107 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8108
8109 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8110 return cast<ArrayType>(Val: getDependentSizedArrayType(
8111 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8112 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8113
8114 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8115 return cast<ArrayType>(
8116 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8117 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8118}
8119
8120QualType ASTContext::getAdjustedParameterType(QualType T) const {
8121 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8122 return getLValueReferenceType(T);
8123 if (getLangOpts().HLSL && T->isConstantArrayType())
8124 return getArrayParameterType(Ty: T);
8125 if (T->isArrayType() || T->isFunctionType())
8126 return getDecayedType(T);
8127 return T;
8128}
8129
8130QualType ASTContext::getSignatureParameterType(QualType T) const {
8131 T = getVariableArrayDecayedType(type: T);
8132 T = getAdjustedParameterType(T);
8133 return T.getUnqualifiedType();
8134}
8135
8136QualType ASTContext::getExceptionObjectType(QualType T) const {
8137 // C++ [except.throw]p3:
8138 // A throw-expression initializes a temporary object, called the exception
8139 // object, the type of which is determined by removing any top-level
8140 // cv-qualifiers from the static type of the operand of throw and adjusting
8141 // the type from "array of T" or "function returning T" to "pointer to T"
8142 // or "pointer to function returning T", [...]
8143 T = getVariableArrayDecayedType(type: T);
8144 if (T->isArrayType() || T->isFunctionType())
8145 T = getDecayedType(T);
8146 return T.getUnqualifiedType();
8147}
8148
8149/// getArrayDecayedType - Return the properly qualified result of decaying the
8150/// specified array type to a pointer. This operation is non-trivial when
8151/// handling typedefs etc. The canonical type of "T" must be an array type,
8152/// this returns a pointer to a properly qualified element of the array.
8153///
8154/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8155QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8156 // Get the element type with 'getAsArrayType' so that we don't lose any
8157 // typedefs in the element type of the array. This also handles propagation
8158 // of type qualifiers from the array type into the element type if present
8159 // (C99 6.7.3p8).
8160 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8161 assert(PrettyArrayType && "Not an array type!");
8162
8163 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8164
8165 // int x[restrict 4] -> int *restrict
8166 QualType Result = getQualifiedType(T: PtrTy,
8167 Qs: PrettyArrayType->getIndexTypeQualifiers());
8168
8169 // int x[_Nullable] -> int * _Nullable
8170 if (auto Nullability = Ty->getNullability()) {
8171 Result = getAttributedType(nullability: *Nullability, modifiedType: Result, equivalentType: Result);
8172 }
8173 return Result;
8174}
8175
8176QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8177 return getBaseElementType(QT: array->getElementType());
8178}
8179
8180QualType ASTContext::getBaseElementType(QualType type) const {
8181 Qualifiers qs;
8182 while (true) {
8183 SplitQualType split = type.getSplitDesugaredType();
8184 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8185 if (!array) break;
8186
8187 type = array->getElementType();
8188 qs.addConsistentQualifiers(qs: split.Quals);
8189 }
8190
8191 return getQualifiedType(T: type, Qs: qs);
8192}
8193
8194uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) {
8195 uint64_t ElementCount = 1;
8196 do {
8197 ElementCount *= CA->getZExtSize();
8198 CA = dyn_cast_if_present<ConstantArrayType>(
8199 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8200 } while (CA);
8201 return ElementCount;
8202}
8203
8204uint64_t
8205ASTContext::getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) {
8206 if (!AILE)
8207 return 0;
8208
8209 uint64_t ElementCount = 1;
8210
8211 do {
8212 ElementCount *= AILE->getArraySize().getZExtValue();
8213 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8214 } while (AILE);
8215
8216 return ElementCount;
8217}
8218
8219/// getFloatingRank - Return a relative rank for floating point types.
8220/// This routine will assert if passed a built-in type that isn't a float.
8221static FloatingRank getFloatingRank(QualType T) {
8222 if (const auto *CT = T->getAs<ComplexType>())
8223 return getFloatingRank(T: CT->getElementType());
8224
8225 switch (T->castAs<BuiltinType>()->getKind()) {
8226 default: llvm_unreachable("getFloatingRank(): not a floating type");
8227 case BuiltinType::Float16: return Float16Rank;
8228 case BuiltinType::Half: return HalfRank;
8229 case BuiltinType::Float: return FloatRank;
8230 case BuiltinType::Double: return DoubleRank;
8231 case BuiltinType::LongDouble: return LongDoubleRank;
8232 case BuiltinType::Float128: return Float128Rank;
8233 case BuiltinType::BFloat16: return BFloat16Rank;
8234 case BuiltinType::Ibm128: return Ibm128Rank;
8235 }
8236}
8237
8238/// getFloatingTypeOrder - Compare the rank of the two specified floating
8239/// point types, ignoring the domain of the type (i.e. 'double' ==
8240/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8241/// LHS < RHS, return -1.
8242int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8243 FloatingRank LHSR = getFloatingRank(T: LHS);
8244 FloatingRank RHSR = getFloatingRank(T: RHS);
8245
8246 if (LHSR == RHSR)
8247 return 0;
8248 if (LHSR > RHSR)
8249 return 1;
8250 return -1;
8251}
8252
8253int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8254 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8255 return 0;
8256 return getFloatingTypeOrder(LHS, RHS);
8257}
8258
8259/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8260/// routine will assert if passed a built-in type that isn't an integer or enum,
8261/// or if it is not canonicalized.
8262unsigned ASTContext::getIntegerRank(const Type *T) const {
8263 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8264
8265 // Results in this 'losing' to any type of the same size, but winning if
8266 // larger.
8267 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8268 return 0 + (EIT->getNumBits() << 3);
8269
8270 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8271 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8272
8273 switch (cast<BuiltinType>(Val: T)->getKind()) {
8274 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8275 case BuiltinType::Bool:
8276 return 1 + (getIntWidth(T: BoolTy) << 3);
8277 case BuiltinType::Char_S:
8278 case BuiltinType::Char_U:
8279 case BuiltinType::SChar:
8280 case BuiltinType::UChar:
8281 return 2 + (getIntWidth(T: CharTy) << 3);
8282 case BuiltinType::Short:
8283 case BuiltinType::UShort:
8284 return 3 + (getIntWidth(T: ShortTy) << 3);
8285 case BuiltinType::Int:
8286 case BuiltinType::UInt:
8287 return 4 + (getIntWidth(T: IntTy) << 3);
8288 case BuiltinType::Long:
8289 case BuiltinType::ULong:
8290 return 5 + (getIntWidth(T: LongTy) << 3);
8291 case BuiltinType::LongLong:
8292 case BuiltinType::ULongLong:
8293 return 6 + (getIntWidth(T: LongLongTy) << 3);
8294 case BuiltinType::Int128:
8295 case BuiltinType::UInt128:
8296 return 7 + (getIntWidth(T: Int128Ty) << 3);
8297
8298 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8299 // their underlying types" [c++20 conv.rank]
8300 case BuiltinType::Char8:
8301 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8302 case BuiltinType::Char16:
8303 return getIntegerRank(
8304 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8305 case BuiltinType::Char32:
8306 return getIntegerRank(
8307 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8308 case BuiltinType::WChar_S:
8309 case BuiltinType::WChar_U:
8310 return getIntegerRank(
8311 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8312 }
8313}
8314
8315/// Whether this is a promotable bitfield reference according
8316/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8317///
8318/// \returns the type this bit-field will promote to, or NULL if no
8319/// promotion occurs.
8320QualType ASTContext::isPromotableBitField(Expr *E) const {
8321 if (E->isTypeDependent() || E->isValueDependent())
8322 return {};
8323
8324 // C++ [conv.prom]p5:
8325 // If the bit-field has an enumerated type, it is treated as any other
8326 // value of that type for promotion purposes.
8327 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8328 return {};
8329
8330 // FIXME: We should not do this unless E->refersToBitField() is true. This
8331 // matters in C where getSourceBitField() will find bit-fields for various
8332 // cases where the source expression is not a bit-field designator.
8333
8334 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8335 if (!Field)
8336 return {};
8337
8338 QualType FT = Field->getType();
8339
8340 uint64_t BitWidth = Field->getBitWidthValue();
8341 uint64_t IntSize = getTypeSize(T: IntTy);
8342 // C++ [conv.prom]p5:
8343 // A prvalue for an integral bit-field can be converted to a prvalue of type
8344 // int if int can represent all the values of the bit-field; otherwise, it
8345 // can be converted to unsigned int if unsigned int can represent all the
8346 // values of the bit-field. If the bit-field is larger yet, no integral
8347 // promotion applies to it.
8348 // C11 6.3.1.1/2:
8349 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8350 // If an int can represent all values of the original type (as restricted by
8351 // the width, for a bit-field), the value is converted to an int; otherwise,
8352 // it is converted to an unsigned int.
8353 //
8354 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8355 // We perform that promotion here to match GCC and C++.
8356 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8357 // greater than that of 'int'. We perform that promotion to match GCC.
8358 //
8359 // C23 6.3.1.1p2:
8360 // The value from a bit-field of a bit-precise integer type is converted to
8361 // the corresponding bit-precise integer type. (The rest is the same as in
8362 // C11.)
8363 if (QualType QT = Field->getType(); QT->isBitIntType())
8364 return QT;
8365
8366 if (BitWidth < IntSize)
8367 return IntTy;
8368
8369 if (BitWidth == IntSize)
8370 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8371
8372 // Bit-fields wider than int are not subject to promotions, and therefore act
8373 // like the base type. GCC has some weird bugs in this area that we
8374 // deliberately do not follow (GCC follows a pre-standard resolution to
8375 // C's DR315 which treats bit-width as being part of the type, and this leaks
8376 // into their semantics in some cases).
8377 return {};
8378}
8379
8380/// getPromotedIntegerType - Returns the type that Promotable will
8381/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8382/// integer type.
8383QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8384 assert(!Promotable.isNull());
8385 assert(isPromotableIntegerType(Promotable));
8386 if (const auto *ED = Promotable->getAsEnumDecl())
8387 return ED->getPromotionType();
8388
8389 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8390 // qualifier.
8391 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8392 QualType PromotedUnderlying =
8393 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8394 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8395 }
8396
8397 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8398 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8399 // (3.9.1) can be converted to a prvalue of the first of the following
8400 // types that can represent all the values of its underlying type:
8401 // int, unsigned int, long int, unsigned long int, long long int, or
8402 // unsigned long long int [...]
8403 // FIXME: Is there some better way to compute this?
8404 if (BT->getKind() == BuiltinType::WChar_S ||
8405 BT->getKind() == BuiltinType::WChar_U ||
8406 BT->getKind() == BuiltinType::Char8 ||
8407 BT->getKind() == BuiltinType::Char16 ||
8408 BT->getKind() == BuiltinType::Char32) {
8409 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8410 uint64_t FromSize = getTypeSize(T: BT);
8411 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8412 LongLongTy, UnsignedLongLongTy };
8413 for (const auto &PT : PromoteTypes) {
8414 uint64_t ToSize = getTypeSize(T: PT);
8415 if (FromSize < ToSize ||
8416 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8417 return PT;
8418 }
8419 llvm_unreachable("char type should fit into long long");
8420 }
8421 }
8422
8423 // At this point, we should have a signed or unsigned integer type.
8424 if (Promotable->isSignedIntegerType())
8425 return IntTy;
8426 uint64_t PromotableSize = getIntWidth(T: Promotable);
8427 uint64_t IntSize = getIntWidth(T: IntTy);
8428 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8429 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8430}
8431
8432/// Recurses in pointer/array types until it finds an objc retainable
8433/// type and returns its ownership.
8434Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8435 while (!T.isNull()) {
8436 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8437 return T.getObjCLifetime();
8438 if (T->isArrayType())
8439 T = getBaseElementType(type: T);
8440 else if (const auto *PT = T->getAs<PointerType>())
8441 T = PT->getPointeeType();
8442 else if (const auto *RT = T->getAs<ReferenceType>())
8443 T = RT->getPointeeType();
8444 else
8445 break;
8446 }
8447
8448 return Qualifiers::OCL_None;
8449}
8450
8451static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8452 // Incomplete enum types are not treated as integer types.
8453 // FIXME: In C++, enum types are never integer types.
8454 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8455 if (ED->isComplete() && !ED->isScoped())
8456 return ED->getIntegerType().getTypePtr();
8457 return nullptr;
8458}
8459
8460/// getIntegerTypeOrder - Returns the highest ranked integer type:
8461/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8462/// LHS < RHS, return -1.
8463int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8464 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8465 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8466
8467 // Unwrap enums to their underlying type.
8468 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8469 LHSC = getIntegerTypeForEnum(ET);
8470 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8471 RHSC = getIntegerTypeForEnum(ET);
8472
8473 if (LHSC == RHSC) return 0;
8474
8475 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8476 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8477
8478 unsigned LHSRank = getIntegerRank(T: LHSC);
8479 unsigned RHSRank = getIntegerRank(T: RHSC);
8480
8481 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8482 if (LHSRank == RHSRank) return 0;
8483 return LHSRank > RHSRank ? 1 : -1;
8484 }
8485
8486 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8487 if (LHSUnsigned) {
8488 // If the unsigned [LHS] type is larger, return it.
8489 if (LHSRank >= RHSRank)
8490 return 1;
8491
8492 // If the signed type can represent all values of the unsigned type, it
8493 // wins. Because we are dealing with 2's complement and types that are
8494 // powers of two larger than each other, this is always safe.
8495 return -1;
8496 }
8497
8498 // If the unsigned [RHS] type is larger, return it.
8499 if (RHSRank >= LHSRank)
8500 return -1;
8501
8502 // If the signed type can represent all values of the unsigned type, it
8503 // wins. Because we are dealing with 2's complement and types that are
8504 // powers of two larger than each other, this is always safe.
8505 return 1;
8506}
8507
8508TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8509 if (CFConstantStringTypeDecl)
8510 return CFConstantStringTypeDecl;
8511
8512 assert(!CFConstantStringTagDecl &&
8513 "tag and typedef should be initialized together");
8514 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8515 CFConstantStringTagDecl->startDefinition();
8516
8517 struct {
8518 QualType Type;
8519 const char *Name;
8520 } Fields[5];
8521 unsigned Count = 0;
8522
8523 /// Objective-C ABI
8524 ///
8525 /// typedef struct __NSConstantString_tag {
8526 /// const int *isa;
8527 /// int flags;
8528 /// const char *str;
8529 /// long length;
8530 /// } __NSConstantString;
8531 ///
8532 /// Swift ABI (4.1, 4.2)
8533 ///
8534 /// typedef struct __NSConstantString_tag {
8535 /// uintptr_t _cfisa;
8536 /// uintptr_t _swift_rc;
8537 /// _Atomic(uint64_t) _cfinfoa;
8538 /// const char *_ptr;
8539 /// uint32_t _length;
8540 /// } __NSConstantString;
8541 ///
8542 /// Swift ABI (5.0)
8543 ///
8544 /// typedef struct __NSConstantString_tag {
8545 /// uintptr_t _cfisa;
8546 /// uintptr_t _swift_rc;
8547 /// _Atomic(uint64_t) _cfinfoa;
8548 /// const char *_ptr;
8549 /// uintptr_t _length;
8550 /// } __NSConstantString;
8551
8552 const auto CFRuntime = getLangOpts().CFRuntime;
8553 if (static_cast<unsigned>(CFRuntime) <
8554 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8555 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8556 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8557 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8558 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8559 } else {
8560 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8561 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8562 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8563 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8564 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8565 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8566 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8567 else
8568 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8569 }
8570
8571 // Create fields
8572 for (unsigned i = 0; i < Count; ++i) {
8573 FieldDecl *Field =
8574 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8575 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8576 T: Fields[i].Type, /*TInfo=*/nullptr,
8577 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8578 Field->setAccess(AS_public);
8579 CFConstantStringTagDecl->addDecl(D: Field);
8580 }
8581
8582 CFConstantStringTagDecl->completeDefinition();
8583 // This type is designed to be compatible with NSConstantString, but cannot
8584 // use the same name, since NSConstantString is an interface.
8585 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8586 CFConstantStringTypeDecl =
8587 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8588
8589 return CFConstantStringTypeDecl;
8590}
8591
8592RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8593 if (!CFConstantStringTagDecl)
8594 getCFConstantStringDecl(); // Build the tag and the typedef.
8595 return CFConstantStringTagDecl;
8596}
8597
8598// getCFConstantStringType - Return the type used for constant CFStrings.
8599QualType ASTContext::getCFConstantStringType() const {
8600 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8601 Decl: getCFConstantStringDecl());
8602}
8603
8604QualType ASTContext::getObjCSuperType() const {
8605 if (ObjCSuperType.isNull()) {
8606 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8607 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8608 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8609 }
8610 return ObjCSuperType;
8611}
8612
8613void ASTContext::setCFConstantStringType(QualType T) {
8614 const auto *TT = T->castAs<TypedefType>();
8615 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8616 CFConstantStringTagDecl = TT->castAsRecordDecl();
8617}
8618
8619QualType ASTContext::getBlockDescriptorType() const {
8620 if (BlockDescriptorType)
8621 return getCanonicalTagType(TD: BlockDescriptorType);
8622
8623 RecordDecl *RD;
8624 // FIXME: Needs the FlagAppleBlock bit.
8625 RD = buildImplicitRecord(Name: "__block_descriptor");
8626 RD->startDefinition();
8627
8628 QualType FieldTypes[] = {
8629 UnsignedLongTy,
8630 UnsignedLongTy,
8631 };
8632
8633 static const char *const FieldNames[] = {
8634 "reserved",
8635 "Size"
8636 };
8637
8638 for (size_t i = 0; i < 2; ++i) {
8639 FieldDecl *Field = FieldDecl::Create(
8640 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8641 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8642 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8643 Field->setAccess(AS_public);
8644 RD->addDecl(D: Field);
8645 }
8646
8647 RD->completeDefinition();
8648
8649 BlockDescriptorType = RD;
8650
8651 return getCanonicalTagType(TD: BlockDescriptorType);
8652}
8653
8654QualType ASTContext::getBlockDescriptorExtendedType() const {
8655 if (BlockDescriptorExtendedType)
8656 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8657
8658 RecordDecl *RD;
8659 // FIXME: Needs the FlagAppleBlock bit.
8660 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8661 RD->startDefinition();
8662
8663 QualType FieldTypes[] = {
8664 UnsignedLongTy,
8665 UnsignedLongTy,
8666 getPointerType(T: VoidPtrTy),
8667 getPointerType(T: VoidPtrTy)
8668 };
8669
8670 static const char *const FieldNames[] = {
8671 "reserved",
8672 "Size",
8673 "CopyFuncPtr",
8674 "DestroyFuncPtr"
8675 };
8676
8677 for (size_t i = 0; i < 4; ++i) {
8678 FieldDecl *Field = FieldDecl::Create(
8679 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8680 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8681 /*BitWidth=*/BW: nullptr,
8682 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8683 Field->setAccess(AS_public);
8684 RD->addDecl(D: Field);
8685 }
8686
8687 RD->completeDefinition();
8688
8689 BlockDescriptorExtendedType = RD;
8690 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8691}
8692
8693OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8694 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8695
8696 if (!BT) {
8697 if (isa<PipeType>(Val: T))
8698 return OCLTK_Pipe;
8699
8700 return OCLTK_Default;
8701 }
8702
8703 switch (BT->getKind()) {
8704#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8705 case BuiltinType::Id: \
8706 return OCLTK_Image;
8707#include "clang/Basic/OpenCLImageTypes.def"
8708
8709 case BuiltinType::OCLClkEvent:
8710 return OCLTK_ClkEvent;
8711
8712 case BuiltinType::OCLEvent:
8713 return OCLTK_Event;
8714
8715 case BuiltinType::OCLQueue:
8716 return OCLTK_Queue;
8717
8718 case BuiltinType::OCLReserveID:
8719 return OCLTK_ReserveID;
8720
8721 case BuiltinType::OCLSampler:
8722 return OCLTK_Sampler;
8723
8724 default:
8725 return OCLTK_Default;
8726 }
8727}
8728
8729LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8730 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8731}
8732
8733/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8734/// requires copy/dispose. Note that this must match the logic
8735/// in buildByrefHelpers.
8736bool ASTContext::BlockRequiresCopying(QualType Ty,
8737 const VarDecl *D) {
8738 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8739 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8740 if (!copyExpr && record->hasTrivialDestructor()) return false;
8741
8742 return true;
8743 }
8744
8745 if (Ty.hasAddressDiscriminatedPointerAuth())
8746 return true;
8747
8748 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8749 // move or destroy.
8750 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8751 return true;
8752
8753 if (!Ty->isObjCRetainableType()) return false;
8754
8755 Qualifiers qs = Ty.getQualifiers();
8756
8757 // If we have lifetime, that dominates.
8758 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8759 switch (lifetime) {
8760 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8761
8762 // These are just bits as far as the runtime is concerned.
8763 case Qualifiers::OCL_ExplicitNone:
8764 case Qualifiers::OCL_Autoreleasing:
8765 return false;
8766
8767 // These cases should have been taken care of when checking the type's
8768 // non-triviality.
8769 case Qualifiers::OCL_Weak:
8770 case Qualifiers::OCL_Strong:
8771 llvm_unreachable("impossible");
8772 }
8773 llvm_unreachable("fell out of lifetime switch!");
8774 }
8775 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8776 Ty->isObjCObjectPointerType());
8777}
8778
8779bool ASTContext::getByrefLifetime(QualType Ty,
8780 Qualifiers::ObjCLifetime &LifeTime,
8781 bool &HasByrefExtendedLayout) const {
8782 if (!getLangOpts().ObjC ||
8783 getLangOpts().getGC() != LangOptions::NonGC)
8784 return false;
8785
8786 HasByrefExtendedLayout = false;
8787 if (Ty->isRecordType()) {
8788 HasByrefExtendedLayout = true;
8789 LifeTime = Qualifiers::OCL_None;
8790 } else if ((LifeTime = Ty.getObjCLifetime())) {
8791 // Honor the ARC qualifiers.
8792 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8793 // The MRR rule.
8794 LifeTime = Qualifiers::OCL_ExplicitNone;
8795 } else {
8796 LifeTime = Qualifiers::OCL_None;
8797 }
8798 return true;
8799}
8800
8801CanQualType ASTContext::getNSUIntegerType() const {
8802 assert(Target && "Expected target to be initialized");
8803 const llvm::Triple &T = Target->getTriple();
8804 // Windows is LLP64 rather than LP64
8805 if (T.isOSWindows() && T.isArch64Bit())
8806 return UnsignedLongLongTy;
8807 return UnsignedLongTy;
8808}
8809
8810CanQualType ASTContext::getNSIntegerType() const {
8811 assert(Target && "Expected target to be initialized");
8812 const llvm::Triple &T = Target->getTriple();
8813 // Windows is LLP64 rather than LP64
8814 if (T.isOSWindows() && T.isArch64Bit())
8815 return LongLongTy;
8816 return LongTy;
8817}
8818
8819TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8820 if (!ObjCInstanceTypeDecl)
8821 ObjCInstanceTypeDecl =
8822 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8823 return ObjCInstanceTypeDecl;
8824}
8825
8826// This returns true if a type has been typedefed to BOOL:
8827// typedef <type> BOOL;
8828static bool isTypeTypedefedAsBOOL(QualType T) {
8829 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8830 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8831 return II->isStr(Str: "BOOL");
8832
8833 return false;
8834}
8835
8836/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8837/// purpose.
8838CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8839 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8840 return CharUnits::Zero();
8841
8842 CharUnits sz = getTypeSizeInChars(T: type);
8843
8844 // Make all integer and enum types at least as large as an int
8845 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8846 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8847 // Treat arrays as pointers, since that's how they're passed in.
8848 else if (type->isArrayType())
8849 sz = getTypeSizeInChars(T: VoidPtrTy);
8850 return sz;
8851}
8852
8853bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8854 return getTargetInfo().getCXXABI().isMicrosoft() &&
8855 VD->isStaticDataMember() &&
8856 VD->getType()->isIntegralOrEnumerationType() &&
8857 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8858}
8859
8860ASTContext::InlineVariableDefinitionKind
8861ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8862 if (!VD->isInline())
8863 return InlineVariableDefinitionKind::None;
8864
8865 // In almost all cases, it's a weak definition.
8866 auto *First = VD->getFirstDecl();
8867 if (First->isInlineSpecified() || !First->isStaticDataMember())
8868 return InlineVariableDefinitionKind::Weak;
8869
8870 // If there's a file-context declaration in this translation unit, it's a
8871 // non-discardable definition.
8872 for (auto *D : VD->redecls())
8873 if (D->getLexicalDeclContext()->isFileContext() &&
8874 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8875 return InlineVariableDefinitionKind::Strong;
8876
8877 // If we've not seen one yet, we don't know.
8878 return InlineVariableDefinitionKind::WeakUnknown;
8879}
8880
8881static std::string charUnitsToString(const CharUnits &CU) {
8882 return llvm::itostr(X: CU.getQuantity());
8883}
8884
8885/// getObjCEncodingForBlock - Return the encoded type for this block
8886/// declaration.
8887std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8888 std::string S;
8889
8890 const BlockDecl *Decl = Expr->getBlockDecl();
8891 QualType BlockTy =
8892 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8893 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8894 // Encode result type.
8895 if (getLangOpts().EncodeExtendedBlockSig)
8896 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8897 Extended: true /*Extended*/);
8898 else
8899 getObjCEncodingForType(T: BlockReturnTy, S);
8900 // Compute size of all parameters.
8901 // Start with computing size of a pointer in number of bytes.
8902 // FIXME: There might(should) be a better way of doing this computation!
8903 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8904 CharUnits ParmOffset = PtrSize;
8905 for (auto *PI : Decl->parameters()) {
8906 QualType PType = PI->getType();
8907 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8908 if (sz.isZero())
8909 continue;
8910 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8911 ParmOffset += sz;
8912 }
8913 // Size of the argument frame
8914 S += charUnitsToString(CU: ParmOffset);
8915 // Block pointer and offset.
8916 S += "@?0";
8917
8918 // Argument types.
8919 ParmOffset = PtrSize;
8920 for (auto *PVDecl : Decl->parameters()) {
8921 QualType PType = PVDecl->getOriginalType();
8922 if (const auto *AT =
8923 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8924 // Use array's original type only if it has known number of
8925 // elements.
8926 if (!isa<ConstantArrayType>(Val: AT))
8927 PType = PVDecl->getType();
8928 } else if (PType->isFunctionType())
8929 PType = PVDecl->getType();
8930 if (getLangOpts().EncodeExtendedBlockSig)
8931 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8932 S, Extended: true /*Extended*/);
8933 else
8934 getObjCEncodingForType(T: PType, S);
8935 S += charUnitsToString(CU: ParmOffset);
8936 ParmOffset += getObjCEncodingTypeSize(type: PType);
8937 }
8938
8939 return S;
8940}
8941
8942std::string
8943ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8944 std::string S;
8945 // Encode result type.
8946 getObjCEncodingForType(T: Decl->getReturnType(), S);
8947 CharUnits ParmOffset;
8948 // Compute size of all parameters.
8949 for (auto *PI : Decl->parameters()) {
8950 QualType PType = PI->getType();
8951 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8952 if (sz.isZero())
8953 continue;
8954
8955 assert(sz.isPositive() &&
8956 "getObjCEncodingForFunctionDecl - Incomplete param type");
8957 ParmOffset += sz;
8958 }
8959 S += charUnitsToString(CU: ParmOffset);
8960 ParmOffset = CharUnits::Zero();
8961
8962 // Argument types.
8963 for (auto *PVDecl : Decl->parameters()) {
8964 QualType PType = PVDecl->getOriginalType();
8965 if (const auto *AT =
8966 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8967 // Use array's original type only if it has known number of
8968 // elements.
8969 if (!isa<ConstantArrayType>(Val: AT))
8970 PType = PVDecl->getType();
8971 } else if (PType->isFunctionType())
8972 PType = PVDecl->getType();
8973 getObjCEncodingForType(T: PType, S);
8974 S += charUnitsToString(CU: ParmOffset);
8975 ParmOffset += getObjCEncodingTypeSize(type: PType);
8976 }
8977
8978 return S;
8979}
8980
8981/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8982/// method parameter or return type. If Extended, include class names and
8983/// block object types.
8984void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
8985 QualType T, std::string& S,
8986 bool Extended) const {
8987 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8988 getObjCEncodingForTypeQualifier(QT, S);
8989 // Encode parameter type.
8990 ObjCEncOptions Options = ObjCEncOptions()
8991 .setExpandPointedToStructures()
8992 .setExpandStructures()
8993 .setIsOutermostType();
8994 if (Extended)
8995 Options.setEncodeBlockParameters().setEncodeClassNames();
8996 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
8997}
8998
8999/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9000/// declaration.
9001std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9002 bool Extended) const {
9003 // FIXME: This is not very efficient.
9004 // Encode return type.
9005 std::string S;
9006 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9007 T: Decl->getReturnType(), S, Extended);
9008 // Compute size of all parameters.
9009 // Start with computing size of a pointer in number of bytes.
9010 // FIXME: There might(should) be a better way of doing this computation!
9011 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9012 // The first two arguments (self and _cmd) are pointers; account for
9013 // their size.
9014 CharUnits ParmOffset = 2 * PtrSize;
9015 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9016 E = Decl->sel_param_end(); PI != E; ++PI) {
9017 QualType PType = (*PI)->getType();
9018 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9019 if (sz.isZero())
9020 continue;
9021
9022 assert(sz.isPositive() &&
9023 "getObjCEncodingForMethodDecl - Incomplete param type");
9024 ParmOffset += sz;
9025 }
9026 S += charUnitsToString(CU: ParmOffset);
9027 S += "@0:";
9028 S += charUnitsToString(CU: PtrSize);
9029
9030 // Argument types.
9031 ParmOffset = 2 * PtrSize;
9032 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9033 E = Decl->sel_param_end(); PI != E; ++PI) {
9034 const ParmVarDecl *PVDecl = *PI;
9035 QualType PType = PVDecl->getOriginalType();
9036 if (const auto *AT =
9037 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9038 // Use array's original type only if it has known number of
9039 // elements.
9040 if (!isa<ConstantArrayType>(Val: AT))
9041 PType = PVDecl->getType();
9042 } else if (PType->isFunctionType())
9043 PType = PVDecl->getType();
9044 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9045 T: PType, S, Extended);
9046 S += charUnitsToString(CU: ParmOffset);
9047 ParmOffset += getObjCEncodingTypeSize(type: PType);
9048 }
9049
9050 return S;
9051}
9052
9053ObjCPropertyImplDecl *
9054ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9055 const ObjCPropertyDecl *PD,
9056 const Decl *Container) const {
9057 if (!Container)
9058 return nullptr;
9059 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9060 for (auto *PID : CID->property_impls())
9061 if (PID->getPropertyDecl() == PD)
9062 return PID;
9063 } else {
9064 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9065 for (auto *PID : OID->property_impls())
9066 if (PID->getPropertyDecl() == PD)
9067 return PID;
9068 }
9069 return nullptr;
9070}
9071
9072/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9073/// property declaration. If non-NULL, Container must be either an
9074/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9075/// NULL when getting encodings for protocol properties.
9076/// Property attributes are stored as a comma-delimited C string. The simple
9077/// attributes readonly and bycopy are encoded as single characters. The
9078/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9079/// encoded as single characters, followed by an identifier. Property types
9080/// are also encoded as a parametrized attribute. The characters used to encode
9081/// these attributes are defined by the following enumeration:
9082/// @code
9083/// enum PropertyAttributes {
9084/// kPropertyReadOnly = 'R', // property is read-only.
9085/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9086/// kPropertyByref = '&', // property is a reference to the value last assigned
9087/// kPropertyDynamic = 'D', // property is dynamic
9088/// kPropertyGetter = 'G', // followed by getter selector name
9089/// kPropertySetter = 'S', // followed by setter selector name
9090/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9091/// kPropertyType = 'T' // followed by old-style type encoding.
9092/// kPropertyWeak = 'W' // 'weak' property
9093/// kPropertyStrong = 'P' // property GC'able
9094/// kPropertyNonAtomic = 'N' // property non-atomic
9095/// kPropertyOptional = '?' // property optional
9096/// };
9097/// @endcode
9098std::string
9099ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9100 const Decl *Container) const {
9101 // Collect information from the property implementation decl(s).
9102 bool Dynamic = false;
9103 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9104
9105 if (ObjCPropertyImplDecl *PropertyImpDecl =
9106 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9107 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9108 Dynamic = true;
9109 else
9110 SynthesizePID = PropertyImpDecl;
9111 }
9112
9113 // FIXME: This is not very efficient.
9114 std::string S = "T";
9115
9116 // Encode result type.
9117 // GCC has some special rules regarding encoding of properties which
9118 // closely resembles encoding of ivars.
9119 getObjCEncodingForPropertyType(T: PD->getType(), S);
9120
9121 if (PD->isOptional())
9122 S += ",?";
9123
9124 if (PD->isReadOnly()) {
9125 S += ",R";
9126 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9127 S += ",C";
9128 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9129 S += ",&";
9130 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9131 S += ",W";
9132 } else {
9133 switch (PD->getSetterKind()) {
9134 case ObjCPropertyDecl::Assign: break;
9135 case ObjCPropertyDecl::Copy: S += ",C"; break;
9136 case ObjCPropertyDecl::Retain: S += ",&"; break;
9137 case ObjCPropertyDecl::Weak: S += ",W"; break;
9138 }
9139 }
9140
9141 // It really isn't clear at all what this means, since properties
9142 // are "dynamic by default".
9143 if (Dynamic)
9144 S += ",D";
9145
9146 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9147 S += ",N";
9148
9149 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9150 S += ",G";
9151 S += PD->getGetterName().getAsString();
9152 }
9153
9154 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9155 S += ",S";
9156 S += PD->getSetterName().getAsString();
9157 }
9158
9159 if (SynthesizePID) {
9160 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9161 S += ",V";
9162 S += OID->getNameAsString();
9163 }
9164
9165 // FIXME: OBJCGC: weak & strong
9166 return S;
9167}
9168
9169/// getLegacyIntegralTypeEncoding -
9170/// Another legacy compatibility encoding: 32-bit longs are encoded as
9171/// 'l' or 'L' , but not always. For typedefs, we need to use
9172/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9173void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9174 if (PointeeTy->getAs<TypedefType>()) {
9175 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9176 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9177 PointeeTy = UnsignedIntTy;
9178 else
9179 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9180 PointeeTy = IntTy;
9181 }
9182 }
9183}
9184
9185void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9186 const FieldDecl *Field,
9187 QualType *NotEncodedT) const {
9188 // We follow the behavior of gcc, expanding structures which are
9189 // directly pointed to, and expanding embedded structures. Note that
9190 // these rules are sufficient to prevent recursive encoding of the
9191 // same type.
9192 getObjCEncodingForTypeImpl(t: T, S,
9193 Options: ObjCEncOptions()
9194 .setExpandPointedToStructures()
9195 .setExpandStructures()
9196 .setIsOutermostType(),
9197 Field, NotEncodedT);
9198}
9199
9200void ASTContext::getObjCEncodingForPropertyType(QualType T,
9201 std::string& S) const {
9202 // Encode result type.
9203 // GCC has some special rules regarding encoding of properties which
9204 // closely resembles encoding of ivars.
9205 getObjCEncodingForTypeImpl(t: T, S,
9206 Options: ObjCEncOptions()
9207 .setExpandPointedToStructures()
9208 .setExpandStructures()
9209 .setIsOutermostType()
9210 .setEncodingProperty(),
9211 /*Field=*/nullptr);
9212}
9213
9214static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9215 const BuiltinType *BT) {
9216 BuiltinType::Kind kind = BT->getKind();
9217 switch (kind) {
9218 case BuiltinType::Void: return 'v';
9219 case BuiltinType::Bool: return 'B';
9220 case BuiltinType::Char8:
9221 case BuiltinType::Char_U:
9222 case BuiltinType::UChar: return 'C';
9223 case BuiltinType::Char16:
9224 case BuiltinType::UShort: return 'S';
9225 case BuiltinType::Char32:
9226 case BuiltinType::UInt: return 'I';
9227 case BuiltinType::ULong:
9228 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9229 case BuiltinType::UInt128: return 'T';
9230 case BuiltinType::ULongLong: return 'Q';
9231 case BuiltinType::Char_S:
9232 case BuiltinType::SChar: return 'c';
9233 case BuiltinType::Short: return 's';
9234 case BuiltinType::WChar_S:
9235 case BuiltinType::WChar_U:
9236 case BuiltinType::Int: return 'i';
9237 case BuiltinType::Long:
9238 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9239 case BuiltinType::LongLong: return 'q';
9240 case BuiltinType::Int128: return 't';
9241 case BuiltinType::Float: return 'f';
9242 case BuiltinType::Double: return 'd';
9243 case BuiltinType::LongDouble: return 'D';
9244 case BuiltinType::NullPtr: return '*'; // like char*
9245
9246 case BuiltinType::BFloat16:
9247 case BuiltinType::Float16:
9248 case BuiltinType::Float128:
9249 case BuiltinType::Ibm128:
9250 case BuiltinType::Half:
9251 case BuiltinType::ShortAccum:
9252 case BuiltinType::Accum:
9253 case BuiltinType::LongAccum:
9254 case BuiltinType::UShortAccum:
9255 case BuiltinType::UAccum:
9256 case BuiltinType::ULongAccum:
9257 case BuiltinType::ShortFract:
9258 case BuiltinType::Fract:
9259 case BuiltinType::LongFract:
9260 case BuiltinType::UShortFract:
9261 case BuiltinType::UFract:
9262 case BuiltinType::ULongFract:
9263 case BuiltinType::SatShortAccum:
9264 case BuiltinType::SatAccum:
9265 case BuiltinType::SatLongAccum:
9266 case BuiltinType::SatUShortAccum:
9267 case BuiltinType::SatUAccum:
9268 case BuiltinType::SatULongAccum:
9269 case BuiltinType::SatShortFract:
9270 case BuiltinType::SatFract:
9271 case BuiltinType::SatLongFract:
9272 case BuiltinType::SatUShortFract:
9273 case BuiltinType::SatUFract:
9274 case BuiltinType::SatULongFract:
9275 // FIXME: potentially need @encodes for these!
9276 return ' ';
9277
9278#define SVE_TYPE(Name, Id, SingletonId) \
9279 case BuiltinType::Id:
9280#include "clang/Basic/AArch64ACLETypes.def"
9281#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9282#include "clang/Basic/RISCVVTypes.def"
9283#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9284#include "clang/Basic/WebAssemblyReferenceTypes.def"
9285#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9286#include "clang/Basic/AMDGPUTypes.def"
9287#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9288#include "clang/Basic/SPIRVTypes.def"
9289 {
9290 DiagnosticsEngine &Diags = C->getDiagnostics();
9291 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9292 << QualType(BT, 0);
9293 return ' ';
9294 }
9295
9296 case BuiltinType::ObjCId:
9297 case BuiltinType::ObjCClass:
9298 case BuiltinType::ObjCSel:
9299 llvm_unreachable("@encoding ObjC primitive type");
9300
9301 // OpenCL and placeholder types don't need @encodings.
9302#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9303 case BuiltinType::Id:
9304#include "clang/Basic/OpenCLImageTypes.def"
9305#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9306 case BuiltinType::Id:
9307#include "clang/Basic/OpenCLExtensionTypes.def"
9308 case BuiltinType::OCLEvent:
9309 case BuiltinType::OCLClkEvent:
9310 case BuiltinType::OCLQueue:
9311 case BuiltinType::OCLReserveID:
9312 case BuiltinType::OCLSampler:
9313 case BuiltinType::Dependent:
9314#define PPC_VECTOR_TYPE(Name, Id, Size) \
9315 case BuiltinType::Id:
9316#include "clang/Basic/PPCTypes.def"
9317#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9318#include "clang/Basic/HLSLIntangibleTypes.def"
9319#define BUILTIN_TYPE(KIND, ID)
9320#define PLACEHOLDER_TYPE(KIND, ID) \
9321 case BuiltinType::KIND:
9322#include "clang/AST/BuiltinTypes.def"
9323 llvm_unreachable("invalid builtin type for @encode");
9324 }
9325 llvm_unreachable("invalid BuiltinType::Kind value");
9326}
9327
9328static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9329 EnumDecl *Enum = ED->getDefinitionOrSelf();
9330
9331 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9332 if (!Enum->isFixed())
9333 return 'i';
9334
9335 // The encoding of a fixed enum type matches its fixed underlying type.
9336 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9337 return getObjCEncodingForPrimitiveType(C, BT);
9338}
9339
9340static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9341 QualType T, const FieldDecl *FD) {
9342 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9343 S += 'b';
9344 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9345 // The GNU runtime requires more information; bitfields are encoded as b,
9346 // then the offset (in bits) of the first element, then the type of the
9347 // bitfield, then the size in bits. For example, in this structure:
9348 //
9349 // struct
9350 // {
9351 // int integer;
9352 // int flags:2;
9353 // };
9354 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9355 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9356 // information is not especially sensible, but we're stuck with it for
9357 // compatibility with GCC, although providing it breaks anything that
9358 // actually uses runtime introspection and wants to work on both runtimes...
9359 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9360 uint64_t Offset;
9361
9362 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9363 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9364 } else {
9365 const RecordDecl *RD = FD->getParent();
9366 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9367 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9368 }
9369
9370 S += llvm::utostr(X: Offset);
9371
9372 if (const auto *ET = T->getAsCanonical<EnumType>())
9373 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9374 else {
9375 const auto *BT = T->castAs<BuiltinType>();
9376 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9377 }
9378 }
9379 S += llvm::utostr(X: FD->getBitWidthValue());
9380}
9381
9382// Helper function for determining whether the encoded type string would include
9383// a template specialization type.
9384static bool hasTemplateSpecializationInEncodedString(const Type *T,
9385 bool VisitBasesAndFields) {
9386 T = T->getBaseElementTypeUnsafe();
9387
9388 if (auto *PT = T->getAs<PointerType>())
9389 return hasTemplateSpecializationInEncodedString(
9390 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9391
9392 auto *CXXRD = T->getAsCXXRecordDecl();
9393
9394 if (!CXXRD)
9395 return false;
9396
9397 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9398 return true;
9399
9400 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9401 return false;
9402
9403 for (const auto &B : CXXRD->bases())
9404 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9405 VisitBasesAndFields: true))
9406 return true;
9407
9408 for (auto *FD : CXXRD->fields())
9409 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9410 VisitBasesAndFields: true))
9411 return true;
9412
9413 return false;
9414}
9415
9416// FIXME: Use SmallString for accumulating string.
9417void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9418 const ObjCEncOptions Options,
9419 const FieldDecl *FD,
9420 QualType *NotEncodedT) const {
9421 CanQualType CT = getCanonicalType(T);
9422 switch (CT->getTypeClass()) {
9423 case Type::Builtin:
9424 case Type::Enum:
9425 if (FD && FD->isBitField())
9426 return EncodeBitField(Ctx: this, S, T, FD);
9427 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9428 S += getObjCEncodingForPrimitiveType(C: this, BT);
9429 else
9430 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9431 return;
9432
9433 case Type::Complex:
9434 S += 'j';
9435 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9436 Options: ObjCEncOptions(),
9437 /*Field=*/FD: nullptr);
9438 return;
9439
9440 case Type::Atomic:
9441 S += 'A';
9442 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9443 Options: ObjCEncOptions(),
9444 /*Field=*/FD: nullptr);
9445 return;
9446
9447 // encoding for pointer or reference types.
9448 case Type::Pointer:
9449 case Type::LValueReference:
9450 case Type::RValueReference: {
9451 QualType PointeeTy;
9452 if (isa<PointerType>(Val: CT)) {
9453 const auto *PT = T->castAs<PointerType>();
9454 if (PT->isObjCSelType()) {
9455 S += ':';
9456 return;
9457 }
9458 PointeeTy = PT->getPointeeType();
9459 } else {
9460 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9461 }
9462
9463 bool isReadOnly = false;
9464 // For historical/compatibility reasons, the read-only qualifier of the
9465 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9466 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9467 // Also, do not emit the 'r' for anything but the outermost type!
9468 if (T->getAs<TypedefType>()) {
9469 if (Options.IsOutermostType() && T.isConstQualified()) {
9470 isReadOnly = true;
9471 S += 'r';
9472 }
9473 } else if (Options.IsOutermostType()) {
9474 QualType P = PointeeTy;
9475 while (auto PT = P->getAs<PointerType>())
9476 P = PT->getPointeeType();
9477 if (P.isConstQualified()) {
9478 isReadOnly = true;
9479 S += 'r';
9480 }
9481 }
9482 if (isReadOnly) {
9483 // Another legacy compatibility encoding. Some ObjC qualifier and type
9484 // combinations need to be rearranged.
9485 // Rewrite "in const" from "nr" to "rn"
9486 if (StringRef(S).ends_with(Suffix: "nr"))
9487 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9488 }
9489
9490 if (PointeeTy->isCharType()) {
9491 // char pointer types should be encoded as '*' unless it is a
9492 // type that has been typedef'd to 'BOOL'.
9493 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9494 S += '*';
9495 return;
9496 }
9497 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9498 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9499 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9500 if (II == &Idents.get(Name: "objc_class")) {
9501 S += '#';
9502 return;
9503 }
9504 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9505 if (II == &Idents.get(Name: "objc_object")) {
9506 S += '@';
9507 return;
9508 }
9509 // If the encoded string for the class includes template names, just emit
9510 // "^v" for pointers to the class.
9511 if (getLangOpts().CPlusPlus &&
9512 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9513 hasTemplateSpecializationInEncodedString(
9514 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9515 S += "^v";
9516 return;
9517 }
9518 // fall through...
9519 }
9520 S += '^';
9521 getLegacyIntegralTypeEncoding(PointeeTy);
9522
9523 ObjCEncOptions NewOptions;
9524 if (Options.ExpandPointedToStructures())
9525 NewOptions.setExpandStructures();
9526 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9527 /*Field=*/FD: nullptr, NotEncodedT);
9528 return;
9529 }
9530
9531 case Type::ConstantArray:
9532 case Type::IncompleteArray:
9533 case Type::VariableArray: {
9534 const auto *AT = cast<ArrayType>(Val&: CT);
9535
9536 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9537 // Incomplete arrays are encoded as a pointer to the array element.
9538 S += '^';
9539
9540 getObjCEncodingForTypeImpl(
9541 T: AT->getElementType(), S,
9542 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9543 } else {
9544 S += '[';
9545
9546 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9547 S += llvm::utostr(X: CAT->getZExtSize());
9548 else {
9549 //Variable length arrays are encoded as a regular array with 0 elements.
9550 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9551 "Unknown array type!");
9552 S += '0';
9553 }
9554
9555 getObjCEncodingForTypeImpl(
9556 T: AT->getElementType(), S,
9557 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9558 NotEncodedT);
9559 S += ']';
9560 }
9561 return;
9562 }
9563
9564 case Type::FunctionNoProto:
9565 case Type::FunctionProto:
9566 S += '?';
9567 return;
9568
9569 case Type::Record: {
9570 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9571 S += RDecl->isUnion() ? '(' : '{';
9572 // Anonymous structures print as '?'
9573 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9574 S += II->getName();
9575 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9576 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9577 llvm::raw_string_ostream OS(S);
9578 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9579 Policy: getPrintingPolicy());
9580 }
9581 } else {
9582 S += '?';
9583 }
9584 if (Options.ExpandStructures()) {
9585 S += '=';
9586 if (!RDecl->isUnion()) {
9587 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9588 } else {
9589 for (const auto *Field : RDecl->fields()) {
9590 if (FD) {
9591 S += '"';
9592 S += Field->getNameAsString();
9593 S += '"';
9594 }
9595
9596 // Special case bit-fields.
9597 if (Field->isBitField()) {
9598 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9599 Options: ObjCEncOptions().setExpandStructures(),
9600 FD: Field);
9601 } else {
9602 QualType qt = Field->getType();
9603 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9604 getObjCEncodingForTypeImpl(
9605 T: qt, S,
9606 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9607 NotEncodedT);
9608 }
9609 }
9610 }
9611 }
9612 S += RDecl->isUnion() ? ')' : '}';
9613 return;
9614 }
9615
9616 case Type::BlockPointer: {
9617 const auto *BT = T->castAs<BlockPointerType>();
9618 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9619 if (Options.EncodeBlockParameters()) {
9620 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9621
9622 S += '<';
9623 // Block return type
9624 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9625 Options: Options.forComponentType(), FD, NotEncodedT);
9626 // Block self
9627 S += "@?";
9628 // Block parameters
9629 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9630 for (const auto &I : FPT->param_types())
9631 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9632 NotEncodedT);
9633 }
9634 S += '>';
9635 }
9636 return;
9637 }
9638
9639 case Type::ObjCObject: {
9640 // hack to match legacy encoding of *id and *Class
9641 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9642 if (Ty->isObjCIdType()) {
9643 S += "{objc_object=}";
9644 return;
9645 }
9646 else if (Ty->isObjCClassType()) {
9647 S += "{objc_class=}";
9648 return;
9649 }
9650 // TODO: Double check to make sure this intentionally falls through.
9651 [[fallthrough]];
9652 }
9653
9654 case Type::ObjCInterface: {
9655 // Ignore protocol qualifiers when mangling at this level.
9656 // @encode(class_name)
9657 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9658 S += '{';
9659 S += OI->getObjCRuntimeNameAsString();
9660 if (Options.ExpandStructures()) {
9661 S += '=';
9662 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9663 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9664 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9665 const FieldDecl *Field = Ivars[i];
9666 if (Field->isBitField())
9667 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9668 Options: ObjCEncOptions().setExpandStructures(),
9669 FD: Field);
9670 else
9671 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9672 Options: ObjCEncOptions().setExpandStructures(), FD,
9673 NotEncodedT);
9674 }
9675 }
9676 S += '}';
9677 return;
9678 }
9679
9680 case Type::ObjCObjectPointer: {
9681 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9682 if (OPT->isObjCIdType()) {
9683 S += '@';
9684 return;
9685 }
9686
9687 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9688 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9689 // Since this is a binary compatibility issue, need to consult with
9690 // runtime folks. Fortunately, this is a *very* obscure construct.
9691 S += '#';
9692 return;
9693 }
9694
9695 if (OPT->isObjCQualifiedIdType()) {
9696 getObjCEncodingForTypeImpl(
9697 T: getObjCIdType(), S,
9698 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9699 .setExpandPointedToStructures()
9700 .setExpandStructures()),
9701 FD);
9702 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9703 // Note that we do extended encoding of protocol qualifier list
9704 // Only when doing ivar or property encoding.
9705 S += '"';
9706 for (const auto *I : OPT->quals()) {
9707 S += '<';
9708 S += I->getObjCRuntimeNameAsString();
9709 S += '>';
9710 }
9711 S += '"';
9712 }
9713 return;
9714 }
9715
9716 S += '@';
9717 if (OPT->getInterfaceDecl() &&
9718 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9719 S += '"';
9720 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9721 for (const auto *I : OPT->quals()) {
9722 S += '<';
9723 S += I->getObjCRuntimeNameAsString();
9724 S += '>';
9725 }
9726 S += '"';
9727 }
9728 return;
9729 }
9730
9731 // gcc just blithely ignores member pointers.
9732 // FIXME: we should do better than that. 'M' is available.
9733 case Type::MemberPointer:
9734 // This matches gcc's encoding, even though technically it is insufficient.
9735 //FIXME. We should do a better job than gcc.
9736 case Type::Vector:
9737 case Type::ExtVector:
9738 // Until we have a coherent encoding of these three types, issue warning.
9739 if (NotEncodedT)
9740 *NotEncodedT = T;
9741 return;
9742
9743 case Type::ConstantMatrix:
9744 if (NotEncodedT)
9745 *NotEncodedT = T;
9746 return;
9747
9748 case Type::BitInt:
9749 if (NotEncodedT)
9750 *NotEncodedT = T;
9751 return;
9752
9753 // We could see an undeduced auto type here during error recovery.
9754 // Just ignore it.
9755 case Type::Auto:
9756 case Type::DeducedTemplateSpecialization:
9757 return;
9758
9759 case Type::HLSLAttributedResource:
9760 case Type::HLSLInlineSpirv:
9761 case Type::OverflowBehavior:
9762 llvm_unreachable("unexpected type");
9763
9764 case Type::ArrayParameter:
9765 case Type::Pipe:
9766#define ABSTRACT_TYPE(KIND, BASE)
9767#define TYPE(KIND, BASE)
9768#define DEPENDENT_TYPE(KIND, BASE) \
9769 case Type::KIND:
9770#define NON_CANONICAL_TYPE(KIND, BASE) \
9771 case Type::KIND:
9772#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9773 case Type::KIND:
9774#include "clang/AST/TypeNodes.inc"
9775 llvm_unreachable("@encode for dependent type!");
9776 }
9777 llvm_unreachable("bad type kind!");
9778}
9779
9780void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9781 std::string &S,
9782 const FieldDecl *FD,
9783 bool includeVBases,
9784 QualType *NotEncodedT) const {
9785 assert(RDecl && "Expected non-null RecordDecl");
9786 assert(!RDecl->isUnion() && "Should not be called for unions");
9787 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9788 return;
9789
9790 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9791 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9792 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9793
9794 if (CXXRec) {
9795 for (const auto &BI : CXXRec->bases()) {
9796 if (!BI.isVirtual()) {
9797 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9798 if (base->isEmpty())
9799 continue;
9800 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9801 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9802 x: std::make_pair(x&: offs, y&: base));
9803 }
9804 }
9805 }
9806
9807 for (FieldDecl *Field : RDecl->fields()) {
9808 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9809 continue;
9810 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9811 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9812 x: std::make_pair(x&: offs, y&: Field));
9813 }
9814
9815 if (CXXRec && includeVBases) {
9816 for (const auto &BI : CXXRec->vbases()) {
9817 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9818 if (base->isEmpty())
9819 continue;
9820 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9821 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9822 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9823 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9824 x: std::make_pair(x&: offs, y&: base));
9825 }
9826 }
9827
9828 CharUnits size;
9829 if (CXXRec) {
9830 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9831 } else {
9832 size = layout.getSize();
9833 }
9834
9835#ifndef NDEBUG
9836 uint64_t CurOffs = 0;
9837#endif
9838 std::multimap<uint64_t, NamedDecl *>::iterator
9839 CurLayObj = FieldOrBaseOffsets.begin();
9840
9841 if (CXXRec && CXXRec->isDynamicClass() &&
9842 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9843 if (FD) {
9844 S += "\"_vptr$";
9845 std::string recname = CXXRec->getNameAsString();
9846 if (recname.empty()) recname = "?";
9847 S += recname;
9848 S += '"';
9849 }
9850 S += "^^?";
9851#ifndef NDEBUG
9852 CurOffs += getTypeSize(VoidPtrTy);
9853#endif
9854 }
9855
9856 if (!RDecl->hasFlexibleArrayMember()) {
9857 // Mark the end of the structure.
9858 uint64_t offs = toBits(CharSize: size);
9859 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9860 x: std::make_pair(x&: offs, y: nullptr));
9861 }
9862
9863 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9864#ifndef NDEBUG
9865 assert(CurOffs <= CurLayObj->first);
9866 if (CurOffs < CurLayObj->first) {
9867 uint64_t padding = CurLayObj->first - CurOffs;
9868 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9869 // packing/alignment of members is different that normal, in which case
9870 // the encoding will be out-of-sync with the real layout.
9871 // If the runtime switches to just consider the size of types without
9872 // taking into account alignment, we could make padding explicit in the
9873 // encoding (e.g. using arrays of chars). The encoding strings would be
9874 // longer then though.
9875 CurOffs += padding;
9876 }
9877#endif
9878
9879 NamedDecl *dcl = CurLayObj->second;
9880 if (!dcl)
9881 break; // reached end of structure.
9882
9883 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9884 // We expand the bases without their virtual bases since those are going
9885 // in the initial structure. Note that this differs from gcc which
9886 // expands virtual bases each time one is encountered in the hierarchy,
9887 // making the encoding type bigger than it really is.
9888 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9889 NotEncodedT);
9890 assert(!base->isEmpty());
9891#ifndef NDEBUG
9892 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9893#endif
9894 } else {
9895 const auto *field = cast<FieldDecl>(Val: dcl);
9896 if (FD) {
9897 S += '"';
9898 S += field->getNameAsString();
9899 S += '"';
9900 }
9901
9902 if (field->isBitField()) {
9903 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9904#ifndef NDEBUG
9905 CurOffs += field->getBitWidthValue();
9906#endif
9907 } else {
9908 QualType qt = field->getType();
9909 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9910 getObjCEncodingForTypeImpl(
9911 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9912 FD, NotEncodedT);
9913#ifndef NDEBUG
9914 CurOffs += getTypeSize(field->getType());
9915#endif
9916 }
9917 }
9918 }
9919}
9920
9921void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9922 std::string& S) const {
9923 if (QT & Decl::OBJC_TQ_In)
9924 S += 'n';
9925 if (QT & Decl::OBJC_TQ_Inout)
9926 S += 'N';
9927 if (QT & Decl::OBJC_TQ_Out)
9928 S += 'o';
9929 if (QT & Decl::OBJC_TQ_Bycopy)
9930 S += 'O';
9931 if (QT & Decl::OBJC_TQ_Byref)
9932 S += 'R';
9933 if (QT & Decl::OBJC_TQ_Oneway)
9934 S += 'V';
9935}
9936
9937TypedefDecl *ASTContext::getObjCIdDecl() const {
9938 if (!ObjCIdDecl) {
9939 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9940 T = getObjCObjectPointerType(ObjectT: T);
9941 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9942 }
9943 return ObjCIdDecl;
9944}
9945
9946TypedefDecl *ASTContext::getObjCSelDecl() const {
9947 if (!ObjCSelDecl) {
9948 QualType T = getPointerType(T: ObjCBuiltinSelTy);
9949 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
9950 }
9951 return ObjCSelDecl;
9952}
9953
9954TypedefDecl *ASTContext::getObjCClassDecl() const {
9955 if (!ObjCClassDecl) {
9956 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
9957 T = getObjCObjectPointerType(ObjectT: T);
9958 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
9959 }
9960 return ObjCClassDecl;
9961}
9962
9963ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
9964 if (!ObjCProtocolClassDecl) {
9965 ObjCProtocolClassDecl
9966 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
9967 atLoc: SourceLocation(),
9968 Id: &Idents.get(Name: "Protocol"),
9969 /*typeParamList=*/nullptr,
9970 /*PrevDecl=*/nullptr,
9971 ClassLoc: SourceLocation(), isInternal: true);
9972 }
9973
9974 return ObjCProtocolClassDecl;
9975}
9976
9977PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
9978 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9979 return PointerAuthQualifier();
9980 return PointerAuthQualifier::Create(
9981 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
9982 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
9983 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
9984 /*isIsaPointer=*/IsIsaPointer: false,
9985 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
9986}
9987
9988//===----------------------------------------------------------------------===//
9989// __builtin_va_list Construction Functions
9990//===----------------------------------------------------------------------===//
9991
9992static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
9993 StringRef Name) {
9994 // typedef char* __builtin[_ms]_va_list;
9995 QualType T = Context->getPointerType(T: Context->CharTy);
9996 return Context->buildImplicitTypedef(T, Name);
9997}
9998
9999static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10000 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10001}
10002
10003static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10004 // typedef char *__builtin_zos_va_list[2];
10005 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10006 QualType T = Context->getPointerType(T: Context->CharTy);
10007 QualType ArrayType = Context->getConstantArrayType(
10008 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10009 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10010}
10011
10012static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10013 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10014}
10015
10016static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10017 // typedef void* __builtin_va_list;
10018 QualType T = Context->getPointerType(T: Context->VoidTy);
10019 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10020}
10021
10022static TypedefDecl *
10023CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10024 // struct __va_list
10025 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10026 if (Context->getLangOpts().CPlusPlus) {
10027 // namespace std { struct __va_list {
10028 auto *NS = NamespaceDecl::Create(
10029 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10030 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10031 Id: &Context->Idents.get(Name: "std"),
10032 /*PrevDecl=*/nullptr, /*Nested=*/false);
10033 NS->setImplicit();
10034 VaListTagDecl->setDeclContext(NS);
10035 }
10036
10037 VaListTagDecl->startDefinition();
10038
10039 const size_t NumFields = 5;
10040 QualType FieldTypes[NumFields];
10041 const char *FieldNames[NumFields];
10042
10043 // void *__stack;
10044 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10045 FieldNames[0] = "__stack";
10046
10047 // void *__gr_top;
10048 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10049 FieldNames[1] = "__gr_top";
10050
10051 // void *__vr_top;
10052 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10053 FieldNames[2] = "__vr_top";
10054
10055 // int __gr_offs;
10056 FieldTypes[3] = Context->IntTy;
10057 FieldNames[3] = "__gr_offs";
10058
10059 // int __vr_offs;
10060 FieldTypes[4] = Context->IntTy;
10061 FieldNames[4] = "__vr_offs";
10062
10063 // Create fields
10064 for (unsigned i = 0; i < NumFields; ++i) {
10065 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10066 DC: VaListTagDecl,
10067 StartLoc: SourceLocation(),
10068 IdLoc: SourceLocation(),
10069 Id: &Context->Idents.get(Name: FieldNames[i]),
10070 T: FieldTypes[i], /*TInfo=*/nullptr,
10071 /*BitWidth=*/BW: nullptr,
10072 /*Mutable=*/false,
10073 InitStyle: ICIS_NoInit);
10074 Field->setAccess(AS_public);
10075 VaListTagDecl->addDecl(D: Field);
10076 }
10077 VaListTagDecl->completeDefinition();
10078 Context->VaListTagDecl = VaListTagDecl;
10079 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10080
10081 // } __builtin_va_list;
10082 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10083}
10084
10085static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10086 // typedef struct __va_list_tag {
10087 RecordDecl *VaListTagDecl;
10088
10089 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10090 VaListTagDecl->startDefinition();
10091
10092 const size_t NumFields = 5;
10093 QualType FieldTypes[NumFields];
10094 const char *FieldNames[NumFields];
10095
10096 // unsigned char gpr;
10097 FieldTypes[0] = Context->UnsignedCharTy;
10098 FieldNames[0] = "gpr";
10099
10100 // unsigned char fpr;
10101 FieldTypes[1] = Context->UnsignedCharTy;
10102 FieldNames[1] = "fpr";
10103
10104 // unsigned short reserved;
10105 FieldTypes[2] = Context->UnsignedShortTy;
10106 FieldNames[2] = "reserved";
10107
10108 // void* overflow_arg_area;
10109 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10110 FieldNames[3] = "overflow_arg_area";
10111
10112 // void* reg_save_area;
10113 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10114 FieldNames[4] = "reg_save_area";
10115
10116 // Create fields
10117 for (unsigned i = 0; i < NumFields; ++i) {
10118 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10119 StartLoc: SourceLocation(),
10120 IdLoc: SourceLocation(),
10121 Id: &Context->Idents.get(Name: FieldNames[i]),
10122 T: FieldTypes[i], /*TInfo=*/nullptr,
10123 /*BitWidth=*/BW: nullptr,
10124 /*Mutable=*/false,
10125 InitStyle: ICIS_NoInit);
10126 Field->setAccess(AS_public);
10127 VaListTagDecl->addDecl(D: Field);
10128 }
10129 VaListTagDecl->completeDefinition();
10130 Context->VaListTagDecl = VaListTagDecl;
10131 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10132
10133 // } __va_list_tag;
10134 TypedefDecl *VaListTagTypedefDecl =
10135 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10136
10137 QualType VaListTagTypedefType =
10138 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10139 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10140
10141 // typedef __va_list_tag __builtin_va_list[1];
10142 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10143 QualType VaListTagArrayType = Context->getConstantArrayType(
10144 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10145 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10146}
10147
10148static TypedefDecl *
10149CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10150 // struct __va_list_tag {
10151 RecordDecl *VaListTagDecl;
10152 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10153 VaListTagDecl->startDefinition();
10154
10155 const size_t NumFields = 4;
10156 QualType FieldTypes[NumFields];
10157 const char *FieldNames[NumFields];
10158
10159 // unsigned gp_offset;
10160 FieldTypes[0] = Context->UnsignedIntTy;
10161 FieldNames[0] = "gp_offset";
10162
10163 // unsigned fp_offset;
10164 FieldTypes[1] = Context->UnsignedIntTy;
10165 FieldNames[1] = "fp_offset";
10166
10167 // void* overflow_arg_area;
10168 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10169 FieldNames[2] = "overflow_arg_area";
10170
10171 // void* reg_save_area;
10172 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10173 FieldNames[3] = "reg_save_area";
10174
10175 // Create fields
10176 for (unsigned i = 0; i < NumFields; ++i) {
10177 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10178 DC: VaListTagDecl,
10179 StartLoc: SourceLocation(),
10180 IdLoc: SourceLocation(),
10181 Id: &Context->Idents.get(Name: FieldNames[i]),
10182 T: FieldTypes[i], /*TInfo=*/nullptr,
10183 /*BitWidth=*/BW: nullptr,
10184 /*Mutable=*/false,
10185 InitStyle: ICIS_NoInit);
10186 Field->setAccess(AS_public);
10187 VaListTagDecl->addDecl(D: Field);
10188 }
10189 VaListTagDecl->completeDefinition();
10190 Context->VaListTagDecl = VaListTagDecl;
10191 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10192
10193 // };
10194
10195 // typedef struct __va_list_tag __builtin_va_list[1];
10196 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10197 QualType VaListTagArrayType = Context->getConstantArrayType(
10198 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10199 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10200}
10201
10202static TypedefDecl *
10203CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10204 // struct __va_list
10205 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10206 if (Context->getLangOpts().CPlusPlus) {
10207 // namespace std { struct __va_list {
10208 NamespaceDecl *NS;
10209 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10210 DC: Context->getTranslationUnitDecl(),
10211 /*Inline=*/false, StartLoc: SourceLocation(),
10212 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10213 /*PrevDecl=*/nullptr, /*Nested=*/false);
10214 NS->setImplicit();
10215 VaListDecl->setDeclContext(NS);
10216 }
10217
10218 VaListDecl->startDefinition();
10219
10220 // void * __ap;
10221 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10222 DC: VaListDecl,
10223 StartLoc: SourceLocation(),
10224 IdLoc: SourceLocation(),
10225 Id: &Context->Idents.get(Name: "__ap"),
10226 T: Context->getPointerType(T: Context->VoidTy),
10227 /*TInfo=*/nullptr,
10228 /*BitWidth=*/BW: nullptr,
10229 /*Mutable=*/false,
10230 InitStyle: ICIS_NoInit);
10231 Field->setAccess(AS_public);
10232 VaListDecl->addDecl(D: Field);
10233
10234 // };
10235 VaListDecl->completeDefinition();
10236 Context->VaListTagDecl = VaListDecl;
10237
10238 // typedef struct __va_list __builtin_va_list;
10239 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10240 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10241}
10242
10243static TypedefDecl *
10244CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10245 // struct __va_list_tag {
10246 RecordDecl *VaListTagDecl;
10247 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10248 VaListTagDecl->startDefinition();
10249
10250 const size_t NumFields = 4;
10251 QualType FieldTypes[NumFields];
10252 const char *FieldNames[NumFields];
10253
10254 // long __gpr;
10255 FieldTypes[0] = Context->LongTy;
10256 FieldNames[0] = "__gpr";
10257
10258 // long __fpr;
10259 FieldTypes[1] = Context->LongTy;
10260 FieldNames[1] = "__fpr";
10261
10262 // void *__overflow_arg_area;
10263 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10264 FieldNames[2] = "__overflow_arg_area";
10265
10266 // void *__reg_save_area;
10267 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10268 FieldNames[3] = "__reg_save_area";
10269
10270 // Create fields
10271 for (unsigned i = 0; i < NumFields; ++i) {
10272 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10273 DC: VaListTagDecl,
10274 StartLoc: SourceLocation(),
10275 IdLoc: SourceLocation(),
10276 Id: &Context->Idents.get(Name: FieldNames[i]),
10277 T: FieldTypes[i], /*TInfo=*/nullptr,
10278 /*BitWidth=*/BW: nullptr,
10279 /*Mutable=*/false,
10280 InitStyle: ICIS_NoInit);
10281 Field->setAccess(AS_public);
10282 VaListTagDecl->addDecl(D: Field);
10283 }
10284 VaListTagDecl->completeDefinition();
10285 Context->VaListTagDecl = VaListTagDecl;
10286 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10287
10288 // };
10289
10290 // typedef __va_list_tag __builtin_va_list[1];
10291 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10292 QualType VaListTagArrayType = Context->getConstantArrayType(
10293 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10294
10295 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10296}
10297
10298static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10299 // typedef struct __va_list_tag {
10300 RecordDecl *VaListTagDecl;
10301 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10302 VaListTagDecl->startDefinition();
10303
10304 const size_t NumFields = 3;
10305 QualType FieldTypes[NumFields];
10306 const char *FieldNames[NumFields];
10307
10308 // void *CurrentSavedRegisterArea;
10309 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10310 FieldNames[0] = "__current_saved_reg_area_pointer";
10311
10312 // void *SavedRegAreaEnd;
10313 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10314 FieldNames[1] = "__saved_reg_area_end_pointer";
10315
10316 // void *OverflowArea;
10317 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10318 FieldNames[2] = "__overflow_area_pointer";
10319
10320 // Create fields
10321 for (unsigned i = 0; i < NumFields; ++i) {
10322 FieldDecl *Field = FieldDecl::Create(
10323 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10324 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10325 /*TInfo=*/nullptr,
10326 /*BitWidth=*/BW: nullptr,
10327 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10328 Field->setAccess(AS_public);
10329 VaListTagDecl->addDecl(D: Field);
10330 }
10331 VaListTagDecl->completeDefinition();
10332 Context->VaListTagDecl = VaListTagDecl;
10333 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10334
10335 // } __va_list_tag;
10336 TypedefDecl *VaListTagTypedefDecl =
10337 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10338
10339 QualType VaListTagTypedefType =
10340 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10341 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10342
10343 // typedef __va_list_tag __builtin_va_list[1];
10344 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10345 QualType VaListTagArrayType = Context->getConstantArrayType(
10346 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10347
10348 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10349}
10350
10351static TypedefDecl *
10352CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10353 // typedef struct __va_list_tag {
10354 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10355
10356 VaListTagDecl->startDefinition();
10357
10358 // int* __va_stk;
10359 // int* __va_reg;
10360 // int __va_ndx;
10361 constexpr size_t NumFields = 3;
10362 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10363 Context->getPointerType(T: Context->IntTy),
10364 Context->IntTy};
10365 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10366
10367 // Create fields
10368 for (unsigned i = 0; i < NumFields; ++i) {
10369 FieldDecl *Field = FieldDecl::Create(
10370 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10371 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10372 /*BitWidth=*/BW: nullptr,
10373 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10374 Field->setAccess(AS_public);
10375 VaListTagDecl->addDecl(D: Field);
10376 }
10377 VaListTagDecl->completeDefinition();
10378 Context->VaListTagDecl = VaListTagDecl;
10379 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10380
10381 // } __va_list_tag;
10382 TypedefDecl *VaListTagTypedefDecl =
10383 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10384
10385 return VaListTagTypedefDecl;
10386}
10387
10388static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10389 TargetInfo::BuiltinVaListKind Kind) {
10390 switch (Kind) {
10391 case TargetInfo::CharPtrBuiltinVaList:
10392 return CreateCharPtrBuiltinVaListDecl(Context);
10393 case TargetInfo::VoidPtrBuiltinVaList:
10394 return CreateVoidPtrBuiltinVaListDecl(Context);
10395 case TargetInfo::AArch64ABIBuiltinVaList:
10396 return CreateAArch64ABIBuiltinVaListDecl(Context);
10397 case TargetInfo::PowerABIBuiltinVaList:
10398 return CreatePowerABIBuiltinVaListDecl(Context);
10399 case TargetInfo::X86_64ABIBuiltinVaList:
10400 return CreateX86_64ABIBuiltinVaListDecl(Context);
10401 case TargetInfo::AAPCSABIBuiltinVaList:
10402 return CreateAAPCSABIBuiltinVaListDecl(Context);
10403 case TargetInfo::SystemZBuiltinVaList:
10404 return CreateSystemZBuiltinVaListDecl(Context);
10405 case TargetInfo::HexagonBuiltinVaList:
10406 return CreateHexagonBuiltinVaListDecl(Context);
10407 case TargetInfo::XtensaABIBuiltinVaList:
10408 return CreateXtensaABIBuiltinVaListDecl(Context);
10409 }
10410
10411 llvm_unreachable("Unhandled __builtin_va_list type kind");
10412}
10413
10414TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10415 if (!BuiltinVaListDecl) {
10416 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10417 assert(BuiltinVaListDecl->isImplicit());
10418 }
10419
10420 return BuiltinVaListDecl;
10421}
10422
10423Decl *ASTContext::getVaListTagDecl() const {
10424 // Force the creation of VaListTagDecl by building the __builtin_va_list
10425 // declaration.
10426 if (!VaListTagDecl)
10427 (void)getBuiltinVaListDecl();
10428
10429 return VaListTagDecl;
10430}
10431
10432TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10433 if (!BuiltinMSVaListDecl)
10434 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10435
10436 return BuiltinMSVaListDecl;
10437}
10438
10439TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10440 if (!BuiltinZOSVaListDecl)
10441 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10442
10443 return BuiltinZOSVaListDecl;
10444}
10445
10446bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10447 // Allow redecl custom type checking builtin for HLSL.
10448 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10449 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10450 return true;
10451 // Allow redecl custom type checking builtin for SPIR-V.
10452 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10453 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10454 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10455 return true;
10456 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10457}
10458
10459void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10460 assert(ObjCConstantStringType.isNull() &&
10461 "'NSConstantString' type already set!");
10462
10463 ObjCConstantStringType = getObjCInterfaceType(Decl);
10464}
10465
10466/// Retrieve the template name that corresponds to a non-empty
10467/// lookup.
10468TemplateName
10469ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10470 UnresolvedSetIterator End) const {
10471 unsigned size = End - Begin;
10472 assert(size > 1 && "set is not overloaded!");
10473
10474 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10475 size * sizeof(FunctionTemplateDecl*));
10476 auto *OT = new (memory) OverloadedTemplateStorage(size);
10477
10478 NamedDecl **Storage = OT->getStorage();
10479 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10480 NamedDecl *D = *I;
10481 assert(isa<FunctionTemplateDecl>(D) ||
10482 isa<UnresolvedUsingValueDecl>(D) ||
10483 (isa<UsingShadowDecl>(D) &&
10484 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10485 *Storage++ = D;
10486 }
10487
10488 return TemplateName(OT);
10489}
10490
10491/// Retrieve a template name representing an unqualified-id that has been
10492/// assumed to name a template for ADL purposes.
10493TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10494 auto *OT = new (*this) AssumedTemplateStorage(Name);
10495 return TemplateName(OT);
10496}
10497
10498/// Retrieve the template name that represents a qualified
10499/// template name such as \c std::vector.
10500TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10501 bool TemplateKeyword,
10502 TemplateName Template) const {
10503 assert(Template.getKind() == TemplateName::Template ||
10504 Template.getKind() == TemplateName::UsingTemplate);
10505
10506 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10507 assert(!Qualifier && "unexpected qualified template template parameter");
10508 assert(TemplateKeyword == false);
10509 return Template;
10510 }
10511
10512 // FIXME: Canonicalization?
10513 llvm::FoldingSetNodeID ID;
10514 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10515
10516 llvm::FoldingSetInsertToken Token;
10517 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10518 if (!QTN) {
10519 QTN = new (*this, alignof(QualifiedTemplateName))
10520 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10521 QualifiedTemplateNames.insert(N: QTN, Token);
10522 }
10523
10524 return TemplateName(QTN);
10525}
10526
10527/// Retrieve the template name that represents a dependent
10528/// template name such as \c MetaFun::template operator+.
10529TemplateName
10530ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10531 llvm::FoldingSetNodeID ID;
10532 S.Profile(ID);
10533
10534 llvm::FoldingSetInsertToken Token;
10535 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10536 return TemplateName(QTN);
10537
10538 DependentTemplateName *QTN =
10539 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10540 DependentTemplateNames.insert(N: QTN, Token);
10541 return TemplateName(QTN);
10542}
10543
10544TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10545 Decl *AssociatedDecl,
10546 unsigned Index,
10547 UnsignedOrNone PackIndex,
10548 bool Final) const {
10549 llvm::FoldingSetNodeID ID;
10550 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10551 Index, PackIndex, Final);
10552
10553 llvm::FoldingSetInsertToken Token;
10554 SubstTemplateTemplateParmStorage *subst =
10555 SubstTemplateTemplateParms.lookup(ID, Token);
10556
10557 if (!subst) {
10558 subst = new (*this) SubstTemplateTemplateParmStorage(
10559 Replacement, AssociatedDecl, Index, PackIndex, Final);
10560 SubstTemplateTemplateParms.insert(N: subst, Token);
10561 }
10562
10563 return TemplateName(subst);
10564}
10565
10566TemplateName
10567ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10568 Decl *AssociatedDecl,
10569 unsigned Index, bool Final) const {
10570 auto &Self = const_cast<ASTContext &>(*this);
10571 llvm::FoldingSetNodeID ID;
10572 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10573 AssociatedDecl, Index, Final);
10574
10575 llvm::FoldingSetInsertToken Token;
10576 SubstTemplateTemplateParmPackStorage *Subst =
10577 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10578
10579 if (!Subst) {
10580 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10581 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10582 SubstTemplateTemplateParmPacks.insert(N: Subst, Token);
10583 }
10584
10585 return TemplateName(Subst);
10586}
10587
10588/// Retrieve the template name that represents a template name
10589/// deduced from a specialization.
10590TemplateName
10591ASTContext::getDeducedTemplateName(TemplateName Underlying,
10592 DefaultArguments DefaultArgs) const {
10593 if (!DefaultArgs)
10594 return Underlying;
10595
10596 llvm::FoldingSetNodeID ID;
10597 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10598
10599 llvm::FoldingSetInsertToken Token;
10600 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10601 if (!DTS) {
10602 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10603 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10604 Align: alignof(DeducedTemplateStorage));
10605 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10606 DeducedTemplates.insert(N: DTS, Token);
10607 }
10608 return TemplateName(DTS);
10609}
10610
10611TemplateName ASTContext::getPackIndexingTemplateName(
10612 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10613 ArrayRef<TemplateName> Expansions) const {
10614 auto &Self = const_cast<ASTContext &>(*this);
10615 llvm::FoldingSetNodeID ID;
10616 PackIndexingTemplateStorage::Profile(ID, Context: Self, Pattern, IndexExpr,
10617 FullySubstituted, Expansions);
10618
10619 llvm::FoldingSetInsertToken Token;
10620 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10621 if (!PI) {
10622 void *Mem =
10623 Allocate(Size: PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10624 Counts: Expansions.size()),
10625 Align: alignof(PackIndexingTemplateStorage));
10626 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10627 FullySubstituted, Expansions);
10628 PackIndexingTemplates.insert(N: PI, Token);
10629 }
10630 return TemplateName(PI);
10631}
10632
10633/// getFromTargetType - Given one of the integer types provided by
10634/// TargetInfo, produce the corresponding type. The unsigned @p Type
10635/// is actually a value of type @c TargetInfo::IntType.
10636CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10637 switch (Type) {
10638 case TargetInfo::NoInt: return {};
10639 case TargetInfo::SignedChar: return SignedCharTy;
10640 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10641 case TargetInfo::SignedShort: return ShortTy;
10642 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10643 case TargetInfo::SignedInt: return IntTy;
10644 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10645 case TargetInfo::SignedLong: return LongTy;
10646 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10647 case TargetInfo::SignedLongLong: return LongLongTy;
10648 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10649 }
10650
10651 llvm_unreachable("Unhandled TargetInfo::IntType value");
10652}
10653
10654//===----------------------------------------------------------------------===//
10655// Type Predicates.
10656//===----------------------------------------------------------------------===//
10657
10658/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10659/// garbage collection attribute.
10660///
10661Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10662 if (getLangOpts().getGC() == LangOptions::NonGC)
10663 return Qualifiers::GCNone;
10664
10665 assert(getLangOpts().ObjC);
10666 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10667
10668 // Default behaviour under objective-C's gc is for ObjC pointers
10669 // (or pointers to them) be treated as though they were declared
10670 // as __strong.
10671 if (GCAttrs == Qualifiers::GCNone) {
10672 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10673 return Qualifiers::Strong;
10674 else if (Ty->isPointerType())
10675 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10676 } else {
10677 // It's not valid to set GC attributes on anything that isn't a
10678 // pointer.
10679#ifndef NDEBUG
10680 QualType CT = Ty->getCanonicalTypeInternal();
10681 while (const auto *AT = dyn_cast<ArrayType>(CT))
10682 CT = AT->getElementType();
10683 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10684#endif
10685 }
10686 return GCAttrs;
10687}
10688
10689//===----------------------------------------------------------------------===//
10690// Type Compatibility Testing
10691//===----------------------------------------------------------------------===//
10692
10693/// areCompatVectorTypes - Return true if the two specified vector types are
10694/// compatible.
10695static bool areCompatVectorTypes(const VectorType *LHS,
10696 const VectorType *RHS) {
10697 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10698 return LHS->getElementType() == RHS->getElementType() &&
10699 LHS->getNumElements() == RHS->getNumElements();
10700}
10701
10702/// areCompatMatrixTypes - Return true if the two specified matrix types are
10703/// compatible.
10704static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10705 const ConstantMatrixType *RHS) {
10706 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10707 return LHS->getElementType() == RHS->getElementType() &&
10708 LHS->getNumRows() == RHS->getNumRows() &&
10709 LHS->getNumColumns() == RHS->getNumColumns();
10710}
10711
10712bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10713 QualType SecondVec) {
10714 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10715 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10716
10717 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10718 return true;
10719
10720 // Treat Neon vector types and most AltiVec vector types as if they are the
10721 // equivalent GCC vector types.
10722 const auto *First = FirstVec->castAs<VectorType>();
10723 const auto *Second = SecondVec->castAs<VectorType>();
10724 if (First->getNumElements() == Second->getNumElements() &&
10725 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10726 First->getVectorKind() != VectorKind::AltiVecPixel &&
10727 First->getVectorKind() != VectorKind::AltiVecBool &&
10728 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10729 Second->getVectorKind() != VectorKind::AltiVecBool &&
10730 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10731 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10732 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10733 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10734 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10735 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10736 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10737 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10738 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10739 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10740 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10741 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10742 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10743 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10744 return true;
10745
10746 // In OpenCL, treat half and _Float16 vector types as compatible.
10747 if (getLangOpts().OpenCL &&
10748 First->getNumElements() == Second->getNumElements()) {
10749 QualType FirstElt = First->getElementType();
10750 QualType SecondElt = Second->getElementType();
10751
10752 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10753 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10754 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10755 First->getVectorKind() != VectorKind::AltiVecBool &&
10756 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10757 Second->getVectorKind() != VectorKind::AltiVecBool)
10758 return true;
10759 }
10760 }
10761 return false;
10762}
10763
10764bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10765 QualType RHS) {
10766 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10767 return Result != OBTAssignResult::IncompatibleKinds;
10768}
10769
10770ASTContext::OBTAssignResult
10771ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10772 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10773 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10774
10775 if (!LHSOBT && !RHSOBT)
10776 return OBTAssignResult::Compatible;
10777
10778 if (LHSOBT && RHSOBT) {
10779 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10780 return OBTAssignResult::IncompatibleKinds;
10781 return OBTAssignResult::Compatible;
10782 }
10783
10784 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10785 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10786
10787 if (RHSOBT && !LHSOBT) {
10788 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10789 return OBTAssignResult::Discards;
10790 }
10791
10792 return OBTAssignResult::NotApplicable;
10793}
10794
10795/// getRVVTypeSize - Return RVV vector register size.
10796static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10797 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10798 auto VScale = Context.getTargetInfo().getVScaleRange(
10799 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10800 if (!VScale)
10801 return 0;
10802
10803 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10804
10805 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10806 if (Info.ElementType == Context.BoolTy)
10807 EltSize = 1;
10808
10809 uint64_t MinElts = Info.EC.getKnownMinValue();
10810 return VScale->first * MinElts * EltSize;
10811}
10812
10813bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10814 QualType SecondType) {
10815 assert(
10816 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10817 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10818 "Expected RVV builtin type and vector type!");
10819
10820 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10821 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10822 if (const auto *VT = SecondType->getAs<VectorType>()) {
10823 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10824 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10825 return FirstType->isRVVVLSBuiltinType() &&
10826 Info.ElementType == BoolTy &&
10827 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10828 }
10829 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10830 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10831 return FirstType->isRVVVLSBuiltinType() &&
10832 Info.ElementType == BoolTy &&
10833 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10834 }
10835 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10836 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10837 return FirstType->isRVVVLSBuiltinType() &&
10838 Info.ElementType == BoolTy &&
10839 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10840 }
10841 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10842 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10843 return FirstType->isRVVVLSBuiltinType() &&
10844 Info.ElementType == BoolTy &&
10845 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10846 }
10847 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10848 VT->getVectorKind() == VectorKind::Generic)
10849 return FirstType->isRVVVLSBuiltinType() &&
10850 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10851 hasSameType(T1: VT->getElementType(),
10852 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10853 }
10854 }
10855 return false;
10856 };
10857
10858 return IsValidCast(FirstType, SecondType) ||
10859 IsValidCast(SecondType, FirstType);
10860}
10861
10862bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10863 QualType SecondType) {
10864 assert(
10865 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10866 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10867 "Expected RVV builtin type and vector type!");
10868
10869 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10870 const auto *BT = FirstType->getAs<BuiltinType>();
10871 if (!BT)
10872 return false;
10873
10874 if (!BT->isRVVVLSBuiltinType())
10875 return false;
10876
10877 const auto *VecTy = SecondType->getAs<VectorType>();
10878 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10879 const LangOptions::LaxVectorConversionKind LVCKind =
10880 getLangOpts().getLaxVectorConversions();
10881
10882 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10883 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10884 return false;
10885
10886 // If -flax-vector-conversions=all is specified, the types are
10887 // certainly compatible.
10888 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10889 return true;
10890
10891 // If -flax-vector-conversions=integer is specified, the types are
10892 // compatible if the elements are integer types.
10893 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10894 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10895 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10896 }
10897
10898 return false;
10899 };
10900
10901 return IsLaxCompatible(FirstType, SecondType) ||
10902 IsLaxCompatible(SecondType, FirstType);
10903}
10904
10905bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10906 while (true) {
10907 // __strong id
10908 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10909 if (Attr->getAttrKind() == attr::ObjCOwnership)
10910 return true;
10911
10912 Ty = Attr->getModifiedType();
10913
10914 // X *__strong (...)
10915 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10916 Ty = Paren->getInnerType();
10917
10918 // We do not want to look through typedefs, typeof(expr),
10919 // typeof(type), or any other way that the type is somehow
10920 // abstracted.
10921 } else {
10922 return false;
10923 }
10924 }
10925}
10926
10927//===----------------------------------------------------------------------===//
10928// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10929//===----------------------------------------------------------------------===//
10930
10931/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10932/// inheritance hierarchy of 'rProto'.
10933bool
10934ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10935 ObjCProtocolDecl *rProto) const {
10936 if (declaresSameEntity(D1: lProto, D2: rProto))
10937 return true;
10938 for (auto *PI : rProto->protocols())
10939 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10940 return true;
10941 return false;
10942}
10943
10944/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10945/// Class<pr1, ...>.
10946bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10947 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10948 for (auto *lhsProto : lhs->quals()) {
10949 bool match = false;
10950 for (auto *rhsProto : rhs->quals()) {
10951 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
10952 match = true;
10953 break;
10954 }
10955 }
10956 if (!match)
10957 return false;
10958 }
10959 return true;
10960}
10961
10962/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10963/// ObjCQualifiedIDType.
10964bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
10965 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10966 bool compare) {
10967 // Allow id<P..> and an 'id' in all cases.
10968 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10969 return true;
10970
10971 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10972 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10973 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
10974 return false;
10975
10976 if (lhs->isObjCQualifiedIdType()) {
10977 if (rhs->qual_empty()) {
10978 // If the RHS is a unqualified interface pointer "NSString*",
10979 // make sure we check the class hierarchy.
10980 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10981 for (auto *I : lhs->quals()) {
10982 // when comparing an id<P> on lhs with a static type on rhs,
10983 // see if static class implements all of id's protocols, directly or
10984 // through its super class and categories.
10985 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
10986 return false;
10987 }
10988 }
10989 // If there are no qualifiers and no interface, we have an 'id'.
10990 return true;
10991 }
10992 // Both the right and left sides have qualifiers.
10993 for (auto *lhsProto : lhs->quals()) {
10994 bool match = false;
10995
10996 // when comparing an id<P> on lhs with a static type on rhs,
10997 // see if static class implements all of id's protocols, directly or
10998 // through its super class and categories.
10999 for (auto *rhsProto : rhs->quals()) {
11000 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11001 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11002 match = true;
11003 break;
11004 }
11005 }
11006 // If the RHS is a qualified interface pointer "NSString<P>*",
11007 // make sure we check the class hierarchy.
11008 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11009 for (auto *I : lhs->quals()) {
11010 // when comparing an id<P> on lhs with a static type on rhs,
11011 // see if static class implements all of id's protocols, directly or
11012 // through its super class and categories.
11013 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11014 match = true;
11015 break;
11016 }
11017 }
11018 }
11019 if (!match)
11020 return false;
11021 }
11022
11023 return true;
11024 }
11025
11026 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11027
11028 if (lhs->getInterfaceType()) {
11029 // If both the right and left sides have qualifiers.
11030 for (auto *lhsProto : lhs->quals()) {
11031 bool match = false;
11032
11033 // when comparing an id<P> on rhs with a static type on lhs,
11034 // see if static class implements all of id's protocols, directly or
11035 // through its super class and categories.
11036 // First, lhs protocols in the qualifier list must be found, direct
11037 // or indirect in rhs's qualifier list or it is a mismatch.
11038 for (auto *rhsProto : rhs->quals()) {
11039 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11040 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11041 match = true;
11042 break;
11043 }
11044 }
11045 if (!match)
11046 return false;
11047 }
11048
11049 // Static class's protocols, or its super class or category protocols
11050 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11051 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11052 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11053 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11054 // This is rather dubious but matches gcc's behavior. If lhs has
11055 // no type qualifier and its class has no static protocol(s)
11056 // assume that it is mismatch.
11057 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11058 return false;
11059 for (auto *lhsProto : LHSInheritedProtocols) {
11060 bool match = false;
11061 for (auto *rhsProto : rhs->quals()) {
11062 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11063 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11064 match = true;
11065 break;
11066 }
11067 }
11068 if (!match)
11069 return false;
11070 }
11071 }
11072 return true;
11073 }
11074 return false;
11075}
11076
11077/// canAssignObjCInterfaces - Return true if the two interface types are
11078/// compatible for assignment from RHS to LHS. This handles validation of any
11079/// protocol qualifiers on the LHS or RHS.
11080bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11081 const ObjCObjectPointerType *RHSOPT) {
11082 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11083 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11084
11085 // If either type represents the built-in 'id' type, return true.
11086 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11087 return true;
11088
11089 // Function object that propagates a successful result or handles
11090 // __kindof types.
11091 auto finish = [&](bool succeeded) -> bool {
11092 if (succeeded)
11093 return true;
11094
11095 if (!RHS->isKindOfType())
11096 return false;
11097
11098 // Strip off __kindof and protocol qualifiers, then check whether
11099 // we can assign the other way.
11100 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11101 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11102 };
11103
11104 // Casts from or to id<P> are allowed when the other side has compatible
11105 // protocols.
11106 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11107 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11108 }
11109
11110 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11111 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11112 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11113 }
11114
11115 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11116 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11117 return true;
11118 }
11119
11120 // If we have 2 user-defined types, fall into that path.
11121 if (LHS->getInterface() && RHS->getInterface()) {
11122 return finish(canAssignObjCInterfaces(LHS, RHS));
11123 }
11124
11125 return false;
11126}
11127
11128/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11129/// for providing type-safety for objective-c pointers used to pass/return
11130/// arguments in block literals. When passed as arguments, passing 'A*' where
11131/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11132/// not OK. For the return type, the opposite is not OK.
11133bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11134 const ObjCObjectPointerType *LHSOPT,
11135 const ObjCObjectPointerType *RHSOPT,
11136 bool BlockReturnType) {
11137
11138 // Function object that propagates a successful result or handles
11139 // __kindof types.
11140 auto finish = [&](bool succeeded) -> bool {
11141 if (succeeded)
11142 return true;
11143
11144 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11145 if (!Expected->isKindOfType())
11146 return false;
11147
11148 // Strip off __kindof and protocol qualifiers, then check whether
11149 // we can assign the other way.
11150 return canAssignObjCInterfacesInBlockPointer(
11151 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11152 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11153 BlockReturnType);
11154 };
11155
11156 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11157 return true;
11158
11159 if (LHSOPT->isObjCBuiltinType()) {
11160 return finish(RHSOPT->isObjCBuiltinType() ||
11161 RHSOPT->isObjCQualifiedIdType());
11162 }
11163
11164 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11165 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11166 // Use for block parameters previous type checking for compatibility.
11167 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11168 // Or corrected type checking as in non-compat mode.
11169 (!BlockReturnType &&
11170 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11171 else
11172 return finish(ObjCQualifiedIdTypesAreCompatible(
11173 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11174 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11175 }
11176
11177 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11178 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11179 if (LHS && RHS) { // We have 2 user-defined types.
11180 if (LHS != RHS) {
11181 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11182 return finish(BlockReturnType);
11183 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11184 return finish(!BlockReturnType);
11185 }
11186 else
11187 return true;
11188 }
11189 return false;
11190}
11191
11192/// Comparison routine for Objective-C protocols to be used with
11193/// llvm::array_pod_sort.
11194static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11195 ObjCProtocolDecl * const *rhs) {
11196 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11197}
11198
11199/// getIntersectionOfProtocols - This routine finds the intersection of set
11200/// of protocols inherited from two distinct objective-c pointer objects with
11201/// the given common base.
11202/// It is used to build composite qualifier list of the composite type of
11203/// the conditional expression involving two objective-c pointer objects.
11204static
11205void getIntersectionOfProtocols(ASTContext &Context,
11206 const ObjCInterfaceDecl *CommonBase,
11207 const ObjCObjectPointerType *LHSOPT,
11208 const ObjCObjectPointerType *RHSOPT,
11209 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11210
11211 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11212 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11213 assert(LHS->getInterface() && "LHS must have an interface base");
11214 assert(RHS->getInterface() && "RHS must have an interface base");
11215
11216 // Add all of the protocols for the LHS.
11217 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11218
11219 // Start with the protocol qualifiers.
11220 for (auto *proto : LHS->quals()) {
11221 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11222 }
11223
11224 // Also add the protocols associated with the LHS interface.
11225 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11226
11227 // Add all of the protocols for the RHS.
11228 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11229
11230 // Start with the protocol qualifiers.
11231 for (auto *proto : RHS->quals()) {
11232 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11233 }
11234
11235 // Also add the protocols associated with the RHS interface.
11236 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11237
11238 // Compute the intersection of the collected protocol sets.
11239 for (auto *proto : LHSProtocolSet) {
11240 if (RHSProtocolSet.count(Ptr: proto))
11241 IntersectionSet.push_back(Elt: proto);
11242 }
11243
11244 // Compute the set of protocols that is implied by either the common type or
11245 // the protocols within the intersection.
11246 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11247 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11248
11249 // Remove any implied protocols from the list of inherited protocols.
11250 if (!ImpliedProtocols.empty()) {
11251 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11252 return ImpliedProtocols.contains(Ptr: proto);
11253 });
11254 }
11255
11256 // Sort the remaining protocols by name.
11257 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11258 Compare: compareObjCProtocolsByName);
11259}
11260
11261/// Determine whether the first type is a subtype of the second.
11262static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11263 QualType rhs) {
11264 // Common case: two object pointers.
11265 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11266 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11267 if (lhsOPT && rhsOPT)
11268 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11269
11270 // Two block pointers.
11271 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11272 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11273 if (lhsBlock && rhsBlock)
11274 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11275
11276 // If either is an unqualified 'id' and the other is a block, it's
11277 // acceptable.
11278 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11279 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11280 return true;
11281
11282 return false;
11283}
11284
11285// Check that the given Objective-C type argument lists are equivalent.
11286static bool sameObjCTypeArgs(ASTContext &ctx,
11287 const ObjCInterfaceDecl *iface,
11288 ArrayRef<QualType> lhsArgs,
11289 ArrayRef<QualType> rhsArgs,
11290 bool stripKindOf) {
11291 if (lhsArgs.size() != rhsArgs.size())
11292 return false;
11293
11294 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11295 if (!typeParams)
11296 return false;
11297
11298 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11299 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11300 continue;
11301
11302 switch (typeParams->begin()[i]->getVariance()) {
11303 case ObjCTypeParamVariance::Invariant:
11304 if (!stripKindOf ||
11305 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11306 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11307 return false;
11308 }
11309 break;
11310
11311 case ObjCTypeParamVariance::Covariant:
11312 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11313 return false;
11314 break;
11315
11316 case ObjCTypeParamVariance::Contravariant:
11317 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11318 return false;
11319 break;
11320 }
11321 }
11322
11323 return true;
11324}
11325
11326QualType ASTContext::areCommonBaseCompatible(
11327 const ObjCObjectPointerType *Lptr,
11328 const ObjCObjectPointerType *Rptr) {
11329 const ObjCObjectType *LHS = Lptr->getObjectType();
11330 const ObjCObjectType *RHS = Rptr->getObjectType();
11331 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11332 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11333
11334 if (!LDecl || !RDecl)
11335 return {};
11336
11337 // When either LHS or RHS is a kindof type, we should return a kindof type.
11338 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11339 // kindof(A).
11340 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11341
11342 // Follow the left-hand side up the class hierarchy until we either hit a
11343 // root or find the RHS. Record the ancestors in case we don't find it.
11344 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11345 LHSAncestors;
11346 while (true) {
11347 // Record this ancestor. We'll need this if the common type isn't in the
11348 // path from the LHS to the root.
11349 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11350
11351 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11352 // Get the type arguments.
11353 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11354 bool anyChanges = false;
11355 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11356 // Both have type arguments, compare them.
11357 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11358 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11359 /*stripKindOf=*/true))
11360 return {};
11361 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11362 // If only one has type arguments, the result will not have type
11363 // arguments.
11364 LHSTypeArgs = {};
11365 anyChanges = true;
11366 }
11367
11368 // Compute the intersection of protocols.
11369 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11370 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11371 IntersectionSet&: Protocols);
11372 if (!Protocols.empty())
11373 anyChanges = true;
11374
11375 // If anything in the LHS will have changed, build a new result type.
11376 // If we need to return a kindof type but LHS is not a kindof type, we
11377 // build a new result type.
11378 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11379 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11380 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11381 isKindOf: anyKindOf || LHS->isKindOfType());
11382 return getObjCObjectPointerType(ObjectT: Result);
11383 }
11384
11385 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11386 }
11387
11388 // Find the superclass.
11389 QualType LHSSuperType = LHS->getSuperClassType();
11390 if (LHSSuperType.isNull())
11391 break;
11392
11393 LHS = LHSSuperType->castAs<ObjCObjectType>();
11394 }
11395
11396 // We didn't find anything by following the LHS to its root; now check
11397 // the RHS against the cached set of ancestors.
11398 while (true) {
11399 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11400 if (KnownLHS != LHSAncestors.end()) {
11401 LHS = KnownLHS->second;
11402
11403 // Get the type arguments.
11404 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11405 bool anyChanges = false;
11406 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11407 // Both have type arguments, compare them.
11408 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11409 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11410 /*stripKindOf=*/true))
11411 return {};
11412 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11413 // If only one has type arguments, the result will not have type
11414 // arguments.
11415 RHSTypeArgs = {};
11416 anyChanges = true;
11417 }
11418
11419 // Compute the intersection of protocols.
11420 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11421 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11422 IntersectionSet&: Protocols);
11423 if (!Protocols.empty())
11424 anyChanges = true;
11425
11426 // If we need to return a kindof type but RHS is not a kindof type, we
11427 // build a new result type.
11428 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11429 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11430 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11431 isKindOf: anyKindOf || RHS->isKindOfType());
11432 return getObjCObjectPointerType(ObjectT: Result);
11433 }
11434
11435 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11436 }
11437
11438 // Find the superclass of the RHS.
11439 QualType RHSSuperType = RHS->getSuperClassType();
11440 if (RHSSuperType.isNull())
11441 break;
11442
11443 RHS = RHSSuperType->castAs<ObjCObjectType>();
11444 }
11445
11446 return {};
11447}
11448
11449bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11450 const ObjCObjectType *RHS) {
11451 assert(LHS->getInterface() && "LHS is not an interface type");
11452 assert(RHS->getInterface() && "RHS is not an interface type");
11453
11454 // Verify that the base decls are compatible: the RHS must be a subclass of
11455 // the LHS.
11456 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11457 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11458 if (!IsSuperClass)
11459 return false;
11460
11461 // If the LHS has protocol qualifiers, determine whether all of them are
11462 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11463 // LHS).
11464 if (LHS->getNumProtocols() > 0) {
11465 // OK if conversion of LHS to SuperClass results in narrowing of types
11466 // ; i.e., SuperClass may implement at least one of the protocols
11467 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11468 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11469 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11470 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11471 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11472 // qualifiers.
11473 for (auto *RHSPI : RHS->quals())
11474 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11475 // If there is no protocols associated with RHS, it is not a match.
11476 if (SuperClassInheritedProtocols.empty())
11477 return false;
11478
11479 for (const auto *LHSProto : LHS->quals()) {
11480 bool SuperImplementsProtocol = false;
11481 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11482 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11483 SuperImplementsProtocol = true;
11484 break;
11485 }
11486 if (!SuperImplementsProtocol)
11487 return false;
11488 }
11489 }
11490
11491 // If the LHS is specialized, we may need to check type arguments.
11492 if (LHS->isSpecialized()) {
11493 // Follow the superclass chain until we've matched the LHS class in the
11494 // hierarchy. This substitutes type arguments through.
11495 const ObjCObjectType *RHSSuper = RHS;
11496 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11497 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11498
11499 // If the RHS is specializd, compare type arguments.
11500 if (RHSSuper->isSpecialized() &&
11501 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11502 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11503 /*stripKindOf=*/true)) {
11504 return false;
11505 }
11506 }
11507
11508 return true;
11509}
11510
11511bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11512 // get the "pointed to" types
11513 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11514 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11515
11516 if (!LHSOPT || !RHSOPT)
11517 return false;
11518
11519 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11520 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11521}
11522
11523bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11524 return canAssignObjCInterfaces(
11525 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11526 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11527}
11528
11529/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11530/// both shall have the identically qualified version of a compatible type.
11531/// C99 6.2.7p1: Two types have compatible types if their types are the
11532/// same. See 6.7.[2,3,5] for additional rules.
11533bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11534 bool CompareUnqualified) {
11535 if (getLangOpts().CPlusPlus)
11536 return hasSameType(T1: LHS, T2: RHS);
11537
11538 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11539}
11540
11541bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11542 return typesAreCompatible(LHS, RHS);
11543}
11544
11545bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11546 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11547}
11548
11549/// mergeTransparentUnionType - if T is a transparent union type and a member
11550/// of T is compatible with SubType, return the merged type, else return
11551/// QualType()
11552QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11553 bool OfBlockPointer,
11554 bool Unqualified) {
11555 if (const RecordType *UT = T->getAsUnionType()) {
11556 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11557 if (UD->hasAttr<TransparentUnionAttr>()) {
11558 for (const auto *I : UD->fields()) {
11559 QualType ET = I->getType().getUnqualifiedType();
11560 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11561 if (!MT.isNull())
11562 return MT;
11563 }
11564 }
11565 }
11566
11567 return {};
11568}
11569
11570/// mergeFunctionParameterTypes - merge two types which appear as function
11571/// parameter types
11572QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11573 bool OfBlockPointer,
11574 bool Unqualified) {
11575 // GNU extension: two types are compatible if they appear as a function
11576 // argument, one of the types is a transparent union type and the other
11577 // type is compatible with a union member
11578 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11579 Unqualified);
11580 if (!lmerge.isNull())
11581 return lmerge;
11582
11583 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11584 Unqualified);
11585 if (!rmerge.isNull())
11586 return rmerge;
11587
11588 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11589}
11590
11591QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11592 bool OfBlockPointer, bool Unqualified,
11593 bool AllowCXX,
11594 bool IsConditionalOperator) {
11595 const auto *lbase = lhs->castAs<FunctionType>();
11596 const auto *rbase = rhs->castAs<FunctionType>();
11597 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11598 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11599 bool allLTypes = true;
11600 bool allRTypes = true;
11601
11602 // Check return type
11603 QualType retType;
11604 if (OfBlockPointer) {
11605 QualType RHS = rbase->getReturnType();
11606 QualType LHS = lbase->getReturnType();
11607 bool UnqualifiedResult = Unqualified;
11608 if (!UnqualifiedResult)
11609 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11610 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11611 }
11612 else
11613 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11614 Unqualified);
11615 if (retType.isNull())
11616 return {};
11617
11618 if (Unqualified)
11619 retType = retType.getUnqualifiedType();
11620
11621 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11622 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11623 if (Unqualified) {
11624 LRetType = LRetType.getUnqualifiedType();
11625 RRetType = RRetType.getUnqualifiedType();
11626 }
11627
11628 if (getCanonicalType(T: retType) != LRetType)
11629 allLTypes = false;
11630 if (getCanonicalType(T: retType) != RRetType)
11631 allRTypes = false;
11632
11633 // FIXME: double check this
11634 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11635 // rbase->getRegParmAttr() != 0 &&
11636 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11637 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11638 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11639
11640 // Compatible functions must have compatible calling conventions
11641 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11642 return {};
11643
11644 // Regparm is part of the calling convention.
11645 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11646 return {};
11647 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11648 return {};
11649
11650 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11651 return {};
11652 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11653 return {};
11654 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11655 return {};
11656
11657 // When merging declarations, it's common for supplemental information like
11658 // attributes to only be present in one of the declarations, and we generally
11659 // want type merging to preserve the union of information. So a merged
11660 // function type should be noreturn if it was noreturn in *either* operand
11661 // type.
11662 //
11663 // But for the conditional operator, this is backwards. The result of the
11664 // operator could be either operand, and its type should conservatively
11665 // reflect that. So a function type in a composite type is noreturn only
11666 // if it's noreturn in *both* operand types.
11667 //
11668 // Arguably, noreturn is a kind of subtype, and the conditional operator
11669 // ought to produce the most specific common supertype of its operand types.
11670 // That would differ from this rule in contravariant positions. However,
11671 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11672 // as a practical matter, it would only affect C code that does abstraction of
11673 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11674 // say the least. So we use the simpler rule.
11675 bool NoReturn = IsConditionalOperator
11676 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11677 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11678 if (lbaseInfo.getNoReturn() != NoReturn)
11679 allLTypes = false;
11680 if (rbaseInfo.getNoReturn() != NoReturn)
11681 allRTypes = false;
11682
11683 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11684
11685 std::optional<FunctionEffectSet> MergedFX;
11686
11687 if (lproto && rproto) { // two C99 style function prototypes
11688 assert((AllowCXX ||
11689 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11690 "C++ shouldn't be here");
11691 // Compatible functions must have the same number of parameters
11692 if (lproto->getNumParams() != rproto->getNumParams())
11693 return {};
11694
11695 // Variadic and non-variadic functions aren't compatible
11696 if (lproto->isVariadic() != rproto->isVariadic())
11697 return {};
11698
11699 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11700 return {};
11701
11702 // Function protos with different 'cfi_salt' values aren't compatible.
11703 if (lproto->getExtraAttributeInfo().CFISalt !=
11704 rproto->getExtraAttributeInfo().CFISalt)
11705 return {};
11706
11707 // Function effects are handled similarly to noreturn, see above.
11708 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11709 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11710 if (LHSFX != RHSFX) {
11711 if (IsConditionalOperator)
11712 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11713 else {
11714 FunctionEffectSet::Conflicts Errs;
11715 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11716 // Here we're discarding a possible error due to conflicts in the effect
11717 // sets. But we're not in a context where we can report it. The
11718 // operation does however guarantee maintenance of invariants.
11719 }
11720 if (*MergedFX != LHSFX)
11721 allLTypes = false;
11722 if (*MergedFX != RHSFX)
11723 allRTypes = false;
11724 }
11725
11726 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11727 bool canUseLeft, canUseRight;
11728 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11729 NewParamInfos&: newParamInfos))
11730 return {};
11731
11732 if (!canUseLeft)
11733 allLTypes = false;
11734 if (!canUseRight)
11735 allRTypes = false;
11736
11737 // Check parameter type compatibility
11738 SmallVector<QualType, 10> types;
11739 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11740 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11741 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11742 QualType paramType = mergeFunctionParameterTypes(
11743 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11744 if (paramType.isNull())
11745 return {};
11746
11747 if (Unqualified)
11748 paramType = paramType.getUnqualifiedType();
11749
11750 types.push_back(Elt: paramType);
11751 if (Unqualified) {
11752 lParamType = lParamType.getUnqualifiedType();
11753 rParamType = rParamType.getUnqualifiedType();
11754 }
11755
11756 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11757 allLTypes = false;
11758 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11759 allRTypes = false;
11760 }
11761
11762 if (allLTypes) return lhs;
11763 if (allRTypes) return rhs;
11764
11765 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11766 EPI.ExtInfo = einfo;
11767 EPI.ExtParameterInfos =
11768 newParamInfos.empty() ? nullptr : newParamInfos.data();
11769 if (MergedFX)
11770 EPI.FunctionEffects = *MergedFX;
11771 return getFunctionType(ResultTy: retType, Args: types, EPI);
11772 }
11773
11774 if (lproto) allRTypes = false;
11775 if (rproto) allLTypes = false;
11776
11777 const FunctionProtoType *proto = lproto ? lproto : rproto;
11778 if (proto) {
11779 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11780 if (proto->isVariadic())
11781 return {};
11782 // Check that the types are compatible with the types that
11783 // would result from default argument promotions (C99 6.7.5.3p15).
11784 // The only types actually affected are promotable integer
11785 // types and floats, which would be passed as a different
11786 // type depending on whether the prototype is visible.
11787 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11788 QualType paramTy = proto->getParamType(i);
11789
11790 // Look at the converted type of enum types, since that is the type used
11791 // to pass enum values.
11792 if (const auto *ED = paramTy->getAsEnumDecl()) {
11793 paramTy = ED->getIntegerType();
11794 if (paramTy.isNull())
11795 return {};
11796 }
11797
11798 if (isPromotableIntegerType(T: paramTy) ||
11799 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11800 return {};
11801 }
11802
11803 if (allLTypes) return lhs;
11804 if (allRTypes) return rhs;
11805
11806 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11807 EPI.ExtInfo = einfo;
11808 if (MergedFX)
11809 EPI.FunctionEffects = *MergedFX;
11810 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11811 }
11812
11813 if (allLTypes) return lhs;
11814 if (allRTypes) return rhs;
11815 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11816}
11817
11818/// Given that we have an enum type and a non-enum type, try to merge them.
11819static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11820 QualType other, bool isBlockReturnType) {
11821 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11822 // a signed integer type, or an unsigned integer type.
11823 // Compatibility is based on the underlying type, not the promotion
11824 // type.
11825 QualType underlyingType =
11826 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11827 if (underlyingType.isNull())
11828 return {};
11829 if (Context.hasSameType(T1: underlyingType, T2: other))
11830 return other;
11831
11832 // In block return types, we're more permissive and accept any
11833 // integral type of the same size.
11834 if (isBlockReturnType && other->isIntegerType() &&
11835 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11836 return other;
11837
11838 return {};
11839}
11840
11841QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11842 // C17 and earlier and C++ disallow two tag definitions within the same TU
11843 // from being compatible.
11844 if (LangOpts.CPlusPlus || !LangOpts.C23)
11845 return {};
11846
11847 // Nameless tags are comparable only within outer definitions. At the top
11848 // level they are not comparable.
11849 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11850 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11851 return {};
11852
11853 // C23, on the other hand, requires the members to be "the same enough", so
11854 // we use a structural equivalence check.
11855 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11856 StructuralEquivalenceContext Ctx(
11857 getLangOpts(), *this, *this, NonEquivalentDecls,
11858 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11859 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11860 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11861}
11862
11863std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11864 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11865 bool BlockReturnType, bool IsConditionalOperator) {
11866 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11867 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11868
11869 if (!LHSOBT && !RHSOBT)
11870 return std::nullopt;
11871
11872 if (LHSOBT) {
11873 if (RHSOBT) {
11874 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11875 return QualType();
11876
11877 QualType MergedUnderlying = mergeTypes(
11878 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11879 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11880
11881 if (MergedUnderlying.isNull())
11882 return QualType();
11883
11884 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11885 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11886 return getCommonSugaredType(X: LHS, Y: RHS);
11887 return getOverflowBehaviorType(
11888 Kind: LHSOBT->getBehaviorKind(),
11889 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11890 }
11891
11892 // For different underlying types that successfully merge, wrap the
11893 // merged underlying type with the common overflow behavior
11894 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11895 Underlying: MergedUnderlying);
11896 }
11897 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11898 Unqualified, BlockReturnType, IsConditionalOperator);
11899 }
11900
11901 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11902 Unqualified, BlockReturnType, IsConditionalOperator);
11903}
11904
11905QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11906 bool Unqualified, bool BlockReturnType,
11907 bool IsConditionalOperator) {
11908 // For C++ we will not reach this code with reference types (see below),
11909 // for OpenMP variant call overloading we might.
11910 //
11911 // C++ [expr]: If an expression initially has the type "reference to T", the
11912 // type is adjusted to "T" prior to any further analysis, the expression
11913 // designates the object or function denoted by the reference, and the
11914 // expression is an lvalue unless the reference is an rvalue reference and
11915 // the expression is a function call (possibly inside parentheses).
11916 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11917 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11918 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11919 LHS->getTypeClass() == RHS->getTypeClass())
11920 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11921 OfBlockPointer, Unqualified, BlockReturnType);
11922 if (LHSRefTy || RHSRefTy)
11923 return {};
11924
11925 if (std::optional<QualType> MergedOBT =
11926 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11927 BlockReturnType, IsConditionalOperator))
11928 return *MergedOBT;
11929
11930 if (Unqualified) {
11931 LHS = LHS.getUnqualifiedType();
11932 RHS = RHS.getUnqualifiedType();
11933 }
11934
11935 QualType LHSCan = getCanonicalType(T: LHS),
11936 RHSCan = getCanonicalType(T: RHS);
11937
11938 // If two types are identical, they are compatible.
11939 if (LHSCan == RHSCan)
11940 return LHS;
11941
11942 // If the qualifiers are different, the types aren't compatible... mostly.
11943 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11944 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11945 if (LQuals != RQuals) {
11946 // If any of these qualifiers are different, we have a type
11947 // mismatch.
11948 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11949 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11950 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11951 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
11952 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11953 return {};
11954
11955 // Exactly one GC qualifier difference is allowed: __strong is
11956 // okay if the other type has no GC qualifier but is an Objective
11957 // C object pointer (i.e. implicitly strong by default). We fix
11958 // this by pretending that the unqualified type was actually
11959 // qualified __strong.
11960 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11961 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11962 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11963
11964 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11965 return {};
11966
11967 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11968 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
11969 }
11970 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11971 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
11972 }
11973 return {};
11974 }
11975
11976 // Okay, qualifiers are equal.
11977
11978 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11979 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11980
11981 // We want to consider the two function types to be the same for these
11982 // comparisons, just force one to the other.
11983 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11984 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11985
11986 // Same as above for arrays
11987 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11988 LHSClass = Type::ConstantArray;
11989 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11990 RHSClass = Type::ConstantArray;
11991
11992 // ObjCInterfaces are just specialized ObjCObjects.
11993 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11994 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11995
11996 // Canonicalize ExtVector -> Vector.
11997 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11998 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11999
12000 // If the canonical type classes don't match.
12001 if (LHSClass != RHSClass) {
12002 // Note that we only have special rules for turning block enum
12003 // returns into block int returns, not vice-versa.
12004 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12005 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12006 }
12007 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12008 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12009 }
12010 // allow block pointer type to match an 'id' type.
12011 if (OfBlockPointer && !BlockReturnType) {
12012 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12013 return LHS;
12014 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12015 return RHS;
12016 }
12017 // Allow __auto_type to match anything; it merges to the type with more
12018 // information.
12019 if (const auto *AT = LHS->getAs<AutoType>()) {
12020 if (!AT->isDeduced() && AT->isGNUAutoType())
12021 return RHS;
12022 }
12023 if (const auto *AT = RHS->getAs<AutoType>()) {
12024 if (!AT->isDeduced() && AT->isGNUAutoType())
12025 return LHS;
12026 }
12027 return {};
12028 }
12029
12030 // The canonical type classes match.
12031 switch (LHSClass) {
12032#define TYPE(Class, Base)
12033#define ABSTRACT_TYPE(Class, Base)
12034#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12035#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12036#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12037#include "clang/AST/TypeNodes.inc"
12038 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12039
12040 case Type::Auto:
12041 case Type::DeducedTemplateSpecialization:
12042 case Type::LValueReference:
12043 case Type::RValueReference:
12044 case Type::MemberPointer:
12045 llvm_unreachable("C++ should never be in mergeTypes");
12046
12047 case Type::ObjCInterface:
12048 case Type::IncompleteArray:
12049 case Type::VariableArray:
12050 case Type::FunctionProto:
12051 case Type::ExtVector:
12052 case Type::OverflowBehavior:
12053 llvm_unreachable("Types are eliminated above");
12054
12055 case Type::Pointer:
12056 {
12057 // Merge two pointer types, while trying to preserve typedef info
12058 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12059 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12060 if (Unqualified) {
12061 LHSPointee = LHSPointee.getUnqualifiedType();
12062 RHSPointee = RHSPointee.getUnqualifiedType();
12063 }
12064 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12065 Unqualified);
12066 if (ResultType.isNull())
12067 return {};
12068 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12069 return LHS;
12070 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12071 return RHS;
12072 return getPointerType(T: ResultType);
12073 }
12074 case Type::BlockPointer:
12075 {
12076 // Merge two block pointer types, while trying to preserve typedef info
12077 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12078 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12079 if (Unqualified) {
12080 LHSPointee = LHSPointee.getUnqualifiedType();
12081 RHSPointee = RHSPointee.getUnqualifiedType();
12082 }
12083 if (getLangOpts().OpenCL) {
12084 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12085 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12086 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12087 // 6.12.5) thus the following check is asymmetric.
12088 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12089 return {};
12090 LHSPteeQual.removeAddressSpace();
12091 RHSPteeQual.removeAddressSpace();
12092 LHSPointee =
12093 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12094 RHSPointee =
12095 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12096 }
12097 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12098 Unqualified);
12099 if (ResultType.isNull())
12100 return {};
12101 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12102 return LHS;
12103 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12104 return RHS;
12105 return getBlockPointerType(T: ResultType);
12106 }
12107 case Type::Atomic:
12108 {
12109 // Merge two pointer types, while trying to preserve typedef info
12110 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12111 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12112 if (Unqualified) {
12113 LHSValue = LHSValue.getUnqualifiedType();
12114 RHSValue = RHSValue.getUnqualifiedType();
12115 }
12116 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12117 Unqualified);
12118 if (ResultType.isNull())
12119 return {};
12120 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12121 return LHS;
12122 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12123 return RHS;
12124 return getAtomicType(T: ResultType);
12125 }
12126 case Type::ConstantArray:
12127 {
12128 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12129 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12130 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12131 return {};
12132
12133 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12134 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12135 if (Unqualified) {
12136 LHSElem = LHSElem.getUnqualifiedType();
12137 RHSElem = RHSElem.getUnqualifiedType();
12138 }
12139
12140 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12141 if (ResultType.isNull())
12142 return {};
12143
12144 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12145 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12146
12147 // If either side is a variable array, and both are complete, check whether
12148 // the current dimension is definite.
12149 if (LVAT || RVAT) {
12150 auto SizeFetch = [this](const VariableArrayType* VAT,
12151 const ConstantArrayType* CAT)
12152 -> std::pair<bool,llvm::APInt> {
12153 if (VAT) {
12154 std::optional<llvm::APSInt> TheInt;
12155 Expr *E = VAT->getSizeExpr();
12156 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12157 return std::make_pair(x: true, y&: *TheInt);
12158 return std::make_pair(x: false, y: llvm::APSInt());
12159 }
12160 if (CAT)
12161 return std::make_pair(x: true, y: CAT->getSize());
12162 return std::make_pair(x: false, y: llvm::APInt());
12163 };
12164
12165 bool HaveLSize, HaveRSize;
12166 llvm::APInt LSize, RSize;
12167 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12168 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12169 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12170 return {}; // Definite, but unequal, array dimension
12171 }
12172
12173 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12174 return LHS;
12175 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12176 return RHS;
12177 if (LCAT)
12178 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12179 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12180 if (RCAT)
12181 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12182 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12183 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12184 return LHS;
12185 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12186 return RHS;
12187 if (LVAT) {
12188 // FIXME: This isn't correct! But tricky to implement because
12189 // the array's size has to be the size of LHS, but the type
12190 // has to be different.
12191 return LHS;
12192 }
12193 if (RVAT) {
12194 // FIXME: This isn't correct! But tricky to implement because
12195 // the array's size has to be the size of RHS, but the type
12196 // has to be different.
12197 return RHS;
12198 }
12199 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12200 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12201 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12202 }
12203 case Type::FunctionNoProto:
12204 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12205 /*AllowCXX=*/false, IsConditionalOperator);
12206 case Type::Record:
12207 case Type::Enum:
12208 return mergeTagDefinitions(LHS, RHS);
12209 case Type::Builtin:
12210 // Only exactly equal builtin types are compatible, which is tested above.
12211 return {};
12212 case Type::Complex:
12213 // Distinct complex types are incompatible.
12214 return {};
12215 case Type::Vector:
12216 // FIXME: The merged type should be an ExtVector!
12217 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12218 RHS: RHSCan->castAs<VectorType>()))
12219 return LHS;
12220 return {};
12221 case Type::ConstantMatrix:
12222 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12223 RHS: RHSCan->castAs<ConstantMatrixType>()))
12224 return LHS;
12225 return {};
12226 case Type::ObjCObject: {
12227 // Check if the types are assignment compatible.
12228 // FIXME: This should be type compatibility, e.g. whether
12229 // "LHS x; RHS x;" at global scope is legal.
12230 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12231 RHS: RHS->castAs<ObjCObjectType>()))
12232 return LHS;
12233 return {};
12234 }
12235 case Type::ObjCObjectPointer:
12236 if (OfBlockPointer) {
12237 if (canAssignObjCInterfacesInBlockPointer(
12238 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12239 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12240 return LHS;
12241 return {};
12242 }
12243 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12244 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12245 return LHS;
12246 return {};
12247 case Type::Pipe:
12248 assert(LHS != RHS &&
12249 "Equivalent pipe types should have already been handled!");
12250 return {};
12251 case Type::ArrayParameter:
12252 assert(LHS != RHS &&
12253 "Equivalent ArrayParameter types should have already been handled!");
12254 return {};
12255 case Type::BitInt: {
12256 // Merge two bit-precise int types, while trying to preserve typedef info.
12257 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12258 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12259 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12260 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12261
12262 // Like unsigned/int, shouldn't have a type if they don't match.
12263 if (LHSUnsigned != RHSUnsigned)
12264 return {};
12265
12266 if (LHSBits != RHSBits)
12267 return {};
12268 return LHS;
12269 }
12270 case Type::HLSLAttributedResource: {
12271 const HLSLAttributedResourceType *LHSTy =
12272 LHS->castAs<HLSLAttributedResourceType>();
12273 const HLSLAttributedResourceType *RHSTy =
12274 RHS->castAs<HLSLAttributedResourceType>();
12275 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12276 LHSTy->getWrappedType()->isHLSLResourceType() &&
12277 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12278
12279 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12280 LHSTy->getContainedType() == RHSTy->getContainedType())
12281 return LHS;
12282 return {};
12283 }
12284 case Type::HLSLInlineSpirv:
12285 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12286 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12287
12288 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12289 LHSTy->getSize() == RHSTy->getSize() &&
12290 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12291 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12292 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12293 return {};
12294
12295 return LHS;
12296 }
12297 return {};
12298 }
12299
12300 llvm_unreachable("Invalid Type::Class!");
12301}
12302
12303bool ASTContext::mergeExtParameterInfo(
12304 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12305 bool &CanUseFirst, bool &CanUseSecond,
12306 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12307 assert(NewParamInfos.empty() && "param info list not empty");
12308 CanUseFirst = CanUseSecond = true;
12309 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12310 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12311
12312 // Fast path: if the first type doesn't have ext parameter infos,
12313 // we match if and only if the second type also doesn't have them.
12314 if (!FirstHasInfo && !SecondHasInfo)
12315 return true;
12316
12317 bool NeedParamInfo = false;
12318 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12319 : SecondFnType->getExtParameterInfos().size();
12320
12321 for (size_t I = 0; I < E; ++I) {
12322 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12323 if (FirstHasInfo)
12324 FirstParam = FirstFnType->getExtParameterInfo(I);
12325 if (SecondHasInfo)
12326 SecondParam = SecondFnType->getExtParameterInfo(I);
12327
12328 // Cannot merge unless everything except the noescape flag matches.
12329 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12330 return false;
12331
12332 bool FirstNoEscape = FirstParam.isNoEscape();
12333 bool SecondNoEscape = SecondParam.isNoEscape();
12334 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12335 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12336 if (NewParamInfos.back().getOpaqueValue())
12337 NeedParamInfo = true;
12338 if (FirstNoEscape != IsNoEscape)
12339 CanUseFirst = false;
12340 if (SecondNoEscape != IsNoEscape)
12341 CanUseSecond = false;
12342 }
12343
12344 if (!NeedParamInfo)
12345 NewParamInfos.clear();
12346
12347 return true;
12348}
12349
12350void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12351 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12352 It->second = nullptr;
12353 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12354 ResetObjCLayout(D: SubClass);
12355 }
12356}
12357
12358/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12359/// 'RHS' attributes and returns the merged version; including for function
12360/// return types.
12361QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12362 QualType LHSCan = getCanonicalType(T: LHS),
12363 RHSCan = getCanonicalType(T: RHS);
12364 // If two types are identical, they are compatible.
12365 if (LHSCan == RHSCan)
12366 return LHS;
12367 if (RHSCan->isFunctionType()) {
12368 if (!LHSCan->isFunctionType())
12369 return {};
12370 QualType OldReturnType =
12371 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12372 QualType NewReturnType =
12373 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12374 QualType ResReturnType =
12375 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12376 if (ResReturnType.isNull())
12377 return {};
12378 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12379 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12380 // In either case, use OldReturnType to build the new function type.
12381 const auto *F = LHS->castAs<FunctionType>();
12382 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12383 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12384 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12385 QualType ResultType =
12386 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12387 return ResultType;
12388 }
12389 }
12390 return {};
12391 }
12392
12393 // If the qualifiers are different, the types can still be merged.
12394 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12395 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12396
12397 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12398 // Reject immediately, if anything but the GC qualifiers is different.
12399 return {};
12400 }
12401
12402 if (LQuals != RQuals) {
12403 // Exactly one GC qualifier difference is allowed: __strong is
12404 // okay if the other type has no GC qualifier but is an Objective
12405 // C object pointer (i.e. implicitly strong by default). We fix
12406 // this by pretending that the unqualified type was actually
12407 // qualified __strong.
12408 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12409 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12410 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12411
12412 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12413 return {};
12414
12415 if (GC_L == Qualifiers::Strong)
12416 return LHS;
12417 if (GC_R == Qualifiers::Strong)
12418 return RHS;
12419 return {};
12420 }
12421
12422 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12423 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12424 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12425 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12426 if (ResQT == LHSBaseQT)
12427 return LHS;
12428 if (ResQT == RHSBaseQT)
12429 return RHS;
12430 }
12431 return {};
12432}
12433
12434//===----------------------------------------------------------------------===//
12435// Integer Predicates
12436//===----------------------------------------------------------------------===//
12437
12438unsigned ASTContext::getIntWidth(QualType T) const {
12439 if (const auto *ED = T->getAsEnumDecl())
12440 T = ED->getIntegerType();
12441 if (T->isBooleanType())
12442 return 1;
12443 if (const auto *EIT = T->getAs<BitIntType>())
12444 return EIT->getNumBits();
12445 // For builtin types, just use the standard type sizing method
12446 return (unsigned)getTypeSize(T);
12447}
12448
12449QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12450 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12451 T->isFixedPointType()) &&
12452 "Unexpected type");
12453
12454 // Turn <4 x signed int> -> <4 x unsigned int>
12455 if (const auto *VTy = T->getAs<VectorType>())
12456 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12457 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12458
12459 // For _BitInt, return an unsigned _BitInt with same width.
12460 if (const auto *EITy = T->getAs<BitIntType>())
12461 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12462
12463 // For the overflow behavior types, construct a new unsigned variant
12464 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12465 return getOverflowBehaviorType(
12466 Kind: OBT->getBehaviorKind(),
12467 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12468
12469 // For enums, get the underlying integer type of the enum, and let the general
12470 // integer type signchanging code handle it.
12471 if (const auto *ED = T->getAsEnumDecl())
12472 T = ED->getIntegerType();
12473
12474 switch (T->castAs<BuiltinType>()->getKind()) {
12475 case BuiltinType::Char_U:
12476 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12477 case BuiltinType::Char_S:
12478 case BuiltinType::SChar:
12479 case BuiltinType::Char8:
12480 return UnsignedCharTy;
12481 case BuiltinType::Short:
12482 return UnsignedShortTy;
12483 case BuiltinType::Int:
12484 return UnsignedIntTy;
12485 case BuiltinType::Long:
12486 return UnsignedLongTy;
12487 case BuiltinType::LongLong:
12488 return UnsignedLongLongTy;
12489 case BuiltinType::Int128:
12490 return UnsignedInt128Ty;
12491 // wchar_t is special. It is either signed or not, but when it's signed,
12492 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12493 // version of its underlying type instead.
12494 case BuiltinType::WChar_S:
12495 return getUnsignedWCharType();
12496
12497 case BuiltinType::ShortAccum:
12498 return UnsignedShortAccumTy;
12499 case BuiltinType::Accum:
12500 return UnsignedAccumTy;
12501 case BuiltinType::LongAccum:
12502 return UnsignedLongAccumTy;
12503 case BuiltinType::SatShortAccum:
12504 return SatUnsignedShortAccumTy;
12505 case BuiltinType::SatAccum:
12506 return SatUnsignedAccumTy;
12507 case BuiltinType::SatLongAccum:
12508 return SatUnsignedLongAccumTy;
12509 case BuiltinType::ShortFract:
12510 return UnsignedShortFractTy;
12511 case BuiltinType::Fract:
12512 return UnsignedFractTy;
12513 case BuiltinType::LongFract:
12514 return UnsignedLongFractTy;
12515 case BuiltinType::SatShortFract:
12516 return SatUnsignedShortFractTy;
12517 case BuiltinType::SatFract:
12518 return SatUnsignedFractTy;
12519 case BuiltinType::SatLongFract:
12520 return SatUnsignedLongFractTy;
12521 default:
12522 assert((T->hasUnsignedIntegerRepresentation() ||
12523 T->isUnsignedFixedPointType()) &&
12524 "Unexpected signed integer or fixed point type");
12525 return T;
12526 }
12527}
12528
12529QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12530 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12531 T->isFixedPointType()) &&
12532 "Unexpected type");
12533
12534 // Turn <4 x unsigned int> -> <4 x signed int>
12535 if (const auto *VTy = T->getAs<VectorType>())
12536 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12537 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12538
12539 // For _BitInt, return a signed _BitInt with same width.
12540 if (const auto *EITy = T->getAs<BitIntType>())
12541 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12542
12543 // For enums, get the underlying integer type of the enum, and let the general
12544 // integer type signchanging code handle it.
12545 if (const auto *ED = T->getAsEnumDecl())
12546 T = ED->getIntegerType();
12547
12548 switch (T->castAs<BuiltinType>()->getKind()) {
12549 case BuiltinType::Char_S:
12550 // Plain `char` is mapped to `signed char` even if it's already signed
12551 case BuiltinType::Char_U:
12552 case BuiltinType::UChar:
12553 case BuiltinType::Char8:
12554 return SignedCharTy;
12555 case BuiltinType::UShort:
12556 return ShortTy;
12557 case BuiltinType::UInt:
12558 return IntTy;
12559 case BuiltinType::ULong:
12560 return LongTy;
12561 case BuiltinType::ULongLong:
12562 return LongLongTy;
12563 case BuiltinType::UInt128:
12564 return Int128Ty;
12565 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12566 // there's no matching "signed wchar_t". Therefore we return the signed
12567 // version of its underlying type instead.
12568 case BuiltinType::WChar_U:
12569 return getSignedWCharType();
12570
12571 case BuiltinType::UShortAccum:
12572 return ShortAccumTy;
12573 case BuiltinType::UAccum:
12574 return AccumTy;
12575 case BuiltinType::ULongAccum:
12576 return LongAccumTy;
12577 case BuiltinType::SatUShortAccum:
12578 return SatShortAccumTy;
12579 case BuiltinType::SatUAccum:
12580 return SatAccumTy;
12581 case BuiltinType::SatULongAccum:
12582 return SatLongAccumTy;
12583 case BuiltinType::UShortFract:
12584 return ShortFractTy;
12585 case BuiltinType::UFract:
12586 return FractTy;
12587 case BuiltinType::ULongFract:
12588 return LongFractTy;
12589 case BuiltinType::SatUShortFract:
12590 return SatShortFractTy;
12591 case BuiltinType::SatUFract:
12592 return SatFractTy;
12593 case BuiltinType::SatULongFract:
12594 return SatLongFractTy;
12595 default:
12596 assert(
12597 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12598 "Unexpected signed integer or fixed point type");
12599 return T;
12600 }
12601}
12602
12603ASTMutationListener::~ASTMutationListener() = default;
12604
12605void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12606 QualType ReturnType) {}
12607
12608//===----------------------------------------------------------------------===//
12609// Builtin Type Computation
12610//===----------------------------------------------------------------------===//
12611
12612/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12613/// pointer over the consumed characters. This returns the resultant type. If
12614/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12615/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12616/// a vector of "i*".
12617///
12618/// RequiresICE is filled in on return to indicate whether the value is required
12619/// to be an Integer Constant Expression.
12620static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12621 ASTContext::GetBuiltinTypeError &Error,
12622 bool &RequiresICE,
12623 bool AllowTypeModifiers) {
12624 // Modifiers.
12625 int HowLong = 0;
12626 bool Signed = false, Unsigned = false;
12627 bool IsChar = false, IsShort = false;
12628 RequiresICE = false;
12629
12630 // Read the prefixed modifiers first.
12631 bool Done = false;
12632 #ifndef NDEBUG
12633 bool IsSpecial = false;
12634 #endif
12635 while (!Done) {
12636 switch (*Str++) {
12637 default: Done = true; --Str; break;
12638 case 'I':
12639 RequiresICE = true;
12640 break;
12641 case 'S':
12642 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12643 assert(!Signed && "Can't use 'S' modifier multiple times!");
12644 Signed = true;
12645 break;
12646 case 'U':
12647 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12648 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12649 Unsigned = true;
12650 break;
12651 case 'B':
12652 // This modifier represents int8 type (byte-width).
12653 assert(!IsSpecial &&
12654 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12655 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12656#ifndef NDEBUG
12657 IsSpecial = true;
12658#endif
12659 IsChar = true;
12660 break;
12661 case 'T':
12662 // This modifier represents int16 type (short-width).
12663 assert(!IsSpecial &&
12664 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12665 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12666#ifndef NDEBUG
12667 IsSpecial = true;
12668#endif
12669 IsShort = true;
12670 break;
12671 case 'L':
12672 assert(!IsSpecial &&
12673 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12674 assert(HowLong <= 2 && "Can't have LLLL modifier");
12675 ++HowLong;
12676 break;
12677 case 'N':
12678 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12679 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12680 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12681 #ifndef NDEBUG
12682 IsSpecial = true;
12683 #endif
12684 if (Context.getTargetInfo().getLongWidth() == 32)
12685 ++HowLong;
12686 break;
12687 case 'W':
12688 // This modifier represents int64 type.
12689 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12690 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12691 #ifndef NDEBUG
12692 IsSpecial = true;
12693 #endif
12694 switch (Context.getTargetInfo().getInt64Type()) {
12695 default:
12696 llvm_unreachable("Unexpected integer type");
12697 case TargetInfo::SignedLong:
12698 HowLong = 1;
12699 break;
12700 case TargetInfo::SignedLongLong:
12701 HowLong = 2;
12702 break;
12703 }
12704 break;
12705 case 'Z':
12706 // This modifier represents int32 type.
12707 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12708 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12709 #ifndef NDEBUG
12710 IsSpecial = true;
12711 #endif
12712 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12713 default:
12714 llvm_unreachable("Unexpected integer type");
12715 case TargetInfo::SignedInt:
12716 HowLong = 0;
12717 break;
12718 case TargetInfo::SignedLong:
12719 HowLong = 1;
12720 break;
12721 case TargetInfo::SignedLongLong:
12722 HowLong = 2;
12723 break;
12724 }
12725 break;
12726 case 'O':
12727 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12728 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12729 #ifndef NDEBUG
12730 IsSpecial = true;
12731 #endif
12732 if (Context.getLangOpts().OpenCL)
12733 HowLong = 1;
12734 else
12735 HowLong = 2;
12736 break;
12737 }
12738 }
12739
12740 QualType Type;
12741
12742 // Read the base type.
12743 switch (*Str++) {
12744 default:
12745 llvm_unreachable("Unknown builtin type letter!");
12746 case 'x':
12747 assert(HowLong == 0 && !Signed && !Unsigned &&
12748 "Bad modifiers used with 'x'!");
12749 Type = Context.Float16Ty;
12750 break;
12751 case 'y':
12752 assert(HowLong == 0 && !Signed && !Unsigned &&
12753 "Bad modifiers used with 'y'!");
12754 Type = Context.BFloat16Ty;
12755 break;
12756 case 'v':
12757 assert(HowLong == 0 && !Signed && !Unsigned &&
12758 "Bad modifiers used with 'v'!");
12759 Type = Context.VoidTy;
12760 break;
12761 case 'h':
12762 assert(HowLong == 0 && !Signed && !Unsigned &&
12763 "Bad modifiers used with 'h'!");
12764 Type = Context.HalfTy;
12765 break;
12766 case 'f':
12767 assert(HowLong == 0 && !Signed && !Unsigned &&
12768 "Bad modifiers used with 'f'!");
12769 Type = Context.FloatTy;
12770 break;
12771 case 'd':
12772 assert(HowLong < 3 && !Signed && !Unsigned &&
12773 "Bad modifiers used with 'd'!");
12774 if (HowLong == 1)
12775 Type = Context.LongDoubleTy;
12776 else if (HowLong == 2)
12777 Type = Context.Float128Ty;
12778 else
12779 Type = Context.DoubleTy;
12780 break;
12781 case 's':
12782 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12783 if (Unsigned)
12784 Type = Context.UnsignedShortTy;
12785 else
12786 Type = Context.ShortTy;
12787 break;
12788 case 'i':
12789 if (IsChar)
12790 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12791 else if (IsShort)
12792 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12793 else if (HowLong == 3)
12794 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12795 else if (HowLong == 2)
12796 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12797 else if (HowLong == 1)
12798 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12799 else
12800 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12801 break;
12802 case 'c':
12803 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12804 if (Signed)
12805 Type = Context.SignedCharTy;
12806 else if (Unsigned)
12807 Type = Context.UnsignedCharTy;
12808 else
12809 Type = Context.CharTy;
12810 break;
12811 case 'b': // boolean
12812 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12813 Type = Context.BoolTy;
12814 break;
12815 case 'z': // size_t.
12816 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12817 Type = Context.getSizeType();
12818 break;
12819 case 'w': // wchar_t.
12820 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12821 Type = Context.getWideCharType();
12822 break;
12823 case 'F':
12824 Type = Context.getCFConstantStringType();
12825 break;
12826 case 'G':
12827 Type = Context.getObjCIdType();
12828 break;
12829 case 'H':
12830 Type = Context.getObjCSelType();
12831 break;
12832 case 'M':
12833 Type = Context.getObjCSuperType();
12834 break;
12835 case 'a':
12836 Type = Context.getBuiltinVaListType();
12837 assert(!Type.isNull() && "builtin va list type not initialized!");
12838 break;
12839 case 'A':
12840 // This is a "reference" to a va_list; however, what exactly
12841 // this means depends on how va_list is defined. There are two
12842 // different kinds of va_list: ones passed by value, and ones
12843 // passed by reference. An example of a by-value va_list is
12844 // x86, where va_list is a char*. An example of by-ref va_list
12845 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12846 // we want this argument to be a char*&; for x86-64, we want
12847 // it to be a __va_list_tag*.
12848 Type = Context.getBuiltinVaListType();
12849 assert(!Type.isNull() && "builtin va list type not initialized!");
12850 if (Type->isArrayType())
12851 Type = Context.getArrayDecayedType(Ty: Type);
12852 else
12853 Type = Context.getLValueReferenceType(T: Type);
12854 break;
12855 case 'q': {
12856 char *End;
12857 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12858 assert(End != Str && "Missing vector size");
12859 Str = End;
12860
12861 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12862 RequiresICE, AllowTypeModifiers: false);
12863 assert(!RequiresICE && "Can't require vector ICE");
12864
12865 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12866 break;
12867 }
12868 case 'Q': {
12869 switch (*Str++) {
12870 case 'a': {
12871 Type = Context.SveCountTy;
12872 break;
12873 }
12874 case 'b': {
12875 Type = Context.AMDGPUBufferRsrcTy;
12876 break;
12877 }
12878 case 'c': {
12879 Type = Context.AMDGPUFeaturePredicateTy;
12880 break;
12881 }
12882 case 't': {
12883 Type = Context.AMDGPUTextureTy;
12884 break;
12885 }
12886 case 'r': {
12887 Type = Context.HLSLResourceTy;
12888 break;
12889 }
12890 default:
12891 llvm_unreachable("Unexpected target builtin type");
12892 }
12893 break;
12894 }
12895 case 'V': {
12896 char *End;
12897 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12898 assert(End != Str && "Missing vector size");
12899 Str = End;
12900
12901 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12902 RequiresICE, AllowTypeModifiers: false);
12903 assert(!RequiresICE && "Can't require vector ICE");
12904
12905 // TODO: No way to make AltiVec vectors in builtins yet.
12906 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12907 break;
12908 }
12909 case 'E': {
12910 char *End;
12911
12912 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12913 assert(End != Str && "Missing vector size");
12914
12915 Str = End;
12916
12917 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12918 AllowTypeModifiers: false);
12919 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12920 break;
12921 }
12922 case 'X': {
12923 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12924 AllowTypeModifiers: false);
12925 assert(!RequiresICE && "Can't require complex ICE");
12926 Type = Context.getComplexType(T: ElementType);
12927 break;
12928 }
12929 case 'Y':
12930 Type = Context.getPointerDiffType();
12931 break;
12932 case 'P':
12933 Type = Context.getFILEType();
12934 if (Type.isNull()) {
12935 Error = ASTContext::GE_Missing_stdio;
12936 return {};
12937 }
12938 break;
12939 case 'J':
12940 if (Signed)
12941 Type = Context.getsigjmp_bufType();
12942 else
12943 Type = Context.getjmp_bufType();
12944
12945 if (Type.isNull()) {
12946 Error = ASTContext::GE_Missing_setjmp;
12947 return {};
12948 }
12949 break;
12950 case 'K':
12951 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12952 Type = Context.getucontext_tType();
12953
12954 if (Type.isNull()) {
12955 Error = ASTContext::GE_Missing_ucontext;
12956 return {};
12957 }
12958 break;
12959 case 'p':
12960 Type = Context.getProcessIDType();
12961 break;
12962 case 'm':
12963 Type = Context.MFloat8Ty;
12964 break;
12965 }
12966
12967 // If there are modifiers and if we're allowed to parse them, go for it.
12968 Done = !AllowTypeModifiers;
12969 while (!Done) {
12970 switch (char c = *Str++) {
12971 default: Done = true; --Str; break;
12972 case '*':
12973 case '&': {
12974 // Both pointers and references can have their pointee types
12975 // qualified with an address space.
12976 char *End;
12977 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
12978 if (End != Str) {
12979 // Note AddrSpace == 0 is not the same as an unspecified address space.
12980 Type = Context.getAddrSpaceQualType(
12981 T: Type,
12982 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
12983 Str = End;
12984 }
12985 if (c == '*')
12986 Type = Context.getPointerType(T: Type);
12987 else
12988 Type = Context.getLValueReferenceType(T: Type);
12989 break;
12990 }
12991 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12992 case 'C':
12993 Type = Type.withConst();
12994 break;
12995 case 'D':
12996 Type = Context.getVolatileType(T: Type);
12997 break;
12998 case 'R':
12999 Type = Type.withRestrict();
13000 break;
13001 }
13002 }
13003
13004 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13005 "Integer constant 'I' type must be an integer");
13006
13007 return Type;
13008}
13009
13010// On some targets such as PowerPC, some of the builtins are defined with custom
13011// type descriptors for target-dependent types. These descriptors are decoded in
13012// other functions, but it may be useful to be able to fall back to default
13013// descriptor decoding to define builtins mixing target-dependent and target-
13014// independent types. This function allows decoding one type descriptor with
13015// default decoding.
13016QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13017 GetBuiltinTypeError &Error, bool &RequireICE,
13018 bool AllowTypeModifiers) const {
13019 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13020}
13021
13022/// GetBuiltinType - Return the type for the specified builtin.
13023QualType ASTContext::GetBuiltinType(unsigned Id,
13024 GetBuiltinTypeError &Error,
13025 unsigned *IntegerConstantArgs) const {
13026 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13027 if (TypeStr[0] == '\0') {
13028 Error = GE_Missing_type;
13029 return {};
13030 }
13031
13032 SmallVector<QualType, 8> ArgTypes;
13033
13034 bool RequiresICE = false;
13035 Error = GE_None;
13036 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13037 RequiresICE, AllowTypeModifiers: true);
13038 if (Error != GE_None)
13039 return {};
13040
13041 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13042
13043 while (TypeStr[0] && TypeStr[0] != '.') {
13044 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13045 if (Error != GE_None)
13046 return {};
13047
13048 // If this argument is required to be an IntegerConstantExpression and the
13049 // caller cares, fill in the bitmask we return.
13050 if (RequiresICE && IntegerConstantArgs)
13051 *IntegerConstantArgs |= 1 << ArgTypes.size();
13052
13053 // Do array -> pointer decay. The builtin should use the decayed type.
13054 if (Ty->isArrayType())
13055 Ty = getArrayDecayedType(Ty);
13056
13057 ArgTypes.push_back(Elt: Ty);
13058 }
13059
13060 if (Id == Builtin::BI__GetExceptionInfo)
13061 return {};
13062
13063 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13064 "'.' should only occur at end of builtin type list!");
13065
13066 bool Variadic = (TypeStr[0] == '.');
13067
13068 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13069 if (BuiltinInfo.isNoReturn(ID: Id))
13070 EI = EI.withNoReturn(noReturn: true);
13071
13072 // We really shouldn't be making a no-proto type here.
13073 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13074 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13075
13076 FunctionProtoType::ExtProtoInfo EPI;
13077 EPI.ExtInfo = EI;
13078 EPI.Variadic = Variadic;
13079 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13080 EPI.ExceptionSpec.Type =
13081 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13082
13083 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13084}
13085
13086static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13087 const FunctionDecl *FD) {
13088 if (!FD->isExternallyVisible())
13089 return GVA_Internal;
13090
13091 // Non-user-provided functions get emitted as weak definitions with every
13092 // use, no matter whether they've been explicitly instantiated etc.
13093 if (!FD->isUserProvided())
13094 return GVA_DiscardableODR;
13095
13096 GVALinkage External;
13097 switch (FD->getTemplateSpecializationKind()) {
13098 case TSK_Undeclared:
13099 case TSK_ExplicitSpecialization:
13100 External = GVA_StrongExternal;
13101 break;
13102
13103 case TSK_ExplicitInstantiationDefinition:
13104 return GVA_StrongODR;
13105
13106 // C++11 [temp.explicit]p10:
13107 // [ Note: The intent is that an inline function that is the subject of
13108 // an explicit instantiation declaration will still be implicitly
13109 // instantiated when used so that the body can be considered for
13110 // inlining, but that no out-of-line copy of the inline function would be
13111 // generated in the translation unit. -- end note ]
13112 case TSK_ExplicitInstantiationDeclaration:
13113 return GVA_AvailableExternally;
13114
13115 case TSK_ImplicitInstantiation:
13116 External = GVA_DiscardableODR;
13117 break;
13118 }
13119
13120 if (!FD->isInlined())
13121 return External;
13122
13123 if ((!Context.getLangOpts().CPlusPlus &&
13124 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13125 !FD->hasAttr<DLLExportAttr>()) ||
13126 FD->hasAttr<GNUInlineAttr>()) {
13127 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13128
13129 // GNU or C99 inline semantics. Determine whether this symbol should be
13130 // externally visible.
13131 if (auto *Def = FD->getDefinition();
13132 Def && Def->isInlineDefinitionExternallyVisible())
13133 return External;
13134
13135 // C99 inline semantics, where the symbol is not externally visible.
13136 return GVA_AvailableExternally;
13137 }
13138
13139 // Functions specified with extern and inline in -fms-compatibility mode
13140 // forcibly get emitted. While the body of the function cannot be later
13141 // replaced, the function definition cannot be discarded.
13142 if (FD->isMSExternInline())
13143 return GVA_StrongODR;
13144
13145 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13146 isa<CXXConstructorDecl>(Val: FD) &&
13147 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13148 !FD->hasAttr<DLLExportAttr>()) {
13149 // Both Clang and MSVC implement inherited constructors as forwarding
13150 // thunks that delegate to the base constructor. Keep non-dllexport
13151 // inheriting constructor thunks internal since they are not needed
13152 // outside the translation unit.
13153 //
13154 // dllexport inherited constructors are exempted so they are externally
13155 // visible, matching MSVC's export behavior. Inherited constructors
13156 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13157 // cleanup types) are excluded from export in Sema to avoid silent
13158 // runtime mismatches.
13159 return GVA_Internal;
13160 }
13161
13162 return GVA_DiscardableODR;
13163}
13164
13165static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13166 const Decl *D, GVALinkage L) {
13167 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13168 // dllexport/dllimport on inline functions.
13169 if (D->hasAttr<DLLImportAttr>()) {
13170 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13171 return GVA_AvailableExternally;
13172 } else if (D->hasAttr<DLLExportAttr>()) {
13173 if (L == GVA_DiscardableODR)
13174 return GVA_StrongODR;
13175 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13176 // Device-side functions with __global__ attribute must always be
13177 // visible externally so they can be launched from host.
13178 if (D->hasAttr<CUDAGlobalAttr>() &&
13179 (L == GVA_DiscardableODR || L == GVA_Internal))
13180 return GVA_StrongODR;
13181 // Single source offloading languages like CUDA/HIP need to be able to
13182 // access static device variables from host code of the same compilation
13183 // unit. This is done by externalizing the static variable with a shared
13184 // name between the host and device compilation which is the same for the
13185 // same compilation unit whereas different among different compilation
13186 // units.
13187 if (Context.shouldExternalize(D))
13188 return GVA_StrongExternal;
13189 }
13190 return L;
13191}
13192
13193/// Adjust the GVALinkage for a declaration based on what an external AST source
13194/// knows about whether there can be other definitions of this declaration.
13195static GVALinkage
13196adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13197 GVALinkage L) {
13198 ExternalASTSource *Source = Ctx.getExternalSource();
13199 if (!Source)
13200 return L;
13201
13202 switch (Source->hasExternalDefinitions(D)) {
13203 case ExternalASTSource::EK_Never:
13204 // Other translation units rely on us to provide the definition.
13205 if (L == GVA_DiscardableODR)
13206 return GVA_StrongODR;
13207 break;
13208
13209 case ExternalASTSource::EK_Always:
13210 return GVA_AvailableExternally;
13211
13212 case ExternalASTSource::EK_ReplyHazy:
13213 break;
13214 }
13215 return L;
13216}
13217
13218GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13219 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13220 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13221 L: basicGVALinkageForFunction(Context: *this, FD)));
13222}
13223
13224static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13225 const VarDecl *VD) {
13226 // As an extension for interactive REPLs, make sure constant variables are
13227 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13228 // marking them as internal.
13229 if (Context.getLangOpts().CPlusPlus &&
13230 Context.getLangOpts().IncrementalExtensions &&
13231 VD->getType().isConstQualified() &&
13232 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13233 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13234 return GVA_DiscardableODR;
13235
13236 if (!VD->isExternallyVisible())
13237 return GVA_Internal;
13238
13239 if (VD->isStaticLocal()) {
13240 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13241 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13242 LexicalContext = LexicalContext->getLexicalParent();
13243
13244 // ObjC Blocks can create local variables that don't have a FunctionDecl
13245 // LexicalContext.
13246 if (!LexicalContext)
13247 return GVA_DiscardableODR;
13248
13249 // Otherwise, let the static local variable inherit its linkage from the
13250 // nearest enclosing function.
13251 auto StaticLocalLinkage =
13252 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13253
13254 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13255 // be emitted in any object with references to the symbol for the object it
13256 // contains, whether inline or out-of-line."
13257 // Similar behavior is observed with MSVC. An alternative ABI could use
13258 // StrongODR/AvailableExternally to match the function, but none are
13259 // known/supported currently.
13260 if (StaticLocalLinkage == GVA_StrongODR ||
13261 StaticLocalLinkage == GVA_AvailableExternally)
13262 return GVA_DiscardableODR;
13263 return StaticLocalLinkage;
13264 }
13265
13266 // MSVC treats in-class initialized static data members as definitions.
13267 // By giving them non-strong linkage, out-of-line definitions won't
13268 // cause link errors.
13269 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13270 return GVA_DiscardableODR;
13271
13272 // Most non-template variables have strong linkage; inline variables are
13273 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13274 GVALinkage StrongLinkage;
13275 switch (Context.getInlineVariableDefinitionKind(VD)) {
13276 case ASTContext::InlineVariableDefinitionKind::None:
13277 StrongLinkage = GVA_StrongExternal;
13278 break;
13279 case ASTContext::InlineVariableDefinitionKind::Weak:
13280 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13281 StrongLinkage = GVA_DiscardableODR;
13282 break;
13283 case ASTContext::InlineVariableDefinitionKind::Strong:
13284 StrongLinkage = GVA_StrongODR;
13285 break;
13286 }
13287
13288 switch (VD->getTemplateSpecializationKind()) {
13289 case TSK_Undeclared:
13290 return StrongLinkage;
13291
13292 case TSK_ExplicitSpecialization:
13293 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13294 VD->isStaticDataMember()
13295 ? GVA_StrongODR
13296 : StrongLinkage;
13297
13298 case TSK_ExplicitInstantiationDefinition:
13299 return GVA_StrongODR;
13300
13301 case TSK_ExplicitInstantiationDeclaration:
13302 return GVA_AvailableExternally;
13303
13304 case TSK_ImplicitInstantiation:
13305 return GVA_DiscardableODR;
13306 }
13307
13308 llvm_unreachable("Invalid Linkage!");
13309}
13310
13311GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13312 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13313 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13314 L: basicGVALinkageForVariable(Context: *this, VD)));
13315}
13316
13317bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13318 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13319 if (!VD->isFileVarDecl())
13320 return false;
13321 // Global named register variables (GNU extension) are never emitted.
13322 if (VD->getStorageClass() == SC_Register)
13323 return false;
13324 if (VD->getDescribedVarTemplate() ||
13325 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13326 return false;
13327 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13328 // We never need to emit an uninstantiated function template.
13329 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13330 return false;
13331 } else if (isa<PragmaCommentDecl>(Val: D))
13332 return true;
13333 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13334 return true;
13335 else if (isa<OMPRequiresDecl>(Val: D))
13336 return true;
13337 else if (isa<OMPThreadPrivateDecl>(Val: D))
13338 return !D->getDeclContext()->isDependentContext();
13339 else if (isa<OMPAllocateDecl>(Val: D))
13340 return !D->getDeclContext()->isDependentContext();
13341 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13342 return !D->getDeclContext()->isDependentContext();
13343 else if (isa<ImportDecl>(Val: D))
13344 return true;
13345 else
13346 return false;
13347
13348 // If this is a member of a class template, we do not need to emit it.
13349 if (D->getDeclContext()->isDependentContext())
13350 return false;
13351
13352 // Weak references don't produce any output by themselves.
13353 if (D->hasAttr<WeakRefAttr>())
13354 return false;
13355
13356 // SYCL device compilation requires that functions defined with the
13357 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13358 // other entities are emitted only if they are used by a function
13359 // defined with one of those attributes.
13360 if (LangOpts.SYCLIsDevice)
13361 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13362 D->hasAttr<SYCLExternalAttr>());
13363
13364 // Aliases and used decls are required.
13365 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13366 return true;
13367
13368 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13369 // Forward declarations aren't required.
13370 if (!FD->doesThisDeclarationHaveABody())
13371 return FD->doesDeclarationForceExternallyVisibleDefinition();
13372
13373 // Constructors and destructors are required.
13374 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13375 return true;
13376
13377 // The key function for a class is required. This rule only comes
13378 // into play when inline functions can be key functions, though.
13379 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13380 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13381 const CXXRecordDecl *RD = MD->getParent();
13382 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13383 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13384 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13385 return true;
13386 }
13387 }
13388 }
13389
13390 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13391
13392 // static, static inline, always_inline, and extern inline functions can
13393 // always be deferred. Normal inline functions can be deferred in C99/C++.
13394 // Implicit template instantiations can also be deferred in C++.
13395 return !isDiscardableGVALinkage(L: Linkage);
13396 }
13397
13398 const auto *VD = cast<VarDecl>(Val: D);
13399 assert(VD->isFileVarDecl() && "Expected file scoped var");
13400
13401 // If the decl is marked as `declare target to`, it should be emitted for the
13402 // host and for the device.
13403 if (LangOpts.OpenMP &&
13404 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13405 return true;
13406
13407 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13408 !isMSStaticDataMemberInlineDefinition(VD))
13409 return false;
13410
13411 if (VD->shouldEmitInExternalSource())
13412 return false;
13413
13414 // Variables that can be needed in other TUs are required.
13415 auto Linkage = GetGVALinkageForVariable(VD);
13416 if (!isDiscardableGVALinkage(L: Linkage))
13417 return true;
13418
13419 // We never need to emit a variable that is available in another TU.
13420 if (Linkage == GVA_AvailableExternally)
13421 return false;
13422
13423 // Variables that have destruction with side-effects are required.
13424 if (VD->needsDestruction(Ctx: *this))
13425 return true;
13426
13427 // Variables that have initialization with side-effects are required.
13428 if (VD->hasInitWithSideEffects())
13429 return true;
13430
13431 // Likewise, variables with tuple-like bindings are required if their
13432 // bindings have side-effects.
13433 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13434 for (const auto *BD : DD->flat_bindings())
13435 if (const auto *BindingVD = BD->getHoldingVar())
13436 if (DeclMustBeEmitted(D: BindingVD))
13437 return true;
13438 }
13439
13440 return false;
13441}
13442
13443void ASTContext::forEachMultiversionedFunctionVersion(
13444 const FunctionDecl *FD,
13445 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13446 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13447 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13448 FD = FD->getMostRecentDecl();
13449 // FIXME: The order of traversal here matters and depends on the order of
13450 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13451 // shouldn't rely on that.
13452 for (auto *CurDecl :
13453 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13454 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13455 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13456 SeenDecls.insert(V: CurFD).second) {
13457 Pred(CurFD);
13458 }
13459 }
13460}
13461
13462CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13463 bool IsCXXMethod) const {
13464 // Pass through to the C++ ABI object
13465 if (IsCXXMethod)
13466 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13467
13468 switch (LangOpts.getDefaultCallingConv()) {
13469 case LangOptions::DCC_None:
13470 break;
13471 case LangOptions::DCC_CDecl:
13472 return CC_C;
13473 case LangOptions::DCC_FastCall:
13474 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13475 return CC_X86FastCall;
13476 break;
13477 case LangOptions::DCC_StdCall:
13478 if (!IsVariadic)
13479 return CC_X86StdCall;
13480 break;
13481 case LangOptions::DCC_VectorCall:
13482 // __vectorcall cannot be applied to variadic functions.
13483 if (!IsVariadic)
13484 return CC_X86VectorCall;
13485 break;
13486 case LangOptions::DCC_RegCall:
13487 // __regcall cannot be applied to variadic functions.
13488 if (!IsVariadic)
13489 return CC_X86RegCall;
13490 break;
13491 case LangOptions::DCC_RtdCall:
13492 if (!IsVariadic)
13493 return CC_M68kRTD;
13494 break;
13495 }
13496 return Target->getDefaultCallingConv();
13497}
13498
13499bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13500 // Pass through to the C++ ABI object
13501 return ABI->isNearlyEmpty(RD);
13502}
13503
13504VTableContextBase *ASTContext::getVTableContext() {
13505 if (!VTContext) {
13506 auto ABI = Target->getCXXABI();
13507 if (ABI.isMicrosoft())
13508 VTContext.reset(p: new MicrosoftVTableContext(*this));
13509 else {
13510 VTContext.reset(p: new ItaniumVTableContext(*this));
13511 }
13512 }
13513 return VTContext.get();
13514}
13515
13516MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13517 if (!T)
13518 T = Target;
13519 switch (T->getCXXABI().getKind()) {
13520 case TargetCXXABI::AppleARM64:
13521 case TargetCXXABI::Fuchsia:
13522 case TargetCXXABI::GenericAArch64:
13523 case TargetCXXABI::GenericItanium:
13524 case TargetCXXABI::GenericARM:
13525 case TargetCXXABI::GenericMIPS:
13526 case TargetCXXABI::iOS:
13527 case TargetCXXABI::WebAssembly:
13528 case TargetCXXABI::WatchOS:
13529 case TargetCXXABI::XL:
13530 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13531 case TargetCXXABI::Microsoft:
13532 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13533 }
13534 llvm_unreachable("Unsupported ABI");
13535}
13536
13537MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13538 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13539 "Device mangle context does not support Microsoft mangling.");
13540 switch (T.getCXXABI().getKind()) {
13541 case TargetCXXABI::AppleARM64:
13542 case TargetCXXABI::Fuchsia:
13543 case TargetCXXABI::GenericAArch64:
13544 case TargetCXXABI::GenericItanium:
13545 case TargetCXXABI::GenericARM:
13546 case TargetCXXABI::GenericMIPS:
13547 case TargetCXXABI::iOS:
13548 case TargetCXXABI::WebAssembly:
13549 case TargetCXXABI::WatchOS:
13550 case TargetCXXABI::XL:
13551 return ItaniumMangleContext::create(
13552 Context&: *this, Diags&: getDiagnostics(),
13553 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13554 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13555 return RD->getDeviceLambdaManglingNumber();
13556 return std::nullopt;
13557 },
13558 /*IsAux=*/true);
13559 case TargetCXXABI::Microsoft:
13560 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13561 /*IsAux=*/true);
13562 }
13563 llvm_unreachable("Unsupported ABI");
13564}
13565
13566MangleContext *ASTContext::cudaNVInitDeviceMC() {
13567 // If the host and device have different C++ ABIs, mark it as the device
13568 // mangle context so that the mangling needs to retrieve the additional
13569 // device lambda mangling number instead of the regular host one.
13570 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13571 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13572 return createDeviceMangleContext(T: *getAuxTargetInfo());
13573 }
13574
13575 return createMangleContext(T: getAuxTargetInfo());
13576}
13577
13578CXXABI::~CXXABI() = default;
13579
13580size_t ASTContext::getSideTableAllocatedMemory() const {
13581 return ASTRecordLayouts.getMemorySize() +
13582 llvm::capacity_in_bytes(X: ObjCLayouts) +
13583 llvm::capacity_in_bytes(X: KeyFunctions) +
13584 llvm::capacity_in_bytes(X: ObjCImpls) +
13585 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13586 llvm::capacity_in_bytes(X: DeclAttrs) +
13587 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13588 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13589 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13590 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13591 llvm::capacity_in_bytes(X: OverriddenMethods) +
13592 llvm::capacity_in_bytes(X: Types) +
13593 llvm::capacity_in_bytes(x: VariableArrayTypes);
13594}
13595
13596/// getIntTypeForBitwidth -
13597/// sets integer QualTy according to specified details:
13598/// bitwidth, signed/unsigned.
13599/// Returns empty type if there is no appropriate target types.
13600QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13601 unsigned Signed) const {
13602 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13603 CanQualType QualTy = getFromTargetType(Type: Ty);
13604 if (!QualTy && DestWidth == 128)
13605 return Signed ? Int128Ty : UnsignedInt128Ty;
13606 return QualTy;
13607}
13608
13609QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13610 unsigned Signed) const {
13611 return getFromTargetType(
13612 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13613}
13614
13615/// getRealTypeForBitwidth -
13616/// sets floating point QualTy according to specified bitwidth.
13617/// Returns empty type if there is no appropriate target types.
13618QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13619 FloatModeKind ExplicitType) const {
13620 FloatModeKind Ty =
13621 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13622 switch (Ty) {
13623 case FloatModeKind::Half:
13624 return HalfTy;
13625 case FloatModeKind::Float:
13626 return FloatTy;
13627 case FloatModeKind::Double:
13628 return DoubleTy;
13629 case FloatModeKind::LongDouble:
13630 return LongDoubleTy;
13631 case FloatModeKind::Float128:
13632 return Float128Ty;
13633 case FloatModeKind::Ibm128:
13634 return Ibm128Ty;
13635 case FloatModeKind::NoFloat:
13636 return {};
13637 }
13638
13639 llvm_unreachable("Unhandled TargetInfo::RealType value");
13640}
13641
13642void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13643 if (Number <= 1)
13644 return;
13645
13646 MangleNumbers[ND] = Number;
13647
13648 if (Listener)
13649 Listener->AddedManglingNumber(D: ND, Number);
13650}
13651
13652unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13653 bool ForAuxTarget) const {
13654 auto I = MangleNumbers.find(Key: ND);
13655 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13656 // CUDA/HIP host compilation encodes host and device mangling numbers
13657 // as lower and upper half of 32 bit integer.
13658 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13659 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13660 } else {
13661 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13662 "number for aux target");
13663 }
13664 return Res > 1 ? Res : 1;
13665}
13666
13667void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13668 if (Number <= 1)
13669 return;
13670
13671 StaticLocalNumbers[VD] = Number;
13672
13673 if (Listener)
13674 Listener->AddedStaticLocalNumbers(D: VD, Number);
13675}
13676
13677unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13678 auto I = StaticLocalNumbers.find(Key: VD);
13679 return I != StaticLocalNumbers.end() ? I->second : 1;
13680}
13681
13682void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13683 bool IsDestroying) {
13684 if (!IsDestroying) {
13685 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13686 return;
13687 }
13688 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13689}
13690
13691bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13692 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13693}
13694
13695void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13696 bool IsTypeAware) {
13697 if (!IsTypeAware) {
13698 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13699 return;
13700 }
13701 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13702}
13703
13704bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13705 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13706}
13707
13708void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13709 FunctionDecl *OperatorDelete,
13710 OperatorDeleteKind K) const {
13711 switch (K) {
13712 case OperatorDeleteKind::Regular:
13713 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13714 break;
13715 case OperatorDeleteKind::GlobalRegular:
13716 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13717 OperatorDelete;
13718 break;
13719 case OperatorDeleteKind::Array:
13720 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13721 OperatorDelete;
13722 break;
13723 case OperatorDeleteKind::ArrayGlobal:
13724 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13725 OperatorDelete;
13726 break;
13727 }
13728}
13729
13730bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13731 OperatorDeleteKind K) const {
13732 switch (K) {
13733 case OperatorDeleteKind::Regular:
13734 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13735 case OperatorDeleteKind::GlobalRegular:
13736 return GlobalOperatorDeletesForVirtualDtor.contains(
13737 Val: Dtor->getCanonicalDecl());
13738 case OperatorDeleteKind::Array:
13739 return ArrayOperatorDeletesForVirtualDtor.contains(
13740 Val: Dtor->getCanonicalDecl());
13741 case OperatorDeleteKind::ArrayGlobal:
13742 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13743 Val: Dtor->getCanonicalDecl());
13744 }
13745 return false;
13746}
13747
13748FunctionDecl *
13749ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13750 OperatorDeleteKind K) const {
13751 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13752 switch (K) {
13753 case OperatorDeleteKind::Regular:
13754 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13755 return OperatorDeletesForVirtualDtor[Canon];
13756 return nullptr;
13757 case OperatorDeleteKind::GlobalRegular:
13758 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13759 return GlobalOperatorDeletesForVirtualDtor[Canon];
13760 return nullptr;
13761 case OperatorDeleteKind::Array:
13762 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13763 return ArrayOperatorDeletesForVirtualDtor[Canon];
13764 return nullptr;
13765 case OperatorDeleteKind::ArrayGlobal:
13766 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13767 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13768 return nullptr;
13769 }
13770 return nullptr;
13771}
13772
13773bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13774 const CXXRecordDecl *RD) {
13775 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13776 return false;
13777
13778 return MaybeRequireVectorDeletingDtor.count(V: RD);
13779}
13780
13781void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13782 const CXXRecordDecl *RD) {
13783 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13784 return;
13785
13786 MaybeRequireVectorDeletingDtor.insert(V: RD);
13787}
13788
13789MangleNumberingContext &
13790ASTContext::getManglingNumberContext(const DeclContext *DC) {
13791 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13792 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13793 if (!MCtx)
13794 MCtx = createMangleNumberingContext();
13795 return *MCtx;
13796}
13797
13798MangleNumberingContext &
13799ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13800 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13801 std::unique_ptr<MangleNumberingContext> &MCtx =
13802 ExtraMangleNumberingContexts[D];
13803 if (!MCtx)
13804 MCtx = createMangleNumberingContext();
13805 return *MCtx;
13806}
13807
13808std::unique_ptr<MangleNumberingContext>
13809ASTContext::createMangleNumberingContext() const {
13810 return ABI->createMangleNumberingContext();
13811}
13812
13813const CXXConstructorDecl *
13814ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13815 return ABI->getCopyConstructorForExceptionObject(
13816 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13817}
13818
13819void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13820 CXXConstructorDecl *CD) {
13821 return ABI->addCopyConstructorForExceptionObject(
13822 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13823 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13824}
13825
13826void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13827 TypedefNameDecl *DD) {
13828 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13829}
13830
13831TypedefNameDecl *
13832ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13833 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13834}
13835
13836void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13837 DeclaratorDecl *DD) {
13838 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13839}
13840
13841DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13842 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13843}
13844
13845void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13846 ParamIndices[D] = index;
13847}
13848
13849unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13850 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13851 assert(I != ParamIndices.end() &&
13852 "ParmIndices lacks entry set by ParmVarDecl");
13853 return I->second;
13854}
13855
13856QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13857 unsigned Length) const {
13858 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13859 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13860 EltTy = EltTy.withConst();
13861
13862 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13863
13864 // Get an array type for the string, according to C99 6.4.5. This includes
13865 // the null terminator character.
13866 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13867 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13868}
13869
13870StringLiteral *
13871ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13872 StringLiteral *&Result = StringLiteralCache[Key];
13873 if (!Result)
13874 Result = StringLiteral::Create(
13875 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13876 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13877 Locs: SourceLocation());
13878 return Result;
13879}
13880
13881MSGuidDecl *
13882ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13883 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13884
13885 llvm::FoldingSetNodeID ID;
13886 MSGuidDecl::Profile(ID, P: Parts);
13887
13888 llvm::FoldingSetInsertToken Token;
13889 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13890 return Existing;
13891
13892 QualType GUIDType = getMSGuidType().withConst();
13893 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13894 MSGuidDecls.insert(N: New, Token);
13895 return New;
13896}
13897
13898UnnamedGlobalConstantDecl *
13899ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13900 const APValue &APVal) const {
13901 llvm::FoldingSetNodeID ID;
13902 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13903
13904 llvm::FoldingSetInsertToken Token;
13905 if (UnnamedGlobalConstantDecl *Existing =
13906 UnnamedGlobalConstantDecls.lookup(ID, Token))
13907 return Existing;
13908
13909 UnnamedGlobalConstantDecl *New =
13910 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13911 UnnamedGlobalConstantDecls.insert(N: New, Token);
13912 return New;
13913}
13914
13915TemplateParamObjectDecl *
13916ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13917 assert(T->isRecordType() && "template param object of unexpected type");
13918
13919 // C++ [temp.param]p8:
13920 // [...] a static storage duration object of type 'const T' [...]
13921 T.addConst();
13922
13923 llvm::FoldingSetNodeID ID;
13924 TemplateParamObjectDecl::Profile(ID, T, V);
13925
13926 llvm::FoldingSetInsertToken Token;
13927 if (TemplateParamObjectDecl *Existing =
13928 TemplateParamObjectDecls.lookup(ID, Token))
13929 return Existing;
13930
13931 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
13932 TemplateParamObjectDecls.insert(N: New, Token);
13933 return New;
13934}
13935
13936bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13937 const llvm::Triple &T = getTargetInfo().getTriple();
13938 if (!T.isOSDarwin())
13939 return false;
13940
13941 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
13942 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
13943 return false;
13944
13945 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13946 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
13947 uint64_t Size = sizeChars.getQuantity();
13948 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
13949 unsigned Align = alignChars.getQuantity();
13950 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13951 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
13952}
13953
13954bool
13955ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
13956 const ObjCMethodDecl *MethodImpl) {
13957 // No point trying to match an unavailable/deprecated mothod.
13958 if (MethodDecl->hasAttr<UnavailableAttr>()
13959 || MethodDecl->hasAttr<DeprecatedAttr>())
13960 return false;
13961 if (MethodDecl->getObjCDeclQualifier() !=
13962 MethodImpl->getObjCDeclQualifier())
13963 return false;
13964 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
13965 return false;
13966
13967 if (MethodDecl->param_size() != MethodImpl->param_size())
13968 return false;
13969
13970 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13971 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13972 EF = MethodDecl->param_end();
13973 IM != EM && IF != EF; ++IM, ++IF) {
13974 const ParmVarDecl *DeclVar = (*IF);
13975 const ParmVarDecl *ImplVar = (*IM);
13976 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13977 return false;
13978 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
13979 return false;
13980 }
13981
13982 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13983}
13984
13985uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
13986 LangAS AS;
13987 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
13988 AS = LangAS::Default;
13989 else
13990 AS = QT->getPointeeType().getAddressSpace();
13991
13992 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
13993}
13994
13995unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
13996 return getTargetInfo().getTargetAddressSpace(AS);
13997}
13998
13999bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14000 if (X == Y)
14001 return true;
14002 if (!X || !Y)
14003 return false;
14004 llvm::FoldingSetNodeID IDX, IDY;
14005 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14006 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14007 return IDX == IDY;
14008}
14009
14010// The getCommon* helpers return, for given 'same' X and Y entities given as
14011// inputs, another entity which is also the 'same' as the inputs, but which
14012// is closer to the canonical form of the inputs, each according to a given
14013// criteria.
14014// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14015// the regular ones.
14016
14017static Decl *getCommonDecl(Decl *X, Decl *Y) {
14018 if (!declaresSameEntity(D1: X, D2: Y))
14019 return nullptr;
14020 for (const Decl *DX : X->redecls()) {
14021 // If we reach Y before reaching the first decl, that means X is older.
14022 if (DX == Y)
14023 return X;
14024 // If we reach the first decl, then Y is older.
14025 if (DX->isFirstDecl())
14026 return Y;
14027 }
14028 llvm_unreachable("Corrupt redecls chain");
14029}
14030
14031template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14032static T *getCommonDecl(T *X, T *Y) {
14033 return cast_or_null<T>(
14034 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14035 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14036}
14037
14038template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14039static T *getCommonDeclChecked(T *X, T *Y) {
14040 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14041 Y: const_cast<Decl *>(cast<Decl>(Y))));
14042}
14043
14044static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14045 TemplateName Y,
14046 bool IgnoreDeduced = false) {
14047 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14048 return X;
14049 // FIXME: There are cases here where we could find a common template name
14050 // with more sugar. For example one could be a SubstTemplateTemplate*
14051 // replacing the other.
14052 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14053 if (CX.getAsVoidPointer() !=
14054 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14055 return TemplateName();
14056 return CX;
14057}
14058
14059static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14060 TemplateName X, TemplateName Y,
14061 bool IgnoreDeduced) {
14062 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14063 assert(R.getAsVoidPointer() != nullptr);
14064 return R;
14065}
14066
14067static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14068 ArrayRef<QualType> Ys, bool Unqualified = false) {
14069 assert(Xs.size() == Ys.size());
14070 SmallVector<QualType, 8> Rs(Xs.size());
14071 for (size_t I = 0; I < Rs.size(); ++I)
14072 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14073 return Rs;
14074}
14075
14076template <class T>
14077static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14078 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14079 : SourceLocation();
14080}
14081
14082static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14083 const TemplateArgument &X,
14084 const TemplateArgument &Y) {
14085 if (X.getKind() != Y.getKind())
14086 return TemplateArgument();
14087
14088 switch (X.getKind()) {
14089 case TemplateArgument::ArgKind::Type:
14090 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14091 return TemplateArgument();
14092 return TemplateArgument(
14093 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14094 case TemplateArgument::ArgKind::NullPtr:
14095 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14096 return TemplateArgument();
14097 return TemplateArgument(
14098 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14099 /*Unqualified=*/true);
14100 case TemplateArgument::ArgKind::Expression:
14101 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14102 return TemplateArgument();
14103 // FIXME: Try to keep the common sugar.
14104 return X;
14105 case TemplateArgument::ArgKind::Template: {
14106 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14107 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14108 if (!CTN.getAsVoidPointer())
14109 return TemplateArgument();
14110 return TemplateArgument(CTN);
14111 }
14112 case TemplateArgument::ArgKind::TemplateExpansion: {
14113 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14114 TY = Y.getAsTemplateOrTemplatePattern();
14115 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14116 if (!CTN.getAsVoidPointer())
14117 return TemplateName();
14118 auto NExpX = X.getNumTemplateExpansions();
14119 assert(NExpX == Y.getNumTemplateExpansions());
14120 return TemplateArgument(CTN, NExpX);
14121 }
14122 default:
14123 // FIXME: Handle the other argument kinds.
14124 return X;
14125 }
14126}
14127
14128static bool getCommonTemplateArguments(const ASTContext &Ctx,
14129 SmallVectorImpl<TemplateArgument> &R,
14130 ArrayRef<TemplateArgument> Xs,
14131 ArrayRef<TemplateArgument> Ys) {
14132 if (Xs.size() != Ys.size())
14133 return true;
14134 R.resize(N: Xs.size());
14135 for (size_t I = 0; I < R.size(); ++I) {
14136 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14137 if (R[I].isNull())
14138 return true;
14139 }
14140 return false;
14141}
14142
14143static auto getCommonTemplateArguments(const ASTContext &Ctx,
14144 ArrayRef<TemplateArgument> Xs,
14145 ArrayRef<TemplateArgument> Ys) {
14146 SmallVector<TemplateArgument, 8> R;
14147 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14148 assert(!Different);
14149 (void)Different;
14150 return R;
14151}
14152
14153template <class T>
14154static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14155 bool IsSame) {
14156 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14157 if (KX == KY)
14158 return KX;
14159 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14160 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14161 return KX;
14162}
14163
14164/// Returns a NestedNameSpecifier which has only the common sugar
14165/// present in both NNS1 and NNS2.
14166static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14167 NestedNameSpecifier NNS1,
14168 NestedNameSpecifier NNS2, bool IsSame) {
14169 // If they are identical, all sugar is common.
14170 if (NNS1 == NNS2)
14171 return NNS1;
14172
14173 // IsSame implies both Qualifiers are equivalent.
14174 NestedNameSpecifier Canon = NNS1.getCanonical();
14175 if (Canon != NNS2.getCanonical()) {
14176 assert(!IsSame && "Should be the same NestedNameSpecifier");
14177 // If they are not the same, there is nothing to unify.
14178 return std::nullopt;
14179 }
14180
14181 NestedNameSpecifier R = std::nullopt;
14182 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14183 assert(Kind == NNS2.getKind());
14184 switch (Kind) {
14185 case NestedNameSpecifier::Kind::Namespace: {
14186 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14187 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14188 auto Kind = Namespace1->getKind();
14189 if (Kind != Namespace2->getKind() ||
14190 (Kind == Decl::NamespaceAlias &&
14191 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14192 R = NestedNameSpecifier(
14193 Ctx,
14194 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14195 Y: Namespace2->getNamespace()),
14196 /*Prefix=*/std::nullopt);
14197 break;
14198 }
14199 // The prefixes for namespaces are not significant, its declaration
14200 // identifies it uniquely.
14201 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14202 /*IsSame=*/false);
14203 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14204 Prefix);
14205 break;
14206 }
14207 case NestedNameSpecifier::Kind::Type: {
14208 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14209 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14210 /*Unqualified=*/true)
14211 .getTypePtr();
14212 R = NestedNameSpecifier(T);
14213 break;
14214 }
14215 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14216 // FIXME: Can __super even be used with data members?
14217 // If it's only usable in functions, we will never see it here,
14218 // unless we save the qualifiers used in function types.
14219 // In that case, it might be possible NNS2 is a type,
14220 // in which case we should degrade the result to
14221 // a CXXRecordType.
14222 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14223 Y: NNS2.getAsMicrosoftSuper()));
14224 break;
14225 }
14226 case NestedNameSpecifier::Kind::Null:
14227 case NestedNameSpecifier::Kind::Global:
14228 // These are singletons.
14229 llvm_unreachable("singletons did not compare equal");
14230 }
14231 assert(R.getCanonical() == Canon);
14232 return R;
14233}
14234
14235template <class T>
14236static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14237 const T *Y, bool IsSame) {
14238 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14239}
14240
14241template <class T>
14242static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14243 const T *Y) {
14244 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14245}
14246
14247static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14248 QualType X, QualType Y,
14249 Qualifiers &QX,
14250 Qualifiers &QY) {
14251 QualType R = Ctx.getCommonSugaredType(X, Y,
14252 /*Unqualified=*/true);
14253 // Qualifiers common to both element types.
14254 Qualifiers RQ = R.getQualifiers();
14255 // For each side, move to the top level any qualifiers which are not common to
14256 // both element types. The caller must assume top level qualifiers might
14257 // be different, even if they are the same type, and can be treated as sugar.
14258 QX += X.getQualifiers() - RQ;
14259 QY += Y.getQualifiers() - RQ;
14260 return R;
14261}
14262
14263template <class T>
14264static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14265 Qualifiers &QX, const T *Y,
14266 Qualifiers &QY) {
14267 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14268 Y->getElementType(), QX, QY);
14269}
14270
14271template <class T>
14272static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14273 const T *Y) {
14274 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14275}
14276
14277template <class T>
14278static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14279 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14280 return X->getSizeExpr();
14281}
14282
14283static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14284 assert(X->getSizeModifier() == Y->getSizeModifier());
14285 return X->getSizeModifier();
14286}
14287
14288static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14289 const ArrayType *Y) {
14290 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14291 return X->getIndexTypeCVRQualifiers();
14292}
14293
14294// Merges two type lists such that the resulting vector will contain
14295// each type (in a canonical sense) only once, in the order they appear
14296// from X to Y. If they occur in both X and Y, the result will contain
14297// the common sugared type between them.
14298static void mergeTypeLists(const ASTContext &Ctx,
14299 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14300 ArrayRef<QualType> Y) {
14301 llvm::DenseMap<QualType, unsigned> Found;
14302 for (auto Ts : {X, Y}) {
14303 for (QualType T : Ts) {
14304 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14305 if (!Res.second) {
14306 QualType &U = Out[Res.first->second];
14307 U = Ctx.getCommonSugaredType(X: U, Y: T);
14308 } else {
14309 Out.emplace_back(Args&: T);
14310 }
14311 }
14312 }
14313}
14314
14315FunctionProtoType::ExceptionSpecInfo
14316ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14317 FunctionProtoType::ExceptionSpecInfo ESI2,
14318 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14319 bool AcceptDependent) const {
14320 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14321
14322 // If either of them can throw anything, that is the result.
14323 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14324 if (EST1 == I)
14325 return ESI1;
14326 if (EST2 == I)
14327 return ESI2;
14328 }
14329
14330 // If either of them is non-throwing, the result is the other.
14331 for (auto I :
14332 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14333 if (EST1 == I)
14334 return ESI2;
14335 if (EST2 == I)
14336 return ESI1;
14337 }
14338
14339 // If we're left with value-dependent computed noexcept expressions, we're
14340 // stuck. Before C++17, we can just drop the exception specification entirely,
14341 // since it's not actually part of the canonical type. And this should never
14342 // happen in C++17, because it would mean we were computing the composite
14343 // pointer type of dependent types, which should never happen.
14344 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14345 assert(AcceptDependent &&
14346 "computing composite pointer type of dependent types");
14347 return FunctionProtoType::ExceptionSpecInfo();
14348 }
14349
14350 // Switch over the possibilities so that people adding new values know to
14351 // update this function.
14352 switch (EST1) {
14353 case EST_None:
14354 case EST_DynamicNone:
14355 case EST_MSAny:
14356 case EST_BasicNoexcept:
14357 case EST_DependentNoexcept:
14358 case EST_NoexceptFalse:
14359 case EST_NoexceptTrue:
14360 case EST_NoThrow:
14361 llvm_unreachable("These ESTs should be handled above");
14362
14363 case EST_Dynamic: {
14364 // This is the fun case: both exception specifications are dynamic. Form
14365 // the union of the two lists.
14366 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14367 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14368 Y: ESI2.Exceptions);
14369 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14370 Result.Exceptions = ExceptionTypeStorage;
14371 return Result;
14372 }
14373
14374 case EST_Unevaluated:
14375 case EST_Uninstantiated:
14376 case EST_Unparsed:
14377 llvm_unreachable("shouldn't see unresolved exception specifications here");
14378 }
14379
14380 llvm_unreachable("invalid ExceptionSpecificationType");
14381}
14382
14383static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14384 Qualifiers &QX, const Type *Y,
14385 Qualifiers &QY) {
14386 Type::TypeClass TC = X->getTypeClass();
14387 assert(TC == Y->getTypeClass());
14388 switch (TC) {
14389#define UNEXPECTED_TYPE(Class, Kind) \
14390 case Type::Class: \
14391 llvm_unreachable("Unexpected " Kind ": " #Class);
14392
14393#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14394#define TYPE(Class, Base)
14395#include "clang/AST/TypeNodes.inc"
14396
14397#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14398 SUGAR_FREE_TYPE(Builtin)
14399 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14400 SUGAR_FREE_TYPE(DependentBitInt)
14401 SUGAR_FREE_TYPE(BitInt)
14402 SUGAR_FREE_TYPE(ObjCInterface)
14403 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14404 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14405 SUGAR_FREE_TYPE(UnresolvedUsing)
14406 SUGAR_FREE_TYPE(HLSLAttributedResource)
14407 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14408#undef SUGAR_FREE_TYPE
14409#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14410 NON_UNIQUE_TYPE(TypeOfExpr)
14411 NON_UNIQUE_TYPE(VariableArray)
14412#undef NON_UNIQUE_TYPE
14413
14414 UNEXPECTED_TYPE(TypeOf, "sugar")
14415
14416#undef UNEXPECTED_TYPE
14417
14418 case Type::Auto: {
14419 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14420 assert(AX->getDeducedKind() == AY->getDeducedKind());
14421 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14422 assert(AX->getKeyword() == AY->getKeyword());
14423 TemplateDecl *CD =
14424 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14425 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14426 SmallVector<TemplateArgument, 8> As;
14427 if (CD &&
14428 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14429 Ys: AY->getTypeConstraintArguments())) {
14430 CD = nullptr; // The arguments differ, so make it unconstrained.
14431 As.clear();
14432 }
14433 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14434 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14435 }
14436 case Type::IncompleteArray: {
14437 const auto *AX = cast<IncompleteArrayType>(Val: X),
14438 *AY = cast<IncompleteArrayType>(Val: Y);
14439 return Ctx.getIncompleteArrayType(
14440 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14441 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14442 }
14443 case Type::DependentSizedArray: {
14444 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14445 *AY = cast<DependentSizedArrayType>(Val: Y);
14446 return Ctx.getDependentSizedArrayType(
14447 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14448 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14449 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14450 }
14451 case Type::ConstantArray: {
14452 const auto *AX = cast<ConstantArrayType>(Val: X),
14453 *AY = cast<ConstantArrayType>(Val: Y);
14454 assert(AX->getSize() == AY->getSize());
14455 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14456 ? AX->getSizeExpr()
14457 : nullptr;
14458 return Ctx.getConstantArrayType(
14459 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14460 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14461 }
14462 case Type::ArrayParameter: {
14463 const auto *AX = cast<ArrayParameterType>(Val: X),
14464 *AY = cast<ArrayParameterType>(Val: Y);
14465 assert(AX->getSize() == AY->getSize());
14466 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14467 ? AX->getSizeExpr()
14468 : nullptr;
14469 auto ArrayTy = Ctx.getConstantArrayType(
14470 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14471 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14472 return Ctx.getArrayParameterType(Ty: ArrayTy);
14473 }
14474 case Type::Atomic: {
14475 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14476 return Ctx.getAtomicType(
14477 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14478 }
14479 case Type::Complex: {
14480 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14481 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14482 }
14483 case Type::Pointer: {
14484 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14485 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14486 }
14487 case Type::BlockPointer: {
14488 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14489 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14490 }
14491 case Type::ObjCObjectPointer: {
14492 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14493 *PY = cast<ObjCObjectPointerType>(Val: Y);
14494 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14495 }
14496 case Type::MemberPointer: {
14497 const auto *PX = cast<MemberPointerType>(Val: X),
14498 *PY = cast<MemberPointerType>(Val: Y);
14499 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14500 PY->getMostRecentCXXRecordDecl()));
14501 return Ctx.getMemberPointerType(
14502 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14503 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14504 Cls: PX->getMostRecentCXXRecordDecl());
14505 }
14506 case Type::LValueReference: {
14507 const auto *PX = cast<LValueReferenceType>(Val: X),
14508 *PY = cast<LValueReferenceType>(Val: Y);
14509 // FIXME: Preserve PointeeTypeAsWritten.
14510 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14511 SpelledAsLValue: PX->isSpelledAsLValue() ||
14512 PY->isSpelledAsLValue());
14513 }
14514 case Type::RValueReference: {
14515 const auto *PX = cast<RValueReferenceType>(Val: X),
14516 *PY = cast<RValueReferenceType>(Val: Y);
14517 // FIXME: Preserve PointeeTypeAsWritten.
14518 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14519 }
14520 case Type::DependentAddressSpace: {
14521 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14522 *PY = cast<DependentAddressSpaceType>(Val: Y);
14523 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14524 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14525 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14526 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14527 }
14528 case Type::FunctionNoProto: {
14529 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14530 *FY = cast<FunctionNoProtoType>(Val: Y);
14531 assert(FX->getExtInfo() == FY->getExtInfo());
14532 return Ctx.getFunctionNoProtoType(
14533 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14534 Info: FX->getExtInfo());
14535 }
14536 case Type::FunctionProto: {
14537 const auto *FX = cast<FunctionProtoType>(Val: X),
14538 *FY = cast<FunctionProtoType>(Val: Y);
14539 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14540 EPIY = FY->getExtProtoInfo();
14541 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14542 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14543 assert(!EPIX.ExtParameterInfos ||
14544 llvm::equal(
14545 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14546 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14547 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14548 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14549 assert(EPIX.Variadic == EPIY.Variadic);
14550
14551 // FIXME: Can we handle an empty EllipsisLoc?
14552 // Use emtpy EllipsisLoc if X and Y differ.
14553
14554 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14555
14556 QualType R =
14557 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14558 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14559 /*Unqualified=*/true);
14560
14561 SmallVector<QualType, 8> Exceptions;
14562 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14563 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14564 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14565 }
14566 case Type::ObjCObject: {
14567 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14568 assert(
14569 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14570 OY->getProtocols().begin(), OY->getProtocols().end(),
14571 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14572 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14573 }) &&
14574 "protocol lists must be the same");
14575 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14576 Ys: OY->getTypeArgsAsWritten());
14577 return Ctx.getObjCObjectType(
14578 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14579 protocols: OX->getProtocols(),
14580 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14581 }
14582 case Type::ConstantMatrix: {
14583 const auto *MX = cast<ConstantMatrixType>(Val: X),
14584 *MY = cast<ConstantMatrixType>(Val: Y);
14585 assert(MX->getNumRows() == MY->getNumRows());
14586 assert(MX->getNumColumns() == MY->getNumColumns());
14587 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14588 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14589 }
14590 case Type::DependentSizedMatrix: {
14591 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14592 *MY = cast<DependentSizedMatrixType>(Val: Y);
14593 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14594 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14595 return Ctx.getDependentSizedMatrixType(
14596 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14597 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14598 }
14599 case Type::Vector: {
14600 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14601 assert(VX->getNumElements() == VY->getNumElements());
14602 assert(VX->getVectorKind() == VY->getVectorKind());
14603 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14604 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14605 }
14606 case Type::ExtVector: {
14607 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14608 assert(VX->getNumElements() == VY->getNumElements());
14609 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14610 NumElts: VX->getNumElements());
14611 }
14612 case Type::DependentSizedExtVector: {
14613 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14614 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14615 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14616 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14617 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14618 }
14619 case Type::DependentVector: {
14620 const auto *VX = cast<DependentVectorType>(Val: X),
14621 *VY = cast<DependentVectorType>(Val: Y);
14622 assert(VX->getVectorKind() == VY->getVectorKind());
14623 return Ctx.getDependentVectorType(
14624 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14625 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14626 }
14627 case Type::Enum:
14628 case Type::Record:
14629 case Type::InjectedClassName: {
14630 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14631 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14632 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14633 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14634 /*OwnedTag=*/OwnsTag: false);
14635 }
14636 case Type::TemplateSpecialization: {
14637 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14638 *TY = cast<TemplateSpecializationType>(Val: Y);
14639 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14640 Ys: TY->template_arguments());
14641 return Ctx.getTemplateSpecializationType(
14642 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14643 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14644 Y: TY->getTemplateName(),
14645 /*IgnoreDeduced=*/true),
14646 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14647 }
14648 case Type::Decltype: {
14649 const auto *DX = cast<DecltypeType>(Val: X);
14650 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14651 assert(DX->isDependentType());
14652 assert(DY->isDependentType());
14653 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14654 // As Decltype is not uniqued, building a common type would be wasteful.
14655 return QualType(DX, 0);
14656 }
14657 case Type::PackIndexing: {
14658 const auto *DX = cast<PackIndexingType>(Val: X);
14659 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14660 assert(DX->isDependentType());
14661 assert(DY->isDependentType());
14662 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14663 return QualType(DX, 0);
14664 }
14665 case Type::DependentName: {
14666 const auto *NX = cast<DependentNameType>(Val: X),
14667 *NY = cast<DependentNameType>(Val: Y);
14668 assert(NX->getIdentifier() == NY->getIdentifier());
14669 return Ctx.getDependentNameType(
14670 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14671 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14672 }
14673 case Type::OverflowBehavior: {
14674 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14675 *NY = cast<OverflowBehaviorType>(Val: Y);
14676 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14677 return Ctx.getOverflowBehaviorType(
14678 Kind: NX->getBehaviorKind(),
14679 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14680 Y: NY->getUnderlyingType(), QX, QY));
14681 }
14682 case Type::UnaryTransform: {
14683 const auto *TX = cast<UnaryTransformType>(Val: X),
14684 *TY = cast<UnaryTransformType>(Val: Y);
14685 assert(TX->getUTTKind() == TY->getUTTKind());
14686 return Ctx.getUnaryTransformType(
14687 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14688 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14689 Y: TY->getUnderlyingType()),
14690 Kind: TX->getUTTKind());
14691 }
14692 case Type::PackExpansion: {
14693 const auto *PX = cast<PackExpansionType>(Val: X),
14694 *PY = cast<PackExpansionType>(Val: Y);
14695 assert(PX->getNumExpansions() == PY->getNumExpansions());
14696 return Ctx.getPackExpansionType(
14697 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14698 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14699 }
14700 case Type::Pipe: {
14701 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14702 assert(PX->isReadOnly() == PY->isReadOnly());
14703 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14704 : &ASTContext::getWritePipeType;
14705 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14706 }
14707 case Type::TemplateTypeParm: {
14708 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14709 *TY = cast<TemplateTypeParmType>(Val: Y);
14710 assert(TX->getDepth() == TY->getDepth());
14711 assert(TX->getIndex() == TY->getIndex());
14712 assert(TX->isParameterPack() == TY->isParameterPack());
14713 return Ctx.getTemplateTypeParmType(
14714 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14715 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14716 }
14717 }
14718 llvm_unreachable("Unknown Type Class");
14719}
14720
14721static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14722 const Type *Y,
14723 SplitQualType Underlying) {
14724 Type::TypeClass TC = X->getTypeClass();
14725 if (TC != Y->getTypeClass())
14726 return QualType();
14727 switch (TC) {
14728#define UNEXPECTED_TYPE(Class, Kind) \
14729 case Type::Class: \
14730 llvm_unreachable("Unexpected " Kind ": " #Class);
14731#define TYPE(Class, Base)
14732#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14733#include "clang/AST/TypeNodes.inc"
14734
14735#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14736 CANONICAL_TYPE(Atomic)
14737 CANONICAL_TYPE(BitInt)
14738 CANONICAL_TYPE(BlockPointer)
14739 CANONICAL_TYPE(Builtin)
14740 CANONICAL_TYPE(Complex)
14741 CANONICAL_TYPE(ConstantArray)
14742 CANONICAL_TYPE(ArrayParameter)
14743 CANONICAL_TYPE(ConstantMatrix)
14744 CANONICAL_TYPE(Enum)
14745 CANONICAL_TYPE(ExtVector)
14746 CANONICAL_TYPE(FunctionNoProto)
14747 CANONICAL_TYPE(FunctionProto)
14748 CANONICAL_TYPE(IncompleteArray)
14749 CANONICAL_TYPE(HLSLAttributedResource)
14750 CANONICAL_TYPE(HLSLInlineSpirv)
14751 CANONICAL_TYPE(LValueReference)
14752 CANONICAL_TYPE(ObjCInterface)
14753 CANONICAL_TYPE(ObjCObject)
14754 CANONICAL_TYPE(ObjCObjectPointer)
14755 CANONICAL_TYPE(OverflowBehavior)
14756 CANONICAL_TYPE(Pipe)
14757 CANONICAL_TYPE(Pointer)
14758 CANONICAL_TYPE(Record)
14759 CANONICAL_TYPE(RValueReference)
14760 CANONICAL_TYPE(VariableArray)
14761 CANONICAL_TYPE(Vector)
14762#undef CANONICAL_TYPE
14763
14764#undef UNEXPECTED_TYPE
14765
14766 case Type::Adjusted: {
14767 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14768 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14769 if (!Ctx.hasSameType(T1: OX, T2: OY))
14770 return QualType();
14771 // FIXME: It's inefficient to have to unify the original types.
14772 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14773 New: Ctx.getQualifiedType(split: Underlying));
14774 }
14775 case Type::Decayed: {
14776 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14777 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14778 if (!Ctx.hasSameType(T1: OX, T2: OY))
14779 return QualType();
14780 // FIXME: It's inefficient to have to unify the original types.
14781 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14782 Decayed: Ctx.getQualifiedType(split: Underlying));
14783 }
14784 case Type::Attributed: {
14785 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14786 AttributedType::Kind Kind = AX->getAttrKind();
14787 if (Kind != AY->getAttrKind())
14788 return QualType();
14789 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14790 if (!Ctx.hasSameType(T1: MX, T2: MY))
14791 return QualType();
14792 // FIXME: It's inefficient to have to unify the modified types.
14793 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14794 equivalentType: Ctx.getQualifiedType(split: Underlying),
14795 attr: AX->getAttr());
14796 }
14797 case Type::BTFTagAttributed: {
14798 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14799 const BTFTypeTagAttr *AX = BX->getAttr();
14800 // The attribute is not uniqued, so just compare the tag.
14801 if (AX->getBTFTypeTag() !=
14802 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14803 return QualType();
14804 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14805 }
14806 case Type::Auto: {
14807 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14808 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14809 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14810
14811 AutoTypeKeyword KW = AX->getKeyword();
14812 if (KW != AY->getKeyword())
14813 return QualType();
14814
14815 TemplateDecl *CD =
14816 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14817 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14818 SmallVector<TemplateArgument, 8> As;
14819 if (CD &&
14820 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14821 Ys: AY->getTypeConstraintArguments())) {
14822 CD = nullptr; // The arguments differ, so make it unconstrained.
14823 As.clear();
14824 }
14825
14826 // Both auto types can't be dependent, otherwise they wouldn't have been
14827 // sugar. This implies they can't contain unexpanded packs either.
14828 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14829 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14830 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14831 }
14832 case Type::PackIndexing:
14833 case Type::Decltype:
14834 return QualType();
14835 case Type::DeducedTemplateSpecialization:
14836 // FIXME: Try to merge these.
14837 return QualType();
14838 case Type::MacroQualified: {
14839 const auto *MX = cast<MacroQualifiedType>(Val: X),
14840 *MY = cast<MacroQualifiedType>(Val: Y);
14841 const IdentifierInfo *IX = MX->getMacroIdentifier();
14842 if (IX != MY->getMacroIdentifier())
14843 return QualType();
14844 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14845 }
14846 case Type::SubstTemplateTypeParm: {
14847 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14848 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14849 Decl *CD =
14850 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14851 if (!CD)
14852 return QualType();
14853 unsigned Index = SX->getIndex();
14854 if (Index != SY->getIndex())
14855 return QualType();
14856 auto PackIndex = SX->getPackIndex();
14857 if (PackIndex != SY->getPackIndex())
14858 return QualType();
14859 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14860 AssociatedDecl: CD, Index, PackIndex,
14861 Final: SX->getFinal() && SY->getFinal());
14862 }
14863 case Type::ObjCTypeParam:
14864 // FIXME: Try to merge these.
14865 return QualType();
14866 case Type::Paren:
14867 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14868
14869 case Type::TemplateSpecialization: {
14870 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14871 *TY = cast<TemplateSpecializationType>(Val: Y);
14872 TemplateName CTN =
14873 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14874 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14875 if (!CTN.getAsVoidPointer())
14876 return QualType();
14877 SmallVector<TemplateArgument, 8> As;
14878 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14879 Ys: TY->template_arguments()))
14880 return QualType();
14881 return Ctx.getTemplateSpecializationType(
14882 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14883 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14884 }
14885 case Type::Typedef: {
14886 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14887 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14888 if (!CD)
14889 return QualType();
14890 return Ctx.getTypedefType(
14891 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14892 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14893 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14894 }
14895 case Type::TypeOf: {
14896 // The common sugar between two typeof expressions, where one is
14897 // potentially a typeof_unqual and the other is not, we unify to the
14898 // qualified type as that retains the most information along with the type.
14899 // We only return a typeof_unqual type when both types are unqual types.
14900 TypeOfKind Kind = TypeOfKind::Qualified;
14901 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14902 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14903 Kind = TypeOfKind::Unqualified;
14904 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14905 }
14906 case Type::TypeOfExpr:
14907 return QualType();
14908
14909 case Type::UnaryTransform: {
14910 const auto *UX = cast<UnaryTransformType>(Val: X),
14911 *UY = cast<UnaryTransformType>(Val: Y);
14912 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14913 if (KX != UY->getUTTKind())
14914 return QualType();
14915 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14916 if (!Ctx.hasSameType(T1: BX, T2: BY))
14917 return QualType();
14918 // FIXME: It's inefficient to have to unify the base types.
14919 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
14920 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
14921 }
14922 case Type::Using: {
14923 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
14924 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
14925 if (!CD)
14926 return QualType();
14927 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
14928 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
14929 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14930 }
14931 case Type::MemberPointer: {
14932 const auto *PX = cast<MemberPointerType>(Val: X),
14933 *PY = cast<MemberPointerType>(Val: Y);
14934 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14935 assert(Cls == PY->getMostRecentCXXRecordDecl());
14936 return Ctx.getMemberPointerType(
14937 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
14938 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
14939 }
14940 case Type::CountAttributed: {
14941 const auto *DX = cast<CountAttributedType>(Val: X),
14942 *DY = cast<CountAttributedType>(Val: Y);
14943 if (DX->isCountInBytes() != DY->isCountInBytes())
14944 return QualType();
14945 if (DX->isOrNull() != DY->isOrNull())
14946 return QualType();
14947 Expr *CEX = DX->getCountExpr();
14948 Expr *CEY = DY->getCountExpr();
14949 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14950 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
14951 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14952 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14953 DependentDecls: CDX);
14954 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14955 return QualType();
14956 // Two declarations with the same integer constant may still differ in their
14957 // expression pointers, so we need to evaluate them.
14958 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14959 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14960 if (VX != VY)
14961 return QualType();
14962 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14963 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14964 DependentDecls: CDX);
14965 }
14966
14967 case Type::LateParsedAttr:
14968 return QualType();
14969
14970 case Type::PredefinedSugar:
14971 assert(cast<PredefinedSugarType>(X)->getKind() !=
14972 cast<PredefinedSugarType>(Y)->getKind());
14973 return QualType();
14974 }
14975 llvm_unreachable("Unhandled Type Class");
14976}
14977
14978static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14979 SmallVector<SplitQualType, 8> R;
14980 while (true) {
14981 QTotal.addConsistentQualifiers(qs: T.Quals);
14982 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14983 if (NT == QualType(T.Ty, 0))
14984 break;
14985 R.push_back(Elt: T);
14986 T = NT.split();
14987 }
14988 return R;
14989}
14990
14991QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
14992 bool Unqualified) const {
14993 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14994 if (X == Y)
14995 return X;
14996 if (!Unqualified) {
14997 if (X.isCanonical())
14998 return X;
14999 if (Y.isCanonical())
15000 return Y;
15001 }
15002
15003 SplitQualType SX = X.split(), SY = Y.split();
15004 Qualifiers QX, QY;
15005 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15006 // until we reach their underlying "canonical nodes". Note these are not
15007 // necessarily canonical types, as they may still have sugared properties.
15008 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15009 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
15010
15011 // If this is an ArrayType, the element qualifiers are interchangeable with
15012 // the top level qualifiers.
15013 // * In case the canonical nodes are the same, the elements types are already
15014 // the same.
15015 // * Otherwise, the element types will be made the same, and any different
15016 // element qualifiers will be moved up to the top level qualifiers, per
15017 // 'getCommonArrayElementType'.
15018 // In both cases, this means there may be top level qualifiers which differ
15019 // between X and Y. If so, these differing qualifiers are redundant with the
15020 // element qualifiers, and can be removed without changing the canonical type.
15021 // The desired behaviour is the same as for the 'Unqualified' case here:
15022 // treat the redundant qualifiers as sugar, remove the ones which are not
15023 // common to both sides.
15024 bool KeepCommonQualifiers =
15025 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15026
15027 if (SX.Ty != SY.Ty) {
15028 // The canonical nodes differ. Build a common canonical node out of the two,
15029 // unifying their sugar. This may recurse back here.
15030 SX.Ty =
15031 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15032 } else {
15033 // The canonical nodes were identical: We may have desugared too much.
15034 // Add any common sugar back in.
15035 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15036 QX -= SX.Quals;
15037 QY -= SY.Quals;
15038 SX = Xs.pop_back_val();
15039 SY = Ys.pop_back_val();
15040 }
15041 }
15042 if (KeepCommonQualifiers)
15043 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15044 else
15045 assert(QX == QY);
15046
15047 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15048 // related. Walk up these nodes, unifying them and adding the result.
15049 while (!Xs.empty() && !Ys.empty()) {
15050 auto Underlying = SplitQualType(
15051 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15052 SX = Xs.pop_back_val();
15053 SY = Ys.pop_back_val();
15054 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15055 .getTypePtrOrNull();
15056 // Stop at the first pair which is unrelated.
15057 if (!SX.Ty) {
15058 SX.Ty = Underlying.Ty;
15059 break;
15060 }
15061 QX -= Underlying.Quals;
15062 };
15063
15064 // Add back the missing accumulated qualifiers, which were stripped off
15065 // with the sugar nodes we could not unify.
15066 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15067 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15068 return R;
15069}
15070
15071QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15072 assert(Ty->isFixedPointType());
15073
15074 if (Ty->isUnsaturatedFixedPointType())
15075 return Ty;
15076
15077 switch (Ty->castAs<BuiltinType>()->getKind()) {
15078 default:
15079 llvm_unreachable("Not a saturated fixed point type!");
15080 case BuiltinType::SatShortAccum:
15081 return ShortAccumTy;
15082 case BuiltinType::SatAccum:
15083 return AccumTy;
15084 case BuiltinType::SatLongAccum:
15085 return LongAccumTy;
15086 case BuiltinType::SatUShortAccum:
15087 return UnsignedShortAccumTy;
15088 case BuiltinType::SatUAccum:
15089 return UnsignedAccumTy;
15090 case BuiltinType::SatULongAccum:
15091 return UnsignedLongAccumTy;
15092 case BuiltinType::SatShortFract:
15093 return ShortFractTy;
15094 case BuiltinType::SatFract:
15095 return FractTy;
15096 case BuiltinType::SatLongFract:
15097 return LongFractTy;
15098 case BuiltinType::SatUShortFract:
15099 return UnsignedShortFractTy;
15100 case BuiltinType::SatUFract:
15101 return UnsignedFractTy;
15102 case BuiltinType::SatULongFract:
15103 return UnsignedLongFractTy;
15104 }
15105}
15106
15107QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15108 assert(Ty->isFixedPointType());
15109
15110 if (Ty->isSaturatedFixedPointType()) return Ty;
15111
15112 switch (Ty->castAs<BuiltinType>()->getKind()) {
15113 default:
15114 llvm_unreachable("Not a fixed point type!");
15115 case BuiltinType::ShortAccum:
15116 return SatShortAccumTy;
15117 case BuiltinType::Accum:
15118 return SatAccumTy;
15119 case BuiltinType::LongAccum:
15120 return SatLongAccumTy;
15121 case BuiltinType::UShortAccum:
15122 return SatUnsignedShortAccumTy;
15123 case BuiltinType::UAccum:
15124 return SatUnsignedAccumTy;
15125 case BuiltinType::ULongAccum:
15126 return SatUnsignedLongAccumTy;
15127 case BuiltinType::ShortFract:
15128 return SatShortFractTy;
15129 case BuiltinType::Fract:
15130 return SatFractTy;
15131 case BuiltinType::LongFract:
15132 return SatLongFractTy;
15133 case BuiltinType::UShortFract:
15134 return SatUnsignedShortFractTy;
15135 case BuiltinType::UFract:
15136 return SatUnsignedFractTy;
15137 case BuiltinType::ULongFract:
15138 return SatUnsignedLongFractTy;
15139 }
15140}
15141
15142LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15143 if (LangOpts.OpenCL)
15144 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15145
15146 if (LangOpts.CUDA)
15147 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15148
15149 return getLangASFromTargetAS(TargetAS: AS);
15150}
15151
15152unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15153 assert(Ty->isFixedPointType());
15154
15155 const TargetInfo &Target = getTargetInfo();
15156 switch (Ty->castAs<BuiltinType>()->getKind()) {
15157 default:
15158 llvm_unreachable("Not a fixed point type!");
15159 case BuiltinType::ShortAccum:
15160 case BuiltinType::SatShortAccum:
15161 return Target.getShortAccumScale();
15162 case BuiltinType::Accum:
15163 case BuiltinType::SatAccum:
15164 return Target.getAccumScale();
15165 case BuiltinType::LongAccum:
15166 case BuiltinType::SatLongAccum:
15167 return Target.getLongAccumScale();
15168 case BuiltinType::UShortAccum:
15169 case BuiltinType::SatUShortAccum:
15170 return Target.getUnsignedShortAccumScale();
15171 case BuiltinType::UAccum:
15172 case BuiltinType::SatUAccum:
15173 return Target.getUnsignedAccumScale();
15174 case BuiltinType::ULongAccum:
15175 case BuiltinType::SatULongAccum:
15176 return Target.getUnsignedLongAccumScale();
15177 case BuiltinType::ShortFract:
15178 case BuiltinType::SatShortFract:
15179 return Target.getShortFractScale();
15180 case BuiltinType::Fract:
15181 case BuiltinType::SatFract:
15182 return Target.getFractScale();
15183 case BuiltinType::LongFract:
15184 case BuiltinType::SatLongFract:
15185 return Target.getLongFractScale();
15186 case BuiltinType::UShortFract:
15187 case BuiltinType::SatUShortFract:
15188 return Target.getUnsignedShortFractScale();
15189 case BuiltinType::UFract:
15190 case BuiltinType::SatUFract:
15191 return Target.getUnsignedFractScale();
15192 case BuiltinType::ULongFract:
15193 case BuiltinType::SatULongFract:
15194 return Target.getUnsignedLongFractScale();
15195 }
15196}
15197
15198unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15199 assert(Ty->isFixedPointType());
15200
15201 const TargetInfo &Target = getTargetInfo();
15202 switch (Ty->castAs<BuiltinType>()->getKind()) {
15203 default:
15204 llvm_unreachable("Not a fixed point type!");
15205 case BuiltinType::ShortAccum:
15206 case BuiltinType::SatShortAccum:
15207 return Target.getShortAccumIBits();
15208 case BuiltinType::Accum:
15209 case BuiltinType::SatAccum:
15210 return Target.getAccumIBits();
15211 case BuiltinType::LongAccum:
15212 case BuiltinType::SatLongAccum:
15213 return Target.getLongAccumIBits();
15214 case BuiltinType::UShortAccum:
15215 case BuiltinType::SatUShortAccum:
15216 return Target.getUnsignedShortAccumIBits();
15217 case BuiltinType::UAccum:
15218 case BuiltinType::SatUAccum:
15219 return Target.getUnsignedAccumIBits();
15220 case BuiltinType::ULongAccum:
15221 case BuiltinType::SatULongAccum:
15222 return Target.getUnsignedLongAccumIBits();
15223 case BuiltinType::ShortFract:
15224 case BuiltinType::SatShortFract:
15225 case BuiltinType::Fract:
15226 case BuiltinType::SatFract:
15227 case BuiltinType::LongFract:
15228 case BuiltinType::SatLongFract:
15229 case BuiltinType::UShortFract:
15230 case BuiltinType::SatUShortFract:
15231 case BuiltinType::UFract:
15232 case BuiltinType::SatUFract:
15233 case BuiltinType::ULongFract:
15234 case BuiltinType::SatULongFract:
15235 return 0;
15236 }
15237}
15238
15239llvm::FixedPointSemantics
15240ASTContext::getFixedPointSemantics(QualType Ty) const {
15241 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15242 "Can only get the fixed point semantics for a "
15243 "fixed point or integer type.");
15244 if (Ty->isIntegerType())
15245 return llvm::FixedPointSemantics::GetIntegerSemantics(
15246 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15247
15248 bool isSigned = Ty->isSignedFixedPointType();
15249 return llvm::FixedPointSemantics(
15250 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15251 Ty->isSaturatedFixedPointType(),
15252 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15253}
15254
15255llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15256 assert(Ty->isFixedPointType());
15257 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15258}
15259
15260llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15261 assert(Ty->isFixedPointType());
15262 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15263}
15264
15265QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15266 assert(Ty->isUnsignedFixedPointType() &&
15267 "Expected unsigned fixed point type");
15268
15269 switch (Ty->castAs<BuiltinType>()->getKind()) {
15270 case BuiltinType::UShortAccum:
15271 return ShortAccumTy;
15272 case BuiltinType::UAccum:
15273 return AccumTy;
15274 case BuiltinType::ULongAccum:
15275 return LongAccumTy;
15276 case BuiltinType::SatUShortAccum:
15277 return SatShortAccumTy;
15278 case BuiltinType::SatUAccum:
15279 return SatAccumTy;
15280 case BuiltinType::SatULongAccum:
15281 return SatLongAccumTy;
15282 case BuiltinType::UShortFract:
15283 return ShortFractTy;
15284 case BuiltinType::UFract:
15285 return FractTy;
15286 case BuiltinType::ULongFract:
15287 return LongFractTy;
15288 case BuiltinType::SatUShortFract:
15289 return SatShortFractTy;
15290 case BuiltinType::SatUFract:
15291 return SatFractTy;
15292 case BuiltinType::SatULongFract:
15293 return SatLongFractTy;
15294 default:
15295 llvm_unreachable("Unexpected unsigned fixed point type");
15296 }
15297}
15298
15299// Given a list of FMV features, return a concatenated list of the
15300// corresponding backend features (which may contain duplicates).
15301static std::vector<std::string> getFMVBackendFeaturesFor(
15302 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15303 std::vector<std::string> BackendFeats;
15304 llvm::AArch64::ExtensionSet FeatureBits;
15305 for (StringRef F : FMVFeatStrings)
15306 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15307 if (FMVExt->ID)
15308 FeatureBits.enable(E: *FMVExt->ID);
15309 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15310 return BackendFeats;
15311}
15312
15313ParsedTargetAttr
15314ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15315 assert(TD != nullptr);
15316 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15317
15318 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15319 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15320 });
15321 return ParsedAttr;
15322}
15323
15324void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15325 const FunctionDecl *FD) const {
15326 if (FD)
15327 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15328 else
15329 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15330 CPU: Target->getTargetOpts().CPU,
15331 FeatureVec: Target->getTargetOpts().Features);
15332}
15333
15334// Fills in the supplied string map with the set of target features for the
15335// passed in function.
15336void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15337 GlobalDecl GD) const {
15338 StringRef TargetCPU = Target->getTargetOpts().CPU;
15339 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15340 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15341 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15342
15343 // Make a copy of the features as passed on the command line into the
15344 // beginning of the additional features from the function to override.
15345 // AArch64 handles command line option features in parseTargetAttr().
15346 if (!Target->getTriple().isAArch64())
15347 ParsedAttr.Features.insert(
15348 position: ParsedAttr.Features.begin(),
15349 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15350 last: Target->getTargetOpts().FeaturesAsWritten.end());
15351
15352 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15353 TargetCPU = ParsedAttr.CPU;
15354
15355 // Now populate the feature map, first with the TargetCPU which is either
15356 // the default or a new one from the target attribute string. Then we'll use
15357 // the passed in features (FeaturesAsWritten) along with the new ones from
15358 // the attribute.
15359 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15360 FeatureVec: ParsedAttr.Features);
15361 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15362 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15363 Target->getCPUSpecificCPUDispatchFeatures(
15364 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15365 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15366 Features.insert(position: Features.begin(),
15367 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15368 last: Target->getTargetOpts().FeaturesAsWritten.end());
15369 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15370 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15371 if (Target->getTriple().isAArch64()) {
15372 llvm::SmallVector<StringRef, 8> Feats;
15373 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15374 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15375 Features.insert(position: Features.begin(),
15376 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15377 last: Target->getTargetOpts().FeaturesAsWritten.end());
15378 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15379 } else if (Target->getTriple().isRISCV()) {
15380 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15381 std::vector<std::string> Features;
15382 if (VersionStr != "default") {
15383 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15384 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15385 last: ParsedAttr.Features.end());
15386 }
15387 Features.insert(position: Features.begin(),
15388 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15389 last: Target->getTargetOpts().FeaturesAsWritten.end());
15390 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15391 } else if (Target->getTriple().isOSAIX()) {
15392 std::vector<std::string> Features;
15393 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15394 if (VersionStr.starts_with(Prefix: "cpu="))
15395 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15396 else
15397 assert(VersionStr == "default");
15398 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15399 } else {
15400 std::vector<std::string> Features;
15401 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15402 if (VersionStr.starts_with(Prefix: "arch="))
15403 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15404 else if (VersionStr != "default")
15405 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15406 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15407 }
15408 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15409 std::vector<std::string> Features;
15410 if (Target->getTriple().isRISCV()) {
15411 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15412 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15413 last: ParsedAttr.Features.end());
15414 } else {
15415 assert(Target->getTriple().isAArch64());
15416 llvm::SmallVector<StringRef, 8> Feats;
15417 TV->getFeatures(Out&: Feats);
15418 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15419 }
15420 Features.insert(position: Features.begin(),
15421 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15422 last: Target->getTargetOpts().FeaturesAsWritten.end());
15423 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15424 } else {
15425 FeatureMap = Target->getTargetOpts().FeatureMap;
15426 }
15427}
15428
15429static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15430 CanQualType KernelNameType,
15431 const FunctionDecl *FD) {
15432 // Host and device compilation may use different ABIs and different ABIs
15433 // may allocate name mangling discriminators differently. A discriminator
15434 // override is used to ensure consistent discriminator allocation across
15435 // host and device compilation.
15436 auto DeviceDiscriminatorOverrider =
15437 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15438 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15439 if (RD->isLambda())
15440 return RD->getDeviceLambdaManglingNumber();
15441 return std::nullopt;
15442 };
15443 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15444 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15445
15446 // Construct a mangled name for the SYCL kernel caller offload entry point.
15447 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15448 // name the SYCL kernel caller offload entry point function. This mangling
15449 // does not suffice to clearly identify symbols that correspond to SYCL
15450 // kernel caller functions, nor is this mangling natural for targets that
15451 // use a non-Itanium ABI.
15452 std::string Buffer;
15453 Buffer.reserve(res_arg: 128);
15454 llvm::raw_string_ostream Out(Buffer);
15455 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15456 std::string KernelName = Out.str();
15457
15458 return {KernelNameType, FD, KernelName};
15459}
15460
15461void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15462 // If the function declaration to register is invalid or dependent, the
15463 // registration attempt is ignored.
15464 if (FD->isInvalidDecl() || FD->isTemplated())
15465 return;
15466
15467 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15468 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15469
15470 // Be tolerant of multiple registration attempts so long as each attempt
15471 // is for the same entity. Callers are obligated to detect and diagnose
15472 // conflicting kernel names prior to calling this function.
15473 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15474 auto IT = SYCLKernels.find(Val: KernelNameType);
15475 assert((IT == SYCLKernels.end() ||
15476 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15477 "SYCL kernel name conflict");
15478 (void)IT;
15479 SYCLKernels.insert(KV: std::make_pair(
15480 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15481}
15482
15483const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15484 CanQualType KernelNameType = getCanonicalType(T);
15485 return SYCLKernels.at(Val: KernelNameType);
15486}
15487
15488const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15489 CanQualType KernelNameType = getCanonicalType(T);
15490 auto IT = SYCLKernels.find(Val: KernelNameType);
15491 if (IT != SYCLKernels.end())
15492 return &IT->second;
15493 return nullptr;
15494}
15495
15496OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15497 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15498 return *OMPTraitInfoVector.back();
15499}
15500
15501const StreamingDiagnostic &clang::
15502operator<<(const StreamingDiagnostic &DB,
15503 const ASTContext::SectionInfo &Section) {
15504 if (Section.Decl)
15505 return DB << Section.Decl;
15506 return DB << "a prior #pragma section";
15507}
15508
15509bool ASTContext::mayExternalize(const Decl *D) const {
15510 bool IsInternalVar =
15511 isa<VarDecl>(Val: D) &&
15512 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15513 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15514 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15515 (D->hasAttr<CUDAConstantAttr>() &&
15516 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15517 // CUDA/HIP: managed variables need to be externalized since it is
15518 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15519 // anonymous name space needs to be externalized to avoid duplicate symbols.
15520 return (IsInternalVar &&
15521 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15522 (D->hasAttr<CUDAGlobalAttr>() &&
15523 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15524 GVA_Internal);
15525}
15526
15527bool ASTContext::shouldExternalize(const Decl *D) const {
15528 return mayExternalize(D) &&
15529 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15530 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15531}
15532
15533StringRef ASTContext::getCUIDHash() const {
15534 if (!CUIDHash.empty())
15535 return CUIDHash;
15536 if (LangOpts.CUID.empty())
15537 return StringRef();
15538 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15539 return CUIDHash;
15540}
15541
15542const CXXRecordDecl *
15543ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15544 assert(ThisClass);
15545 assert(ThisClass->isPolymorphic());
15546 const CXXRecordDecl *PrimaryBase = ThisClass;
15547 while (1) {
15548 assert(PrimaryBase);
15549 assert(PrimaryBase->isPolymorphic());
15550 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15551 auto Base = Layout.getPrimaryBase();
15552 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15553 break;
15554 PrimaryBase = Base;
15555 }
15556 return PrimaryBase;
15557}
15558
15559bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15560 StringRef MangledName) {
15561 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15562 assert(Method->isVirtual());
15563 bool DefaultIncludesPointerAuth =
15564 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15565
15566 if (!DefaultIncludesPointerAuth)
15567 return true;
15568
15569 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15570 if (Existing != ThunksToBeAbbreviated.end())
15571 return Existing->second.contains(key: MangledName.str());
15572
15573 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15574 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15575 auto VtableContext = getVTableContext();
15576 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15577 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15578 for (const auto &Thunk : *ThunkInfos) {
15579 SmallString<256> ElidedName;
15580 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15581 if (Destructor)
15582 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15583 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15584 ElidedNameStream);
15585 else
15586 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15587 ElidedNameStream);
15588 SmallString<256> MangledName;
15589 llvm::raw_svector_ostream mangledNameStream(MangledName);
15590 if (Destructor)
15591 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15592 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15593 mangledNameStream);
15594 else
15595 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15596 mangledNameStream);
15597
15598 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15599 }
15600 }
15601 llvm::StringSet<> SimplifiedThunkNames;
15602 for (auto &ThunkList : Thunks) {
15603 llvm::sort(C&: ThunkList.second);
15604 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15605 }
15606 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15607 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15608 return Result;
15609}
15610
15611bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15612 // Check for trivially-destructible here because non-trivially-destructible
15613 // types will always cause the type and any types derived from it to be
15614 // considered non-trivially-copyable. The same cannot be said for
15615 // trivially-copyable because deleting special members of a type derived from
15616 // a non-trivially-copyable type can cause the derived type to be considered
15617 // trivially copyable.
15618 if (getLangOpts().PointerFieldProtectionTagged)
15619 return !isa<CXXRecordDecl>(Val: RD) ||
15620 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15621 return true;
15622}
15623
15624static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15625 std::vector<PFPField> &Fields, bool IncludeVBases) {
15626 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15627 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15628 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15629 for (unsigned i = 0; i != AT->getSize(); ++i)
15630 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15631 Fields, IncludeVBases: true);
15632 }
15633 }
15634 auto *Decl = Ty->getAsCXXRecordDecl();
15635 // isPFPType() is inherited from bases and members (including via arrays), so
15636 // we can early exit if it is false. Unions are excluded per the API
15637 // documentation.
15638 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15639 return;
15640 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15641 for (FieldDecl *Field : Decl->fields()) {
15642 CharUnits FieldOffset =
15643 Offset +
15644 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15645 if (Ctx.isPFPField(Field))
15646 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15647 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15648 /*IncludeVBases=*/true);
15649 }
15650 // Pass false for IncludeVBases below because vbases are only included in
15651 // layout for top-level types, i.e. not bases or vbases.
15652 for (CXXBaseSpecifier &Base : Decl->bases()) {
15653 if (Base.isVirtual())
15654 continue;
15655 CharUnits BaseOffset =
15656 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15657 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15658 /*IncludeVBases=*/false);
15659 }
15660 if (IncludeVBases) {
15661 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15662 CharUnits BaseOffset =
15663 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15664 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15665 /*IncludeVBases=*/false);
15666 }
15667 }
15668}
15669
15670std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15671 std::vector<PFPField> PFPFields;
15672 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15673 return PFPFields;
15674}
15675
15676bool ASTContext::hasPFPFields(QualType Ty) const {
15677 return !findPFPFields(Ty).empty();
15678}
15679
15680bool ASTContext::isPFPField(const FieldDecl *FD) {
15681 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15682 return RD->isPFPType() && FD->getType()->isPointerType() &&
15683 !FD->hasAttr<NoFieldProtectionAttr>();
15684 return false;
15685}
15686
15687void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15688 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15689 if (!FD)
15690 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15691 if (isPFPField(FD))
15692 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15693}
15694
15695void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15696 if (E->getNumComponents() == 0)
15697 return;
15698 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15699 if (Comp.getKind() != OffsetOfNode::Field)
15700 return;
15701 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15702 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15703}
15704
15705namespace {
15706// PaddingCalculator is a utility class that calculates the padding bits in a
15707// c/c++ type. It traverses the type recursively, collecting occupied
15708// bit intervals, and then computes the padding intervals.
15709// If a byte only contains some padding bits, it gets intervals for only those
15710// bits. This is the case for bit-fields.
15711struct PaddingCalculator {
15712 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15713
15714 void run(QualType Ty) {
15715 OccuppiedIntervals.clear();
15716 Stack.clear();
15717
15718 TySizeInBits = Ctx.getTypeSize(T: Ty);
15719
15720 Stack.push_back(Elt: Data{.StartBitOffset: 0, .Ty: Ty.getCanonicalType(), .VisitVirtualBase: true});
15721 while (!Stack.empty()) {
15722 Data Current = Stack.back();
15723 Stack.pop_back();
15724 Visit(D: Current);
15725 }
15726 MergeOccuppiedIntervals();
15727 }
15728
15729 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15730 llvm::SmallVector<ASTContext::BitInterval> Results;
15731 if (OccuppiedIntervals.size() == 1 &&
15732 OccuppiedIntervals.front().First == 0 &&
15733 OccuppiedIntervals.front().Last == TySizeInBits) {
15734 return Results;
15735 }
15736 Results.reserve(N: OccuppiedIntervals.size() + 1);
15737 uint64_t CurrentPos = 0;
15738 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15739 if (OccupiedInterval.First > CurrentPos) {
15740 Results.push_back(
15741 Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: OccupiedInterval.First});
15742 }
15743 CurrentPos = OccupiedInterval.Last;
15744 }
15745 if (TySizeInBits > CurrentPos) {
15746 Results.push_back(Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: TySizeInBits});
15747 }
15748 return Results;
15749 }
15750
15751private:
15752 struct Data {
15753 uint64_t StartBitOffset;
15754 QualType Ty;
15755 bool VisitVirtualBase;
15756 };
15757
15758 // Return the number of non padding bits of a scalar type.
15759 //
15760 // The property that we specifically care about here is whether the scalar
15761 // type has padding bits, i.e. are there bits in the type which are not
15762 // specified by the ABI.
15763 //
15764 // We currently don't care about this anywhere else in clang: layout cares
15765 // about the ABI size, calling convention code cares about specific types,
15766 // but nothing cares about padding specifically. And it's not something we can
15767 // easily query from LLVM due to the type system mismatches.
15768 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15769 // DataLayout methods aren't really designed for this usage.
15770 //
15771 // Therefore, it is better to explicitly list all the scalar types
15772 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15773 // double.
15774 //
15775 // FIXME: There are likely other scalar types we need to think about here, as
15776 // brought up in review for #215823:
15777 // - bool
15778 // - enums(both with/without fixed underlying type)
15779 // - nullptr_t
15780 // - more?
15781 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15782 if (const auto *BIT = Ty->getAs<BitIntType>())
15783 return BIT->getNumBits();
15784
15785 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15786 if (BT->getKind() == BuiltinType::LongDouble &&
15787 &Ctx.getTargetInfo().getLongDoubleFormat() ==
15788 &llvm::APFloat::x87DoubleExtended())
15789 return llvm::APFloat::getSizeInBits(
15790 Sem: Ctx.getTargetInfo().getLongDoubleFormat());
15791 }
15792
15793 return Ctx.getTypeSize(T: Ty);
15794 }
15795
15796 void Visit(const Data &D) {
15797 if (auto *AT = dyn_cast<ConstantArrayType>(Val: D.Ty)) {
15798 VisitArray(AT, StartBitOffset: D.StartBitOffset);
15799 return;
15800 }
15801
15802 if (auto *Record = D.Ty->getAsRecordDecl()) {
15803 VisitStruct(R: Record, StartBitOffset: D.StartBitOffset, VisitVirtualBase: D.VisitVirtualBase);
15804 return;
15805 }
15806
15807 if (D.Ty->isAtomicType()) {
15808 auto Unwrapped = D;
15809 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15810 Stack.push_back(Elt: Unwrapped);
15811 return;
15812 }
15813
15814 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15815 VisitComplex(CT: Complex, StartBitOffset: D.StartBitOffset);
15816 return;
15817 }
15818
15819 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15820 VisitVector(VT, StartBitOffset: D.StartBitOffset);
15821 return;
15822 }
15823
15824 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15825 VisitBitInt(Ty: BITy, StartBitOffset: D.StartBitOffset);
15826 return;
15827 }
15828
15829 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: D.Ty);
15830 OccuppiedIntervals.push_back(
15831 Elt: ASTContext::BitInterval{.First: D.StartBitOffset, .Last: D.StartBitOffset + SizeBit});
15832 }
15833
15834 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15835 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15836 ++ArrIndex) {
15837
15838 QualType ElementQualType = AT->getElementType();
15839 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15840 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15841 auto Offset = ElementSize.alignTo(Align: ElementAlign);
15842
15843 Stack.push_back(Elt: Data{
15844 .StartBitOffset: StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15845 .Ty: ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15846 }
15847 }
15848
15849 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15850 bool VisitVirtualBase) {
15851 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(D: R);
15852 auto *CXXRecord = dyn_cast<CXXRecordDecl>(Val: R);
15853
15854 unsigned PointerSizeInBits = Ctx.getTypeSize(T: Ctx.NullPtrTy);
15855
15856 if (CXXRecord) {
15857 if (ASTLayout.hasOwnVFPtr()) {
15858 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15859 .First: StartBitOffset, .Last: StartBitOffset + PointerSizeInBits});
15860 }
15861
15862 if (ASTLayout.hasOwnVBPtr()) {
15863 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15864 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15865 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15866 .First: StartVBPtr, .Last: StartVBPtr + PointerSizeInBits});
15867 }
15868
15869 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15870 const CXXBaseSpecifier &Base, auto GetOffset) {
15871 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15872 if (!BaseRecord) {
15873 return;
15874 }
15875 auto BaseOffset =
15876 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15877
15878 Stack.push_back(
15879 Elt: Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15880 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15881 false});
15882 };
15883
15884 for (auto Base : CXXRecord->bases()) {
15885 if (!Base.isVirtual()) {
15886 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15887 }
15888 }
15889
15890 if (VisitVirtualBase) {
15891 for (auto VBase : CXXRecord->vbases()) {
15892 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15893 }
15894 }
15895 }
15896
15897 for (auto *Field : R->fields()) {
15898 // Treat unnamed bitfields as padding.
15899 if (Field->isUnnamedBitField())
15900 continue;
15901
15902 auto FieldOffset = ASTLayout.getFieldOffset(FieldNo: Field->getFieldIndex());
15903 if (Field->isBitField()) {
15904 VisitBitfield(Field, StartBitOffset: StartBitOffset + FieldOffset);
15905 } else {
15906 Stack.push_back(Elt: Data{.StartBitOffset: StartBitOffset + FieldOffset,
15907 .Ty: Field->getType().getCanonicalType(),
15908 /*VisitVirtualBase*/ true});
15909 }
15910 }
15911 }
15912
15913 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
15914 assert(Field->isBitField() && !Field->isUnnamedBitField());
15915 if (Field->isZeroLengthBitField())
15916 return;
15917
15918 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
15919
15920 // Handle over-sized bitfields:
15921 // unsigned char a : 12;
15922 // In this case, DeclaredSizeInBits is 12, but the actually occupied bit
15923 // size is 8, while the remaining 4 bits are padding.
15924 const uint64_t OccupiedSizeInBits =
15925 std::min(a: DeclaredSizeInBits,
15926 b: static_cast<uint64_t>(Ctx.getIntWidth(T: Field->getType())));
15927
15928 if (Ctx.getTargetInfo().isLittleEndian()) {
15929 OccuppiedIntervals.push_back(
15930 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
15931 return;
15932 }
15933
15934 // In big endian mode, the sequence of occupied bits traverses bytes in
15935 // increasing address order, just like in little endian. However, within
15936 // each byte, the traversal starts from the most significant bit. This is
15937 // where it differs from little endian.
15938 //
15939 // If the interval contains whole bytes in the middle, then for these
15940 // nothing changes, and they constitute a contiguous interval. However for
15941 // the partially occupied bytes in either end, if present, their bit
15942 // intervals need to be adjusted so that they count from the MSB instead.
15943 //
15944 // FIXME: For over-sized bitfields in BE, Clang allocates padding bits
15945 // before the occupied bits. This violates the ABI rules, which say that
15946 // padding should be allocated after, regardless of endianness (Itanium C++
15947 // ABI §2.4, II.1(b)). The current code accommodates for Clang's current
15948 // behaviour though, and bumps Start forward to skip the leading padding
15949 // bits.
15950 const uint64_t Start =
15951 StartBitOffset + DeclaredSizeInBits - OccupiedSizeInBits;
15952 const uint64_t End = Start + OccupiedSizeInBits;
15953 const uint64_t CharWidth = Ctx.getCharWidth();
15954
15955 // Special case: all the occupied bits are contained within a single byte.
15956 const uint64_t ByteStart = llvm::alignDown(Value: Start, Align: CharWidth);
15957 const uint64_t ByteEnd = llvm::alignTo(Value: End, Align: CharWidth);
15958 if (ByteStart == ByteEnd - CharWidth) {
15959 const uint64_t Length = End - Start;
15960 const uint64_t Offset = Start - ByteStart;
15961 OccuppiedIntervals.push_back(
15962 Elt: {.First: ByteEnd - Offset - Length, .Last: ByteEnd - Offset});
15963 return;
15964 }
15965
15966 // Compute the contiguous interval in the middle, comprised of whole bytes,
15967 // if any.
15968 const uint64_t MiddleIntervalStart = llvm::alignTo(Value: Start, Align: CharWidth);
15969 const uint64_t MiddleIntervalEnd = llvm::alignDown(Value: End, Align: CharWidth);
15970 if (MiddleIntervalStart != MiddleIntervalEnd)
15971 OccuppiedIntervals.push_back(Elt: {.First: MiddleIntervalStart, .Last: MiddleIntervalEnd});
15972
15973 // Compute the partially occupied first byte's interval, if any, counting
15974 // from the MSB.
15975 if (Start != MiddleIntervalStart) {
15976 const uint64_t Length = MiddleIntervalStart - Start;
15977 OccuppiedIntervals.push_back(Elt: {.First: ByteStart, .Last: ByteStart + Length});
15978 }
15979
15980 // Compute the partially occupied last byte's interval, if any, counting
15981 // from the MSB.
15982 if (End != MiddleIntervalEnd) {
15983 const uint64_t Length = End - MiddleIntervalEnd;
15984 OccuppiedIntervals.push_back(Elt: {.First: ByteEnd - Length, .Last: ByteEnd});
15985 }
15986 }
15987
15988 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
15989 QualType ElementQualType = CT->getElementType().getCanonicalType();
15990 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15991 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15992 auto ImgOffset = ElementSize.alignTo(Align: ElementAlign);
15993
15994 Stack.push_back(
15995 Elt: Data{.StartBitOffset: StartBitOffset, .Ty: ElementQualType, /*VisitVirtualBase*/ true});
15996 Stack.push_back(
15997 Elt: Data{.StartBitOffset: StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
15998 .Ty: ElementQualType, /*VisitVirtualBase*/ true});
15999 }
16000
16001 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16002 uint64_t SizeBit = [&]() -> uint64_t {
16003 if (VT->isPackedVectorBoolType(ctx: Ctx))
16004 return VT->getNumElements();
16005 return getScalarOccupiedSizeInBits(Ty: VT->getElementType()) *
16006 VT->getNumElements();
16007 }();
16008 OccuppiedIntervals.push_back(
16009 Elt: ASTContext::BitInterval{.First: StartBitOffset, .Last: StartBitOffset + SizeBit});
16010 }
16011
16012 /// Compute the occupied bit intervals for a BitInt.
16013 ///
16014 /// In the case of little endian, the occupied bits are always contiguous so a
16015 /// single interval is sufficient. However in big endian, the intervals can be
16016 /// disjoint.
16017 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16018 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16019
16020 if (Ctx.getTargetInfo().isLittleEndian()) {
16021 OccuppiedIntervals.push_back(
16022 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16023 return;
16024 }
16025
16026 // In big endian mode, the layout of a BitInt in memory has its bytes in
16027 // reverse order, and is pictured in this order:
16028 // 1. Fully padding bytes.
16029 // 2. One partially occupied byte, with padding at the most significant
16030 // bits. ("remaining occupied bits")
16031 // 3. A sequence of fully occupied bytes up until the end of the storage.
16032 const uint64_t StorageSizeInBits = Ctx.getTypeSize(T: Ty);
16033 const uint64_t CharWidth = Ctx.getCharWidth();
16034 const uint64_t NumFullyPaddingBytes =
16035 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16036 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16037 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16038
16039 // Partially occupied byte
16040 if (NumRemainingOccupiedBits > 0)
16041 OccuppiedIntervals.push_back(
16042 Elt: {.First: StartBitOffset + NumFullyPaddingBytes * CharWidth,
16043 .Last: StartBitOffset + NumFullyPaddingBytes * CharWidth +
16044 NumRemainingOccupiedBits});
16045
16046 // Fully occupied bytes
16047 if (NumFullyOccupiedBytes > 0)
16048 OccuppiedIntervals.push_back(Elt: {.First: StartBitOffset + StorageSizeInBits -
16049 NumFullyOccupiedBytes * CharWidth,
16050 .Last: StartBitOffset + StorageSizeInBits});
16051 }
16052
16053 void MergeOccuppiedIntervals() {
16054 std::sort(first: OccuppiedIntervals.begin(), last: OccuppiedIntervals.end(),
16055 comp: [](const ASTContext::BitInterval &lhs,
16056 const ASTContext::BitInterval &rhs) {
16057 return std::tie(args: lhs.First, args: lhs.Last) <
16058 std::tie(args: rhs.First, args: rhs.Last);
16059 });
16060
16061 llvm::SmallVector<ASTContext::BitInterval> Merged;
16062 Merged.reserve(N: OccuppiedIntervals.size());
16063
16064 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16065 if (Merged.empty()) {
16066 Merged.push_back(Elt: NextInterval);
16067 continue;
16068 }
16069 auto &LastInterval = Merged.back();
16070
16071 if (NextInterval.First > LastInterval.Last) {
16072 Merged.push_back(Elt: NextInterval);
16073 } else {
16074 LastInterval.Last = std::max(a: LastInterval.Last, b: NextInterval.Last);
16075 }
16076 }
16077
16078 OccuppiedIntervals = Merged;
16079 }
16080
16081 const ASTContext &Ctx;
16082 // unsigned PointerSizeInBits;
16083 uint64_t TySizeInBits = 0;
16084 llvm::SmallVector<Data> Stack;
16085 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16086};
16087} // namespace
16088
16089llvm::ArrayRef<ASTContext::BitInterval>
16090ASTContext::getPaddingIntervals(QualType Ty) const {
16091 Ty = Ty.getCanonicalType();
16092 auto cached = PaddingIntervalCache.find(Val: Ty);
16093 if (cached != PaddingIntervalCache.end())
16094 return cached->second;
16095
16096 PaddingCalculator pc{*this};
16097 pc.run(Ty);
16098
16099 auto [itr, res] =
16100 PaddingIntervalCache.insert_or_assign(Key: Ty, Val: pc.GetPaddingIntervals());
16101 assert(res && "Failed to insert?");
16102
16103 return itr->second;
16104}
16105