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