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