]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/AST/ASTContext.cpp
Merge ^/head r364051 through r364081.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / AST / ASTContext.cpp
1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the ASTContext interface.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/ASTContext.h"
14 #include "CXXABI.h"
15 #include "Interp/Context.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Comment.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclContextInternals.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/DeclarationName.h"
32 #include "clang/AST/DependenceFlags.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/ExprConcepts.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/FixedPoint.h"
55 #include "clang/Basic/IdentifierTable.h"
56 #include "clang/Basic/LLVM.h"
57 #include "clang/Basic/LangOptions.h"
58 #include "clang/Basic/Linkage.h"
59 #include "clang/Basic/Module.h"
60 #include "clang/Basic/ObjCRuntime.h"
61 #include "clang/Basic/SanitizerBlacklist.h"
62 #include "clang/Basic/SourceLocation.h"
63 #include "clang/Basic/SourceManager.h"
64 #include "clang/Basic/Specifiers.h"
65 #include "clang/Basic/TargetCXXABI.h"
66 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/XRayLists.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/ArrayRef.h"
71 #include "llvm/ADT/DenseMap.h"
72 #include "llvm/ADT/DenseSet.h"
73 #include "llvm/ADT/FoldingSet.h"
74 #include "llvm/ADT/None.h"
75 #include "llvm/ADT/Optional.h"
76 #include "llvm/ADT/PointerUnion.h"
77 #include "llvm/ADT/STLExtras.h"
78 #include "llvm/ADT/SmallPtrSet.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringExtras.h"
81 #include "llvm/ADT/StringRef.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/Support/Capacity.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <cstdlib>
94 #include <map>
95 #include <memory>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99
100 using namespace clang;
101
102 enum FloatingRank {
103   BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
104 };
105
106 /// \returns location that is relevant when searching for Doc comments related
107 /// to \p D.
108 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
109                                                  SourceManager &SourceMgr) {
110   assert(D);
111
112   // User can not attach documentation to implicit declarations.
113   if (D->isImplicit())
114     return {};
115
116   // User can not attach documentation to implicit instantiations.
117   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
118     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
119       return {};
120   }
121
122   if (const auto *VD = dyn_cast<VarDecl>(D)) {
123     if (VD->isStaticDataMember() &&
124         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
125       return {};
126   }
127
128   if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
129     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130       return {};
131   }
132
133   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
134     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
135     if (TSK == TSK_ImplicitInstantiation ||
136         TSK == TSK_Undeclared)
137       return {};
138   }
139
140   if (const auto *ED = dyn_cast<EnumDecl>(D)) {
141     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142       return {};
143   }
144   if (const auto *TD = dyn_cast<TagDecl>(D)) {
145     // When tag declaration (but not definition!) is part of the
146     // decl-specifier-seq of some other declaration, it doesn't get comment
147     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
148       return {};
149   }
150   // TODO: handle comments for function parameters properly.
151   if (isa<ParmVarDecl>(D))
152     return {};
153
154   // TODO: we could look up template parameter documentation in the template
155   // documentation.
156   if (isa<TemplateTypeParmDecl>(D) ||
157       isa<NonTypeTemplateParmDecl>(D) ||
158       isa<TemplateTemplateParmDecl>(D))
159     return {};
160
161   // Find declaration location.
162   // For Objective-C declarations we generally don't expect to have multiple
163   // declarators, thus use declaration starting location as the "declaration
164   // location".
165   // For all other declarations multiple declarators are used quite frequently,
166   // so we use the location of the identifier as the "declaration location".
167   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
168       isa<ObjCPropertyDecl>(D) ||
169       isa<RedeclarableTemplateDecl>(D) ||
170       isa<ClassTemplateSpecializationDecl>(D) ||
171       // Allow association with Y across {} in `typedef struct X {} Y`.
172       isa<TypedefDecl>(D))
173     return D->getBeginLoc();
174   else {
175     const SourceLocation DeclLoc = D->getLocation();
176     if (DeclLoc.isMacroID()) {
177       if (isa<TypedefDecl>(D)) {
178         // If location of the typedef name is in a macro, it is because being
179         // declared via a macro. Try using declaration's starting location as
180         // the "declaration location".
181         return D->getBeginLoc();
182       } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
183         // If location of the tag decl is inside a macro, but the spelling of
184         // the tag name comes from a macro argument, it looks like a special
185         // macro like NS_ENUM is being used to define the tag decl.  In that
186         // case, adjust the source location to the expansion loc so that we can
187         // attach the comment to the tag decl.
188         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
189             TD->isCompleteDefinition())
190           return SourceMgr.getExpansionLoc(DeclLoc);
191       }
192     }
193     return DeclLoc;
194   }
195
196   return {};
197 }
198
199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
200     const Decl *D, const SourceLocation RepresentativeLocForDecl,
201     const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
202   // If the declaration doesn't map directly to a location in a file, we
203   // can't find the comment.
204   if (RepresentativeLocForDecl.isInvalid() ||
205       !RepresentativeLocForDecl.isFileID())
206     return nullptr;
207
208   // If there are no comments anywhere, we won't find anything.
209   if (CommentsInTheFile.empty())
210     return nullptr;
211
212   // Decompose the location for the declaration and find the beginning of the
213   // file buffer.
214   const std::pair<FileID, unsigned> DeclLocDecomp =
215       SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
216
217   // Slow path.
218   auto OffsetCommentBehindDecl =
219       CommentsInTheFile.lower_bound(DeclLocDecomp.second);
220
221   // First check whether we have a trailing comment.
222   if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
223     RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
224     if ((CommentBehindDecl->isDocumentation() ||
225          LangOpts.CommentOpts.ParseAllComments) &&
226         CommentBehindDecl->isTrailingComment() &&
227         (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
228          isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
229
230       // Check that Doxygen trailing comment comes after the declaration, starts
231       // on the same line and in the same file as the declaration.
232       if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
233           Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
234                                        OffsetCommentBehindDecl->first)) {
235         return CommentBehindDecl;
236       }
237     }
238   }
239
240   // The comment just after the declaration was not a trailing comment.
241   // Let's look at the previous comment.
242   if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
243     return nullptr;
244
245   auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
246   RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
247
248   // Check that we actually have a non-member Doxygen comment.
249   if (!(CommentBeforeDecl->isDocumentation() ||
250         LangOpts.CommentOpts.ParseAllComments) ||
251       CommentBeforeDecl->isTrailingComment())
252     return nullptr;
253
254   // Decompose the end of the comment.
255   const unsigned CommentEndOffset =
256       Comments.getCommentEndOffset(CommentBeforeDecl);
257
258   // Get the corresponding buffer.
259   bool Invalid = false;
260   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
261                                                &Invalid).data();
262   if (Invalid)
263     return nullptr;
264
265   // Extract text between the comment and declaration.
266   StringRef Text(Buffer + CommentEndOffset,
267                  DeclLocDecomp.second - CommentEndOffset);
268
269   // There should be no other declarations or preprocessor directives between
270   // comment and declaration.
271   if (Text.find_first_of(";{}#@") != StringRef::npos)
272     return nullptr;
273
274   return CommentBeforeDecl;
275 }
276
277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
278   const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
279
280   // If the declaration doesn't map directly to a location in a file, we
281   // can't find the comment.
282   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
283     return nullptr;
284
285   if (ExternalSource && !CommentsLoaded) {
286     ExternalSource->ReadComments();
287     CommentsLoaded = true;
288   }
289
290   if (Comments.empty())
291     return nullptr;
292
293   const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
294   const auto CommentsInThisFile = Comments.getCommentsInFile(File);
295   if (!CommentsInThisFile || CommentsInThisFile->empty())
296     return nullptr;
297
298   return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
299 }
300
301 void ASTContext::addComment(const RawComment &RC) {
302   assert(LangOpts.RetainCommentsFromSystemHeaders ||
303          !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
304   Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
305 }
306
307 /// If we have a 'templated' declaration for a template, adjust 'D' to
308 /// refer to the actual template.
309 /// If we have an implicit instantiation, adjust 'D' to refer to template.
310 static const Decl &adjustDeclToTemplate(const Decl &D) {
311   if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
312     // Is this function declaration part of a function template?
313     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
314       return *FTD;
315
316     // Nothing to do if function is not an implicit instantiation.
317     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
318       return D;
319
320     // Function is an implicit instantiation of a function template?
321     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
322       return *FTD;
323
324     // Function is instantiated from a member definition of a class template?
325     if (const FunctionDecl *MemberDecl =
326             FD->getInstantiatedFromMemberFunction())
327       return *MemberDecl;
328
329     return D;
330   }
331   if (const auto *VD = dyn_cast<VarDecl>(&D)) {
332     // Static data member is instantiated from a member definition of a class
333     // template?
334     if (VD->isStaticDataMember())
335       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
336         return *MemberDecl;
337
338     return D;
339   }
340   if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
341     // Is this class declaration part of a class template?
342     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
343       return *CTD;
344
345     // Class is an implicit instantiation of a class template or partial
346     // specialization?
347     if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
348       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
349         return D;
350       llvm::PointerUnion<ClassTemplateDecl *,
351                          ClassTemplatePartialSpecializationDecl *>
352           PU = CTSD->getSpecializedTemplateOrPartial();
353       return PU.is<ClassTemplateDecl *>()
354                  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
355                  : *static_cast<const Decl *>(
356                        PU.get<ClassTemplatePartialSpecializationDecl *>());
357     }
358
359     // Class is instantiated from a member definition of a class template?
360     if (const MemberSpecializationInfo *Info =
361             CRD->getMemberSpecializationInfo())
362       return *Info->getInstantiatedFrom();
363
364     return D;
365   }
366   if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
367     // Enum is instantiated from a member definition of a class template?
368     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
369       return *MemberDecl;
370
371     return D;
372   }
373   // FIXME: Adjust alias templates?
374   return D;
375 }
376
377 const RawComment *ASTContext::getRawCommentForAnyRedecl(
378                                                 const Decl *D,
379                                                 const Decl **OriginalDecl) const {
380   if (!D) {
381     if (OriginalDecl)
382       OriginalDecl = nullptr;
383     return nullptr;
384   }
385
386   D = &adjustDeclToTemplate(*D);
387
388   // Any comment directly attached to D?
389   {
390     auto DeclComment = DeclRawComments.find(D);
391     if (DeclComment != DeclRawComments.end()) {
392       if (OriginalDecl)
393         *OriginalDecl = D;
394       return DeclComment->second;
395     }
396   }
397
398   // Any comment attached to any redeclaration of D?
399   const Decl *CanonicalD = D->getCanonicalDecl();
400   if (!CanonicalD)
401     return nullptr;
402
403   {
404     auto RedeclComment = RedeclChainComments.find(CanonicalD);
405     if (RedeclComment != RedeclChainComments.end()) {
406       if (OriginalDecl)
407         *OriginalDecl = RedeclComment->second;
408       auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
409       assert(CommentAtRedecl != DeclRawComments.end() &&
410              "This decl is supposed to have comment attached.");
411       return CommentAtRedecl->second;
412     }
413   }
414
415   // Any redeclarations of D that we haven't checked for comments yet?
416   // We can't use DenseMap::iterator directly since it'd get invalid.
417   auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
418     auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
419     if (LookupRes != CommentlessRedeclChains.end())
420       return LookupRes->second;
421     return nullptr;
422   }();
423
424   for (const auto Redecl : D->redecls()) {
425     assert(Redecl);
426     // Skip all redeclarations that have been checked previously.
427     if (LastCheckedRedecl) {
428       if (LastCheckedRedecl == Redecl) {
429         LastCheckedRedecl = nullptr;
430       }
431       continue;
432     }
433     const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
434     if (RedeclComment) {
435       cacheRawCommentForDecl(*Redecl, *RedeclComment);
436       if (OriginalDecl)
437         *OriginalDecl = Redecl;
438       return RedeclComment;
439     }
440     CommentlessRedeclChains[CanonicalD] = Redecl;
441   }
442
443   if (OriginalDecl)
444     *OriginalDecl = nullptr;
445   return nullptr;
446 }
447
448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
449                                         const RawComment &Comment) const {
450   assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
451   DeclRawComments.try_emplace(&OriginalD, &Comment);
452   const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
453   RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
454   CommentlessRedeclChains.erase(CanonicalDecl);
455 }
456
457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
458                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
459   const DeclContext *DC = ObjCMethod->getDeclContext();
460   if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
461     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
462     if (!ID)
463       return;
464     // Add redeclared method here.
465     for (const auto *Ext : ID->known_extensions()) {
466       if (ObjCMethodDecl *RedeclaredMethod =
467             Ext->getMethod(ObjCMethod->getSelector(),
468                                   ObjCMethod->isInstanceMethod()))
469         Redeclared.push_back(RedeclaredMethod);
470     }
471   }
472 }
473
474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
475                                                  const Preprocessor *PP) {
476   if (Comments.empty() || Decls.empty())
477     return;
478
479   FileID File;
480   for (Decl *D : Decls) {
481     SourceLocation Loc = D->getLocation();
482     if (Loc.isValid()) {
483       // See if there are any new comments that are not attached to a decl.
484       // The location doesn't have to be precise - we care only about the file.
485       File = SourceMgr.getDecomposedLoc(Loc).first;
486       break;
487     }
488   }
489
490   if (File.isInvalid())
491     return;
492
493   auto CommentsInThisFile = Comments.getCommentsInFile(File);
494   if (!CommentsInThisFile || CommentsInThisFile->empty() ||
495       CommentsInThisFile->rbegin()->second->isAttached())
496     return;
497
498   // There is at least one comment not attached to a decl.
499   // Maybe it should be attached to one of Decls?
500   //
501   // Note that this way we pick up not only comments that precede the
502   // declaration, but also comments that *follow* the declaration -- thanks to
503   // the lookahead in the lexer: we've consumed the semicolon and looked
504   // ahead through comments.
505
506   for (const Decl *D : Decls) {
507     assert(D);
508     if (D->isInvalidDecl())
509       continue;
510
511     D = &adjustDeclToTemplate(*D);
512
513     const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
514
515     if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
516       continue;
517
518     if (DeclRawComments.count(D) > 0)
519       continue;
520
521     if (RawComment *const DocComment =
522             getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
523       cacheRawCommentForDecl(*D, *DocComment);
524       comments::FullComment *FC = DocComment->parse(*this, PP, D);
525       ParsedComments[D->getCanonicalDecl()] = FC;
526     }
527   }
528 }
529
530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
531                                                     const Decl *D) const {
532   auto *ThisDeclInfo = new (*this) comments::DeclInfo;
533   ThisDeclInfo->CommentDecl = D;
534   ThisDeclInfo->IsFilled = false;
535   ThisDeclInfo->fill();
536   ThisDeclInfo->CommentDecl = FC->getDecl();
537   if (!ThisDeclInfo->TemplateParameters)
538     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
539   comments::FullComment *CFC =
540     new (*this) comments::FullComment(FC->getBlocks(),
541                                       ThisDeclInfo);
542   return CFC;
543 }
544
545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
546   const RawComment *RC = getRawCommentForDeclNoCache(D);
547   return RC ? RC->parse(*this, nullptr, D) : nullptr;
548 }
549
550 comments::FullComment *ASTContext::getCommentForDecl(
551                                               const Decl *D,
552                                               const Preprocessor *PP) const {
553   if (!D || D->isInvalidDecl())
554     return nullptr;
555   D = &adjustDeclToTemplate(*D);
556
557   const Decl *Canonical = D->getCanonicalDecl();
558   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
559       ParsedComments.find(Canonical);
560
561   if (Pos != ParsedComments.end()) {
562     if (Canonical != D) {
563       comments::FullComment *FC = Pos->second;
564       comments::FullComment *CFC = cloneFullComment(FC, D);
565       return CFC;
566     }
567     return Pos->second;
568   }
569
570   const Decl *OriginalDecl = nullptr;
571
572   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
573   if (!RC) {
574     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
575       SmallVector<const NamedDecl*, 8> Overridden;
576       const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
577       if (OMD && OMD->isPropertyAccessor())
578         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
579           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
580             return cloneFullComment(FC, D);
581       if (OMD)
582         addRedeclaredMethods(OMD, Overridden);
583       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
584       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
585         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
586           return cloneFullComment(FC, D);
587     }
588     else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
589       // Attach any tag type's documentation to its typedef if latter
590       // does not have one of its own.
591       QualType QT = TD->getUnderlyingType();
592       if (const auto *TT = QT->getAs<TagType>())
593         if (const Decl *TD = TT->getDecl())
594           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
595             return cloneFullComment(FC, D);
596     }
597     else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
598       while (IC->getSuperClass()) {
599         IC = IC->getSuperClass();
600         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
601           return cloneFullComment(FC, D);
602       }
603     }
604     else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
605       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
606         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
607           return cloneFullComment(FC, D);
608     }
609     else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
610       if (!(RD = RD->getDefinition()))
611         return nullptr;
612       // Check non-virtual bases.
613       for (const auto &I : RD->bases()) {
614         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
615           continue;
616         QualType Ty = I.getType();
617         if (Ty.isNull())
618           continue;
619         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
620           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
621             continue;
622
623           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
624             return cloneFullComment(FC, D);
625         }
626       }
627       // Check virtual bases.
628       for (const auto &I : RD->vbases()) {
629         if (I.getAccessSpecifier() != AS_public)
630           continue;
631         QualType Ty = I.getType();
632         if (Ty.isNull())
633           continue;
634         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
635           if (!(VirtualBase= VirtualBase->getDefinition()))
636             continue;
637           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
638             return cloneFullComment(FC, D);
639         }
640       }
641     }
642     return nullptr;
643   }
644
645   // If the RawComment was attached to other redeclaration of this Decl, we
646   // should parse the comment in context of that other Decl.  This is important
647   // because comments can contain references to parameter names which can be
648   // different across redeclarations.
649   if (D != OriginalDecl && OriginalDecl)
650     return getCommentForDecl(OriginalDecl, PP);
651
652   comments::FullComment *FC = RC->parse(*this, PP, D);
653   ParsedComments[Canonical] = FC;
654   return FC;
655 }
656
657 void
658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
659                                                    const ASTContext &C,
660                                                TemplateTemplateParmDecl *Parm) {
661   ID.AddInteger(Parm->getDepth());
662   ID.AddInteger(Parm->getPosition());
663   ID.AddBoolean(Parm->isParameterPack());
664
665   TemplateParameterList *Params = Parm->getTemplateParameters();
666   ID.AddInteger(Params->size());
667   for (TemplateParameterList::const_iterator P = Params->begin(),
668                                           PEnd = Params->end();
669        P != PEnd; ++P) {
670     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
671       ID.AddInteger(0);
672       ID.AddBoolean(TTP->isParameterPack());
673       const TypeConstraint *TC = TTP->getTypeConstraint();
674       ID.AddBoolean(TC != nullptr);
675       if (TC)
676         TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
677                                                         /*Canonical=*/true);
678       if (TTP->isExpandedParameterPack()) {
679         ID.AddBoolean(true);
680         ID.AddInteger(TTP->getNumExpansionParameters());
681       } else
682         ID.AddBoolean(false);
683       continue;
684     }
685
686     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
687       ID.AddInteger(1);
688       ID.AddBoolean(NTTP->isParameterPack());
689       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
690       if (NTTP->isExpandedParameterPack()) {
691         ID.AddBoolean(true);
692         ID.AddInteger(NTTP->getNumExpansionTypes());
693         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
694           QualType T = NTTP->getExpansionType(I);
695           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
696         }
697       } else
698         ID.AddBoolean(false);
699       continue;
700     }
701
702     auto *TTP = cast<TemplateTemplateParmDecl>(*P);
703     ID.AddInteger(2);
704     Profile(ID, C, TTP);
705   }
706   Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
707   ID.AddBoolean(RequiresClause != nullptr);
708   if (RequiresClause)
709     RequiresClause->Profile(ID, C, /*Canonical=*/true);
710 }
711
712 static Expr *
713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
714                                           QualType ConstrainedType) {
715   // This is a bit ugly - we need to form a new immediately-declared
716   // constraint that references the new parameter; this would ideally
717   // require semantic analysis (e.g. template<C T> struct S {}; - the
718   // converted arguments of C<T> could be an argument pack if C is
719   // declared as template<typename... T> concept C = ...).
720   // We don't have semantic analysis here so we dig deep into the
721   // ready-made constraint expr and change the thing manually.
722   ConceptSpecializationExpr *CSE;
723   if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
724     CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
725   else
726     CSE = cast<ConceptSpecializationExpr>(IDC);
727   ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
728   SmallVector<TemplateArgument, 3> NewConverted;
729   NewConverted.reserve(OldConverted.size());
730   if (OldConverted.front().getKind() == TemplateArgument::Pack) {
731     // The case:
732     // template<typename... T> concept C = true;
733     // template<C<int> T> struct S; -> constraint is C<{T, int}>
734     NewConverted.push_back(ConstrainedType);
735     for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
736       NewConverted.push_back(Arg);
737     TemplateArgument NewPack(NewConverted);
738
739     NewConverted.clear();
740     NewConverted.push_back(NewPack);
741     assert(OldConverted.size() == 1 &&
742            "Template parameter pack should be the last parameter");
743   } else {
744     assert(OldConverted.front().getKind() == TemplateArgument::Type &&
745            "Unexpected first argument kind for immediately-declared "
746            "constraint");
747     NewConverted.push_back(ConstrainedType);
748     for (auto &Arg : OldConverted.drop_front(1))
749       NewConverted.push_back(Arg);
750   }
751   Expr *NewIDC = ConceptSpecializationExpr::Create(
752       C, CSE->getNamedConcept(), NewConverted, nullptr,
753       CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
754
755   if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
756     NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC,
757                                  BinaryOperatorKind::BO_LAnd,
758                                  SourceLocation(), /*RHS=*/nullptr,
759                                  SourceLocation(), /*NumExpansions=*/None);
760   return NewIDC;
761 }
762
763 TemplateTemplateParmDecl *
764 ASTContext::getCanonicalTemplateTemplateParmDecl(
765                                           TemplateTemplateParmDecl *TTP) const {
766   // Check if we already have a canonical template template parameter.
767   llvm::FoldingSetNodeID ID;
768   CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
769   void *InsertPos = nullptr;
770   CanonicalTemplateTemplateParm *Canonical
771     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
772   if (Canonical)
773     return Canonical->getParam();
774
775   // Build a canonical template parameter list.
776   TemplateParameterList *Params = TTP->getTemplateParameters();
777   SmallVector<NamedDecl *, 4> CanonParams;
778   CanonParams.reserve(Params->size());
779   for (TemplateParameterList::const_iterator P = Params->begin(),
780                                           PEnd = Params->end();
781        P != PEnd; ++P) {
782     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
783       TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
784           getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
785           TTP->getDepth(), TTP->getIndex(), nullptr, false,
786           TTP->isParameterPack(), TTP->hasTypeConstraint(),
787           TTP->isExpandedParameterPack() ?
788           llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
789       if (const auto *TC = TTP->getTypeConstraint()) {
790         QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
791         Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
792                 *this, TC->getImmediatelyDeclaredConstraint(),
793                 ParamAsArgument);
794         TemplateArgumentListInfo CanonArgsAsWritten;
795         if (auto *Args = TC->getTemplateArgsAsWritten())
796           for (const auto &ArgLoc : Args->arguments())
797             CanonArgsAsWritten.addArgument(
798                 TemplateArgumentLoc(ArgLoc.getArgument(),
799                                     TemplateArgumentLocInfo()));
800         NewTTP->setTypeConstraint(
801             NestedNameSpecifierLoc(),
802             DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
803                                 SourceLocation()), /*FoundDecl=*/nullptr,
804             // Actually canonicalizing a TemplateArgumentLoc is difficult so we
805             // simply omit the ArgsAsWritten
806             TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
807       }
808       CanonParams.push_back(NewTTP);
809     } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
810       QualType T = getCanonicalType(NTTP->getType());
811       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
812       NonTypeTemplateParmDecl *Param;
813       if (NTTP->isExpandedParameterPack()) {
814         SmallVector<QualType, 2> ExpandedTypes;
815         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
816         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
817           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
818           ExpandedTInfos.push_back(
819                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
820         }
821
822         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
823                                                 SourceLocation(),
824                                                 SourceLocation(),
825                                                 NTTP->getDepth(),
826                                                 NTTP->getPosition(), nullptr,
827                                                 T,
828                                                 TInfo,
829                                                 ExpandedTypes,
830                                                 ExpandedTInfos);
831       } else {
832         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
833                                                 SourceLocation(),
834                                                 SourceLocation(),
835                                                 NTTP->getDepth(),
836                                                 NTTP->getPosition(), nullptr,
837                                                 T,
838                                                 NTTP->isParameterPack(),
839                                                 TInfo);
840       }
841       if (AutoType *AT = T->getContainedAutoType()) {
842         if (AT->isConstrained()) {
843           Param->setPlaceholderTypeConstraint(
844               canonicalizeImmediatelyDeclaredConstraint(
845                   *this, NTTP->getPlaceholderTypeConstraint(), T));
846         }
847       }
848       CanonParams.push_back(Param);
849
850     } else
851       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
852                                            cast<TemplateTemplateParmDecl>(*P)));
853   }
854
855   Expr *CanonRequiresClause = nullptr;
856   if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
857     CanonRequiresClause = RequiresClause;
858
859   TemplateTemplateParmDecl *CanonTTP
860     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
861                                        SourceLocation(), TTP->getDepth(),
862                                        TTP->getPosition(),
863                                        TTP->isParameterPack(),
864                                        nullptr,
865                          TemplateParameterList::Create(*this, SourceLocation(),
866                                                        SourceLocation(),
867                                                        CanonParams,
868                                                        SourceLocation(),
869                                                        CanonRequiresClause));
870
871   // Get the new insert position for the node we care about.
872   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
873   assert(!Canonical && "Shouldn't be in the map!");
874   (void)Canonical;
875
876   // Create the canonical template template parameter entry.
877   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
878   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
879   return CanonTTP;
880 }
881
882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883   if (!LangOpts.CPlusPlus) return nullptr;
884
885   switch (T.getCXXABI().getKind()) {
886   case TargetCXXABI::Fuchsia:
887   case TargetCXXABI::GenericARM: // Same as Itanium at this level
888   case TargetCXXABI::iOS:
889   case TargetCXXABI::iOS64:
890   case TargetCXXABI::WatchOS:
891   case TargetCXXABI::GenericAArch64:
892   case TargetCXXABI::GenericMIPS:
893   case TargetCXXABI::GenericItanium:
894   case TargetCXXABI::WebAssembly:
895   case TargetCXXABI::XL:
896     return CreateItaniumCXXABI(*this);
897   case TargetCXXABI::Microsoft:
898     return CreateMicrosoftCXXABI(*this);
899   }
900   llvm_unreachable("Invalid CXXABI type!");
901 }
902
903 interp::Context &ASTContext::getInterpContext() {
904   if (!InterpContext) {
905     InterpContext.reset(new interp::Context(*this));
906   }
907   return *InterpContext.get();
908 }
909
910 ParentMapContext &ASTContext::getParentMapContext() {
911   if (!ParentMapCtx)
912     ParentMapCtx.reset(new ParentMapContext(*this));
913   return *ParentMapCtx.get();
914 }
915
916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917                                            const LangOptions &LOpts) {
918   if (LOpts.FakeAddressSpaceMap) {
919     // The fake address space map must have a distinct entry for each
920     // language-specific address space.
921     static const unsigned FakeAddrSpaceMap[] = {
922         0, // Default
923         1, // opencl_global
924         3, // opencl_local
925         2, // opencl_constant
926         0, // opencl_private
927         4, // opencl_generic
928         5, // cuda_device
929         6, // cuda_constant
930         7, // cuda_shared
931         8, // ptr32_sptr
932         9, // ptr32_uptr
933         10 // ptr64
934     };
935     return &FakeAddrSpaceMap;
936   } else {
937     return &T.getAddressSpaceMap();
938   }
939 }
940
941 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
942                                           const LangOptions &LangOpts) {
943   switch (LangOpts.getAddressSpaceMapMangling()) {
944   case LangOptions::ASMM_Target:
945     return TI.useAddressSpaceMapMangling();
946   case LangOptions::ASMM_On:
947     return true;
948   case LangOptions::ASMM_Off:
949     return false;
950   }
951   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
952 }
953
954 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
955                        IdentifierTable &idents, SelectorTable &sels,
956                        Builtin::Context &builtins)
957     : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
958       TemplateSpecializationTypes(this_()),
959       DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
960       SubstTemplateTemplateParmPacks(this_()),
961       CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
962       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
963       XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
964                                         LangOpts.XRayNeverInstrumentFiles,
965                                         LangOpts.XRayAttrListFiles, SM)),
966       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
967       BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
968       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
969       CompCategories(this_()), LastSDM(nullptr, 0) {
970   TUDecl = TranslationUnitDecl::Create(*this);
971   TraversalScope = {TUDecl};
972 }
973
974 ASTContext::~ASTContext() {
975   // Release the DenseMaps associated with DeclContext objects.
976   // FIXME: Is this the ideal solution?
977   ReleaseDeclContextMaps();
978
979   // Call all of the deallocation functions on all of their targets.
980   for (auto &Pair : Deallocations)
981     (Pair.first)(Pair.second);
982
983   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
984   // because they can contain DenseMaps.
985   for (llvm::DenseMap<const ObjCContainerDecl*,
986        const ASTRecordLayout*>::iterator
987        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
988     // Increment in loop to prevent using deallocated memory.
989     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
990       R->Destroy(*this);
991
992   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
993        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
994     // Increment in loop to prevent using deallocated memory.
995     if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
996       R->Destroy(*this);
997   }
998
999   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1000                                                     AEnd = DeclAttrs.end();
1001        A != AEnd; ++A)
1002     A->second->~AttrVec();
1003
1004   for (const auto &Value : ModuleInitializers)
1005     Value.second->~PerModuleInitializers();
1006
1007   for (APValue *Value : APValueCleanups)
1008     Value->~APValue();
1009 }
1010
1011 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1012   TraversalScope = TopLevelDecls;
1013   getParentMapContext().clear();
1014 }
1015
1016 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1017   Deallocations.push_back({Callback, Data});
1018 }
1019
1020 void
1021 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1022   ExternalSource = std::move(Source);
1023 }
1024
1025 void ASTContext::PrintStats() const {
1026   llvm::errs() << "\n*** AST Context Stats:\n";
1027   llvm::errs() << "  " << Types.size() << " types total.\n";
1028
1029   unsigned counts[] = {
1030 #define TYPE(Name, Parent) 0,
1031 #define ABSTRACT_TYPE(Name, Parent)
1032 #include "clang/AST/TypeNodes.inc"
1033     0 // Extra
1034   };
1035
1036   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1037     Type *T = Types[i];
1038     counts[(unsigned)T->getTypeClass()]++;
1039   }
1040
1041   unsigned Idx = 0;
1042   unsigned TotalBytes = 0;
1043 #define TYPE(Name, Parent)                                              \
1044   if (counts[Idx])                                                      \
1045     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
1046                  << " types, " << sizeof(Name##Type) << " each "        \
1047                  << "(" << counts[Idx] * sizeof(Name##Type)             \
1048                  << " bytes)\n";                                        \
1049   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
1050   ++Idx;
1051 #define ABSTRACT_TYPE(Name, Parent)
1052 #include "clang/AST/TypeNodes.inc"
1053
1054   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1055
1056   // Implicit special member functions.
1057   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1058                << NumImplicitDefaultConstructors
1059                << " implicit default constructors created\n";
1060   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1061                << NumImplicitCopyConstructors
1062                << " implicit copy constructors created\n";
1063   if (getLangOpts().CPlusPlus)
1064     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1065                  << NumImplicitMoveConstructors
1066                  << " implicit move constructors created\n";
1067   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1068                << NumImplicitCopyAssignmentOperators
1069                << " implicit copy assignment operators created\n";
1070   if (getLangOpts().CPlusPlus)
1071     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1072                  << NumImplicitMoveAssignmentOperators
1073                  << " implicit move assignment operators created\n";
1074   llvm::errs() << NumImplicitDestructorsDeclared << "/"
1075                << NumImplicitDestructors
1076                << " implicit destructors created\n";
1077
1078   if (ExternalSource) {
1079     llvm::errs() << "\n";
1080     ExternalSource->PrintStats();
1081   }
1082
1083   BumpAlloc.PrintStats();
1084 }
1085
1086 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1087                                            bool NotifyListeners) {
1088   if (NotifyListeners)
1089     if (auto *Listener = getASTMutationListener())
1090       Listener->RedefinedHiddenDefinition(ND, M);
1091
1092   MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1093 }
1094
1095 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1096   auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1097   if (It == MergedDefModules.end())
1098     return;
1099
1100   auto &Merged = It->second;
1101   llvm::DenseSet<Module*> Found;
1102   for (Module *&M : Merged)
1103     if (!Found.insert(M).second)
1104       M = nullptr;
1105   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1106 }
1107
1108 ArrayRef<Module *>
1109 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1110   auto MergedIt =
1111       MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1112   if (MergedIt == MergedDefModules.end())
1113     return None;
1114   return MergedIt->second;
1115 }
1116
1117 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1118   if (LazyInitializers.empty())
1119     return;
1120
1121   auto *Source = Ctx.getExternalSource();
1122   assert(Source && "lazy initializers but no external source");
1123
1124   auto LazyInits = std::move(LazyInitializers);
1125   LazyInitializers.clear();
1126
1127   for (auto ID : LazyInits)
1128     Initializers.push_back(Source->GetExternalDecl(ID));
1129
1130   assert(LazyInitializers.empty() &&
1131          "GetExternalDecl for lazy module initializer added more inits");
1132 }
1133
1134 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1135   // One special case: if we add a module initializer that imports another
1136   // module, and that module's only initializer is an ImportDecl, simplify.
1137   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1138     auto It = ModuleInitializers.find(ID->getImportedModule());
1139
1140     // Maybe the ImportDecl does nothing at all. (Common case.)
1141     if (It == ModuleInitializers.end())
1142       return;
1143
1144     // Maybe the ImportDecl only imports another ImportDecl.
1145     auto &Imported = *It->second;
1146     if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1147       Imported.resolve(*this);
1148       auto *OnlyDecl = Imported.Initializers.front();
1149       if (isa<ImportDecl>(OnlyDecl))
1150         D = OnlyDecl;
1151     }
1152   }
1153
1154   auto *&Inits = ModuleInitializers[M];
1155   if (!Inits)
1156     Inits = new (*this) PerModuleInitializers;
1157   Inits->Initializers.push_back(D);
1158 }
1159
1160 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1161   auto *&Inits = ModuleInitializers[M];
1162   if (!Inits)
1163     Inits = new (*this) PerModuleInitializers;
1164   Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1165                                  IDs.begin(), IDs.end());
1166 }
1167
1168 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1169   auto It = ModuleInitializers.find(M);
1170   if (It == ModuleInitializers.end())
1171     return None;
1172
1173   auto *Inits = It->second;
1174   Inits->resolve(*this);
1175   return Inits->Initializers;
1176 }
1177
1178 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1179   if (!ExternCContext)
1180     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1181
1182   return ExternCContext;
1183 }
1184
1185 BuiltinTemplateDecl *
1186 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1187                                      const IdentifierInfo *II) const {
1188   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1189   BuiltinTemplate->setImplicit();
1190   TUDecl->addDecl(BuiltinTemplate);
1191
1192   return BuiltinTemplate;
1193 }
1194
1195 BuiltinTemplateDecl *
1196 ASTContext::getMakeIntegerSeqDecl() const {
1197   if (!MakeIntegerSeqDecl)
1198     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1199                                                   getMakeIntegerSeqName());
1200   return MakeIntegerSeqDecl;
1201 }
1202
1203 BuiltinTemplateDecl *
1204 ASTContext::getTypePackElementDecl() const {
1205   if (!TypePackElementDecl)
1206     TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1207                                                    getTypePackElementName());
1208   return TypePackElementDecl;
1209 }
1210
1211 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1212                                             RecordDecl::TagKind TK) const {
1213   SourceLocation Loc;
1214   RecordDecl *NewDecl;
1215   if (getLangOpts().CPlusPlus)
1216     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217                                     Loc, &Idents.get(Name));
1218   else
1219     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1220                                  &Idents.get(Name));
1221   NewDecl->setImplicit();
1222   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1224   return NewDecl;
1225 }
1226
1227 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1228                                               StringRef Name) const {
1229   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1230   TypedefDecl *NewDecl = TypedefDecl::Create(
1231       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233   NewDecl->setImplicit();
1234   return NewDecl;
1235 }
1236
1237 TypedefDecl *ASTContext::getInt128Decl() const {
1238   if (!Int128Decl)
1239     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1240   return Int128Decl;
1241 }
1242
1243 TypedefDecl *ASTContext::getUInt128Decl() const {
1244   if (!UInt128Decl)
1245     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1246   return UInt128Decl;
1247 }
1248
1249 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250   auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1251   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1252   Types.push_back(Ty);
1253 }
1254
1255 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1256                                   const TargetInfo *AuxTarget) {
1257   assert((!this->Target || this->Target == &Target) &&
1258          "Incorrect target reinitialization");
1259   assert(VoidTy.isNull() && "Context reinitialized?");
1260
1261   this->Target = &Target;
1262   this->AuxTarget = AuxTarget;
1263
1264   ABI.reset(createCXXABI(Target));
1265   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1266   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1267
1268   // C99 6.2.5p19.
1269   InitBuiltinType(VoidTy,              BuiltinType::Void);
1270
1271   // C99 6.2.5p2.
1272   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1273   // C99 6.2.5p3.
1274   if (LangOpts.CharIsSigned)
1275     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1276   else
1277     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1278   // C99 6.2.5p4.
1279   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1280   InitBuiltinType(ShortTy,             BuiltinType::Short);
1281   InitBuiltinType(IntTy,               BuiltinType::Int);
1282   InitBuiltinType(LongTy,              BuiltinType::Long);
1283   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1284
1285   // C99 6.2.5p6.
1286   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1287   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1288   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1289   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1290   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1291
1292   // C99 6.2.5p10.
1293   InitBuiltinType(FloatTy,             BuiltinType::Float);
1294   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1295   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1296
1297   // GNU extension, __float128 for IEEE quadruple precision
1298   InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1299
1300   // C11 extension ISO/IEC TS 18661-3
1301   InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1302
1303   // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1304   InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1305   InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1306   InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1307   InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1308   InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1309   InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1310   InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1311   InitBuiltinType(FractTy,                 BuiltinType::Fract);
1312   InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1313   InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1314   InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1315   InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1316   InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1317   InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1318   InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1319   InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1320   InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1321   InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1322   InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1323   InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1324   InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1325   InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1326   InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1327   InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1328
1329   // GNU extension, 128-bit integers.
1330   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1331   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1332
1333   // C++ 3.9.1p5
1334   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1335     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1336   else  // -fshort-wchar makes wchar_t be unsigned.
1337     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1338   if (LangOpts.CPlusPlus && LangOpts.WChar)
1339     WideCharTy = WCharTy;
1340   else {
1341     // C99 (or C++ using -fno-wchar).
1342     WideCharTy = getFromTargetType(Target.getWCharType());
1343   }
1344
1345   WIntTy = getFromTargetType(Target.getWIntType());
1346
1347   // C++20 (proposed)
1348   InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1349
1350   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1351     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1352   else // C99
1353     Char16Ty = getFromTargetType(Target.getChar16Type());
1354
1355   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1356     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1357   else // C99
1358     Char32Ty = getFromTargetType(Target.getChar32Type());
1359
1360   // Placeholder type for type-dependent expressions whose type is
1361   // completely unknown. No code should ever check a type against
1362   // DependentTy and users should never see it; however, it is here to
1363   // help diagnose failures to properly check for type-dependent
1364   // expressions.
1365   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1366
1367   // Placeholder type for functions.
1368   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1369
1370   // Placeholder type for bound members.
1371   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1372
1373   // Placeholder type for pseudo-objects.
1374   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1375
1376   // "any" type; useful for debugger-like clients.
1377   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1378
1379   // Placeholder type for unbridged ARC casts.
1380   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1381
1382   // Placeholder type for builtin functions.
1383   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1384
1385   // Placeholder type for OMP array sections.
1386   if (LangOpts.OpenMP) {
1387     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1388     InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1389     InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1390   }
1391   if (LangOpts.MatrixTypes)
1392     InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1393
1394   // C99 6.2.5p11.
1395   FloatComplexTy      = getComplexType(FloatTy);
1396   DoubleComplexTy     = getComplexType(DoubleTy);
1397   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1398   Float128ComplexTy   = getComplexType(Float128Ty);
1399
1400   // Builtin types for 'id', 'Class', and 'SEL'.
1401   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1402   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1403   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1404
1405   if (LangOpts.OpenCL) {
1406 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1407     InitBuiltinType(SingletonId, BuiltinType::Id);
1408 #include "clang/Basic/OpenCLImageTypes.def"
1409
1410     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1411     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1412     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1413     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1414     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1415
1416 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1417     InitBuiltinType(Id##Ty, BuiltinType::Id);
1418 #include "clang/Basic/OpenCLExtensionTypes.def"
1419   }
1420
1421   if (Target.hasAArch64SVETypes()) {
1422 #define SVE_TYPE(Name, Id, SingletonId) \
1423     InitBuiltinType(SingletonId, BuiltinType::Id);
1424 #include "clang/Basic/AArch64SVEACLETypes.def"
1425   }
1426
1427   // Builtin type for __objc_yes and __objc_no
1428   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1429                        SignedCharTy : BoolTy);
1430
1431   ObjCConstantStringType = QualType();
1432
1433   ObjCSuperType = QualType();
1434
1435   // void * type
1436   if (LangOpts.OpenCLVersion >= 200) {
1437     auto Q = VoidTy.getQualifiers();
1438     Q.setAddressSpace(LangAS::opencl_generic);
1439     VoidPtrTy = getPointerType(getCanonicalType(
1440         getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1441   } else {
1442     VoidPtrTy = getPointerType(VoidTy);
1443   }
1444
1445   // nullptr type (C++0x 2.14.7)
1446   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1447
1448   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1449   InitBuiltinType(HalfTy, BuiltinType::Half);
1450
1451   InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1452
1453   // Builtin type used to help define __builtin_va_list.
1454   VaListTagDecl = nullptr;
1455
1456   // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1457   if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1458     MSGuidTagDecl = buildImplicitRecord("_GUID");
1459     TUDecl->addDecl(MSGuidTagDecl);
1460   }
1461 }
1462
1463 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1464   return SourceMgr.getDiagnostics();
1465 }
1466
1467 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1468   AttrVec *&Result = DeclAttrs[D];
1469   if (!Result) {
1470     void *Mem = Allocate(sizeof(AttrVec));
1471     Result = new (Mem) AttrVec;
1472   }
1473
1474   return *Result;
1475 }
1476
1477 /// Erase the attributes corresponding to the given declaration.
1478 void ASTContext::eraseDeclAttrs(const Decl *D) {
1479   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1480   if (Pos != DeclAttrs.end()) {
1481     Pos->second->~AttrVec();
1482     DeclAttrs.erase(Pos);
1483   }
1484 }
1485
1486 // FIXME: Remove ?
1487 MemberSpecializationInfo *
1488 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1489   assert(Var->isStaticDataMember() && "Not a static data member");
1490   return getTemplateOrSpecializationInfo(Var)
1491       .dyn_cast<MemberSpecializationInfo *>();
1492 }
1493
1494 ASTContext::TemplateOrSpecializationInfo
1495 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1496   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1497       TemplateOrInstantiation.find(Var);
1498   if (Pos == TemplateOrInstantiation.end())
1499     return {};
1500
1501   return Pos->second;
1502 }
1503
1504 void
1505 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1506                                                 TemplateSpecializationKind TSK,
1507                                           SourceLocation PointOfInstantiation) {
1508   assert(Inst->isStaticDataMember() && "Not a static data member");
1509   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1510   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1511                                             Tmpl, TSK, PointOfInstantiation));
1512 }
1513
1514 void
1515 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1516                                             TemplateOrSpecializationInfo TSI) {
1517   assert(!TemplateOrInstantiation[Inst] &&
1518          "Already noted what the variable was instantiated from");
1519   TemplateOrInstantiation[Inst] = TSI;
1520 }
1521
1522 NamedDecl *
1523 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1524   auto Pos = InstantiatedFromUsingDecl.find(UUD);
1525   if (Pos == InstantiatedFromUsingDecl.end())
1526     return nullptr;
1527
1528   return Pos->second;
1529 }
1530
1531 void
1532 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1533   assert((isa<UsingDecl>(Pattern) ||
1534           isa<UnresolvedUsingValueDecl>(Pattern) ||
1535           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1536          "pattern decl is not a using decl");
1537   assert((isa<UsingDecl>(Inst) ||
1538           isa<UnresolvedUsingValueDecl>(Inst) ||
1539           isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1540          "instantiation did not produce a using decl");
1541   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1542   InstantiatedFromUsingDecl[Inst] = Pattern;
1543 }
1544
1545 UsingShadowDecl *
1546 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1547   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1548     = InstantiatedFromUsingShadowDecl.find(Inst);
1549   if (Pos == InstantiatedFromUsingShadowDecl.end())
1550     return nullptr;
1551
1552   return Pos->second;
1553 }
1554
1555 void
1556 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1557                                                UsingShadowDecl *Pattern) {
1558   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1559   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1560 }
1561
1562 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1563   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1564     = InstantiatedFromUnnamedFieldDecl.find(Field);
1565   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1566     return nullptr;
1567
1568   return Pos->second;
1569 }
1570
1571 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1572                                                      FieldDecl *Tmpl) {
1573   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1574   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1575   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1576          "Already noted what unnamed field was instantiated from");
1577
1578   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1579 }
1580
1581 ASTContext::overridden_cxx_method_iterator
1582 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1583   return overridden_methods(Method).begin();
1584 }
1585
1586 ASTContext::overridden_cxx_method_iterator
1587 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1588   return overridden_methods(Method).end();
1589 }
1590
1591 unsigned
1592 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1593   auto Range = overridden_methods(Method);
1594   return Range.end() - Range.begin();
1595 }
1596
1597 ASTContext::overridden_method_range
1598 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1599   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1600       OverriddenMethods.find(Method->getCanonicalDecl());
1601   if (Pos == OverriddenMethods.end())
1602     return overridden_method_range(nullptr, nullptr);
1603   return overridden_method_range(Pos->second.begin(), Pos->second.end());
1604 }
1605
1606 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1607                                      const CXXMethodDecl *Overridden) {
1608   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1609   OverriddenMethods[Method].push_back(Overridden);
1610 }
1611
1612 void ASTContext::getOverriddenMethods(
1613                       const NamedDecl *D,
1614                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1615   assert(D);
1616
1617   if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1618     Overridden.append(overridden_methods_begin(CXXMethod),
1619                       overridden_methods_end(CXXMethod));
1620     return;
1621   }
1622
1623   const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1624   if (!Method)
1625     return;
1626
1627   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1628   Method->getOverriddenMethods(OverDecls);
1629   Overridden.append(OverDecls.begin(), OverDecls.end());
1630 }
1631
1632 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1633   assert(!Import->getNextLocalImport() &&
1634          "Import declaration already in the chain");
1635   assert(!Import->isFromASTFile() && "Non-local import declaration");
1636   if (!FirstLocalImport) {
1637     FirstLocalImport = Import;
1638     LastLocalImport = Import;
1639     return;
1640   }
1641
1642   LastLocalImport->setNextLocalImport(Import);
1643   LastLocalImport = Import;
1644 }
1645
1646 //===----------------------------------------------------------------------===//
1647 //                         Type Sizing and Analysis
1648 //===----------------------------------------------------------------------===//
1649
1650 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1651 /// scalar floating point type.
1652 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1653   switch (T->castAs<BuiltinType>()->getKind()) {
1654   default:
1655     llvm_unreachable("Not a floating point type!");
1656   case BuiltinType::BFloat16:
1657     return Target->getBFloat16Format();
1658   case BuiltinType::Float16:
1659   case BuiltinType::Half:
1660     return Target->getHalfFormat();
1661   case BuiltinType::Float:      return Target->getFloatFormat();
1662   case BuiltinType::Double:     return Target->getDoubleFormat();
1663   case BuiltinType::LongDouble:
1664     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1665       return AuxTarget->getLongDoubleFormat();
1666     return Target->getLongDoubleFormat();
1667   case BuiltinType::Float128:
1668     if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1669       return AuxTarget->getFloat128Format();
1670     return Target->getFloat128Format();
1671   }
1672 }
1673
1674 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1675   unsigned Align = Target->getCharWidth();
1676
1677   bool UseAlignAttrOnly = false;
1678   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1679     Align = AlignFromAttr;
1680
1681     // __attribute__((aligned)) can increase or decrease alignment
1682     // *except* on a struct or struct member, where it only increases
1683     // alignment unless 'packed' is also specified.
1684     //
1685     // It is an error for alignas to decrease alignment, so we can
1686     // ignore that possibility;  Sema should diagnose it.
1687     if (isa<FieldDecl>(D)) {
1688       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1689         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1690     } else {
1691       UseAlignAttrOnly = true;
1692     }
1693   }
1694   else if (isa<FieldDecl>(D))
1695       UseAlignAttrOnly =
1696         D->hasAttr<PackedAttr>() ||
1697         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1698
1699   // If we're using the align attribute only, just ignore everything
1700   // else about the declaration and its type.
1701   if (UseAlignAttrOnly) {
1702     // do nothing
1703   } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1704     QualType T = VD->getType();
1705     if (const auto *RT = T->getAs<ReferenceType>()) {
1706       if (ForAlignof)
1707         T = RT->getPointeeType();
1708       else
1709         T = getPointerType(RT->getPointeeType());
1710     }
1711     QualType BaseT = getBaseElementType(T);
1712     if (T->isFunctionType())
1713       Align = getTypeInfoImpl(T.getTypePtr()).Align;
1714     else if (!BaseT->isIncompleteType()) {
1715       // Adjust alignments of declarations with array type by the
1716       // large-array alignment on the target.
1717       if (const ArrayType *arrayType = getAsArrayType(T)) {
1718         unsigned MinWidth = Target->getLargeArrayMinWidth();
1719         if (!ForAlignof && MinWidth) {
1720           if (isa<VariableArrayType>(arrayType))
1721             Align = std::max(Align, Target->getLargeArrayAlign());
1722           else if (isa<ConstantArrayType>(arrayType) &&
1723                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1724             Align = std::max(Align, Target->getLargeArrayAlign());
1725         }
1726       }
1727       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1728       if (BaseT.getQualifiers().hasUnaligned())
1729         Align = Target->getCharWidth();
1730       if (const auto *VD = dyn_cast<VarDecl>(D)) {
1731         if (VD->hasGlobalStorage() && !ForAlignof) {
1732           uint64_t TypeSize = getTypeSize(T.getTypePtr());
1733           Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1734         }
1735       }
1736     }
1737
1738     // Fields can be subject to extra alignment constraints, like if
1739     // the field is packed, the struct is packed, or the struct has a
1740     // a max-field-alignment constraint (#pragma pack).  So calculate
1741     // the actual alignment of the field within the struct, and then
1742     // (as we're expected to) constrain that by the alignment of the type.
1743     if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1744       const RecordDecl *Parent = Field->getParent();
1745       // We can only produce a sensible answer if the record is valid.
1746       if (!Parent->isInvalidDecl()) {
1747         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1748
1749         // Start with the record's overall alignment.
1750         unsigned FieldAlign = toBits(Layout.getAlignment());
1751
1752         // Use the GCD of that and the offset within the record.
1753         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1754         if (Offset > 0) {
1755           // Alignment is always a power of 2, so the GCD will be a power of 2,
1756           // which means we get to do this crazy thing instead of Euclid's.
1757           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1758           if (LowBitOfOffset < FieldAlign)
1759             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1760         }
1761
1762         Align = std::min(Align, FieldAlign);
1763       }
1764     }
1765   }
1766
1767   return toCharUnitsFromBits(Align);
1768 }
1769
1770 CharUnits ASTContext::getExnObjectAlignment() const {
1771   return toCharUnitsFromBits(Target->getExnObjectAlignment());
1772 }
1773
1774 // getTypeInfoDataSizeInChars - Return the size of a type, in
1775 // chars. If the type is a record, its data size is returned.  This is
1776 // the size of the memcpy that's performed when assigning this type
1777 // using a trivial copy/move assignment operator.
1778 std::pair<CharUnits, CharUnits>
1779 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1780   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1781
1782   // In C++, objects can sometimes be allocated into the tail padding
1783   // of a base-class subobject.  We decide whether that's possible
1784   // during class layout, so here we can just trust the layout results.
1785   if (getLangOpts().CPlusPlus) {
1786     if (const auto *RT = T->getAs<RecordType>()) {
1787       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1788       sizeAndAlign.first = layout.getDataSize();
1789     }
1790   }
1791
1792   return sizeAndAlign;
1793 }
1794
1795 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1796 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1797 std::pair<CharUnits, CharUnits>
1798 static getConstantArrayInfoInChars(const ASTContext &Context,
1799                                    const ConstantArrayType *CAT) {
1800   std::pair<CharUnits, CharUnits> EltInfo =
1801       Context.getTypeInfoInChars(CAT->getElementType());
1802   uint64_t Size = CAT->getSize().getZExtValue();
1803   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1804               (uint64_t)(-1)/Size) &&
1805          "Overflow in array type char size evaluation");
1806   uint64_t Width = EltInfo.first.getQuantity() * Size;
1807   unsigned Align = EltInfo.second.getQuantity();
1808   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1809       Context.getTargetInfo().getPointerWidth(0) == 64)
1810     Width = llvm::alignTo(Width, Align);
1811   return std::make_pair(CharUnits::fromQuantity(Width),
1812                         CharUnits::fromQuantity(Align));
1813 }
1814
1815 std::pair<CharUnits, CharUnits>
1816 ASTContext::getTypeInfoInChars(const Type *T) const {
1817   if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1818     return getConstantArrayInfoInChars(*this, CAT);
1819   TypeInfo Info = getTypeInfo(T);
1820   return std::make_pair(toCharUnitsFromBits(Info.Width),
1821                         toCharUnitsFromBits(Info.Align));
1822 }
1823
1824 std::pair<CharUnits, CharUnits>
1825 ASTContext::getTypeInfoInChars(QualType T) const {
1826   return getTypeInfoInChars(T.getTypePtr());
1827 }
1828
1829 bool ASTContext::isAlignmentRequired(const Type *T) const {
1830   return getTypeInfo(T).AlignIsRequired;
1831 }
1832
1833 bool ASTContext::isAlignmentRequired(QualType T) const {
1834   return isAlignmentRequired(T.getTypePtr());
1835 }
1836
1837 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1838   // An alignment on a typedef overrides anything else.
1839   if (const auto *TT = T->getAs<TypedefType>())
1840     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1841       return Align;
1842
1843   // If we have an (array of) complete type, we're done.
1844   T = getBaseElementType(T);
1845   if (!T->isIncompleteType())
1846     return getTypeAlign(T);
1847
1848   // If we had an array type, its element type might be a typedef
1849   // type with an alignment attribute.
1850   if (const auto *TT = T->getAs<TypedefType>())
1851     if (unsigned Align = TT->getDecl()->getMaxAlignment())
1852       return Align;
1853
1854   // Otherwise, see if the declaration of the type had an attribute.
1855   if (const auto *TT = T->getAs<TagType>())
1856     return TT->getDecl()->getMaxAlignment();
1857
1858   return 0;
1859 }
1860
1861 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1862   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1863   if (I != MemoizedTypeInfo.end())
1864     return I->second;
1865
1866   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1867   TypeInfo TI = getTypeInfoImpl(T);
1868   MemoizedTypeInfo[T] = TI;
1869   return TI;
1870 }
1871
1872 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1873 /// method does not work on incomplete types.
1874 ///
1875 /// FIXME: Pointers into different addr spaces could have different sizes and
1876 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1877 /// should take a QualType, &c.
1878 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1879   uint64_t Width = 0;
1880   unsigned Align = 8;
1881   bool AlignIsRequired = false;
1882   unsigned AS = 0;
1883   switch (T->getTypeClass()) {
1884 #define TYPE(Class, Base)
1885 #define ABSTRACT_TYPE(Class, Base)
1886 #define NON_CANONICAL_TYPE(Class, Base)
1887 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1888 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1889   case Type::Class:                                                            \
1890   assert(!T->isDependentType() && "should not see dependent types here");      \
1891   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1892 #include "clang/AST/TypeNodes.inc"
1893     llvm_unreachable("Should not see dependent types");
1894
1895   case Type::FunctionNoProto:
1896   case Type::FunctionProto:
1897     // GCC extension: alignof(function) = 32 bits
1898     Width = 0;
1899     Align = 32;
1900     break;
1901
1902   case Type::IncompleteArray:
1903   case Type::VariableArray:
1904   case Type::ConstantArray: {
1905     // Model non-constant sized arrays as size zero, but track the alignment.
1906     uint64_t Size = 0;
1907     if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1908       Size = CAT->getSize().getZExtValue();
1909
1910     TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1911     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1912            "Overflow in array type bit size evaluation");
1913     Width = EltInfo.Width * Size;
1914     Align = EltInfo.Align;
1915     AlignIsRequired = EltInfo.AlignIsRequired;
1916     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1917         getTargetInfo().getPointerWidth(0) == 64)
1918       Width = llvm::alignTo(Width, Align);
1919     break;
1920   }
1921
1922   case Type::ExtVector:
1923   case Type::Vector: {
1924     const auto *VT = cast<VectorType>(T);
1925     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1926     Width = EltInfo.Width * VT->getNumElements();
1927     Align = Width;
1928     // If the alignment is not a power of 2, round up to the next power of 2.
1929     // This happens for non-power-of-2 length vectors.
1930     if (Align & (Align-1)) {
1931       Align = llvm::NextPowerOf2(Align);
1932       Width = llvm::alignTo(Width, Align);
1933     }
1934     // Adjust the alignment based on the target max.
1935     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1936     if (TargetVectorAlign && TargetVectorAlign < Align)
1937       Align = TargetVectorAlign;
1938     break;
1939   }
1940
1941   case Type::ConstantMatrix: {
1942     const auto *MT = cast<ConstantMatrixType>(T);
1943     TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1944     // The internal layout of a matrix value is implementation defined.
1945     // Initially be ABI compatible with arrays with respect to alignment and
1946     // size.
1947     Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1948     Align = ElementInfo.Align;
1949     break;
1950   }
1951
1952   case Type::Builtin:
1953     switch (cast<BuiltinType>(T)->getKind()) {
1954     default: llvm_unreachable("Unknown builtin type!");
1955     case BuiltinType::Void:
1956       // GCC extension: alignof(void) = 8 bits.
1957       Width = 0;
1958       Align = 8;
1959       break;
1960     case BuiltinType::Bool:
1961       Width = Target->getBoolWidth();
1962       Align = Target->getBoolAlign();
1963       break;
1964     case BuiltinType::Char_S:
1965     case BuiltinType::Char_U:
1966     case BuiltinType::UChar:
1967     case BuiltinType::SChar:
1968     case BuiltinType::Char8:
1969       Width = Target->getCharWidth();
1970       Align = Target->getCharAlign();
1971       break;
1972     case BuiltinType::WChar_S:
1973     case BuiltinType::WChar_U:
1974       Width = Target->getWCharWidth();
1975       Align = Target->getWCharAlign();
1976       break;
1977     case BuiltinType::Char16:
1978       Width = Target->getChar16Width();
1979       Align = Target->getChar16Align();
1980       break;
1981     case BuiltinType::Char32:
1982       Width = Target->getChar32Width();
1983       Align = Target->getChar32Align();
1984       break;
1985     case BuiltinType::UShort:
1986     case BuiltinType::Short:
1987       Width = Target->getShortWidth();
1988       Align = Target->getShortAlign();
1989       break;
1990     case BuiltinType::UInt:
1991     case BuiltinType::Int:
1992       Width = Target->getIntWidth();
1993       Align = Target->getIntAlign();
1994       break;
1995     case BuiltinType::ULong:
1996     case BuiltinType::Long:
1997       Width = Target->getLongWidth();
1998       Align = Target->getLongAlign();
1999       break;
2000     case BuiltinType::ULongLong:
2001     case BuiltinType::LongLong:
2002       Width = Target->getLongLongWidth();
2003       Align = Target->getLongLongAlign();
2004       break;
2005     case BuiltinType::Int128:
2006     case BuiltinType::UInt128:
2007       Width = 128;
2008       Align = 128; // int128_t is 128-bit aligned on all targets.
2009       break;
2010     case BuiltinType::ShortAccum:
2011     case BuiltinType::UShortAccum:
2012     case BuiltinType::SatShortAccum:
2013     case BuiltinType::SatUShortAccum:
2014       Width = Target->getShortAccumWidth();
2015       Align = Target->getShortAccumAlign();
2016       break;
2017     case BuiltinType::Accum:
2018     case BuiltinType::UAccum:
2019     case BuiltinType::SatAccum:
2020     case BuiltinType::SatUAccum:
2021       Width = Target->getAccumWidth();
2022       Align = Target->getAccumAlign();
2023       break;
2024     case BuiltinType::LongAccum:
2025     case BuiltinType::ULongAccum:
2026     case BuiltinType::SatLongAccum:
2027     case BuiltinType::SatULongAccum:
2028       Width = Target->getLongAccumWidth();
2029       Align = Target->getLongAccumAlign();
2030       break;
2031     case BuiltinType::ShortFract:
2032     case BuiltinType::UShortFract:
2033     case BuiltinType::SatShortFract:
2034     case BuiltinType::SatUShortFract:
2035       Width = Target->getShortFractWidth();
2036       Align = Target->getShortFractAlign();
2037       break;
2038     case BuiltinType::Fract:
2039     case BuiltinType::UFract:
2040     case BuiltinType::SatFract:
2041     case BuiltinType::SatUFract:
2042       Width = Target->getFractWidth();
2043       Align = Target->getFractAlign();
2044       break;
2045     case BuiltinType::LongFract:
2046     case BuiltinType::ULongFract:
2047     case BuiltinType::SatLongFract:
2048     case BuiltinType::SatULongFract:
2049       Width = Target->getLongFractWidth();
2050       Align = Target->getLongFractAlign();
2051       break;
2052     case BuiltinType::BFloat16:
2053       Width = Target->getBFloat16Width();
2054       Align = Target->getBFloat16Align();
2055       break;
2056     case BuiltinType::Float16:
2057     case BuiltinType::Half:
2058       if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2059           !getLangOpts().OpenMPIsDevice) {
2060         Width = Target->getHalfWidth();
2061         Align = Target->getHalfAlign();
2062       } else {
2063         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2064                "Expected OpenMP device compilation.");
2065         Width = AuxTarget->getHalfWidth();
2066         Align = AuxTarget->getHalfAlign();
2067       }
2068       break;
2069     case BuiltinType::Float:
2070       Width = Target->getFloatWidth();
2071       Align = Target->getFloatAlign();
2072       break;
2073     case BuiltinType::Double:
2074       Width = Target->getDoubleWidth();
2075       Align = Target->getDoubleAlign();
2076       break;
2077     case BuiltinType::LongDouble:
2078       if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2079           (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2080            Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2081         Width = AuxTarget->getLongDoubleWidth();
2082         Align = AuxTarget->getLongDoubleAlign();
2083       } else {
2084         Width = Target->getLongDoubleWidth();
2085         Align = Target->getLongDoubleAlign();
2086       }
2087       break;
2088     case BuiltinType::Float128:
2089       if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2090           !getLangOpts().OpenMPIsDevice) {
2091         Width = Target->getFloat128Width();
2092         Align = Target->getFloat128Align();
2093       } else {
2094         assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2095                "Expected OpenMP device compilation.");
2096         Width = AuxTarget->getFloat128Width();
2097         Align = AuxTarget->getFloat128Align();
2098       }
2099       break;
2100     case BuiltinType::NullPtr:
2101       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2102       Align = Target->getPointerAlign(0); //   == sizeof(void*)
2103       break;
2104     case BuiltinType::ObjCId:
2105     case BuiltinType::ObjCClass:
2106     case BuiltinType::ObjCSel:
2107       Width = Target->getPointerWidth(0);
2108       Align = Target->getPointerAlign(0);
2109       break;
2110     case BuiltinType::OCLSampler:
2111     case BuiltinType::OCLEvent:
2112     case BuiltinType::OCLClkEvent:
2113     case BuiltinType::OCLQueue:
2114     case BuiltinType::OCLReserveID:
2115 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2116     case BuiltinType::Id:
2117 #include "clang/Basic/OpenCLImageTypes.def"
2118 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2119   case BuiltinType::Id:
2120 #include "clang/Basic/OpenCLExtensionTypes.def"
2121       AS = getTargetAddressSpace(
2122           Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2123       Width = Target->getPointerWidth(AS);
2124       Align = Target->getPointerAlign(AS);
2125       break;
2126     // The SVE types are effectively target-specific.  The length of an
2127     // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2128     // of 128 bits.  There is one predicate bit for each vector byte, so the
2129     // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2130     //
2131     // Because the length is only known at runtime, we use a dummy value
2132     // of 0 for the static length.  The alignment values are those defined
2133     // by the Procedure Call Standard for the Arm Architecture.
2134 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2135                         IsSigned, IsFP, IsBF)                                  \
2136   case BuiltinType::Id:                                                        \
2137     Width = 0;                                                                 \
2138     Align = 128;                                                               \
2139     break;
2140 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2141   case BuiltinType::Id:                                                        \
2142     Width = 0;                                                                 \
2143     Align = 16;                                                                \
2144     break;
2145 #include "clang/Basic/AArch64SVEACLETypes.def"
2146     }
2147     break;
2148   case Type::ObjCObjectPointer:
2149     Width = Target->getPointerWidth(0);
2150     Align = Target->getPointerAlign(0);
2151     break;
2152   case Type::BlockPointer:
2153     AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2154     Width = Target->getPointerWidth(AS);
2155     Align = Target->getPointerAlign(AS);
2156     break;
2157   case Type::LValueReference:
2158   case Type::RValueReference:
2159     // alignof and sizeof should never enter this code path here, so we go
2160     // the pointer route.
2161     AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2162     Width = Target->getPointerWidth(AS);
2163     Align = Target->getPointerAlign(AS);
2164     break;
2165   case Type::Pointer:
2166     AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2167     Width = Target->getPointerWidth(AS);
2168     Align = Target->getPointerAlign(AS);
2169     break;
2170   case Type::MemberPointer: {
2171     const auto *MPT = cast<MemberPointerType>(T);
2172     CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2173     Width = MPI.Width;
2174     Align = MPI.Align;
2175     break;
2176   }
2177   case Type::Complex: {
2178     // Complex types have the same alignment as their elements, but twice the
2179     // size.
2180     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2181     Width = EltInfo.Width * 2;
2182     Align = EltInfo.Align;
2183     break;
2184   }
2185   case Type::ObjCObject:
2186     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2187   case Type::Adjusted:
2188   case Type::Decayed:
2189     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2190   case Type::ObjCInterface: {
2191     const auto *ObjCI = cast<ObjCInterfaceType>(T);
2192     if (ObjCI->getDecl()->isInvalidDecl()) {
2193       Width = 8;
2194       Align = 8;
2195       break;
2196     }
2197     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2198     Width = toBits(Layout.getSize());
2199     Align = toBits(Layout.getAlignment());
2200     break;
2201   }
2202   case Type::ExtInt: {
2203     const auto *EIT = cast<ExtIntType>(T);
2204     Align =
2205         std::min(static_cast<unsigned>(std::max(
2206                      getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2207                  Target->getLongLongAlign());
2208     Width = llvm::alignTo(EIT->getNumBits(), Align);
2209     break;
2210   }
2211   case Type::Record:
2212   case Type::Enum: {
2213     const auto *TT = cast<TagType>(T);
2214
2215     if (TT->getDecl()->isInvalidDecl()) {
2216       Width = 8;
2217       Align = 8;
2218       break;
2219     }
2220
2221     if (const auto *ET = dyn_cast<EnumType>(TT)) {
2222       const EnumDecl *ED = ET->getDecl();
2223       TypeInfo Info =
2224           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2225       if (unsigned AttrAlign = ED->getMaxAlignment()) {
2226         Info.Align = AttrAlign;
2227         Info.AlignIsRequired = true;
2228       }
2229       return Info;
2230     }
2231
2232     const auto *RT = cast<RecordType>(TT);
2233     const RecordDecl *RD = RT->getDecl();
2234     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2235     Width = toBits(Layout.getSize());
2236     Align = toBits(Layout.getAlignment());
2237     AlignIsRequired = RD->hasAttr<AlignedAttr>();
2238     break;
2239   }
2240
2241   case Type::SubstTemplateTypeParm:
2242     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2243                        getReplacementType().getTypePtr());
2244
2245   case Type::Auto:
2246   case Type::DeducedTemplateSpecialization: {
2247     const auto *A = cast<DeducedType>(T);
2248     assert(!A->getDeducedType().isNull() &&
2249            "cannot request the size of an undeduced or dependent auto type");
2250     return getTypeInfo(A->getDeducedType().getTypePtr());
2251   }
2252
2253   case Type::Paren:
2254     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2255
2256   case Type::MacroQualified:
2257     return getTypeInfo(
2258         cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2259
2260   case Type::ObjCTypeParam:
2261     return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2262
2263   case Type::Typedef: {
2264     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2265     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2266     // If the typedef has an aligned attribute on it, it overrides any computed
2267     // alignment we have.  This violates the GCC documentation (which says that
2268     // attribute(aligned) can only round up) but matches its implementation.
2269     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2270       Align = AttrAlign;
2271       AlignIsRequired = true;
2272     } else {
2273       Align = Info.Align;
2274       AlignIsRequired = Info.AlignIsRequired;
2275     }
2276     Width = Info.Width;
2277     break;
2278   }
2279
2280   case Type::Elaborated:
2281     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2282
2283   case Type::Attributed:
2284     return getTypeInfo(
2285                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2286
2287   case Type::Atomic: {
2288     // Start with the base type information.
2289     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2290     Width = Info.Width;
2291     Align = Info.Align;
2292
2293     if (!Width) {
2294       // An otherwise zero-sized type should still generate an
2295       // atomic operation.
2296       Width = Target->getCharWidth();
2297       assert(Align);
2298     } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2299       // If the size of the type doesn't exceed the platform's max
2300       // atomic promotion width, make the size and alignment more
2301       // favorable to atomic operations:
2302
2303       // Round the size up to a power of 2.
2304       if (!llvm::isPowerOf2_64(Width))
2305         Width = llvm::NextPowerOf2(Width);
2306
2307       // Set the alignment equal to the size.
2308       Align = static_cast<unsigned>(Width);
2309     }
2310   }
2311   break;
2312
2313   case Type::Pipe:
2314     Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2315     Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2316     break;
2317   }
2318
2319   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2320   return TypeInfo(Width, Align, AlignIsRequired);
2321 }
2322
2323 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2324   UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2325   if (I != MemoizedUnadjustedAlign.end())
2326     return I->second;
2327
2328   unsigned UnadjustedAlign;
2329   if (const auto *RT = T->getAs<RecordType>()) {
2330     const RecordDecl *RD = RT->getDecl();
2331     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2332     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2333   } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2334     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2335     UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2336   } else {
2337     UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2338   }
2339
2340   MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2341   return UnadjustedAlign;
2342 }
2343
2344 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2345   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2346   // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2347   if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2348        getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2349       getTargetInfo().getABI() == "elfv1-qpx" &&
2350       T->isSpecificBuiltinType(BuiltinType::Double))
2351     SimdAlign = 256;
2352   return SimdAlign;
2353 }
2354
2355 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2356 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2357   return CharUnits::fromQuantity(BitSize / getCharWidth());
2358 }
2359
2360 /// toBits - Convert a size in characters to a size in characters.
2361 int64_t ASTContext::toBits(CharUnits CharSize) const {
2362   return CharSize.getQuantity() * getCharWidth();
2363 }
2364
2365 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2366 /// This method does not work on incomplete types.
2367 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2368   return getTypeInfoInChars(T).first;
2369 }
2370 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2371   return getTypeInfoInChars(T).first;
2372 }
2373
2374 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2375 /// characters. This method does not work on incomplete types.
2376 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2377   return toCharUnitsFromBits(getTypeAlign(T));
2378 }
2379 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2380   return toCharUnitsFromBits(getTypeAlign(T));
2381 }
2382
2383 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2384 /// type, in characters, before alignment adustments. This method does
2385 /// not work on incomplete types.
2386 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2387   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2388 }
2389 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2390   return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2391 }
2392
2393 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2394 /// type for the current target in bits.  This can be different than the ABI
2395 /// alignment in cases where it is beneficial for performance to overalign
2396 /// a data type.
2397 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2398   TypeInfo TI = getTypeInfo(T);
2399   unsigned ABIAlign = TI.Align;
2400
2401   T = T->getBaseElementTypeUnsafe();
2402
2403   // The preferred alignment of member pointers is that of a pointer.
2404   if (T->isMemberPointerType())
2405     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2406
2407   if (!Target->allowsLargerPreferedTypeAlignment())
2408     return ABIAlign;
2409
2410   // Double and long long should be naturally aligned if possible.
2411   if (const auto *CT = T->getAs<ComplexType>())
2412     T = CT->getElementType().getTypePtr();
2413   if (const auto *ET = T->getAs<EnumType>())
2414     T = ET->getDecl()->getIntegerType().getTypePtr();
2415   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2416       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2417       T->isSpecificBuiltinType(BuiltinType::ULongLong))
2418     // Don't increase the alignment if an alignment attribute was specified on a
2419     // typedef declaration.
2420     if (!TI.AlignIsRequired)
2421       return std::max(ABIAlign, (unsigned)getTypeSize(T));
2422
2423   return ABIAlign;
2424 }
2425
2426 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2427 /// for __attribute__((aligned)) on this target, to be used if no alignment
2428 /// value is specified.
2429 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2430   return getTargetInfo().getDefaultAlignForAttributeAligned();
2431 }
2432
2433 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2434 /// to a global variable of the specified type.
2435 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2436   uint64_t TypeSize = getTypeSize(T.getTypePtr());
2437   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2438 }
2439
2440 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2441 /// should be given to a global variable of the specified type.
2442 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2443   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2444 }
2445
2446 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2447   CharUnits Offset = CharUnits::Zero();
2448   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2449   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2450     Offset += Layout->getBaseClassOffset(Base);
2451     Layout = &getASTRecordLayout(Base);
2452   }
2453   return Offset;
2454 }
2455
2456 /// DeepCollectObjCIvars -
2457 /// This routine first collects all declared, but not synthesized, ivars in
2458 /// super class and then collects all ivars, including those synthesized for
2459 /// current class. This routine is used for implementation of current class
2460 /// when all ivars, declared and synthesized are known.
2461 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2462                                       bool leafClass,
2463                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2464   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2465     DeepCollectObjCIvars(SuperClass, false, Ivars);
2466   if (!leafClass) {
2467     for (const auto *I : OI->ivars())
2468       Ivars.push_back(I);
2469   } else {
2470     auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2471     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2472          Iv= Iv->getNextIvar())
2473       Ivars.push_back(Iv);
2474   }
2475 }
2476
2477 /// CollectInheritedProtocols - Collect all protocols in current class and
2478 /// those inherited by it.
2479 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2480                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2481   if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2482     // We can use protocol_iterator here instead of
2483     // all_referenced_protocol_iterator since we are walking all categories.
2484     for (auto *Proto : OI->all_referenced_protocols()) {
2485       CollectInheritedProtocols(Proto, Protocols);
2486     }
2487
2488     // Categories of this Interface.
2489     for (const auto *Cat : OI->visible_categories())
2490       CollectInheritedProtocols(Cat, Protocols);
2491
2492     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2493       while (SD) {
2494         CollectInheritedProtocols(SD, Protocols);
2495         SD = SD->getSuperClass();
2496       }
2497   } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2498     for (auto *Proto : OC->protocols()) {
2499       CollectInheritedProtocols(Proto, Protocols);
2500     }
2501   } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2502     // Insert the protocol.
2503     if (!Protocols.insert(
2504           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2505       return;
2506
2507     for (auto *Proto : OP->protocols())
2508       CollectInheritedProtocols(Proto, Protocols);
2509   }
2510 }
2511
2512 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2513                                                 const RecordDecl *RD) {
2514   assert(RD->isUnion() && "Must be union type");
2515   CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2516
2517   for (const auto *Field : RD->fields()) {
2518     if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2519       return false;
2520     CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2521     if (FieldSize != UnionSize)
2522       return false;
2523   }
2524   return !RD->field_empty();
2525 }
2526
2527 static bool isStructEmpty(QualType Ty) {
2528   const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2529
2530   if (!RD->field_empty())
2531     return false;
2532
2533   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2534     return ClassDecl->isEmpty();
2535
2536   return true;
2537 }
2538
2539 static llvm::Optional<int64_t>
2540 structHasUniqueObjectRepresentations(const ASTContext &Context,
2541                                      const RecordDecl *RD) {
2542   assert(!RD->isUnion() && "Must be struct/class type");
2543   const auto &Layout = Context.getASTRecordLayout(RD);
2544
2545   int64_t CurOffsetInBits = 0;
2546   if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2547     if (ClassDecl->isDynamicClass())
2548       return llvm::None;
2549
2550     SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2551     for (const auto &Base : ClassDecl->bases()) {
2552       // Empty types can be inherited from, and non-empty types can potentially
2553       // have tail padding, so just make sure there isn't an error.
2554       if (!isStructEmpty(Base.getType())) {
2555         llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2556             Context, Base.getType()->castAs<RecordType>()->getDecl());
2557         if (!Size)
2558           return llvm::None;
2559         Bases.emplace_back(Base.getType(), Size.getValue());
2560       }
2561     }
2562
2563     llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2564                           const std::pair<QualType, int64_t> &R) {
2565       return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2566              Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2567     });
2568
2569     for (const auto &Base : Bases) {
2570       int64_t BaseOffset = Context.toBits(
2571           Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2572       int64_t BaseSize = Base.second;
2573       if (BaseOffset != CurOffsetInBits)
2574         return llvm::None;
2575       CurOffsetInBits = BaseOffset + BaseSize;
2576     }
2577   }
2578
2579   for (const auto *Field : RD->fields()) {
2580     if (!Field->getType()->isReferenceType() &&
2581         !Context.hasUniqueObjectRepresentations(Field->getType()))
2582       return llvm::None;
2583
2584     int64_t FieldSizeInBits =
2585         Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2586     if (Field->isBitField()) {
2587       int64_t BitfieldSize = Field->getBitWidthValue(Context);
2588
2589       if (BitfieldSize > FieldSizeInBits)
2590         return llvm::None;
2591       FieldSizeInBits = BitfieldSize;
2592     }
2593
2594     int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2595
2596     if (FieldOffsetInBits != CurOffsetInBits)
2597       return llvm::None;
2598
2599     CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2600   }
2601
2602   return CurOffsetInBits;
2603 }
2604
2605 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2606   // C++17 [meta.unary.prop]:
2607   //   The predicate condition for a template specialization
2608   //   has_unique_object_representations<T> shall be
2609   //   satisfied if and only if:
2610   //     (9.1) - T is trivially copyable, and
2611   //     (9.2) - any two objects of type T with the same value have the same
2612   //     object representation, where two objects
2613   //   of array or non-union class type are considered to have the same value
2614   //   if their respective sequences of
2615   //   direct subobjects have the same values, and two objects of union type
2616   //   are considered to have the same
2617   //   value if they have the same active member and the corresponding members
2618   //   have the same value.
2619   //   The set of scalar types for which this condition holds is
2620   //   implementation-defined. [ Note: If a type has padding
2621   //   bits, the condition does not hold; otherwise, the condition holds true
2622   //   for unsigned integral types. -- end note ]
2623   assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2624
2625   // Arrays are unique only if their element type is unique.
2626   if (Ty->isArrayType())
2627     return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2628
2629   // (9.1) - T is trivially copyable...
2630   if (!Ty.isTriviallyCopyableType(*this))
2631     return false;
2632
2633   // All integrals and enums are unique.
2634   if (Ty->isIntegralOrEnumerationType())
2635     return true;
2636
2637   // All other pointers are unique.
2638   if (Ty->isPointerType())
2639     return true;
2640
2641   if (Ty->isMemberPointerType()) {
2642     const auto *MPT = Ty->getAs<MemberPointerType>();
2643     return !ABI->getMemberPointerInfo(MPT).HasPadding;
2644   }
2645
2646   if (Ty->isRecordType()) {
2647     const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2648
2649     if (Record->isInvalidDecl())
2650       return false;
2651
2652     if (Record->isUnion())
2653       return unionHasUniqueObjectRepresentations(*this, Record);
2654
2655     Optional<int64_t> StructSize =
2656         structHasUniqueObjectRepresentations(*this, Record);
2657
2658     return StructSize &&
2659            StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2660   }
2661
2662   // FIXME: More cases to handle here (list by rsmith):
2663   // vectors (careful about, eg, vector of 3 foo)
2664   // _Complex int and friends
2665   // _Atomic T
2666   // Obj-C block pointers
2667   // Obj-C object pointers
2668   // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2669   // clk_event_t, queue_t, reserve_id_t)
2670   // There're also Obj-C class types and the Obj-C selector type, but I think it
2671   // makes sense for those to return false here.
2672
2673   return false;
2674 }
2675
2676 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2677   unsigned count = 0;
2678   // Count ivars declared in class extension.
2679   for (const auto *Ext : OI->known_extensions())
2680     count += Ext->ivar_size();
2681
2682   // Count ivar defined in this class's implementation.  This
2683   // includes synthesized ivars.
2684   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2685     count += ImplDecl->ivar_size();
2686
2687   return count;
2688 }
2689
2690 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2691   if (!E)
2692     return false;
2693
2694   // nullptr_t is always treated as null.
2695   if (E->getType()->isNullPtrType()) return true;
2696
2697   if (E->getType()->isAnyPointerType() &&
2698       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2699                                                 Expr::NPC_ValueDependentIsNull))
2700     return true;
2701
2702   // Unfortunately, __null has type 'int'.
2703   if (isa<GNUNullExpr>(E)) return true;
2704
2705   return false;
2706 }
2707
2708 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2709 /// exists.
2710 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2711   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2712     I = ObjCImpls.find(D);
2713   if (I != ObjCImpls.end())
2714     return cast<ObjCImplementationDecl>(I->second);
2715   return nullptr;
2716 }
2717
2718 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2719 /// exists.
2720 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2721   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2722     I = ObjCImpls.find(D);
2723   if (I != ObjCImpls.end())
2724     return cast<ObjCCategoryImplDecl>(I->second);
2725   return nullptr;
2726 }
2727
2728 /// Set the implementation of ObjCInterfaceDecl.
2729 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2730                            ObjCImplementationDecl *ImplD) {
2731   assert(IFaceD && ImplD && "Passed null params");
2732   ObjCImpls[IFaceD] = ImplD;
2733 }
2734
2735 /// Set the implementation of ObjCCategoryDecl.
2736 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2737                            ObjCCategoryImplDecl *ImplD) {
2738   assert(CatD && ImplD && "Passed null params");
2739   ObjCImpls[CatD] = ImplD;
2740 }
2741
2742 const ObjCMethodDecl *
2743 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2744   return ObjCMethodRedecls.lookup(MD);
2745 }
2746
2747 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2748                                             const ObjCMethodDecl *Redecl) {
2749   assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2750   ObjCMethodRedecls[MD] = Redecl;
2751 }
2752
2753 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2754                                               const NamedDecl *ND) const {
2755   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2756     return ID;
2757   if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2758     return CD->getClassInterface();
2759   if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2760     return IMD->getClassInterface();
2761
2762   return nullptr;
2763 }
2764
2765 /// Get the copy initialization expression of VarDecl, or nullptr if
2766 /// none exists.
2767 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2768   assert(VD && "Passed null params");
2769   assert(VD->hasAttr<BlocksAttr>() &&
2770          "getBlockVarCopyInits - not __block var");
2771   auto I = BlockVarCopyInits.find(VD);
2772   if (I != BlockVarCopyInits.end())
2773     return I->second;
2774   return {nullptr, false};
2775 }
2776
2777 /// Set the copy initialization expression of a block var decl.
2778 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2779                                      bool CanThrow) {
2780   assert(VD && CopyExpr && "Passed null params");
2781   assert(VD->hasAttr<BlocksAttr>() &&
2782          "setBlockVarCopyInits - not __block var");
2783   BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2784 }
2785
2786 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2787                                                  unsigned DataSize) const {
2788   if (!DataSize)
2789     DataSize = TypeLoc::getFullDataSizeForType(T);
2790   else
2791     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2792            "incorrect data size provided to CreateTypeSourceInfo!");
2793
2794   auto *TInfo =
2795     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2796   new (TInfo) TypeSourceInfo(T);
2797   return TInfo;
2798 }
2799
2800 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2801                                                      SourceLocation L) const {
2802   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2803   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2804   return DI;
2805 }
2806
2807 const ASTRecordLayout &
2808 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2809   return getObjCLayout(D, nullptr);
2810 }
2811
2812 const ASTRecordLayout &
2813 ASTContext::getASTObjCImplementationLayout(
2814                                         const ObjCImplementationDecl *D) const {
2815   return getObjCLayout(D->getClassInterface(), D);
2816 }
2817
2818 //===----------------------------------------------------------------------===//
2819 //                   Type creation/memoization methods
2820 //===----------------------------------------------------------------------===//
2821
2822 QualType
2823 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2824   unsigned fastQuals = quals.getFastQualifiers();
2825   quals.removeFastQualifiers();
2826
2827   // Check if we've already instantiated this type.
2828   llvm::FoldingSetNodeID ID;
2829   ExtQuals::Profile(ID, baseType, quals);
2830   void *insertPos = nullptr;
2831   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2832     assert(eq->getQualifiers() == quals);
2833     return QualType(eq, fastQuals);
2834   }
2835
2836   // If the base type is not canonical, make the appropriate canonical type.
2837   QualType canon;
2838   if (!baseType->isCanonicalUnqualified()) {
2839     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2840     canonSplit.Quals.addConsistentQualifiers(quals);
2841     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2842
2843     // Re-find the insert position.
2844     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2845   }
2846
2847   auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2848   ExtQualNodes.InsertNode(eq, insertPos);
2849   return QualType(eq, fastQuals);
2850 }
2851
2852 QualType ASTContext::getAddrSpaceQualType(QualType T,
2853                                           LangAS AddressSpace) const {
2854   QualType CanT = getCanonicalType(T);
2855   if (CanT.getAddressSpace() == AddressSpace)
2856     return T;
2857
2858   // If we are composing extended qualifiers together, merge together
2859   // into one ExtQuals node.
2860   QualifierCollector Quals;
2861   const Type *TypeNode = Quals.strip(T);
2862
2863   // If this type already has an address space specified, it cannot get
2864   // another one.
2865   assert(!Quals.hasAddressSpace() &&
2866          "Type cannot be in multiple addr spaces!");
2867   Quals.addAddressSpace(AddressSpace);
2868
2869   return getExtQualType(TypeNode, Quals);
2870 }
2871
2872 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2873   // If we are composing extended qualifiers together, merge together
2874   // into one ExtQuals node.
2875   QualifierCollector Quals;
2876   const Type *TypeNode = Quals.strip(T);
2877
2878   // If the qualifier doesn't have an address space just return it.
2879   if (!Quals.hasAddressSpace())
2880     return T;
2881
2882   Quals.removeAddressSpace();
2883
2884   // Removal of the address space can mean there are no longer any
2885   // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2886   // or required.
2887   if (Quals.hasNonFastQualifiers())
2888     return getExtQualType(TypeNode, Quals);
2889   else
2890     return QualType(TypeNode, Quals.getFastQualifiers());
2891 }
2892
2893 QualType ASTContext::getObjCGCQualType(QualType T,
2894                                        Qualifiers::GC GCAttr) const {
2895   QualType CanT = getCanonicalType(T);
2896   if (CanT.getObjCGCAttr() == GCAttr)
2897     return T;
2898
2899   if (const auto *ptr = T->getAs<PointerType>()) {
2900     QualType Pointee = ptr->getPointeeType();
2901     if (Pointee->isAnyPointerType()) {
2902       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2903       return getPointerType(ResultType);
2904     }
2905   }
2906
2907   // If we are composing extended qualifiers together, merge together
2908   // into one ExtQuals node.
2909   QualifierCollector Quals;
2910   const Type *TypeNode = Quals.strip(T);
2911
2912   // If this type already has an ObjCGC specified, it cannot get
2913   // another one.
2914   assert(!Quals.hasObjCGCAttr() &&
2915          "Type cannot have multiple ObjCGCs!");
2916   Quals.addObjCGCAttr(GCAttr);
2917
2918   return getExtQualType(TypeNode, Quals);
2919 }
2920
2921 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2922   if (const PointerType *Ptr = T->getAs<PointerType>()) {
2923     QualType Pointee = Ptr->getPointeeType();
2924     if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2925       return getPointerType(removeAddrSpaceQualType(Pointee));
2926     }
2927   }
2928   return T;
2929 }
2930
2931 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2932                                                    FunctionType::ExtInfo Info) {
2933   if (T->getExtInfo() == Info)
2934     return T;
2935
2936   QualType Result;
2937   if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2938     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2939   } else {
2940     const auto *FPT = cast<FunctionProtoType>(T);
2941     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2942     EPI.ExtInfo = Info;
2943     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2944   }
2945
2946   return cast<FunctionType>(Result.getTypePtr());
2947 }
2948
2949 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2950                                                  QualType ResultType) {
2951   FD = FD->getMostRecentDecl();
2952   while (true) {
2953     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2954     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2955     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2956     if (FunctionDecl *Next = FD->getPreviousDecl())
2957       FD = Next;
2958     else
2959       break;
2960   }
2961   if (ASTMutationListener *L = getASTMutationListener())
2962     L->DeducedReturnType(FD, ResultType);
2963 }
2964
2965 /// Get a function type and produce the equivalent function type with the
2966 /// specified exception specification. Type sugar that can be present on a
2967 /// declaration of a function with an exception specification is permitted
2968 /// and preserved. Other type sugar (for instance, typedefs) is not.
2969 QualType ASTContext::getFunctionTypeWithExceptionSpec(
2970     QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
2971   // Might have some parens.
2972   if (const auto *PT = dyn_cast<ParenType>(Orig))
2973     return getParenType(
2974         getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2975
2976   // Might be wrapped in a macro qualified type.
2977   if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2978     return getMacroQualifiedType(
2979         getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2980         MQT->getMacroIdentifier());
2981
2982   // Might have a calling-convention attribute.
2983   if (const auto *AT = dyn_cast<AttributedType>(Orig))
2984     return getAttributedType(
2985         AT->getAttrKind(),
2986         getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2987         getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2988
2989   // Anything else must be a function type. Rebuild it with the new exception
2990   // specification.
2991   const auto *Proto = Orig->castAs<FunctionProtoType>();
2992   return getFunctionType(
2993       Proto->getReturnType(), Proto->getParamTypes(),
2994       Proto->getExtProtoInfo().withExceptionSpec(ESI));
2995 }
2996
2997 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2998                                                           QualType U) {
2999   return hasSameType(T, U) ||
3000          (getLangOpts().CPlusPlus17 &&
3001           hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3002                       getFunctionTypeWithExceptionSpec(U, EST_None)));
3003 }
3004
3005 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3006   if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3007     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3008     SmallVector<QualType, 16> Args(Proto->param_types());
3009     for (unsigned i = 0, n = Args.size(); i != n; ++i)
3010       Args[i] = removePtrSizeAddrSpace(Args[i]);
3011     return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3012   }
3013
3014   if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3015     QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3016     return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3017   }
3018
3019   return T;
3020 }
3021
3022 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3023   return hasSameType(T, U) ||
3024          hasSameType(getFunctionTypeWithoutPtrSizes(T),
3025                      getFunctionTypeWithoutPtrSizes(U));
3026 }
3027
3028 void ASTContext::adjustExceptionSpec(
3029     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3030     bool AsWritten) {
3031   // Update the type.
3032   QualType Updated =
3033       getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3034   FD->setType(Updated);
3035
3036   if (!AsWritten)
3037     return;
3038
3039   // Update the type in the type source information too.
3040   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3041     // If the type and the type-as-written differ, we may need to update
3042     // the type-as-written too.
3043     if (TSInfo->getType() != FD->getType())
3044       Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3045
3046     // FIXME: When we get proper type location information for exceptions,
3047     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3048     // up the TypeSourceInfo;
3049     assert(TypeLoc::getFullDataSizeForType(Updated) ==
3050                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3051            "TypeLoc size mismatch from updating exception specification");
3052     TSInfo->overrideType(Updated);
3053   }
3054 }
3055
3056 /// getComplexType - Return the uniqued reference to the type for a complex
3057 /// number with the specified element type.
3058 QualType ASTContext::getComplexType(QualType T) const {
3059   // Unique pointers, to guarantee there is only one pointer of a particular
3060   // structure.
3061   llvm::FoldingSetNodeID ID;
3062   ComplexType::Profile(ID, T);
3063
3064   void *InsertPos = nullptr;
3065   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3066     return QualType(CT, 0);
3067
3068   // If the pointee type isn't canonical, this won't be a canonical type either,
3069   // so fill in the canonical type field.
3070   QualType Canonical;
3071   if (!T.isCanonical()) {
3072     Canonical = getComplexType(getCanonicalType(T));
3073
3074     // Get the new insert position for the node we care about.
3075     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3076     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3077   }
3078   auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3079   Types.push_back(New);
3080   ComplexTypes.InsertNode(New, InsertPos);
3081   return QualType(New, 0);
3082 }
3083
3084 /// getPointerType - Return the uniqued reference to the type for a pointer to
3085 /// the specified type.
3086 QualType ASTContext::getPointerType(QualType T) const {
3087   // Unique pointers, to guarantee there is only one pointer of a particular
3088   // structure.
3089   llvm::FoldingSetNodeID ID;
3090   PointerType::Profile(ID, T);
3091
3092   void *InsertPos = nullptr;
3093   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3094     return QualType(PT, 0);
3095
3096   // If the pointee type isn't canonical, this won't be a canonical type either,
3097   // so fill in the canonical type field.
3098   QualType Canonical;
3099   if (!T.isCanonical()) {
3100     Canonical = getPointerType(getCanonicalType(T));
3101
3102     // Get the new insert position for the node we care about.
3103     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3104     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3105   }
3106   auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3107   Types.push_back(New);
3108   PointerTypes.InsertNode(New, InsertPos);
3109   return QualType(New, 0);
3110 }
3111
3112 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3113   llvm::FoldingSetNodeID ID;
3114   AdjustedType::Profile(ID, Orig, New);
3115   void *InsertPos = nullptr;
3116   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3117   if (AT)
3118     return QualType(AT, 0);
3119
3120   QualType Canonical = getCanonicalType(New);
3121
3122   // Get the new insert position for the node we care about.
3123   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3124   assert(!AT && "Shouldn't be in the map!");
3125
3126   AT = new (*this, TypeAlignment)
3127       AdjustedType(Type::Adjusted, Orig, New, Canonical);
3128   Types.push_back(AT);
3129   AdjustedTypes.InsertNode(AT, InsertPos);
3130   return QualType(AT, 0);
3131 }
3132
3133 QualType ASTContext::getDecayedType(QualType T) const {
3134   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3135
3136   QualType Decayed;
3137
3138   // C99 6.7.5.3p7:
3139   //   A declaration of a parameter as "array of type" shall be
3140   //   adjusted to "qualified pointer to type", where the type
3141   //   qualifiers (if any) are those specified within the [ and ] of
3142   //   the array type derivation.
3143   if (T->isArrayType())
3144     Decayed = getArrayDecayedType(T);
3145
3146   // C99 6.7.5.3p8:
3147   //   A declaration of a parameter as "function returning type"
3148   //   shall be adjusted to "pointer to function returning type", as
3149   //   in 6.3.2.1.
3150   if (T->isFunctionType())
3151     Decayed = getPointerType(T);
3152
3153   llvm::FoldingSetNodeID ID;
3154   AdjustedType::Profile(ID, T, Decayed);
3155   void *InsertPos = nullptr;
3156   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3157   if (AT)
3158     return QualType(AT, 0);
3159
3160   QualType Canonical = getCanonicalType(Decayed);
3161
3162   // Get the new insert position for the node we care about.
3163   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3164   assert(!AT && "Shouldn't be in the map!");
3165
3166   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3167   Types.push_back(AT);
3168   AdjustedTypes.InsertNode(AT, InsertPos);
3169   return QualType(AT, 0);
3170 }
3171
3172 /// getBlockPointerType - Return the uniqued reference to the type for
3173 /// a pointer to the specified block.
3174 QualType ASTContext::getBlockPointerType(QualType T) const {
3175   assert(T->isFunctionType() && "block of function types only");
3176   // Unique pointers, to guarantee there is only one block of a particular
3177   // structure.
3178   llvm::FoldingSetNodeID ID;
3179   BlockPointerType::Profile(ID, T);
3180
3181   void *InsertPos = nullptr;
3182   if (BlockPointerType *PT =
3183         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3184     return QualType(PT, 0);
3185
3186   // If the block pointee type isn't canonical, this won't be a canonical
3187   // type either so fill in the canonical type field.
3188   QualType Canonical;
3189   if (!T.isCanonical()) {
3190     Canonical = getBlockPointerType(getCanonicalType(T));
3191
3192     // Get the new insert position for the node we care about.
3193     BlockPointerType *NewIP =
3194       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3195     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3196   }
3197   auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3198   Types.push_back(New);
3199   BlockPointerTypes.InsertNode(New, InsertPos);
3200   return QualType(New, 0);
3201 }
3202
3203 /// getLValueReferenceType - Return the uniqued reference to the type for an
3204 /// lvalue reference to the specified type.
3205 QualType
3206 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3207   assert(getCanonicalType(T) != OverloadTy &&
3208          "Unresolved overloaded function type");
3209
3210   // Unique pointers, to guarantee there is only one pointer of a particular
3211   // structure.
3212   llvm::FoldingSetNodeID ID;
3213   ReferenceType::Profile(ID, T, SpelledAsLValue);
3214
3215   void *InsertPos = nullptr;
3216   if (LValueReferenceType *RT =
3217         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3218     return QualType(RT, 0);
3219
3220   const auto *InnerRef = T->getAs<ReferenceType>();
3221
3222   // If the referencee type isn't canonical, this won't be a canonical type
3223   // either, so fill in the canonical type field.
3224   QualType Canonical;
3225   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3226     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3227     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3228
3229     // Get the new insert position for the node we care about.
3230     LValueReferenceType *NewIP =
3231       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3232     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3233   }
3234
3235   auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3236                                                              SpelledAsLValue);
3237   Types.push_back(New);
3238   LValueReferenceTypes.InsertNode(New, InsertPos);
3239
3240   return QualType(New, 0);
3241 }
3242
3243 /// getRValueReferenceType - Return the uniqued reference to the type for an
3244 /// rvalue reference to the specified type.
3245 QualType ASTContext::getRValueReferenceType(QualType T) const {
3246   // Unique pointers, to guarantee there is only one pointer of a particular
3247   // structure.
3248   llvm::FoldingSetNodeID ID;
3249   ReferenceType::Profile(ID, T, false);
3250
3251   void *InsertPos = nullptr;
3252   if (RValueReferenceType *RT =
3253         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3254     return QualType(RT, 0);
3255
3256   const auto *InnerRef = T->getAs<ReferenceType>();
3257
3258   // If the referencee type isn't canonical, this won't be a canonical type
3259   // either, so fill in the canonical type field.
3260   QualType Canonical;
3261   if (InnerRef || !T.isCanonical()) {
3262     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3263     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3264
3265     // Get the new insert position for the node we care about.
3266     RValueReferenceType *NewIP =
3267       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3268     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3269   }
3270
3271   auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3272   Types.push_back(New);
3273   RValueReferenceTypes.InsertNode(New, InsertPos);
3274   return QualType(New, 0);
3275 }
3276
3277 /// getMemberPointerType - Return the uniqued reference to the type for a
3278 /// member pointer to the specified type, in the specified class.
3279 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3280   // Unique pointers, to guarantee there is only one pointer of a particular
3281   // structure.
3282   llvm::FoldingSetNodeID ID;
3283   MemberPointerType::Profile(ID, T, Cls);
3284
3285   void *InsertPos = nullptr;
3286   if (MemberPointerType *PT =
3287       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3288     return QualType(PT, 0);
3289
3290   // If the pointee or class type isn't canonical, this won't be a canonical
3291   // type either, so fill in the canonical type field.
3292   QualType Canonical;
3293   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3294     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3295
3296     // Get the new insert position for the node we care about.
3297     MemberPointerType *NewIP =
3298       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3299     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3300   }
3301   auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3302   Types.push_back(New);
3303   MemberPointerTypes.InsertNode(New, InsertPos);
3304   return QualType(New, 0);
3305 }
3306
3307 /// getConstantArrayType - Return the unique reference to the type for an
3308 /// array of the specified element type.
3309 QualType ASTContext::getConstantArrayType(QualType EltTy,
3310                                           const llvm::APInt &ArySizeIn,
3311                                           const Expr *SizeExpr,
3312                                           ArrayType::ArraySizeModifier ASM,
3313                                           unsigned IndexTypeQuals) const {
3314   assert((EltTy->isDependentType() ||
3315           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3316          "Constant array of VLAs is illegal!");
3317
3318   // We only need the size as part of the type if it's instantiation-dependent.
3319   if (SizeExpr && !SizeExpr->isInstantiationDependent())
3320     SizeExpr = nullptr;
3321
3322   // Convert the array size into a canonical width matching the pointer size for
3323   // the target.
3324   llvm::APInt ArySize(ArySizeIn);
3325   ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3326
3327   llvm::FoldingSetNodeID ID;
3328   ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3329                              IndexTypeQuals);
3330
3331   void *InsertPos = nullptr;
3332   if (ConstantArrayType *ATP =
3333       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3334     return QualType(ATP, 0);
3335
3336   // If the element type isn't canonical or has qualifiers, or the array bound
3337   // is instantiation-dependent, this won't be a canonical type either, so fill
3338   // in the canonical type field.
3339   QualType Canon;
3340   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3341     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3342     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3343                                  ASM, IndexTypeQuals);
3344     Canon = getQualifiedType(Canon, canonSplit.Quals);
3345
3346     // Get the new insert position for the node we care about.
3347     ConstantArrayType *NewIP =
3348       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3349     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3350   }
3351
3352   void *Mem = Allocate(
3353       ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3354       TypeAlignment);
3355   auto *New = new (Mem)
3356     ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3357   ConstantArrayTypes.InsertNode(New, InsertPos);
3358   Types.push_back(New);
3359   return QualType(New, 0);
3360 }
3361
3362 /// getVariableArrayDecayedType - Turns the given type, which may be
3363 /// variably-modified, into the corresponding type with all the known
3364 /// sizes replaced with [*].
3365 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3366   // Vastly most common case.
3367   if (!type->isVariablyModifiedType()) return type;
3368
3369   QualType result;
3370
3371   SplitQualType split = type.getSplitDesugaredType();
3372   const Type *ty = split.Ty;
3373   switch (ty->getTypeClass()) {
3374 #define TYPE(Class, Base)
3375 #define ABSTRACT_TYPE(Class, Base)
3376 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3377 #include "clang/AST/TypeNodes.inc"
3378     llvm_unreachable("didn't desugar past all non-canonical types?");
3379
3380   // These types should never be variably-modified.
3381   case Type::Builtin:
3382   case Type::Complex:
3383   case Type::Vector:
3384   case Type::DependentVector:
3385   case Type::ExtVector:
3386   case Type::DependentSizedExtVector:
3387   case Type::ConstantMatrix:
3388   case Type::DependentSizedMatrix:
3389   case Type::DependentAddressSpace:
3390   case Type::ObjCObject:
3391   case Type::ObjCInterface:
3392   case Type::ObjCObjectPointer:
3393   case Type::Record:
3394   case Type::Enum:
3395   case Type::UnresolvedUsing:
3396   case Type::TypeOfExpr:
3397   case Type::TypeOf:
3398   case Type::Decltype:
3399   case Type::UnaryTransform:
3400   case Type::DependentName:
3401   case Type::InjectedClassName:
3402   case Type::TemplateSpecialization:
3403   case Type::DependentTemplateSpecialization:
3404   case Type::TemplateTypeParm:
3405   case Type::SubstTemplateTypeParmPack:
3406   case Type::Auto:
3407   case Type::DeducedTemplateSpecialization:
3408   case Type::PackExpansion:
3409   case Type::ExtInt:
3410   case Type::DependentExtInt:
3411     llvm_unreachable("type should never be variably-modified");
3412
3413   // These types can be variably-modified but should never need to
3414   // further decay.
3415   case Type::FunctionNoProto:
3416   case Type::FunctionProto:
3417   case Type::BlockPointer:
3418   case Type::MemberPointer:
3419   case Type::Pipe:
3420     return type;
3421
3422   // These types can be variably-modified.  All these modifications
3423   // preserve structure except as noted by comments.
3424   // TODO: if we ever care about optimizing VLAs, there are no-op
3425   // optimizations available here.
3426   case Type::Pointer:
3427     result = getPointerType(getVariableArrayDecayedType(
3428                               cast<PointerType>(ty)->getPointeeType()));
3429     break;
3430
3431   case Type::LValueReference: {
3432     const auto *lv = cast<LValueReferenceType>(ty);
3433     result = getLValueReferenceType(
3434                  getVariableArrayDecayedType(lv->getPointeeType()),
3435                                     lv->isSpelledAsLValue());
3436     break;
3437   }
3438
3439   case Type::RValueReference: {
3440     const auto *lv = cast<RValueReferenceType>(ty);
3441     result = getRValueReferenceType(
3442                  getVariableArrayDecayedType(lv->getPointeeType()));
3443     break;
3444   }
3445
3446   case Type::Atomic: {
3447     const auto *at = cast<AtomicType>(ty);
3448     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3449     break;
3450   }
3451
3452   case Type::ConstantArray: {
3453     const auto *cat = cast<ConstantArrayType>(ty);
3454     result = getConstantArrayType(
3455                  getVariableArrayDecayedType(cat->getElementType()),
3456                                   cat->getSize(),
3457                                   cat->getSizeExpr(),
3458                                   cat->getSizeModifier(),
3459                                   cat->getIndexTypeCVRQualifiers());
3460     break;
3461   }
3462
3463   case Type::DependentSizedArray: {
3464     const auto *dat = cast<DependentSizedArrayType>(ty);
3465     result = getDependentSizedArrayType(
3466                  getVariableArrayDecayedType(dat->getElementType()),
3467                                         dat->getSizeExpr(),
3468                                         dat->getSizeModifier(),
3469                                         dat->getIndexTypeCVRQualifiers(),
3470                                         dat->getBracketsRange());
3471     break;
3472   }
3473
3474   // Turn incomplete types into [*] types.
3475   case Type::IncompleteArray: {
3476     const auto *iat = cast<IncompleteArrayType>(ty);
3477     result = getVariableArrayType(
3478                  getVariableArrayDecayedType(iat->getElementType()),
3479                                   /*size*/ nullptr,
3480                                   ArrayType::Normal,
3481                                   iat->getIndexTypeCVRQualifiers(),
3482                                   SourceRange());
3483     break;
3484   }
3485
3486   // Turn VLA types into [*] types.
3487   case Type::VariableArray: {
3488     const auto *vat = cast<VariableArrayType>(ty);
3489     result = getVariableArrayType(
3490                  getVariableArrayDecayedType(vat->getElementType()),
3491                                   /*size*/ nullptr,
3492                                   ArrayType::Star,
3493                                   vat->getIndexTypeCVRQualifiers(),
3494                                   vat->getBracketsRange());
3495     break;
3496   }
3497   }
3498
3499   // Apply the top-level qualifiers from the original.
3500   return getQualifiedType(result, split.Quals);
3501 }
3502
3503 /// getVariableArrayType - Returns a non-unique reference to the type for a
3504 /// variable array of the specified element type.
3505 QualType ASTContext::getVariableArrayType(QualType EltTy,
3506                                           Expr *NumElts,
3507                                           ArrayType::ArraySizeModifier ASM,
3508                                           unsigned IndexTypeQuals,
3509                                           SourceRange Brackets) const {
3510   // Since we don't unique expressions, it isn't possible to unique VLA's
3511   // that have an expression provided for their size.
3512   QualType Canon;
3513
3514   // Be sure to pull qualifiers off the element type.
3515   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3516     SplitQualType canonSplit = getCanonicalType(EltTy).split();
3517     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3518                                  IndexTypeQuals, Brackets);
3519     Canon = getQualifiedType(Canon, canonSplit.Quals);
3520   }
3521
3522   auto *New = new (*this, TypeAlignment)
3523     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3524
3525   VariableArrayTypes.push_back(New);
3526   Types.push_back(New);
3527   return QualType(New, 0);
3528 }
3529
3530 /// getDependentSizedArrayType - Returns a non-unique reference to
3531 /// the type for a dependently-sized array of the specified element
3532 /// type.
3533 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3534                                                 Expr *numElements,
3535                                                 ArrayType::ArraySizeModifier ASM,
3536                                                 unsigned elementTypeQuals,
3537                                                 SourceRange brackets) const {
3538   assert((!numElements || numElements->isTypeDependent() ||
3539           numElements->isValueDependent()) &&
3540          "Size must be type- or value-dependent!");
3541
3542   // Dependently-sized array types that do not have a specified number
3543   // of elements will have their sizes deduced from a dependent
3544   // initializer.  We do no canonicalization here at all, which is okay
3545   // because they can't be used in most locations.
3546   if (!numElements) {
3547     auto *newType
3548       = new (*this, TypeAlignment)
3549           DependentSizedArrayType(*this, elementType, QualType(),
3550                                   numElements, ASM, elementTypeQuals,
3551                                   brackets);
3552     Types.push_back(newType);
3553     return QualType(newType, 0);
3554   }
3555
3556   // Otherwise, we actually build a new type every time, but we
3557   // also build a canonical type.
3558
3559   SplitQualType canonElementType = getCanonicalType(elementType).split();
3560
3561   void *insertPos = nullptr;
3562   llvm::FoldingSetNodeID ID;
3563   DependentSizedArrayType::Profile(ID, *this,
3564                                    QualType(canonElementType.Ty, 0),
3565                                    ASM, elementTypeQuals, numElements);
3566
3567   // Look for an existing type with these properties.
3568   DependentSizedArrayType *canonTy =
3569     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3570
3571   // If we don't have one, build one.
3572   if (!canonTy) {
3573     canonTy = new (*this, TypeAlignment)
3574       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3575                               QualType(), numElements, ASM, elementTypeQuals,
3576                               brackets);
3577     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3578     Types.push_back(canonTy);
3579   }
3580
3581   // Apply qualifiers from the element type to the array.
3582   QualType canon = getQualifiedType(QualType(canonTy,0),
3583                                     canonElementType.Quals);
3584
3585   // If we didn't need extra canonicalization for the element type or the size
3586   // expression, then just use that as our result.
3587   if (QualType(canonElementType.Ty, 0) == elementType &&
3588       canonTy->getSizeExpr() == numElements)
3589     return canon;
3590
3591   // Otherwise, we need to build a type which follows the spelling
3592   // of the element type.
3593   auto *sugaredType
3594     = new (*this, TypeAlignment)
3595         DependentSizedArrayType(*this, elementType, canon, numElements,
3596                                 ASM, elementTypeQuals, brackets);
3597   Types.push_back(sugaredType);
3598   return QualType(sugaredType, 0);
3599 }
3600
3601 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3602                                             ArrayType::ArraySizeModifier ASM,
3603                                             unsigned elementTypeQuals) const {
3604   llvm::FoldingSetNodeID ID;
3605   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3606
3607   void *insertPos = nullptr;
3608   if (IncompleteArrayType *iat =
3609        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3610     return QualType(iat, 0);
3611
3612   // If the element type isn't canonical, this won't be a canonical type
3613   // either, so fill in the canonical type field.  We also have to pull
3614   // qualifiers off the element type.
3615   QualType canon;
3616
3617   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3618     SplitQualType canonSplit = getCanonicalType(elementType).split();
3619     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3620                                    ASM, elementTypeQuals);
3621     canon = getQualifiedType(canon, canonSplit.Quals);
3622
3623     // Get the new insert position for the node we care about.
3624     IncompleteArrayType *existing =
3625       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3626     assert(!existing && "Shouldn't be in the map!"); (void) existing;
3627   }
3628
3629   auto *newType = new (*this, TypeAlignment)
3630     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3631
3632   IncompleteArrayTypes.InsertNode(newType, insertPos);
3633   Types.push_back(newType);
3634   return QualType(newType, 0);
3635 }
3636
3637 /// getScalableVectorType - Return the unique reference to a scalable vector
3638 /// type of the specified element type and size. VectorType must be a built-in
3639 /// type.
3640 QualType ASTContext::getScalableVectorType(QualType EltTy,
3641                                            unsigned NumElts) const {
3642   if (Target->hasAArch64SVETypes()) {
3643     uint64_t EltTySize = getTypeSize(EltTy);
3644 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3645                         IsSigned, IsFP, IsBF)                                  \
3646   if (!EltTy->isBooleanType() &&                                               \
3647       ((EltTy->hasIntegerRepresentation() &&                                   \
3648         EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3649        (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3650         IsFP && !IsBF) ||                                                      \
3651        (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3652         IsBF && !IsFP)) &&                                                     \
3653       EltTySize == ElBits && NumElts == NumEls) {                              \
3654     return SingletonId;                                                        \
3655   }
3656 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3657   if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3658     return SingletonId;
3659 #include "clang/Basic/AArch64SVEACLETypes.def"
3660   }
3661   return QualType();
3662 }
3663
3664 /// getVectorType - Return the unique reference to a vector type of
3665 /// the specified element type and size. VectorType must be a built-in type.
3666 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3667                                    VectorType::VectorKind VecKind) const {
3668   assert(vecType->isBuiltinType());
3669
3670   // Check if we've already instantiated a vector of this type.
3671   llvm::FoldingSetNodeID ID;
3672   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3673
3674   void *InsertPos = nullptr;
3675   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3676     return QualType(VTP, 0);
3677
3678   // If the element type isn't canonical, this won't be a canonical type either,
3679   // so fill in the canonical type field.
3680   QualType Canonical;
3681   if (!vecType.isCanonical()) {
3682     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3683
3684     // Get the new insert position for the node we care about.
3685     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3686     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3687   }
3688   auto *New = new (*this, TypeAlignment)
3689     VectorType(vecType, NumElts, Canonical, VecKind);
3690   VectorTypes.InsertNode(New, InsertPos);
3691   Types.push_back(New);
3692   return QualType(New, 0);
3693 }
3694
3695 QualType
3696 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3697                                    SourceLocation AttrLoc,
3698                                    VectorType::VectorKind VecKind) const {
3699   llvm::FoldingSetNodeID ID;
3700   DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3701                                VecKind);
3702   void *InsertPos = nullptr;
3703   DependentVectorType *Canon =
3704       DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3705   DependentVectorType *New;
3706
3707   if (Canon) {
3708     New = new (*this, TypeAlignment) DependentVectorType(
3709         *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3710   } else {
3711     QualType CanonVecTy = getCanonicalType(VecType);
3712     if (CanonVecTy == VecType) {
3713       New = new (*this, TypeAlignment) DependentVectorType(
3714           *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3715
3716       DependentVectorType *CanonCheck =
3717           DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3718       assert(!CanonCheck &&
3719              "Dependent-sized vector_size canonical type broken");
3720       (void)CanonCheck;
3721       DependentVectorTypes.InsertNode(New, InsertPos);
3722     } else {
3723       QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3724                                                 SourceLocation(), VecKind);
3725       New = new (*this, TypeAlignment) DependentVectorType(
3726           *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3727     }
3728   }
3729
3730   Types.push_back(New);
3731   return QualType(New, 0);
3732 }
3733
3734 /// getExtVectorType - Return the unique reference to an extended vector type of
3735 /// the specified element type and size. VectorType must be a built-in type.
3736 QualType
3737 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3738   assert(vecType->isBuiltinType() || vecType->isDependentType());
3739
3740   // Check if we've already instantiated a vector of this type.
3741   llvm::FoldingSetNodeID ID;
3742   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3743                       VectorType::GenericVector);
3744   void *InsertPos = nullptr;
3745   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3746     return QualType(VTP, 0);
3747
3748   // If the element type isn't canonical, this won't be a canonical type either,
3749   // so fill in the canonical type field.
3750   QualType Canonical;
3751   if (!vecType.isCanonical()) {
3752     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3753
3754     // Get the new insert position for the node we care about.
3755     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3756     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3757   }
3758   auto *New = new (*this, TypeAlignment)
3759     ExtVectorType(vecType, NumElts, Canonical);
3760   VectorTypes.InsertNode(New, InsertPos);
3761   Types.push_back(New);
3762   return QualType(New, 0);
3763 }
3764
3765 QualType
3766 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3767                                            Expr *SizeExpr,
3768                                            SourceLocation AttrLoc) const {
3769   llvm::FoldingSetNodeID ID;
3770   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3771                                        SizeExpr);
3772
3773   void *InsertPos = nullptr;
3774   DependentSizedExtVectorType *Canon
3775     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3776   DependentSizedExtVectorType *New;
3777   if (Canon) {
3778     // We already have a canonical version of this array type; use it as
3779     // the canonical type for a newly-built type.
3780     New = new (*this, TypeAlignment)
3781       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3782                                   SizeExpr, AttrLoc);
3783   } else {
3784     QualType CanonVecTy = getCanonicalType(vecType);
3785     if (CanonVecTy == vecType) {
3786       New = new (*this, TypeAlignment)
3787         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3788                                     AttrLoc);
3789
3790       DependentSizedExtVectorType *CanonCheck
3791         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3792       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3793       (void)CanonCheck;
3794       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3795     } else {
3796       QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3797                                                            SourceLocation());
3798       New = new (*this, TypeAlignment) DependentSizedExtVectorType(
3799           *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
3800     }
3801   }
3802
3803   Types.push_back(New);
3804   return QualType(New, 0);
3805 }
3806
3807 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
3808                                            unsigned NumColumns) const {
3809   llvm::FoldingSetNodeID ID;
3810   ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
3811                               Type::ConstantMatrix);
3812
3813   assert(MatrixType::isValidElementType(ElementTy) &&
3814          "need a valid element type");
3815   assert(ConstantMatrixType::isDimensionValid(NumRows) &&
3816          ConstantMatrixType::isDimensionValid(NumColumns) &&
3817          "need valid matrix dimensions");
3818   void *InsertPos = nullptr;
3819   if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
3820     return QualType(MTP, 0);
3821
3822   QualType Canonical;
3823   if (!ElementTy.isCanonical()) {
3824     Canonical =
3825         getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
3826
3827     ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3828     assert(!NewIP && "Matrix type shouldn't already exist in the map");
3829     (void)NewIP;
3830   }
3831
3832   auto *New = new (*this, TypeAlignment)
3833       ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
3834   MatrixTypes.InsertNode(New, InsertPos);
3835   Types.push_back(New);
3836   return QualType(New, 0);
3837 }
3838
3839 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
3840                                                  Expr *RowExpr,
3841                                                  Expr *ColumnExpr,
3842                                                  SourceLocation AttrLoc) const {
3843   QualType CanonElementTy = getCanonicalType(ElementTy);
3844   llvm::FoldingSetNodeID ID;
3845   DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
3846                                     ColumnExpr);
3847
3848   void *InsertPos = nullptr;
3849   DependentSizedMatrixType *Canon =
3850       DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3851
3852   if (!Canon) {
3853     Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
3854         *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
3855 #ifndef NDEBUG
3856     DependentSizedMatrixType *CanonCheck =
3857         DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3858     assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
3859 #endif
3860     DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
3861     Types.push_back(Canon);
3862   }
3863
3864   // Already have a canonical version of the matrix type
3865   //
3866   // If it exactly matches the requested type, use it directly.
3867   if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
3868       Canon->getRowExpr() == ColumnExpr)
3869     return QualType(Canon, 0);
3870
3871   // Use Canon as the canonical type for newly-built type.
3872   DependentSizedMatrixType *New = new (*this, TypeAlignment)
3873       DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
3874                                ColumnExpr, AttrLoc);
3875   Types.push_back(New);
3876   return QualType(New, 0);
3877 }
3878
3879 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3880                                                   Expr *AddrSpaceExpr,
3881                                                   SourceLocation AttrLoc) const {
3882   assert(AddrSpaceExpr->isInstantiationDependent());
3883
3884   QualType canonPointeeType = getCanonicalType(PointeeType);
3885
3886   void *insertPos = nullptr;
3887   llvm::FoldingSetNodeID ID;
3888   DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3889                                      AddrSpaceExpr);
3890
3891   DependentAddressSpaceType *canonTy =
3892     DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3893
3894   if (!canonTy) {
3895     canonTy = new (*this, TypeAlignment)
3896       DependentAddressSpaceType(*this, canonPointeeType,
3897                                 QualType(), AddrSpaceExpr, AttrLoc);
3898     DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3899     Types.push_back(canonTy);
3900   }
3901
3902   if (canonPointeeType == PointeeType &&
3903       canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3904     return QualType(canonTy, 0);
3905
3906   auto *sugaredType
3907     = new (*this, TypeAlignment)
3908         DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3909                                   AddrSpaceExpr, AttrLoc);
3910   Types.push_back(sugaredType);
3911   return QualType(sugaredType, 0);
3912 }
3913
3914 /// Determine whether \p T is canonical as the result type of a function.
3915 static bool isCanonicalResultType(QualType T) {
3916   return T.isCanonical() &&
3917          (T.getObjCLifetime() == Qualifiers::OCL_None ||
3918           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3919 }
3920
3921 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3922 QualType
3923 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3924                                    const FunctionType::ExtInfo &Info) const {
3925   // Unique functions, to guarantee there is only one function of a particular
3926   // structure.
3927   llvm::FoldingSetNodeID ID;
3928   FunctionNoProtoType::Profile(ID, ResultTy, Info);
3929
3930   void *InsertPos = nullptr;
3931   if (FunctionNoProtoType *FT =
3932         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3933     return QualType(FT, 0);
3934
3935   QualType Canonical;
3936   if (!isCanonicalResultType(ResultTy)) {
3937     Canonical =
3938       getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3939
3940     // Get the new insert position for the node we care about.
3941     FunctionNoProtoType *NewIP =
3942       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3943     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3944   }
3945
3946   auto *New = new (*this, TypeAlignment)
3947     FunctionNoProtoType(ResultTy, Canonical, Info);
3948   Types.push_back(New);
3949   FunctionNoProtoTypes.InsertNode(New, InsertPos);
3950   return QualType(New, 0);
3951 }
3952
3953 CanQualType
3954 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3955   CanQualType CanResultType = getCanonicalType(ResultType);
3956
3957   // Canonical result types do not have ARC lifetime qualifiers.
3958   if (CanResultType.getQualifiers().hasObjCLifetime()) {
3959     Qualifiers Qs = CanResultType.getQualifiers();
3960     Qs.removeObjCLifetime();
3961     return CanQualType::CreateUnsafe(
3962              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3963   }
3964
3965   return CanResultType;
3966 }
3967
3968 static bool isCanonicalExceptionSpecification(
3969     const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3970   if (ESI.Type == EST_None)
3971     return true;
3972   if (!NoexceptInType)
3973     return false;
3974
3975   // C++17 onwards: exception specification is part of the type, as a simple
3976   // boolean "can this function type throw".
3977   if (ESI.Type == EST_BasicNoexcept)
3978     return true;
3979
3980   // A noexcept(expr) specification is (possibly) canonical if expr is
3981   // value-dependent.
3982   if (ESI.Type == EST_DependentNoexcept)
3983     return true;
3984
3985   // A dynamic exception specification is canonical if it only contains pack
3986   // expansions (so we can't tell whether it's non-throwing) and all its
3987   // contained types are canonical.
3988   if (ESI.Type == EST_Dynamic) {
3989     bool AnyPackExpansions = false;
3990     for (QualType ET : ESI.Exceptions) {
3991       if (!ET.isCanonical())
3992         return false;
3993       if (ET->getAs<PackExpansionType>())
3994         AnyPackExpansions = true;
3995     }
3996     return AnyPackExpansions;
3997   }
3998
3999   return false;
4000 }
4001
4002 QualType ASTContext::getFunctionTypeInternal(
4003     QualType ResultTy, ArrayRef<QualType> ArgArray,
4004     const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4005   size_t NumArgs = ArgArray.size();
4006
4007   // Unique functions, to guarantee there is only one function of a particular
4008   // structure.
4009   llvm::FoldingSetNodeID ID;
4010   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4011                              *this, true);
4012
4013   QualType Canonical;
4014   bool Unique = false;
4015
4016   void *InsertPos = nullptr;
4017   if (FunctionProtoType *FPT =
4018         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4019     QualType Existing = QualType(FPT, 0);
4020
4021     // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4022     // it so long as our exception specification doesn't contain a dependent
4023     // noexcept expression, or we're just looking for a canonical type.
4024     // Otherwise, we're going to need to create a type
4025     // sugar node to hold the concrete expression.
4026     if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4027         EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4028       return Existing;
4029
4030     // We need a new type sugar node for this one, to hold the new noexcept
4031     // expression. We do no canonicalization here, but that's OK since we don't
4032     // expect to see the same noexcept expression much more than once.
4033     Canonical = getCanonicalType(Existing);
4034     Unique = true;
4035   }
4036
4037   bool NoexceptInType = getLangOpts().CPlusPlus17;
4038   bool IsCanonicalExceptionSpec =
4039       isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4040
4041   // Determine whether the type being created is already canonical or not.
4042   bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4043                      isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4044   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4045     if (!ArgArray[i].isCanonicalAsParam())
4046       isCanonical = false;
4047
4048   if (OnlyWantCanonical)
4049     assert(isCanonical &&
4050            "given non-canonical parameters constructing canonical type");
4051
4052   // If this type isn't canonical, get the canonical version of it if we don't
4053   // already have it. The exception spec is only partially part of the
4054   // canonical type, and only in C++17 onwards.
4055   if (!isCanonical && Canonical.isNull()) {
4056     SmallVector<QualType, 16> CanonicalArgs;
4057     CanonicalArgs.reserve(NumArgs);
4058     for (unsigned i = 0; i != NumArgs; ++i)
4059       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4060
4061     llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4062     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4063     CanonicalEPI.HasTrailingReturn = false;
4064
4065     if (IsCanonicalExceptionSpec) {
4066       // Exception spec is already OK.
4067     } else if (NoexceptInType) {
4068       switch (EPI.ExceptionSpec.Type) {
4069       case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4070         // We don't know yet. It shouldn't matter what we pick here; no-one
4071         // should ever look at this.
4072         LLVM_FALLTHROUGH;
4073       case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4074         CanonicalEPI.ExceptionSpec.Type = EST_None;
4075         break;
4076
4077         // A dynamic exception specification is almost always "not noexcept",
4078         // with the exception that a pack expansion might expand to no types.
4079       case EST_Dynamic: {
4080         bool AnyPacks = false;
4081         for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4082           if (ET->getAs<PackExpansionType>())
4083             AnyPacks = true;
4084           ExceptionTypeStorage.push_back(getCanonicalType(ET));
4085         }
4086         if (!AnyPacks)
4087           CanonicalEPI.ExceptionSpec.Type = EST_None;
4088         else {
4089           CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4090           CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4091         }
4092         break;
4093       }
4094
4095       case EST_DynamicNone:
4096       case EST_BasicNoexcept:
4097       case EST_NoexceptTrue:
4098       case EST_NoThrow:
4099         CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4100         break;
4101
4102       case EST_DependentNoexcept:
4103         llvm_unreachable("dependent noexcept is already canonical");
4104       }
4105     } else {
4106       CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4107     }
4108
4109     // Adjust the canonical function result type.
4110     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4111     Canonical =
4112         getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4113
4114     // Get the new insert position for the node we care about.
4115     FunctionProtoType *NewIP =
4116       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4117     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4118   }
4119
4120   // Compute the needed size to hold this FunctionProtoType and the
4121   // various trailing objects.
4122   auto ESH = FunctionProtoType::getExceptionSpecSize(
4123       EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4124   size_t Size = FunctionProtoType::totalSizeToAlloc<
4125       QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4126       FunctionType::ExceptionType, Expr *, FunctionDecl *,
4127       FunctionProtoType::ExtParameterInfo, Qualifiers>(
4128       NumArgs, EPI.Variadic,
4129       FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4130       ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4131       EPI.ExtParameterInfos ? NumArgs : 0,
4132       EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4133
4134   auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4135   FunctionProtoType::ExtProtoInfo newEPI = EPI;
4136   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4137   Types.push_back(FTP);
4138   if (!Unique)
4139     FunctionProtoTypes.InsertNode(FTP, InsertPos);
4140   return QualType(FTP, 0);
4141 }
4142
4143 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4144   llvm::FoldingSetNodeID ID;
4145   PipeType::Profile(ID, T, ReadOnly);
4146
4147   void *InsertPos = nullptr;
4148   if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4149     return QualType(PT, 0);
4150
4151   // If the pipe element type isn't canonical, this won't be a canonical type
4152   // either, so fill in the canonical type field.
4153   QualType Canonical;
4154   if (!T.isCanonical()) {
4155     Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4156
4157     // Get the new insert position for the node we care about.
4158     PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4159     assert(!NewIP && "Shouldn't be in the map!");
4160     (void)NewIP;
4161   }
4162   auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4163   Types.push_back(New);
4164   PipeTypes.InsertNode(New, InsertPos);
4165   return QualType(New, 0);
4166 }
4167
4168 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4169   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4170   return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4171                          : Ty;
4172 }
4173
4174 QualType ASTContext::getReadPipeType(QualType T) const {
4175   return getPipeType(T, true);
4176 }
4177
4178 QualType ASTContext::getWritePipeType(QualType T) const {
4179   return getPipeType(T, false);
4180 }
4181
4182 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4183   llvm::FoldingSetNodeID ID;
4184   ExtIntType::Profile(ID, IsUnsigned, NumBits);
4185
4186   void *InsertPos = nullptr;
4187   if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4188     return QualType(EIT, 0);
4189
4190   auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4191   ExtIntTypes.InsertNode(New, InsertPos);
4192   Types.push_back(New);
4193   return QualType(New, 0);
4194 }
4195
4196 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4197                                             Expr *NumBitsExpr) const {
4198   assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4199   llvm::FoldingSetNodeID ID;
4200   DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4201
4202   void *InsertPos = nullptr;
4203   if (DependentExtIntType *Existing =
4204           DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4205     return QualType(Existing, 0);
4206
4207   auto *New = new (*this, TypeAlignment)
4208       DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4209   DependentExtIntTypes.InsertNode(New, InsertPos);
4210
4211   Types.push_back(New);
4212   return QualType(New, 0);
4213 }
4214
4215 #ifndef NDEBUG
4216 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4217   if (!isa<CXXRecordDecl>(D)) return false;
4218   const auto *RD = cast<CXXRecordDecl>(D);
4219   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4220     return true;
4221   if (RD->getDescribedClassTemplate() &&
4222       !isa<ClassTemplateSpecializationDecl>(RD))
4223     return true;
4224   return false;
4225 }
4226 #endif
4227
4228 /// getInjectedClassNameType - Return the unique reference to the
4229 /// injected class name type for the specified templated declaration.
4230 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4231                                               QualType TST) const {
4232   assert(NeedsInjectedClassNameType(Decl));
4233   if (Decl->TypeForDecl) {
4234     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4235   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4236     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4237     Decl->TypeForDecl = PrevDecl->TypeForDecl;
4238     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4239   } else {
4240     Type *newType =
4241       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4242     Decl->TypeForDecl = newType;
4243     Types.push_back(newType);
4244   }
4245   return QualType(Decl->TypeForDecl, 0);
4246 }
4247
4248 /// getTypeDeclType - Return the unique reference to the type for the
4249 /// specified type declaration.
4250 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4251   assert(Decl && "Passed null for Decl param");
4252   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4253
4254   if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4255     return getTypedefType(Typedef);
4256
4257   assert(!isa<TemplateTypeParmDecl>(Decl) &&
4258          "Template type parameter types are always available.");
4259
4260   if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4261     assert(Record->isFirstDecl() && "struct/union has previous declaration");
4262     assert(!NeedsInjectedClassNameType(Record));
4263     return getRecordType(Record);
4264   } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4265     assert(Enum->isFirstDecl() && "enum has previous declaration");
4266     return getEnumType(Enum);
4267   } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4268     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4269     Decl->TypeForDecl = newType;
4270     Types.push_back(newType);
4271   } else
4272     llvm_unreachable("TypeDecl without a type?");
4273
4274   return QualType(Decl->TypeForDecl, 0);
4275 }
4276
4277 /// getTypedefType - Return the unique reference to the type for the
4278 /// specified typedef name decl.
4279 QualType
4280 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4281                            QualType Canonical) const {
4282   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4283
4284   if (Canonical.isNull())
4285     Canonical = getCanonicalType(Decl->getUnderlyingType());
4286   auto *newType = new (*this, TypeAlignment)
4287     TypedefType(Type::Typedef, Decl, Canonical);
4288   Decl->TypeForDecl = newType;
4289   Types.push_back(newType);
4290   return QualType(newType, 0);
4291 }
4292
4293 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4294   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4295
4296   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4297     if (PrevDecl->TypeForDecl)
4298       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4299
4300   auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4301   Decl->TypeForDecl = newType;
4302   Types.push_back(newType);
4303   return QualType(newType, 0);
4304 }
4305
4306 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4307   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4308
4309   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4310     if (PrevDecl->TypeForDecl)
4311       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4312
4313   auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4314   Decl->TypeForDecl = newType;
4315   Types.push_back(newType);
4316   return QualType(newType, 0);
4317 }
4318
4319 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4320                                        QualType modifiedType,
4321                                        QualType equivalentType) {
4322   llvm::FoldingSetNodeID id;
4323   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4324
4325   void *insertPos = nullptr;
4326   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4327   if (type) return QualType(type, 0);
4328
4329   QualType canon = getCanonicalType(equivalentType);
4330   type = new (*this, TypeAlignment)
4331       AttributedType(canon, attrKind, modifiedType, equivalentType);
4332
4333   Types.push_back(type);
4334   AttributedTypes.InsertNode(type, insertPos);
4335
4336   return QualType(type, 0);
4337 }
4338
4339 /// Retrieve a substitution-result type.
4340 QualType
4341 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4342                                          QualType Replacement) const {
4343   assert(Replacement.isCanonical()
4344          && "replacement types must always be canonical");
4345
4346   llvm::FoldingSetNodeID ID;
4347   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4348   void *InsertPos = nullptr;
4349   SubstTemplateTypeParmType *SubstParm
4350     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4351
4352   if (!SubstParm) {
4353     SubstParm = new (*this, TypeAlignment)
4354       SubstTemplateTypeParmType(Parm, Replacement);
4355     Types.push_back(SubstParm);
4356     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4357   }
4358
4359   return QualType(SubstParm, 0);
4360 }
4361
4362 /// Retrieve a
4363 QualType ASTContext::getSubstTemplateTypeParmPackType(
4364                                           const TemplateTypeParmType *Parm,
4365                                               const TemplateArgument &ArgPack) {
4366 #ifndef NDEBUG
4367   for (const auto &P : ArgPack.pack_elements()) {
4368     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4369     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4370   }
4371 #endif
4372
4373   llvm::FoldingSetNodeID ID;
4374   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4375   void *InsertPos = nullptr;
4376   if (SubstTemplateTypeParmPackType *SubstParm
4377         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4378     return QualType(SubstParm, 0);
4379
4380   QualType Canon;
4381   if (!Parm->isCanonicalUnqualified()) {
4382     Canon = getCanonicalType(QualType(Parm, 0));
4383     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4384                                              ArgPack);
4385     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4386   }
4387
4388   auto *SubstParm
4389     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4390                                                                ArgPack);
4391   Types.push_back(SubstParm);
4392   SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4393   return QualType(SubstParm, 0);
4394 }
4395
4396 /// Retrieve the template type parameter type for a template
4397 /// parameter or parameter pack with the given depth, index, and (optionally)
4398 /// name.
4399 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4400                                              bool ParameterPack,
4401                                              TemplateTypeParmDecl *TTPDecl) const {
4402   llvm::FoldingSetNodeID ID;
4403   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4404   void *InsertPos = nullptr;
4405   TemplateTypeParmType *TypeParm
4406     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4407
4408   if (TypeParm)
4409     return QualType(TypeParm, 0);
4410
4411   if (TTPDecl) {
4412     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4413     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4414
4415     TemplateTypeParmType *TypeCheck
4416       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4417     assert(!TypeCheck && "Template type parameter canonical type broken");
4418     (void)TypeCheck;
4419   } else
4420     TypeParm = new (*this, TypeAlignment)
4421       TemplateTypeParmType(Depth, Index, ParameterPack);
4422
4423   Types.push_back(TypeParm);
4424   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4425
4426   return QualType(TypeParm, 0);
4427 }
4428
4429 TypeSourceInfo *
4430 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4431                                               SourceLocation NameLoc,
4432                                         const TemplateArgumentListInfo &Args,
4433                                               QualType Underlying) const {
4434   assert(!Name.getAsDependentTemplateName() &&
4435          "No dependent template names here!");
4436   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4437
4438   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4439   TemplateSpecializationTypeLoc TL =
4440       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4441   TL.setTemplateKeywordLoc(SourceLocation());
4442   TL.setTemplateNameLoc(NameLoc);
4443   TL.setLAngleLoc(Args.getLAngleLoc());
4444   TL.setRAngleLoc(Args.getRAngleLoc());
4445   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4446     TL.setArgLocInfo(i, Args[i].getLocInfo());
4447   return DI;
4448 }
4449
4450 QualType
4451 ASTContext::getTemplateSpecializationType(TemplateName Template,
4452                                           const TemplateArgumentListInfo &Args,
4453                                           QualType Underlying) const {
4454   assert(!Template.getAsDependentTemplateName() &&
4455          "No dependent template names here!");
4456
4457   SmallVector<TemplateArgument, 4> ArgVec;
4458   ArgVec.reserve(Args.size());
4459   for (const TemplateArgumentLoc &Arg : Args.arguments())
4460     ArgVec.push_back(Arg.getArgument());
4461
4462   return getTemplateSpecializationType(Template, ArgVec, Underlying);
4463 }
4464
4465 #ifndef NDEBUG
4466 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4467   for (const TemplateArgument &Arg : Args)
4468     if (Arg.isPackExpansion())
4469       return true;
4470
4471   return true;
4472 }
4473 #endif
4474
4475 QualType
4476 ASTContext::getTemplateSpecializationType(TemplateName Template,
4477                                           ArrayRef<TemplateArgument> Args,
4478                                           QualType Underlying) const {
4479   assert(!Template.getAsDependentTemplateName() &&
4480          "No dependent template names here!");
4481   // Look through qualified template names.
4482   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4483     Template = TemplateName(QTN->getTemplateDecl());
4484
4485   bool IsTypeAlias =
4486     Template.getAsTemplateDecl() &&
4487     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4488   QualType CanonType;
4489   if (!Underlying.isNull())
4490     CanonType = getCanonicalType(Underlying);
4491   else {
4492     // We can get here with an alias template when the specialization contains
4493     // a pack expansion that does not match up with a parameter pack.
4494     assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4495            "Caller must compute aliased type");
4496     IsTypeAlias = false;
4497     CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4498   }
4499
4500   // Allocate the (non-canonical) template specialization type, but don't
4501   // try to unique it: these types typically have location information that
4502   // we don't unique and don't want to lose.
4503   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4504                        sizeof(TemplateArgument) * Args.size() +
4505                        (IsTypeAlias? sizeof(QualType) : 0),
4506                        TypeAlignment);
4507   auto *Spec
4508     = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4509                                          IsTypeAlias ? Underlying : QualType());
4510
4511   Types.push_back(Spec);
4512   return QualType(Spec, 0);
4513 }
4514
4515 QualType ASTContext::getCanonicalTemplateSpecializationType(
4516     TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4517   assert(!Template.getAsDependentTemplateName() &&
4518          "No dependent template names here!");
4519
4520   // Look through qualified template names.
4521   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4522     Template = TemplateName(QTN->getTemplateDecl());
4523
4524   // Build the canonical template specialization type.
4525   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4526   SmallVector<TemplateArgument, 4> CanonArgs;
4527   unsigned NumArgs = Args.size();
4528   CanonArgs.reserve(NumArgs);
4529   for (const TemplateArgument &Arg : Args)
4530     CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4531
4532   // Determine whether this canonical template specialization type already
4533   // exists.
4534   llvm::FoldingSetNodeID ID;
4535   TemplateSpecializationType::Profile(ID, CanonTemplate,
4536                                       CanonArgs, *this);
4537
4538   void *InsertPos = nullptr;
4539   TemplateSpecializationType *Spec
4540     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4541
4542   if (!Spec) {
4543     // Allocate a new canonical template specialization type.
4544     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4545                           sizeof(TemplateArgument) * NumArgs),
4546                          TypeAlignment);
4547     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4548                                                 CanonArgs,
4549                                                 QualType(), QualType());
4550     Types.push_back(Spec);
4551     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4552   }
4553
4554   assert(Spec->isDependentType() &&
4555          "Non-dependent template-id type must have a canonical type");
4556   return QualType(Spec, 0);
4557 }
4558
4559 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4560                                        NestedNameSpecifier *NNS,
4561                                        QualType NamedType,
4562                                        TagDecl *OwnedTagDecl) const {
4563   llvm::FoldingSetNodeID ID;
4564   ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4565
4566   void *InsertPos = nullptr;
4567   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4568   if (T)
4569     return QualType(T, 0);
4570
4571   QualType Canon = NamedType;
4572   if (!Canon.isCanonical()) {
4573     Canon = getCanonicalType(NamedType);
4574     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4575     assert(!CheckT && "Elaborated canonical type broken");
4576     (void)CheckT;
4577   }
4578
4579   void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4580                        TypeAlignment);
4581   T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4582
4583   Types.push_back(T);
4584   ElaboratedTypes.InsertNode(T, InsertPos);
4585   return QualType(T, 0);
4586 }
4587
4588 QualType
4589 ASTContext::getParenType(QualType InnerType) const {
4590   llvm::FoldingSetNodeID ID;
4591   ParenType::Profile(ID, InnerType);
4592
4593   void *InsertPos = nullptr;
4594   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4595   if (T)
4596     return QualType(T, 0);
4597
4598   QualType Canon = InnerType;
4599   if (!Canon.isCanonical()) {
4600     Canon = getCanonicalType(InnerType);
4601     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4602     assert(!CheckT && "Paren canonical type broken");
4603     (void)CheckT;
4604   }
4605
4606   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4607   Types.push_back(T);
4608   ParenTypes.InsertNode(T, InsertPos);
4609   return QualType(T, 0);
4610 }
4611
4612 QualType
4613 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4614                                   const IdentifierInfo *MacroII) const {
4615   QualType Canon = UnderlyingTy;
4616   if (!Canon.isCanonical())
4617     Canon = getCanonicalType(UnderlyingTy);
4618
4619   auto *newType = new (*this, TypeAlignment)
4620       MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4621   Types.push_back(newType);
4622   return QualType(newType, 0);
4623 }
4624
4625 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4626                                           NestedNameSpecifier *NNS,
4627                                           const IdentifierInfo *Name,
4628                                           QualType Canon) const {
4629   if (Canon.isNull()) {
4630     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4631     if (CanonNNS != NNS)
4632       Canon = getDependentNameType(Keyword, CanonNNS, Name);
4633   }
4634
4635   llvm::FoldingSetNodeID ID;
4636   DependentNameType::Profile(ID, Keyword, NNS, Name);
4637
4638   void *InsertPos = nullptr;
4639   DependentNameType *T
4640     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4641   if (T)
4642     return QualType(T, 0);
4643
4644   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4645   Types.push_back(T);
4646   DependentNameTypes.InsertNode(T, InsertPos);
4647   return QualType(T, 0);
4648 }
4649
4650 QualType
4651 ASTContext::getDependentTemplateSpecializationType(
4652                                  ElaboratedTypeKeyword Keyword,
4653                                  NestedNameSpecifier *NNS,
4654                                  const IdentifierInfo *Name,
4655                                  const TemplateArgumentListInfo &Args) const {
4656   // TODO: avoid this copy
4657   SmallVector<TemplateArgument, 16> ArgCopy;
4658   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4659     ArgCopy.push_back(Args[I].getArgument());
4660   return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4661 }
4662
4663 QualType
4664 ASTContext::getDependentTemplateSpecializationType(
4665                                  ElaboratedTypeKeyword Keyword,
4666                                  NestedNameSpecifier *NNS,
4667                                  const IdentifierInfo *Name,
4668                                  ArrayRef<TemplateArgument> Args) const {
4669   assert((!NNS || NNS->isDependent()) &&
4670          "nested-name-specifier must be dependent");
4671
4672   llvm::FoldingSetNodeID ID;
4673   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4674                                                Name, Args);
4675
4676   void *InsertPos = nullptr;
4677   DependentTemplateSpecializationType *T
4678     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4679   if (T)
4680     return QualType(T, 0);
4681
4682   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4683
4684   ElaboratedTypeKeyword CanonKeyword = Keyword;
4685   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4686
4687   bool AnyNonCanonArgs = false;
4688   unsigned NumArgs = Args.size();
4689   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4690   for (unsigned I = 0; I != NumArgs; ++I) {
4691     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4692     if (!CanonArgs[I].structurallyEquals(Args[I]))
4693       AnyNonCanonArgs = true;
4694   }
4695
4696   QualType Canon;
4697   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4698     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4699                                                    Name,
4700                                                    CanonArgs);
4701
4702     // Find the insert position again.
4703     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4704   }
4705
4706   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4707                         sizeof(TemplateArgument) * NumArgs),
4708                        TypeAlignment);
4709   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4710                                                     Name, Args, Canon);
4711   Types.push_back(T);
4712   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4713   return QualType(T, 0);
4714 }
4715
4716 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4717   TemplateArgument Arg;
4718   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4719     QualType ArgType = getTypeDeclType(TTP);
4720     if (TTP->isParameterPack())
4721       ArgType = getPackExpansionType(ArgType, None);
4722
4723     Arg = TemplateArgument(ArgType);
4724   } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4725     Expr *E = new (*this) DeclRefExpr(
4726         *this, NTTP, /*enclosing*/ false,
4727         NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this),
4728         Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4729
4730     if (NTTP->isParameterPack())
4731       E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4732                                         None);
4733     Arg = TemplateArgument(E);
4734   } else {
4735     auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4736     if (TTP->isParameterPack())
4737       Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4738     else
4739       Arg = TemplateArgument(TemplateName(TTP));
4740   }
4741
4742   if (Param->isTemplateParameterPack())
4743     Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4744
4745   return Arg;
4746 }
4747
4748 void
4749 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4750                                     SmallVectorImpl<TemplateArgument> &Args) {
4751   Args.reserve(Args.size() + Params->size());
4752
4753   for (NamedDecl *Param : *Params)
4754     Args.push_back(getInjectedTemplateArg(Param));
4755 }
4756
4757 QualType ASTContext::getPackExpansionType(QualType Pattern,
4758                                           Optional<unsigned> NumExpansions) {
4759   llvm::FoldingSetNodeID ID;
4760   PackExpansionType::Profile(ID, Pattern, NumExpansions);
4761
4762   // A deduced type can deduce to a pack, eg
4763   //   auto ...x = some_pack;
4764   // That declaration isn't (yet) valid, but is created as part of building an
4765   // init-capture pack:
4766   //   [...x = some_pack] {}
4767   assert((Pattern->containsUnexpandedParameterPack() ||
4768           Pattern->getContainedDeducedType()) &&
4769          "Pack expansions must expand one or more parameter packs");
4770   void *InsertPos = nullptr;
4771   PackExpansionType *T
4772     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4773   if (T)
4774     return QualType(T, 0);
4775
4776   QualType Canon;
4777   if (!Pattern.isCanonical()) {
4778     Canon = getCanonicalType(Pattern);
4779     // The canonical type might not contain an unexpanded parameter pack, if it
4780     // contains an alias template specialization which ignores one of its
4781     // parameters.
4782     if (Canon->containsUnexpandedParameterPack()) {
4783       Canon = getPackExpansionType(Canon, NumExpansions);
4784
4785       // Find the insert position again, in case we inserted an element into
4786       // PackExpansionTypes and invalidated our insert position.
4787       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4788     }
4789   }
4790
4791   T = new (*this, TypeAlignment)
4792       PackExpansionType(Pattern, Canon, NumExpansions);
4793   Types.push_back(T);
4794   PackExpansionTypes.InsertNode(T, InsertPos);
4795   return QualType(T, 0);
4796 }
4797
4798 /// CmpProtocolNames - Comparison predicate for sorting protocols
4799 /// alphabetically.
4800 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4801                             ObjCProtocolDecl *const *RHS) {
4802   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4803 }
4804
4805 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4806   if (Protocols.empty()) return true;
4807
4808   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4809     return false;
4810
4811   for (unsigned i = 1; i != Protocols.size(); ++i)
4812     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4813         Protocols[i]->getCanonicalDecl() != Protocols[i])
4814       return false;
4815   return true;
4816 }
4817
4818 static void
4819 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4820   // Sort protocols, keyed by name.
4821   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4822
4823   // Canonicalize.
4824   for (ObjCProtocolDecl *&P : Protocols)
4825     P = P->getCanonicalDecl();
4826
4827   // Remove duplicates.
4828   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4829   Protocols.erase(ProtocolsEnd, Protocols.end());
4830 }
4831
4832 QualType ASTContext::getObjCObjectType(QualType BaseType,
4833                                        ObjCProtocolDecl * const *Protocols,
4834                                        unsigned NumProtocols) const {
4835   return getObjCObjectType(BaseType, {},
4836                            llvm::makeArrayRef(Protocols, NumProtocols),
4837                            /*isKindOf=*/false);
4838 }
4839
4840 QualType ASTContext::getObjCObjectType(
4841            QualType baseType,
4842            ArrayRef<QualType> typeArgs,
4843            ArrayRef<ObjCProtocolDecl *> protocols,
4844            bool isKindOf) const {
4845   // If the base type is an interface and there aren't any protocols or
4846   // type arguments to add, then the interface type will do just fine.
4847   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4848       isa<ObjCInterfaceType>(baseType))
4849     return baseType;
4850
4851   // Look in the folding set for an existing type.
4852   llvm::FoldingSetNodeID ID;
4853   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4854   void *InsertPos = nullptr;
4855   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4856     return QualType(QT, 0);
4857
4858   // Determine the type arguments to be used for canonicalization,
4859   // which may be explicitly specified here or written on the base
4860   // type.
4861   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4862   if (effectiveTypeArgs.empty()) {
4863     if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4864       effectiveTypeArgs = baseObject->getTypeArgs();
4865   }
4866
4867   // Build the canonical type, which has the canonical base type and a
4868   // sorted-and-uniqued list of protocols and the type arguments
4869   // canonicalized.
4870   QualType canonical;
4871   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4872                                           effectiveTypeArgs.end(),
4873                                           [&](QualType type) {
4874                                             return type.isCanonical();
4875                                           });
4876   bool protocolsSorted = areSortedAndUniqued(protocols);
4877   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4878     // Determine the canonical type arguments.
4879     ArrayRef<QualType> canonTypeArgs;
4880     SmallVector<QualType, 4> canonTypeArgsVec;
4881     if (!typeArgsAreCanonical) {
4882       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4883       for (auto typeArg : effectiveTypeArgs)
4884         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4885       canonTypeArgs = canonTypeArgsVec;
4886     } else {
4887       canonTypeArgs = effectiveTypeArgs;
4888     }
4889
4890     ArrayRef<ObjCProtocolDecl *> canonProtocols;
4891     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4892     if (!protocolsSorted) {
4893       canonProtocolsVec.append(protocols.begin(), protocols.end());
4894       SortAndUniqueProtocols(canonProtocolsVec);
4895       canonProtocols = canonProtocolsVec;
4896     } else {
4897       canonProtocols = protocols;
4898     }
4899
4900     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4901                                   canonProtocols, isKindOf);
4902
4903     // Regenerate InsertPos.
4904     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4905   }
4906
4907   unsigned size = sizeof(ObjCObjectTypeImpl);
4908   size += typeArgs.size() * sizeof(QualType);
4909   size += protocols.size() * sizeof(ObjCProtocolDecl *);
4910   void *mem = Allocate(size, TypeAlignment);
4911   auto *T =
4912     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4913                                  isKindOf);
4914
4915   Types.push_back(T);
4916   ObjCObjectTypes.InsertNode(T, InsertPos);
4917   return QualType(T, 0);
4918 }
4919
4920 /// Apply Objective-C protocol qualifiers to the given type.
4921 /// If this is for the canonical type of a type parameter, we can apply
4922 /// protocol qualifiers on the ObjCObjectPointerType.
4923 QualType
4924 ASTContext::applyObjCProtocolQualifiers(QualType type,
4925                   ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4926                   bool allowOnPointerType) const {
4927   hasError = false;
4928
4929   if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4930     return getObjCTypeParamType(objT->getDecl(), protocols);
4931   }
4932
4933   // Apply protocol qualifiers to ObjCObjectPointerType.
4934   if (allowOnPointerType) {
4935     if (const auto *objPtr =
4936             dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4937       const ObjCObjectType *objT = objPtr->getObjectType();
4938       // Merge protocol lists and construct ObjCObjectType.
4939       SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4940       protocolsVec.append(objT->qual_begin(),
4941                           objT->qual_end());
4942       protocolsVec.append(protocols.begin(), protocols.end());
4943       ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4944       type = getObjCObjectType(
4945              objT->getBaseType(),
4946              objT->getTypeArgsAsWritten(),
4947              protocols,
4948              objT->isKindOfTypeAsWritten());
4949       return getObjCObjectPointerType(type);
4950     }
4951   }
4952
4953   // Apply protocol qualifiers to ObjCObjectType.
4954   if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4955     // FIXME: Check for protocols to which the class type is already
4956     // known to conform.
4957
4958     return getObjCObjectType(objT->getBaseType(),
4959                              objT->getTypeArgsAsWritten(),
4960                              protocols,
4961                              objT->isKindOfTypeAsWritten());
4962   }
4963
4964   // If the canonical type is ObjCObjectType, ...
4965   if (type->isObjCObjectType()) {
4966     // Silently overwrite any existing protocol qualifiers.
4967     // TODO: determine whether that's the right thing to do.
4968
4969     // FIXME: Check for protocols to which the class type is already
4970     // known to conform.
4971     return getObjCObjectType(type, {}, protocols, false);
4972   }
4973
4974   // id<protocol-list>
4975   if (type->isObjCIdType()) {
4976     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4977     type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4978                                  objPtr->isKindOfType());
4979     return getObjCObjectPointerType(type);
4980   }
4981
4982   // Class<protocol-list>
4983   if (type->isObjCClassType()) {
4984     const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4985     type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4986                                  objPtr->isKindOfType());
4987     return getObjCObjectPointerType(type);
4988   }
4989
4990   hasError = true;
4991   return type;
4992 }
4993
4994 QualType
4995 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4996                                  ArrayRef<ObjCProtocolDecl *> protocols) const {
4997   // Look in the folding set for an existing type.
4998   llvm::FoldingSetNodeID ID;
4999   ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5000   void *InsertPos = nullptr;
5001   if (ObjCTypeParamType *TypeParam =
5002       ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5003     return QualType(TypeParam, 0);
5004
5005   // We canonicalize to the underlying type.
5006   QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5007   if (!protocols.empty()) {
5008     // Apply the protocol qualifers.
5009     bool hasError;
5010     Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5011         Canonical, protocols, hasError, true /*allowOnPointerType*/));
5012     assert(!hasError && "Error when apply protocol qualifier to bound type");
5013   }
5014
5015   unsigned size = sizeof(ObjCTypeParamType);
5016   size += protocols.size() * sizeof(ObjCProtocolDecl *);
5017   void *mem = Allocate(size, TypeAlignment);
5018   auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5019
5020   Types.push_back(newType);
5021   ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5022   return QualType(newType, 0);
5023 }
5024
5025 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5026                                               ObjCTypeParamDecl *New) const {
5027   New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5028   // Update TypeForDecl after updating TypeSourceInfo.
5029   auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5030   SmallVector<ObjCProtocolDecl *, 8> protocols;
5031   protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5032   QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5033   New->setTypeForDecl(UpdatedTy.getTypePtr());
5034 }
5035
5036 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5037 /// protocol list adopt all protocols in QT's qualified-id protocol
5038 /// list.
5039 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5040                                                 ObjCInterfaceDecl *IC) {
5041   if (!QT->isObjCQualifiedIdType())
5042     return false;
5043
5044   if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5045     // If both the right and left sides have qualifiers.
5046     for (auto *Proto : OPT->quals()) {
5047       if (!IC->ClassImplementsProtocol(Proto, false))
5048         return false;
5049     }
5050     return true;
5051   }
5052   return false;
5053 }
5054
5055 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5056 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5057 /// of protocols.
5058 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5059                                                 ObjCInterfaceDecl *IDecl) {
5060   if (!QT->isObjCQualifiedIdType())
5061     return false;
5062   const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5063   if (!OPT)
5064     return false;
5065   if (!IDecl->hasDefinition())
5066     return false;
5067   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5068   CollectInheritedProtocols(IDecl, InheritedProtocols);
5069   if (InheritedProtocols.empty())
5070     return false;
5071   // Check that if every protocol in list of id<plist> conforms to a protocol
5072   // of IDecl's, then bridge casting is ok.
5073   bool Conforms = false;
5074   for (auto *Proto : OPT->quals()) {
5075     Conforms = false;
5076     for (auto *PI : InheritedProtocols) {
5077       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5078         Conforms = true;
5079         break;
5080       }
5081     }
5082     if (!Conforms)
5083       break;
5084   }
5085   if (Conforms)
5086     return true;
5087
5088   for (auto *PI : InheritedProtocols) {
5089     // If both the right and left sides have qualifiers.
5090     bool Adopts = false;
5091     for (auto *Proto : OPT->quals()) {
5092       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5093       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5094         break;
5095     }
5096     if (!Adopts)
5097       return false;
5098   }
5099   return true;
5100 }
5101
5102 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5103 /// the given object type.
5104 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5105   llvm::FoldingSetNodeID ID;
5106   ObjCObjectPointerType::Profile(ID, ObjectT);
5107
5108   void *InsertPos = nullptr;
5109   if (ObjCObjectPointerType *QT =
5110               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5111     return QualType(QT, 0);
5112
5113   // Find the canonical object type.
5114   QualType Canonical;
5115   if (!ObjectT.isCanonical()) {
5116     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5117
5118     // Regenerate InsertPos.
5119     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5120   }
5121
5122   // No match.
5123   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5124   auto *QType =
5125     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5126
5127   Types.push_back(QType);
5128   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5129   return QualType(QType, 0);
5130 }
5131
5132 /// getObjCInterfaceType - Return the unique reference to the type for the
5133 /// specified ObjC interface decl. The list of protocols is optional.
5134 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5135                                           ObjCInterfaceDecl *PrevDecl) const {
5136   if (Decl->TypeForDecl)
5137     return QualType(Decl->TypeForDecl, 0);
5138
5139   if (PrevDecl) {
5140     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5141     Decl->TypeForDecl = PrevDecl->TypeForDecl;
5142     return QualType(PrevDecl->TypeForDecl, 0);
5143   }
5144
5145   // Prefer the definition, if there is one.
5146   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5147     Decl = Def;
5148
5149   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5150   auto *T = new (Mem) ObjCInterfaceType(Decl);
5151   Decl->TypeForDecl = T;
5152   Types.push_back(T);
5153   return QualType(T, 0);
5154 }
5155
5156 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5157 /// TypeOfExprType AST's (since expression's are never shared). For example,
5158 /// multiple declarations that refer to "typeof(x)" all contain different
5159 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5160 /// on canonical type's (which are always unique).
5161 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5162   TypeOfExprType *toe;
5163   if (tofExpr->isTypeDependent()) {
5164     llvm::FoldingSetNodeID ID;
5165     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5166
5167     void *InsertPos = nullptr;
5168     DependentTypeOfExprType *Canon
5169       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5170     if (Canon) {
5171       // We already have a "canonical" version of an identical, dependent
5172       // typeof(expr) type. Use that as our canonical type.
5173       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5174                                           QualType((TypeOfExprType*)Canon, 0));
5175     } else {
5176       // Build a new, canonical typeof(expr) type.
5177       Canon
5178         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5179       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5180       toe = Canon;
5181     }
5182   } else {
5183     QualType Canonical = getCanonicalType(tofExpr->getType());
5184     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5185   }
5186   Types.push_back(toe);
5187   return QualType(toe, 0);
5188 }
5189
5190 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5191 /// TypeOfType nodes. The only motivation to unique these nodes would be
5192 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5193 /// an issue. This doesn't affect the type checker, since it operates
5194 /// on canonical types (which are always unique).
5195 QualType ASTContext::getTypeOfType(QualType tofType) const {
5196   QualType Canonical = getCanonicalType(tofType);
5197   auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5198   Types.push_back(tot);
5199   return QualType(tot, 0);
5200 }
5201
5202 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5203 /// nodes. This would never be helpful, since each such type has its own
5204 /// expression, and would not give a significant memory saving, since there
5205 /// is an Expr tree under each such type.
5206 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5207   DecltypeType *dt;
5208
5209   // C++11 [temp.type]p2:
5210   //   If an expression e involves a template parameter, decltype(e) denotes a
5211   //   unique dependent type. Two such decltype-specifiers refer to the same
5212   //   type only if their expressions are equivalent (14.5.6.1).
5213   if (e->isInstantiationDependent()) {
5214     llvm::FoldingSetNodeID ID;
5215     DependentDecltypeType::Profile(ID, *this, e);
5216
5217     void *InsertPos = nullptr;
5218     DependentDecltypeType *Canon
5219       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5220     if (!Canon) {
5221       // Build a new, canonical decltype(expr) type.
5222       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5223       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5224     }
5225     dt = new (*this, TypeAlignment)
5226         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5227   } else {
5228     dt = new (*this, TypeAlignment)
5229         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5230   }
5231   Types.push_back(dt);
5232   return QualType(dt, 0);
5233 }
5234
5235 /// getUnaryTransformationType - We don't unique these, since the memory
5236 /// savings are minimal and these are rare.
5237 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5238                                            QualType UnderlyingType,
5239                                            UnaryTransformType::UTTKind Kind)
5240     const {
5241   UnaryTransformType *ut = nullptr;
5242
5243   if (BaseType->isDependentType()) {
5244     // Look in the folding set for an existing type.
5245     llvm::FoldingSetNodeID ID;
5246     DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5247
5248     void *InsertPos = nullptr;
5249     DependentUnaryTransformType *Canon
5250       = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5251
5252     if (!Canon) {
5253       // Build a new, canonical __underlying_type(type) type.
5254       Canon = new (*this, TypeAlignment)
5255              DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5256                                          Kind);
5257       DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5258     }
5259     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5260                                                         QualType(), Kind,
5261                                                         QualType(Canon, 0));
5262   } else {
5263     QualType CanonType = getCanonicalType(UnderlyingType);
5264     ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5265                                                         UnderlyingType, Kind,
5266                                                         CanonType);
5267   }
5268   Types.push_back(ut);
5269   return QualType(ut, 0);
5270 }
5271
5272 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5273 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5274 /// canonical deduced-but-dependent 'auto' type.
5275 QualType
5276 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5277                         bool IsDependent, bool IsPack,
5278                         ConceptDecl *TypeConstraintConcept,
5279                         ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5280   assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5281   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5282       !TypeConstraintConcept && !IsDependent)
5283     return getAutoDeductType();
5284
5285   // Look in the folding set for an existing type.
5286   void *InsertPos = nullptr;
5287   llvm::FoldingSetNodeID ID;
5288   AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5289                     TypeConstraintConcept, TypeConstraintArgs);
5290   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5291     return QualType(AT, 0);
5292
5293   void *Mem = Allocate(sizeof(AutoType) +
5294                        sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5295                        TypeAlignment);
5296   auto *AT = new (Mem) AutoType(
5297       DeducedType, Keyword,
5298       (IsDependent ? TypeDependence::DependentInstantiation
5299                    : TypeDependence::None) |
5300           (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5301       TypeConstraintConcept, TypeConstraintArgs);
5302   Types.push_back(AT);
5303   if (InsertPos)
5304     AutoTypes.InsertNode(AT, InsertPos);
5305   return QualType(AT, 0);
5306 }
5307
5308 /// Return the uniqued reference to the deduced template specialization type
5309 /// which has been deduced to the given type, or to the canonical undeduced
5310 /// such type, or the canonical deduced-but-dependent such type.
5311 QualType ASTContext::getDeducedTemplateSpecializationType(
5312     TemplateName Template, QualType DeducedType, bool IsDependent) const {
5313   // Look in the folding set for an existing type.
5314   void *InsertPos = nullptr;
5315   llvm::FoldingSetNodeID ID;
5316   DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5317                                              IsDependent);
5318   if (DeducedTemplateSpecializationType *DTST =
5319           DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5320     return QualType(DTST, 0);
5321
5322   auto *DTST = new (*this, TypeAlignment)
5323       DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5324   Types.push_back(DTST);
5325   if (InsertPos)
5326     DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5327   return QualType(DTST, 0);
5328 }
5329
5330 /// getAtomicType - Return the uniqued reference to the atomic type for
5331 /// the given value type.
5332 QualType ASTContext::getAtomicType(QualType T) const {
5333   // Unique pointers, to guarantee there is only one pointer of a particular
5334   // structure.
5335   llvm::FoldingSetNodeID ID;
5336   AtomicType::Profile(ID, T);
5337
5338   void *InsertPos = nullptr;
5339   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5340     return QualType(AT, 0);
5341
5342   // If the atomic value type isn't canonical, this won't be a canonical type
5343   // either, so fill in the canonical type field.
5344   QualType Canonical;
5345   if (!T.isCanonical()) {
5346     Canonical = getAtomicType(getCanonicalType(T));
5347
5348     // Get the new insert position for the node we care about.
5349     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5350     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5351   }
5352   auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5353   Types.push_back(New);
5354   AtomicTypes.InsertNode(New, InsertPos);
5355   return QualType(New, 0);
5356 }
5357
5358 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5359 QualType ASTContext::getAutoDeductType() const {
5360   if (AutoDeductTy.isNull())
5361     AutoDeductTy = QualType(new (*this, TypeAlignment)
5362                                 AutoType(QualType(), AutoTypeKeyword::Auto,
5363                                          TypeDependence::None,
5364                                          /*concept*/ nullptr, /*args*/ {}),
5365                             0);
5366   return AutoDeductTy;
5367 }
5368
5369 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5370 QualType ASTContext::getAutoRRefDeductType() const {
5371   if (AutoRRefDeductTy.isNull())
5372     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5373   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5374   return AutoRRefDeductTy;
5375 }
5376
5377 /// getTagDeclType - Return the unique reference to the type for the
5378 /// specified TagDecl (struct/union/class/enum) decl.
5379 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5380   assert(Decl);
5381   // FIXME: What is the design on getTagDeclType when it requires casting
5382   // away const?  mutable?
5383   return getTypeDeclType(const_cast<TagDecl*>(Decl));
5384 }
5385
5386 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5387 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5388 /// needs to agree with the definition in <stddef.h>.
5389 CanQualType ASTContext::getSizeType() const {
5390   return getFromTargetType(Target->getSizeType());
5391 }
5392
5393 /// Return the unique signed counterpart of the integer type
5394 /// corresponding to size_t.
5395 CanQualType ASTContext::getSignedSizeType() const {
5396   return getFromTargetType(Target->getSignedSizeType());
5397 }
5398
5399 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5400 CanQualType ASTContext::getIntMaxType() const {
5401   return getFromTargetType(Target->getIntMaxType());
5402 }
5403
5404 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5405 CanQualType ASTContext::getUIntMaxType() const {
5406   return getFromTargetType(Target->getUIntMaxType());
5407 }
5408
5409 /// getSignedWCharType - Return the type of "signed wchar_t".
5410 /// Used when in C++, as a GCC extension.
5411 QualType ASTContext::getSignedWCharType() const {
5412   // FIXME: derive from "Target" ?
5413   return WCharTy;
5414 }
5415
5416 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5417 /// Used when in C++, as a GCC extension.
5418 QualType ASTContext::getUnsignedWCharType() const {
5419   // FIXME: derive from "Target" ?
5420   return UnsignedIntTy;
5421 }
5422
5423 QualType ASTContext::getIntPtrType() const {
5424   return getFromTargetType(Target->getIntPtrType());
5425 }
5426
5427 QualType ASTContext::getUIntPtrType() const {
5428   return getCorrespondingUnsignedType(getIntPtrType());
5429 }
5430
5431 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5432 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5433 QualType ASTContext::getPointerDiffType() const {
5434   return getFromTargetType(Target->getPtrDiffType(0));
5435 }
5436
5437 /// Return the unique unsigned counterpart of "ptrdiff_t"
5438 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5439 /// in the definition of %tu format specifier.
5440 QualType ASTContext::getUnsignedPointerDiffType() const {
5441   return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5442 }
5443
5444 /// Return the unique type for "pid_t" defined in
5445 /// <sys/types.h>. We need this to compute the correct type for vfork().
5446 QualType ASTContext::getProcessIDType() const {
5447   return getFromTargetType(Target->getProcessIDType());
5448 }
5449
5450 //===----------------------------------------------------------------------===//
5451 //                              Type Operators
5452 //===----------------------------------------------------------------------===//
5453
5454 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5455   // Push qualifiers into arrays, and then discard any remaining
5456   // qualifiers.
5457   T = getCanonicalType(T);
5458   T = getVariableArrayDecayedType(T);
5459   const Type *Ty = T.getTypePtr();
5460   QualType Result;
5461   if (isa<ArrayType>(Ty)) {
5462     Result = getArrayDecayedType(QualType(Ty,0));
5463   } else if (isa<FunctionType>(Ty)) {
5464     Result = getPointerType(QualType(Ty, 0));
5465   } else {
5466     Result = QualType(Ty, 0);
5467   }
5468
5469   return CanQualType::CreateUnsafe(Result);
5470 }
5471
5472 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5473                                              Qualifiers &quals) {
5474   SplitQualType splitType = type.getSplitUnqualifiedType();
5475
5476   // FIXME: getSplitUnqualifiedType() actually walks all the way to
5477   // the unqualified desugared type and then drops it on the floor.
5478   // We then have to strip that sugar back off with
5479   // getUnqualifiedDesugaredType(), which is silly.
5480   const auto *AT =
5481       dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5482
5483   // If we don't have an array, just use the results in splitType.
5484   if (!AT) {
5485     quals = splitType.Quals;
5486     return QualType(splitType.Ty, 0);
5487   }
5488
5489   // Otherwise, recurse on the array's element type.
5490   QualType elementType = AT->getElementType();
5491   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5492
5493   // If that didn't change the element type, AT has no qualifiers, so we
5494   // can just use the results in splitType.
5495   if (elementType == unqualElementType) {
5496     assert(quals.empty()); // from the recursive call
5497     quals = splitType.Quals;
5498     return QualType(splitType.Ty, 0);
5499   }
5500
5501   // Otherwise, add in the qualifiers from the outermost type, then
5502   // build the type back up.
5503   quals.addConsistentQualifiers(splitType.Quals);
5504
5505   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5506     return getConstantArrayType(unqualElementType, CAT->getSize(),
5507                                 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5508   }
5509
5510   if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5511     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5512   }
5513
5514   if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5515     return getVariableArrayType(unqualElementType,
5516                                 VAT->getSizeExpr(),
5517                                 VAT->getSizeModifier(),
5518                                 VAT->getIndexTypeCVRQualifiers(),
5519                                 VAT->getBracketsRange());
5520   }
5521
5522   const auto *DSAT = cast<DependentSizedArrayType>(AT);
5523   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5524                                     DSAT->getSizeModifier(), 0,
5525                                     SourceRange());
5526 }
5527
5528 /// Attempt to unwrap two types that may both be array types with the same bound
5529 /// (or both be array types of unknown bound) for the purpose of comparing the
5530 /// cv-decomposition of two types per C++ [conv.qual].
5531 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5532   bool UnwrappedAny = false;
5533   while (true) {
5534     auto *AT1 = getAsArrayType(T1);
5535     if (!AT1) return UnwrappedAny;
5536
5537     auto *AT2 = getAsArrayType(T2);
5538     if (!AT2) return UnwrappedAny;
5539
5540     // If we don't have two array types with the same constant bound nor two
5541     // incomplete array types, we've unwrapped everything we can.
5542     if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5543       auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5544       if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5545         return UnwrappedAny;
5546     } else if (!isa<IncompleteArrayType>(AT1) ||
5547                !isa<IncompleteArrayType>(AT2)) {
5548       return UnwrappedAny;
5549     }
5550
5551     T1 = AT1->getElementType();
5552     T2 = AT2->getElementType();
5553     UnwrappedAny = true;
5554   }
5555 }
5556
5557 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5558 ///
5559 /// If T1 and T2 are both pointer types of the same kind, or both array types
5560 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5561 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5562 ///
5563 /// This function will typically be called in a loop that successively
5564 /// "unwraps" pointer and pointer-to-member types to compare them at each
5565 /// level.
5566 ///
5567 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5568 /// pair of types that can't be unwrapped further.
5569 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5570   UnwrapSimilarArrayTypes(T1, T2);
5571
5572   const auto *T1PtrType = T1->getAs<PointerType>();
5573   const auto *T2PtrType = T2->getAs<PointerType>();
5574   if (T1PtrType && T2PtrType) {
5575     T1 = T1PtrType->getPointeeType();
5576     T2 = T2PtrType->getPointeeType();
5577     return true;
5578   }
5579
5580   const auto *T1MPType = T1->getAs<MemberPointerType>();
5581   const auto *T2MPType = T2->getAs<MemberPointerType>();
5582   if (T1MPType && T2MPType &&
5583       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5584                              QualType(T2MPType->getClass(), 0))) {
5585     T1 = T1MPType->getPointeeType();
5586     T2 = T2MPType->getPointeeType();
5587     return true;
5588   }
5589
5590   if (getLangOpts().ObjC) {
5591     const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5592     const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5593     if (T1OPType && T2OPType) {
5594       T1 = T1OPType->getPointeeType();
5595       T2 = T2OPType->getPointeeType();
5596       return true;
5597     }
5598   }
5599
5600   // FIXME: Block pointers, too?
5601
5602   return false;
5603 }
5604
5605 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5606   while (true) {
5607     Qualifiers Quals;
5608     T1 = getUnqualifiedArrayType(T1, Quals);
5609     T2 = getUnqualifiedArrayType(T2, Quals);
5610     if (hasSameType(T1, T2))
5611       return true;
5612     if (!UnwrapSimilarTypes(T1, T2))
5613       return false;
5614   }
5615 }
5616
5617 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5618   while (true) {
5619     Qualifiers Quals1, Quals2;
5620     T1 = getUnqualifiedArrayType(T1, Quals1);
5621     T2 = getUnqualifiedArrayType(T2, Quals2);
5622
5623     Quals1.removeCVRQualifiers();
5624     Quals2.removeCVRQualifiers();
5625     if (Quals1 != Quals2)
5626       return false;
5627
5628     if (hasSameType(T1, T2))
5629       return true;
5630
5631     if (!UnwrapSimilarTypes(T1, T2))
5632       return false;
5633   }
5634 }
5635
5636 DeclarationNameInfo
5637 ASTContext::getNameForTemplate(TemplateName Name,
5638                                SourceLocation NameLoc) const {
5639   switch (Name.getKind()) {
5640   case TemplateName::QualifiedTemplate:
5641   case TemplateName::Template:
5642     // DNInfo work in progress: CHECKME: what about DNLoc?
5643     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5644                                NameLoc);
5645
5646   case TemplateName::OverloadedTemplate: {
5647     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5648     // DNInfo work in progress: CHECKME: what about DNLoc?
5649     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5650   }
5651
5652   case TemplateName::AssumedTemplate: {
5653     AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5654     return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5655   }
5656
5657   case TemplateName::DependentTemplate: {
5658     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5659     DeclarationName DName;
5660     if (DTN->isIdentifier()) {
5661       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5662       return DeclarationNameInfo(DName, NameLoc);
5663     } else {
5664       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5665       // DNInfo work in progress: FIXME: source locations?
5666       DeclarationNameLoc DNLoc;
5667       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5668       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5669       return DeclarationNameInfo(DName, NameLoc, DNLoc);
5670     }
5671   }
5672
5673   case TemplateName::SubstTemplateTemplateParm: {
5674     SubstTemplateTemplateParmStorage *subst
5675       = Name.getAsSubstTemplateTemplateParm();
5676     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5677                                NameLoc);
5678   }
5679
5680   case TemplateName::SubstTemplateTemplateParmPack: {
5681     SubstTemplateTemplateParmPackStorage *subst
5682       = Name.getAsSubstTemplateTemplateParmPack();
5683     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5684                                NameLoc);
5685   }
5686   }
5687
5688   llvm_unreachable("bad template name kind!");
5689 }
5690
5691 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5692   switch (Name.getKind()) {
5693   case TemplateName::QualifiedTemplate:
5694   case TemplateName::Template: {
5695     TemplateDecl *Template = Name.getAsTemplateDecl();
5696     if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
5697       Template = getCanonicalTemplateTemplateParmDecl(TTP);
5698
5699     // The canonical template name is the canonical template declaration.
5700     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5701   }
5702
5703   case TemplateName::OverloadedTemplate:
5704   case TemplateName::AssumedTemplate:
5705     llvm_unreachable("cannot canonicalize unresolved template");
5706
5707   case TemplateName::DependentTemplate: {
5708     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5709     assert(DTN && "Non-dependent template names must refer to template decls.");
5710     return DTN->CanonicalTemplateName;
5711   }
5712
5713   case TemplateName::SubstTemplateTemplateParm: {
5714     SubstTemplateTemplateParmStorage *subst
5715       = Name.getAsSubstTemplateTemplateParm();
5716     return getCanonicalTemplateName(subst->getReplacement());
5717   }
5718
5719   case TemplateName::SubstTemplateTemplateParmPack: {
5720     SubstTemplateTemplateParmPackStorage *subst
5721                                   = Name.getAsSubstTemplateTemplateParmPack();
5722     TemplateTemplateParmDecl *canonParameter
5723       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5724     TemplateArgument canonArgPack
5725       = getCanonicalTemplateArgument(subst->getArgumentPack());
5726     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5727   }
5728   }
5729
5730   llvm_unreachable("bad template name!");
5731 }
5732
5733 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5734   X = getCanonicalTemplateName(X);
5735   Y = getCanonicalTemplateName(Y);
5736   return X.getAsVoidPointer() == Y.getAsVoidPointer();
5737 }
5738
5739 TemplateArgument
5740 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5741   switch (Arg.getKind()) {
5742     case TemplateArgument::Null:
5743       return Arg;
5744
5745     case TemplateArgument::Expression:
5746       return Arg;
5747
5748     case TemplateArgument::Declaration: {
5749       auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5750       return TemplateArgument(D, Arg.getParamTypeForDecl());
5751     }
5752
5753     case TemplateArgument::NullPtr:
5754       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5755                               /*isNullPtr*/true);
5756
5757     case TemplateArgument::Template:
5758       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5759
5760     case TemplateArgument::TemplateExpansion:
5761       return TemplateArgument(getCanonicalTemplateName(
5762                                          Arg.getAsTemplateOrTemplatePattern()),
5763                               Arg.getNumTemplateExpansions());
5764
5765     case TemplateArgument::Integral:
5766       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5767
5768     case TemplateArgument::Type:
5769       return TemplateArgument(getCanonicalType(Arg.getAsType()));
5770
5771     case TemplateArgument::Pack: {
5772       if (Arg.pack_size() == 0)
5773         return Arg;
5774
5775       auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5776       unsigned Idx = 0;
5777       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5778                                         AEnd = Arg.pack_end();
5779            A != AEnd; (void)++A, ++Idx)
5780         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5781
5782       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5783     }
5784   }
5785
5786   // Silence GCC warning
5787   llvm_unreachable("Unhandled template argument kind");
5788 }
5789
5790 NestedNameSpecifier *
5791 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5792   if (!NNS)
5793     return nullptr;
5794
5795   switch (NNS->getKind()) {
5796   case NestedNameSpecifier::Identifier:
5797     // Canonicalize the prefix but keep the identifier the same.
5798     return NestedNameSpecifier::Create(*this,
5799                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5800                                        NNS->getAsIdentifier());
5801
5802   case NestedNameSpecifier::Namespace:
5803     // A namespace is canonical; build a nested-name-specifier with
5804     // this namespace and no prefix.
5805     return NestedNameSpecifier::Create(*this, nullptr,
5806                                  NNS->getAsNamespace()->getOriginalNamespace());
5807
5808   case NestedNameSpecifier::NamespaceAlias:
5809     // A namespace is canonical; build a nested-name-specifier with
5810     // this namespace and no prefix.
5811     return NestedNameSpecifier::Create(*this, nullptr,
5812                                     NNS->getAsNamespaceAlias()->getNamespace()
5813                                                       ->getOriginalNamespace());
5814
5815   case NestedNameSpecifier::TypeSpec:
5816   case NestedNameSpecifier::TypeSpecWithTemplate: {
5817     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5818
5819     // If we have some kind of dependent-named type (e.g., "typename T::type"),
5820     // break it apart into its prefix and identifier, then reconsititute those
5821     // as the canonical nested-name-specifier. This is required to canonicalize
5822     // a dependent nested-name-specifier involving typedefs of dependent-name
5823     // types, e.g.,
5824     //   typedef typename T::type T1;
5825     //   typedef typename T1::type T2;
5826     if (const auto *DNT = T->getAs<DependentNameType>())
5827       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5828                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5829
5830     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5831     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5832     // first place?
5833     return NestedNameSpecifier::Create(*this, nullptr, false,
5834                                        const_cast<Type *>(T.getTypePtr()));
5835   }
5836
5837   case NestedNameSpecifier::Global:
5838   case NestedNameSpecifier::Super:
5839     // The global specifier and __super specifer are canonical and unique.
5840     return NNS;
5841   }
5842
5843   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5844 }
5845
5846 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5847   // Handle the non-qualified case efficiently.
5848   if (!T.hasLocalQualifiers()) {
5849     // Handle the common positive case fast.
5850     if (const auto *AT = dyn_cast<ArrayType>(T))
5851       return AT;
5852   }
5853
5854   // Handle the common negative case fast.
5855   if (!isa<ArrayType>(T.getCanonicalType()))
5856     return nullptr;
5857
5858   // Apply any qualifiers from the array type to the element type.  This
5859   // implements C99 6.7.3p8: "If the specification of an array type includes
5860   // any type qualifiers, the element type is so qualified, not the array type."
5861
5862   // If we get here, we either have type qualifiers on the type, or we have
5863   // sugar such as a typedef in the way.  If we have type qualifiers on the type
5864   // we must propagate them down into the element type.
5865
5866   SplitQualType split = T.getSplitDesugaredType();
5867   Qualifiers qs = split.Quals;
5868
5869   // If we have a simple case, just return now.
5870   const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5871   if (!ATy || qs.empty())
5872     return ATy;
5873
5874   // Otherwise, we have an array and we have qualifiers on it.  Push the
5875   // qualifiers into the array element type and return a new array type.
5876   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5877
5878   if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5879     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5880                                                 CAT->getSizeExpr(),
5881                                                 CAT->getSizeModifier(),
5882                                            CAT->getIndexTypeCVRQualifiers()));
5883   if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5884     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5885                                                   IAT->getSizeModifier(),
5886                                            IAT->getIndexTypeCVRQualifiers()));
5887
5888   if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5889     return cast<ArrayType>(
5890                      getDependentSizedArrayType(NewEltTy,
5891                                                 DSAT->getSizeExpr(),
5892                                                 DSAT->getSizeModifier(),
5893                                               DSAT->getIndexTypeCVRQualifiers(),
5894                                                 DSAT->getBracketsRange()));
5895
5896   const auto *VAT = cast<VariableArrayType>(ATy);
5897   return cast<ArrayType>(getVariableArrayType(NewEltTy,
5898                                               VAT->getSizeExpr(),
5899                                               VAT->getSizeModifier(),
5900                                               VAT->getIndexTypeCVRQualifiers(),
5901                                               VAT->getBracketsRange()));
5902 }
5903
5904 QualType ASTContext::getAdjustedParameterType(QualType T) const {
5905   if (T->isArrayType() || T->isFunctionType())
5906     return getDecayedType(T);
5907   return T;
5908 }
5909
5910 QualType ASTContext::getSignatureParameterType(QualType T) const {
5911   T = getVariableArrayDecayedType(T);
5912   T = getAdjustedParameterType(T);
5913   return T.getUnqualifiedType();
5914 }
5915
5916 QualType ASTContext::getExceptionObjectType(QualType T) const {
5917   // C++ [except.throw]p3:
5918   //   A throw-expression initializes a temporary object, called the exception
5919   //   object, the type of which is determined by removing any top-level
5920   //   cv-qualifiers from the static type of the operand of throw and adjusting
5921   //   the type from "array of T" or "function returning T" to "pointer to T"
5922   //   or "pointer to function returning T", [...]
5923   T = getVariableArrayDecayedType(T);
5924   if (T->isArrayType() || T->isFunctionType())
5925     T = getDecayedType(T);
5926   return T.getUnqualifiedType();
5927 }
5928
5929 /// getArrayDecayedType - Return the properly qualified result of decaying the
5930 /// specified array type to a pointer.  This operation is non-trivial when
5931 /// handling typedefs etc.  The canonical type of "T" must be an array type,
5932 /// this returns a pointer to a properly qualified element of the array.
5933 ///
5934 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5935 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
5936   // Get the element type with 'getAsArrayType' so that we don't lose any
5937   // typedefs in the element type of the array.  This also handles propagation
5938   // of type qualifiers from the array type into the element type if present
5939   // (C99 6.7.3p8).
5940   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5941   assert(PrettyArrayType && "Not an array type!");
5942
5943   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5944
5945   // int x[restrict 4] ->  int *restrict
5946   QualType Result = getQualifiedType(PtrTy,
5947                                      PrettyArrayType->getIndexTypeQualifiers());
5948
5949   // int x[_Nullable] -> int * _Nullable
5950   if (auto Nullability = Ty->getNullability(*this)) {
5951     Result = const_cast<ASTContext *>(this)->getAttributedType(
5952         AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5953   }
5954   return Result;
5955 }
5956
5957 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5958   return getBaseElementType(array->getElementType());
5959 }
5960
5961 QualType ASTContext::getBaseElementType(QualType type) const {
5962   Qualifiers qs;
5963   while (true) {
5964     SplitQualType split = type.getSplitDesugaredType();
5965     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5966     if (!array) break;
5967
5968     type = array->getElementType();
5969     qs.addConsistentQualifiers(split.Quals);
5970   }
5971
5972   return getQualifiedType(type, qs);
5973 }
5974
5975 /// getConstantArrayElementCount - Returns number of constant array elements.
5976 uint64_t
5977 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
5978   uint64_t ElementCount = 1;
5979   do {
5980     ElementCount *= CA->getSize().getZExtValue();
5981     CA = dyn_cast_or_null<ConstantArrayType>(
5982       CA->getElementType()->getAsArrayTypeUnsafe());
5983   } while (CA);
5984   return ElementCount;
5985 }
5986
5987 /// getFloatingRank - Return a relative rank for floating point types.
5988 /// This routine will assert if passed a built-in type that isn't a float.
5989 static FloatingRank getFloatingRank(QualType T) {
5990   if (const auto *CT = T->getAs<ComplexType>())
5991     return getFloatingRank(CT->getElementType());
5992
5993   switch (T->castAs<BuiltinType>()->getKind()) {
5994   default: llvm_unreachable("getFloatingRank(): not a floating type");
5995   case BuiltinType::Float16:    return Float16Rank;
5996   case BuiltinType::Half:       return HalfRank;
5997   case BuiltinType::Float:      return FloatRank;
5998   case BuiltinType::Double:     return DoubleRank;
5999   case BuiltinType::LongDouble: return LongDoubleRank;
6000   case BuiltinType::Float128:   return Float128Rank;
6001   case BuiltinType::BFloat16:   return BFloat16Rank;
6002   }
6003 }
6004
6005 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6006 /// point or a complex type (based on typeDomain/typeSize).
6007 /// 'typeDomain' is a real floating point or complex type.
6008 /// 'typeSize' is a real floating point or complex type.
6009 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6010                                                        QualType Domain) const {
6011   FloatingRank EltRank = getFloatingRank(Size);
6012   if (Domain->isComplexType()) {
6013     switch (EltRank) {
6014     case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6015     case Float16Rank:
6016     case HalfRank: llvm_unreachable("Complex half is not supported");
6017     case FloatRank:      return FloatComplexTy;
6018     case DoubleRank:     return DoubleComplexTy;
6019     case LongDoubleRank: return LongDoubleComplexTy;
6020     case Float128Rank:   return Float128ComplexTy;
6021     }
6022   }
6023
6024   assert(Domain->isRealFloatingType() && "Unknown domain!");
6025   switch (EltRank) {
6026   case Float16Rank:    return HalfTy;
6027   case BFloat16Rank:   return BFloat16Ty;
6028   case HalfRank:       return HalfTy;
6029   case FloatRank:      return FloatTy;
6030   case DoubleRank:     return DoubleTy;
6031   case LongDoubleRank: return LongDoubleTy;
6032   case Float128Rank:   return Float128Ty;
6033   }
6034   llvm_unreachable("getFloatingRank(): illegal value for rank");
6035 }
6036
6037 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6038 /// point types, ignoring the domain of the type (i.e. 'double' ==
6039 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6040 /// LHS < RHS, return -1.
6041 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6042   FloatingRank LHSR = getFloatingRank(LHS);
6043   FloatingRank RHSR = getFloatingRank(RHS);
6044
6045   if (LHSR == RHSR)
6046     return 0;
6047   if (LHSR > RHSR)
6048     return 1;
6049   return -1;
6050 }
6051
6052 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6053   if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6054     return 0;
6055   return getFloatingTypeOrder(LHS, RHS);
6056 }
6057
6058 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6059 /// routine will assert if passed a built-in type that isn't an integer or enum,
6060 /// or if it is not canonicalized.
6061 unsigned ASTContext::getIntegerRank(const Type *T) const {
6062   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6063
6064   // Results in this 'losing' to any type of the same size, but winning if
6065   // larger.
6066   if (const auto *EIT = dyn_cast<ExtIntType>(T))
6067     return 0 + (EIT->getNumBits() << 3);
6068
6069   switch (cast<BuiltinType>(T)->getKind()) {
6070   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6071   case BuiltinType::Bool:
6072     return 1 + (getIntWidth(BoolTy) << 3);
6073   case BuiltinType::Char_S:
6074   case BuiltinType::Char_U:
6075   case BuiltinType::SChar:
6076   case BuiltinType::UChar:
6077     return 2 + (getIntWidth(CharTy) << 3);
6078   case BuiltinType::Short:
6079   case BuiltinType::UShort:
6080     return 3 + (getIntWidth(ShortTy) << 3);
6081   case BuiltinType::Int:
6082   case BuiltinType::UInt:
6083     return 4 + (getIntWidth(IntTy) << 3);
6084   case BuiltinType::Long:
6085   case BuiltinType::ULong:
6086     return 5 + (getIntWidth(LongTy) << 3);
6087   case BuiltinType::LongLong:
6088   case BuiltinType::ULongLong:
6089     return 6 + (getIntWidth(LongLongTy) << 3);
6090   case BuiltinType::Int128:
6091   case BuiltinType::UInt128:
6092     return 7 + (getIntWidth(Int128Ty) << 3);
6093   }
6094 }
6095
6096 /// Whether this is a promotable bitfield reference according
6097 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6098 ///
6099 /// \returns the type this bit-field will promote to, or NULL if no
6100 /// promotion occurs.
6101 QualType ASTContext::isPromotableBitField(Expr *E) const {
6102   if (E->isTypeDependent() || E->isValueDependent())
6103     return {};
6104
6105   // C++ [conv.prom]p5:
6106   //    If the bit-field has an enumerated type, it is treated as any other
6107   //    value of that type for promotion purposes.
6108   if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6109     return {};
6110
6111   // FIXME: We should not do this unless E->refersToBitField() is true. This
6112   // matters in C where getSourceBitField() will find bit-fields for various
6113   // cases where the source expression is not a bit-field designator.
6114
6115   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6116   if (!Field)
6117     return {};
6118
6119   QualType FT = Field->getType();
6120
6121   uint64_t BitWidth = Field->getBitWidthValue(*this);
6122   uint64_t IntSize = getTypeSize(IntTy);
6123   // C++ [conv.prom]p5:
6124   //   A prvalue for an integral bit-field can be converted to a prvalue of type
6125   //   int if int can represent all the values of the bit-field; otherwise, it
6126   //   can be converted to unsigned int if unsigned int can represent all the
6127   //   values of the bit-field. If the bit-field is larger yet, no integral
6128   //   promotion applies to it.
6129   // C11 6.3.1.1/2:
6130   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6131   //   If an int can represent all values of the original type (as restricted by
6132   //   the width, for a bit-field), the value is converted to an int; otherwise,
6133   //   it is converted to an unsigned int.
6134   //
6135   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6136   //        We perform that promotion here to match GCC and C++.
6137   // FIXME: C does not permit promotion of an enum bit-field whose rank is
6138   //        greater than that of 'int'. We perform that promotion to match GCC.
6139   if (BitWidth < IntSize)
6140     return IntTy;
6141
6142   if (BitWidth == IntSize)
6143     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6144
6145   // Bit-fields wider than int are not subject to promotions, and therefore act
6146   // like the base type. GCC has some weird bugs in this area that we
6147   // deliberately do not follow (GCC follows a pre-standard resolution to
6148   // C's DR315 which treats bit-width as being part of the type, and this leaks
6149   // into their semantics in some cases).
6150   return {};
6151 }
6152
6153 /// getPromotedIntegerType - Returns the type that Promotable will
6154 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6155 /// integer type.
6156 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6157   assert(!Promotable.isNull());
6158   assert(Promotable->isPromotableIntegerType());
6159   if (const auto *ET = Promotable->getAs<EnumType>())
6160     return ET->getDecl()->getPromotionType();
6161
6162   if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6163     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6164     // (3.9.1) can be converted to a prvalue of the first of the following
6165     // types that can represent all the values of its underlying type:
6166     // int, unsigned int, long int, unsigned long int, long long int, or
6167     // unsigned long long int [...]
6168     // FIXME: Is there some better way to compute this?
6169     if (BT->getKind() == BuiltinType::WChar_S ||
6170         BT->getKind() == BuiltinType::WChar_U ||
6171         BT->getKind() == BuiltinType::Char8 ||
6172         BT->getKind() == BuiltinType::Char16 ||
6173         BT->getKind() == BuiltinType::Char32) {
6174       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6175       uint64_t FromSize = getTypeSize(BT);
6176       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6177                                   LongLongTy, UnsignedLongLongTy };
6178       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6179         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6180         if (FromSize < ToSize ||
6181             (FromSize == ToSize &&
6182              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6183           return PromoteTypes[Idx];
6184       }
6185       llvm_unreachable("char type should fit into long long");
6186     }
6187   }
6188
6189   // At this point, we should have a signed or unsigned integer type.
6190   if (Promotable->isSignedIntegerType())
6191     return IntTy;
6192   uint64_t PromotableSize = getIntWidth(Promotable);
6193   uint64_t IntSize = getIntWidth(IntTy);
6194   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6195   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6196 }
6197
6198 /// Recurses in pointer/array types until it finds an objc retainable
6199 /// type and returns its ownership.
6200 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6201   while (!T.isNull()) {
6202     if (T.getObjCLifetime() != Qualifiers::OCL_None)
6203       return T.getObjCLifetime();
6204     if (T->isArrayType())
6205       T = getBaseElementType(T);
6206     else if (const auto *PT = T->getAs<PointerType>())
6207       T = PT->getPointeeType();
6208     else if (const auto *RT = T->getAs<ReferenceType>())
6209       T = RT->getPointeeType();
6210     else
6211       break;
6212   }
6213
6214   return Qualifiers::OCL_None;
6215 }
6216
6217 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6218   // Incomplete enum types are not treated as integer types.
6219   // FIXME: In C++, enum types are never integer types.
6220   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6221     return ET->getDecl()->getIntegerType().getTypePtr();
6222   return nullptr;
6223 }
6224
6225 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6226 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
6227 /// LHS < RHS, return -1.
6228 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6229   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6230   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6231
6232   // Unwrap enums to their underlying type.
6233   if (const auto *ET = dyn_cast<EnumType>(LHSC))
6234     LHSC = getIntegerTypeForEnum(ET);
6235   if (const auto *ET = dyn_cast<EnumType>(RHSC))
6236     RHSC = getIntegerTypeForEnum(ET);
6237
6238   if (LHSC == RHSC) return 0;
6239
6240   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6241   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6242
6243   unsigned LHSRank = getIntegerRank(LHSC);
6244   unsigned RHSRank = getIntegerRank(RHSC);
6245
6246   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
6247     if (LHSRank == RHSRank) return 0;
6248     return LHSRank > RHSRank ? 1 : -1;
6249   }
6250
6251   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6252   if (LHSUnsigned) {
6253     // If the unsigned [LHS] type is larger, return it.
6254     if (LHSRank >= RHSRank)
6255       return 1;
6256
6257     // If the signed type can represent all values of the unsigned type, it
6258     // wins.  Because we are dealing with 2's complement and types that are
6259     // powers of two larger than each other, this is always safe.
6260     return -1;
6261   }
6262
6263   // If the unsigned [RHS] type is larger, return it.
6264   if (RHSRank >= LHSRank)
6265     return -1;
6266
6267   // If the signed type can represent all values of the unsigned type, it
6268   // wins.  Because we are dealing with 2's complement and types that are
6269   // powers of two larger than each other, this is always safe.
6270   return 1;
6271 }
6272
6273 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6274   if (CFConstantStringTypeDecl)
6275     return CFConstantStringTypeDecl;
6276
6277   assert(!CFConstantStringTagDecl &&
6278          "tag and typedef should be initialized together");
6279   CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6280   CFConstantStringTagDecl->startDefinition();
6281
6282   struct {
6283     QualType Type;
6284     const char *Name;
6285   } Fields[5];
6286   unsigned Count = 0;
6287
6288   /// Objective-C ABI
6289   ///
6290   ///    typedef struct __NSConstantString_tag {
6291   ///      const int *isa;
6292   ///      int flags;
6293   ///      const char *str;
6294   ///      long length;
6295   ///    } __NSConstantString;
6296   ///
6297   /// Swift ABI (4.1, 4.2)
6298   ///
6299   ///    typedef struct __NSConstantString_tag {
6300   ///      uintptr_t _cfisa;
6301   ///      uintptr_t _swift_rc;
6302   ///      _Atomic(uint64_t) _cfinfoa;
6303   ///      const char *_ptr;
6304   ///      uint32_t _length;
6305   ///    } __NSConstantString;
6306   ///
6307   /// Swift ABI (5.0)
6308   ///
6309   ///    typedef struct __NSConstantString_tag {
6310   ///      uintptr_t _cfisa;
6311   ///      uintptr_t _swift_rc;
6312   ///      _Atomic(uint64_t) _cfinfoa;
6313   ///      const char *_ptr;
6314   ///      uintptr_t _length;
6315   ///    } __NSConstantString;
6316
6317   const auto CFRuntime = getLangOpts().CFRuntime;
6318   if (static_cast<unsigned>(CFRuntime) <
6319       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6320     Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6321     Fields[Count++] = { IntTy, "flags" };
6322     Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6323     Fields[Count++] = { LongTy, "length" };
6324   } else {
6325     Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6326     Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6327     Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6328     Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6329     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6330         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6331       Fields[Count++] = { IntTy, "_ptr" };
6332     else
6333       Fields[Count++] = { getUIntPtrType(), "_ptr" };
6334   }
6335
6336   // Create fields
6337   for (unsigned i = 0; i < Count; ++i) {
6338     FieldDecl *Field =
6339         FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6340                           SourceLocation(), &Idents.get(Fields[i].Name),
6341                           Fields[i].Type, /*TInfo=*/nullptr,
6342                           /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6343     Field->setAccess(AS_public);
6344     CFConstantStringTagDecl->addDecl(Field);
6345   }
6346
6347   CFConstantStringTagDecl->completeDefinition();
6348   // This type is designed to be compatible with NSConstantString, but cannot
6349   // use the same name, since NSConstantString is an interface.
6350   auto tagType = getTagDeclType(CFConstantStringTagDecl);
6351   CFConstantStringTypeDecl =
6352       buildImplicitTypedef(tagType, "__NSConstantString");
6353
6354   return CFConstantStringTypeDecl;
6355 }
6356
6357 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6358   if (!CFConstantStringTagDecl)
6359     getCFConstantStringDecl(); // Build the tag and the typedef.
6360   return CFConstantStringTagDecl;
6361 }
6362
6363 // getCFConstantStringType - Return the type used for constant CFStrings.
6364 QualType ASTContext::getCFConstantStringType() const {
6365   return getTypedefType(getCFConstantStringDecl());
6366 }
6367
6368 QualType ASTContext::getObjCSuperType() const {
6369   if (ObjCSuperType.isNull()) {
6370     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6371     TUDecl->addDecl(ObjCSuperTypeDecl);
6372     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6373   }
6374   return ObjCSuperType;
6375 }
6376
6377 void ASTContext::setCFConstantStringType(QualType T) {
6378   const auto *TD = T->castAs<TypedefType>();
6379   CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6380   const auto *TagType =
6381       CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6382   CFConstantStringTagDecl = TagType->getDecl();
6383 }
6384
6385 QualType ASTContext::getBlockDescriptorType() const {
6386   if (BlockDescriptorType)
6387     return getTagDeclType(BlockDescriptorType);
6388
6389   RecordDecl *RD;
6390   // FIXME: Needs the FlagAppleBlock bit.
6391   RD = buildImplicitRecord("__block_descriptor");
6392   RD->startDefinition();
6393
6394   QualType FieldTypes[] = {
6395     UnsignedLongTy,
6396     UnsignedLongTy,
6397   };
6398
6399   static const char *const FieldNames[] = {
6400     "reserved",
6401     "Size"
6402   };
6403
6404   for (size_t i = 0; i < 2; ++i) {
6405     FieldDecl *Field = FieldDecl::Create(
6406         *this, RD, SourceLocation(), SourceLocation(),
6407         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6408         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6409     Field->setAccess(AS_public);
6410     RD->addDecl(Field);
6411   }
6412
6413   RD->completeDefinition();
6414
6415   BlockDescriptorType = RD;
6416
6417   return getTagDeclType(BlockDescriptorType);
6418 }
6419
6420 QualType ASTContext::getBlockDescriptorExtendedType() const {
6421   if (BlockDescriptorExtendedType)
6422     return getTagDeclType(BlockDescriptorExtendedType);
6423
6424   RecordDecl *RD;
6425   // FIXME: Needs the FlagAppleBlock bit.
6426   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6427   RD->startDefinition();
6428
6429   QualType FieldTypes[] = {
6430     UnsignedLongTy,
6431     UnsignedLongTy,
6432     getPointerType(VoidPtrTy),
6433     getPointerType(VoidPtrTy)
6434   };
6435
6436   static const char *const FieldNames[] = {
6437     "reserved",
6438     "Size",
6439     "CopyFuncPtr",
6440     "DestroyFuncPtr"
6441   };
6442
6443   for (size_t i = 0; i < 4; ++i) {
6444     FieldDecl *Field = FieldDecl::Create(
6445         *this, RD, SourceLocation(), SourceLocation(),
6446         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6447         /*BitWidth=*/nullptr,
6448         /*Mutable=*/false, ICIS_NoInit);
6449     Field->setAccess(AS_public);
6450     RD->addDecl(Field);
6451   }
6452
6453   RD->completeDefinition();
6454
6455   BlockDescriptorExtendedType = RD;
6456   return getTagDeclType(BlockDescriptorExtendedType);
6457 }
6458
6459 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6460   const auto *BT = dyn_cast<BuiltinType>(T);
6461
6462   if (!BT) {
6463     if (isa<PipeType>(T))
6464       return OCLTK_Pipe;
6465
6466     return OCLTK_Default;
6467   }
6468
6469   switch (BT->getKind()) {
6470 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
6471   case BuiltinType::Id:                                                        \
6472     return OCLTK_Image;
6473 #include "clang/Basic/OpenCLImageTypes.def"
6474
6475   case BuiltinType::OCLClkEvent:
6476     return OCLTK_ClkEvent;
6477
6478   case BuiltinType::OCLEvent:
6479     return OCLTK_Event;
6480
6481   case BuiltinType::OCLQueue:
6482     return OCLTK_Queue;
6483
6484   case BuiltinType::OCLReserveID:
6485     return OCLTK_ReserveID;
6486
6487   case BuiltinType::OCLSampler:
6488     return OCLTK_Sampler;
6489
6490   default:
6491     return OCLTK_Default;
6492   }
6493 }
6494
6495 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6496   return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6497 }
6498
6499 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6500 /// requires copy/dispose. Note that this must match the logic
6501 /// in buildByrefHelpers.
6502 bool ASTContext::BlockRequiresCopying(QualType Ty,
6503                                       const VarDecl *D) {
6504   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6505     const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6506     if (!copyExpr && record->hasTrivialDestructor()) return false;
6507
6508     return true;
6509   }
6510
6511   // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6512   // move or destroy.
6513   if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6514     return true;
6515
6516   if (!Ty->isObjCRetainableType()) return false;
6517
6518   Qualifiers qs = Ty.getQualifiers();
6519
6520   // If we have lifetime, that dominates.
6521   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6522     switch (lifetime) {
6523       case Qualifiers::OCL_None: llvm_unreachable("impossible");
6524
6525       // These are just bits as far as the runtime is concerned.
6526       case Qualifiers::OCL_ExplicitNone:
6527       case Qualifiers::OCL_Autoreleasing:
6528         return false;
6529
6530       // These cases should have been taken care of when checking the type's
6531       // non-triviality.
6532       case Qualifiers::OCL_Weak:
6533       case Qualifiers::OCL_Strong:
6534         llvm_unreachable("impossible");
6535     }
6536     llvm_unreachable("fell out of lifetime switch!");
6537   }
6538   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6539           Ty->isObjCObjectPointerType());
6540 }
6541
6542 bool ASTContext::getByrefLifetime(QualType Ty,
6543                               Qualifiers::ObjCLifetime &LifeTime,
6544                               bool &HasByrefExtendedLayout) const {
6545   if (!getLangOpts().ObjC ||
6546       getLangOpts().getGC() != LangOptions::NonGC)
6547     return false;
6548
6549   HasByrefExtendedLayout = false;
6550   if (Ty->isRecordType()) {
6551     HasByrefExtendedLayout = true;
6552     LifeTime = Qualifiers::OCL_None;
6553   } else if ((LifeTime = Ty.getObjCLifetime())) {
6554     // Honor the ARC qualifiers.
6555   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6556     // The MRR rule.
6557     LifeTime = Qualifiers::OCL_ExplicitNone;
6558   } else {
6559     LifeTime = Qualifiers::OCL_None;
6560   }
6561   return true;
6562 }
6563
6564 CanQualType ASTContext::getNSUIntegerType() const {
6565   assert(Target && "Expected target to be initialized");
6566   const llvm::Triple &T = Target->getTriple();
6567   // Windows is LLP64 rather than LP64
6568   if (T.isOSWindows() && T.isArch64Bit())
6569     return UnsignedLongLongTy;
6570   return UnsignedLongTy;
6571 }
6572
6573 CanQualType ASTContext::getNSIntegerType() const {
6574   assert(Target && "Expected target to be initialized");
6575   const llvm::Triple &T = Target->getTriple();
6576   // Windows is LLP64 rather than LP64
6577   if (T.isOSWindows() && T.isArch64Bit())
6578     return LongLongTy;
6579   return LongTy;
6580 }
6581
6582 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6583   if (!ObjCInstanceTypeDecl)
6584     ObjCInstanceTypeDecl =
6585         buildImplicitTypedef(getObjCIdType(), "instancetype");
6586   return ObjCInstanceTypeDecl;
6587 }
6588
6589 // This returns true if a type has been typedefed to BOOL:
6590 // typedef <type> BOOL;
6591 static bool isTypeTypedefedAsBOOL(QualType T) {
6592   if (const auto *TT = dyn_cast<TypedefType>(T))
6593     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6594       return II->isStr("BOOL");
6595
6596   return false;
6597 }
6598
6599 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6600 /// purpose.
6601 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6602   if (!type->isIncompleteArrayType() && type->isIncompleteType())
6603     return CharUnits::Zero();
6604
6605   CharUnits sz = getTypeSizeInChars(type);
6606
6607   // Make all integer and enum types at least as large as an int
6608   if (sz.isPositive() && type->isIntegralOrEnumerationType())
6609     sz = std::max(sz, getTypeSizeInChars(IntTy));
6610   // Treat arrays as pointers, since that's how they're passed in.
6611   else if (type->isArrayType())
6612     sz = getTypeSizeInChars(VoidPtrTy);
6613   return sz;
6614 }
6615
6616 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6617   return getTargetInfo().getCXXABI().isMicrosoft() &&
6618          VD->isStaticDataMember() &&
6619          VD->getType()->isIntegralOrEnumerationType() &&
6620          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6621 }
6622
6623 ASTContext::InlineVariableDefinitionKind
6624 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6625   if (!VD->isInline())
6626     return InlineVariableDefinitionKind::None;
6627
6628   // In almost all cases, it's a weak definition.
6629   auto *First = VD->getFirstDecl();
6630   if (First->isInlineSpecified() || !First->isStaticDataMember())
6631     return InlineVariableDefinitionKind::Weak;
6632
6633   // If there's a file-context declaration in this translation unit, it's a
6634   // non-discardable definition.
6635   for (auto *D : VD->redecls())
6636     if (D->getLexicalDeclContext()->isFileContext() &&
6637         !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6638       return InlineVariableDefinitionKind::Strong;
6639
6640   // If we've not seen one yet, we don't know.
6641   return InlineVariableDefinitionKind::WeakUnknown;
6642 }
6643
6644 static std::string charUnitsToString(const CharUnits &CU) {
6645   return llvm::itostr(CU.getQuantity());
6646 }
6647
6648 /// getObjCEncodingForBlock - Return the encoded type for this block
6649 /// declaration.
6650 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6651   std::string S;
6652
6653   const BlockDecl *Decl = Expr->getBlockDecl();
6654   QualType BlockTy =
6655       Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6656   QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6657   // Encode result type.
6658   if (getLangOpts().EncodeExtendedBlockSig)
6659     getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6660                                       true /*Extended*/);
6661   else
6662     getObjCEncodingForType(BlockReturnTy, S);
6663   // Compute size of all parameters.
6664   // Start with computing size of a pointer in number of bytes.
6665   // FIXME: There might(should) be a better way of doing this computation!
6666   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6667   CharUnits ParmOffset = PtrSize;
6668   for (auto PI : Decl->parameters()) {
6669     QualType PType = PI->getType();
6670     CharUnits sz = getObjCEncodingTypeSize(PType);
6671     if (sz.isZero())
6672       continue;
6673     assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6674     ParmOffset += sz;
6675   }
6676   // Size of the argument frame
6677   S += charUnitsToString(ParmOffset);
6678   // Block pointer and offset.
6679   S += "@?0";
6680
6681   // Argument types.
6682   ParmOffset = PtrSize;
6683   for (auto PVDecl : Decl->parameters()) {
6684     QualType PType = PVDecl->getOriginalType();
6685     if (const auto *AT =
6686             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6687       // Use array's original type only if it has known number of
6688       // elements.
6689       if (!isa<ConstantArrayType>(AT))
6690         PType = PVDecl->getType();
6691     } else if (PType->isFunctionType())
6692       PType = PVDecl->getType();
6693     if (getLangOpts().EncodeExtendedBlockSig)
6694       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6695                                       S, true /*Extended*/);
6696     else
6697       getObjCEncodingForType(PType, S);
6698     S += charUnitsToString(ParmOffset);
6699     ParmOffset += getObjCEncodingTypeSize(PType);
6700   }
6701
6702   return S;
6703 }
6704
6705 std::string
6706 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6707   std::string S;
6708   // Encode result type.
6709   getObjCEncodingForType(Decl->getReturnType(), S);
6710   CharUnits ParmOffset;
6711   // Compute size of all parameters.
6712   for (auto PI : Decl->parameters()) {
6713     QualType PType = PI->getType();
6714     CharUnits sz = getObjCEncodingTypeSize(PType);
6715     if (sz.isZero())
6716       continue;
6717
6718     assert(sz.isPositive() &&
6719            "getObjCEncodingForFunctionDecl - Incomplete param type");
6720     ParmOffset += sz;
6721   }
6722   S += charUnitsToString(ParmOffset);
6723   ParmOffset = CharUnits::Zero();
6724
6725   // Argument types.
6726   for (auto PVDecl : Decl->parameters()) {
6727     QualType PType = PVDecl->getOriginalType();
6728     if (const auto *AT =
6729             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6730       // Use array's original type only if it has known number of
6731       // elements.
6732       if (!isa<ConstantArrayType>(AT))
6733         PType = PVDecl->getType();
6734     } else if (PType->isFunctionType())
6735       PType = PVDecl->getType();
6736     getObjCEncodingForType(PType, S);
6737     S += charUnitsToString(ParmOffset);
6738     ParmOffset += getObjCEncodingTypeSize(PType);
6739   }
6740
6741   return S;
6742 }
6743
6744 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6745 /// method parameter or return type. If Extended, include class names and
6746 /// block object types.
6747 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6748                                                    QualType T, std::string& S,
6749                                                    bool Extended) const {
6750   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6751   getObjCEncodingForTypeQualifier(QT, S);
6752   // Encode parameter type.
6753   ObjCEncOptions Options = ObjCEncOptions()
6754                                .setExpandPointedToStructures()
6755                                .setExpandStructures()
6756                                .setIsOutermostType();
6757   if (Extended)
6758     Options.setEncodeBlockParameters().setEncodeClassNames();
6759   getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6760 }
6761
6762 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6763 /// declaration.
6764 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6765                                                      bool Extended) const {
6766   // FIXME: This is not very efficient.
6767   // Encode return type.
6768   std::string S;
6769   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6770                                     Decl->getReturnType(), S, Extended);
6771   // Compute size of all parameters.
6772   // Start with computing size of a pointer in number of bytes.
6773   // FIXME: There might(should) be a better way of doing this computation!
6774   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6775   // The first two arguments (self and _cmd) are pointers; account for
6776   // their size.
6777   CharUnits ParmOffset = 2 * PtrSize;
6778   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6779        E = Decl->sel_param_end(); PI != E; ++PI) {
6780     QualType PType = (*PI)->getType();
6781     CharUnits sz = getObjCEncodingTypeSize(PType);
6782     if (sz.isZero())
6783       continue;
6784
6785     assert(sz.isPositive() &&
6786            "getObjCEncodingForMethodDecl - Incomplete param type");
6787     ParmOffset += sz;
6788   }
6789   S += charUnitsToString(ParmOffset);
6790   S += "@0:";
6791   S += charUnitsToString(PtrSize);
6792
6793   // Argument types.
6794   ParmOffset = 2 * PtrSize;
6795   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6796        E = Decl->sel_param_end(); PI != E; ++PI) {
6797     const ParmVarDecl *PVDecl = *PI;
6798     QualType PType = PVDecl->getOriginalType();
6799     if (const auto *AT =
6800             dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6801       // Use array's original type only if it has known number of
6802       // elements.
6803       if (!isa<ConstantArrayType>(AT))
6804         PType = PVDecl->getType();
6805     } else if (PType->isFunctionType())
6806       PType = PVDecl->getType();
6807     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6808                                       PType, S, Extended);
6809     S += charUnitsToString(ParmOffset);
6810     ParmOffset += getObjCEncodingTypeSize(PType);
6811   }
6812
6813   return S;
6814 }
6815
6816 ObjCPropertyImplDecl *
6817 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6818                                       const ObjCPropertyDecl *PD,
6819                                       const Decl *Container) const {
6820   if (!Container)
6821     return nullptr;
6822   if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6823     for (auto *PID : CID->property_impls())
6824       if (PID->getPropertyDecl() == PD)
6825         return PID;
6826   } else {
6827     const auto *OID = cast<ObjCImplementationDecl>(Container);
6828     for (auto *PID : OID->property_impls())
6829       if (PID->getPropertyDecl() == PD)
6830         return PID;
6831   }
6832   return nullptr;
6833 }
6834
6835 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6836 /// property declaration. If non-NULL, Container must be either an
6837 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6838 /// NULL when getting encodings for protocol properties.
6839 /// Property attributes are stored as a comma-delimited C string. The simple
6840 /// attributes readonly and bycopy are encoded as single characters. The
6841 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6842 /// encoded as single characters, followed by an identifier. Property types
6843 /// are also encoded as a parametrized attribute. The characters used to encode
6844 /// these attributes are defined by the following enumeration:
6845 /// @code
6846 /// enum PropertyAttributes {
6847 /// kPropertyReadOnly = 'R',   // property is read-only.
6848 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
6849 /// kPropertyByref = '&',  // property is a reference to the value last assigned
6850 /// kPropertyDynamic = 'D',    // property is dynamic
6851 /// kPropertyGetter = 'G',     // followed by getter selector name
6852 /// kPropertySetter = 'S',     // followed by setter selector name
6853 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
6854 /// kPropertyType = 'T'              // followed by old-style type encoding.
6855 /// kPropertyWeak = 'W'              // 'weak' property
6856 /// kPropertyStrong = 'P'            // property GC'able
6857 /// kPropertyNonAtomic = 'N'         // property non-atomic
6858 /// };
6859 /// @endcode
6860 std::string
6861 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6862                                            const Decl *Container) const {
6863   // Collect information from the property implementation decl(s).
6864   bool Dynamic = false;
6865   ObjCPropertyImplDecl *SynthesizePID = nullptr;
6866
6867   if (ObjCPropertyImplDecl *PropertyImpDecl =
6868       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6869     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6870       Dynamic = true;
6871     else
6872       SynthesizePID = PropertyImpDecl;
6873   }
6874
6875   // FIXME: This is not very efficient.
6876   std::string S = "T";
6877
6878   // Encode result type.
6879   // GCC has some special rules regarding encoding of properties which
6880   // closely resembles encoding of ivars.
6881   getObjCEncodingForPropertyType(PD->getType(), S);
6882
6883   if (PD->isReadOnly()) {
6884     S += ",R";
6885     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
6886       S += ",C";
6887     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
6888       S += ",&";
6889     if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
6890       S += ",W";
6891   } else {
6892     switch (PD->getSetterKind()) {
6893     case ObjCPropertyDecl::Assign: break;
6894     case ObjCPropertyDecl::Copy:   S += ",C"; break;
6895     case ObjCPropertyDecl::Retain: S += ",&"; break;
6896     case ObjCPropertyDecl::Weak:   S += ",W"; break;
6897     }
6898   }
6899
6900   // It really isn't clear at all what this means, since properties
6901   // are "dynamic by default".
6902   if (Dynamic)
6903     S += ",D";
6904
6905   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
6906     S += ",N";
6907
6908   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
6909     S += ",G";
6910     S += PD->getGetterName().getAsString();
6911   }
6912
6913   if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
6914     S += ",S";
6915     S += PD->getSetterName().getAsString();
6916   }
6917
6918   if (SynthesizePID) {
6919     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6920     S += ",V";
6921     S += OID->getNameAsString();
6922   }
6923
6924   // FIXME: OBJCGC: weak & strong
6925   return S;
6926 }
6927
6928 /// getLegacyIntegralTypeEncoding -
6929 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6930 /// 'l' or 'L' , but not always.  For typedefs, we need to use
6931 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6932 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
6933   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6934     if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6935       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6936         PointeeTy = UnsignedIntTy;
6937       else
6938         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6939           PointeeTy = IntTy;
6940     }
6941   }
6942 }
6943
6944 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
6945                                         const FieldDecl *Field,
6946                                         QualType *NotEncodedT) const {
6947   // We follow the behavior of gcc, expanding structures which are
6948   // directly pointed to, and expanding embedded structures. Note that
6949   // these rules are sufficient to prevent recursive encoding of the
6950   // same type.
6951   getObjCEncodingForTypeImpl(T, S,
6952                              ObjCEncOptions()
6953                                  .setExpandPointedToStructures()
6954                                  .setExpandStructures()
6955                                  .setIsOutermostType(),
6956                              Field, NotEncodedT);
6957 }
6958
6959 void ASTContext::getObjCEncodingForPropertyType(QualType T,
6960                                                 std::string& S) const {
6961   // Encode result type.
6962   // GCC has some special rules regarding encoding of properties which
6963   // closely resembles encoding of ivars.
6964   getObjCEncodingForTypeImpl(T, S,
6965                              ObjCEncOptions()
6966                                  .setExpandPointedToStructures()
6967                                  .setExpandStructures()
6968                                  .setIsOutermostType()
6969                                  .setEncodingProperty(),
6970                              /*Field=*/nullptr);
6971 }
6972
6973 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6974                                             const BuiltinType *BT) {
6975     BuiltinType::Kind kind = BT->getKind();
6976     switch (kind) {
6977     case BuiltinType::Void:       return 'v';
6978     case BuiltinType::Bool:       return 'B';
6979     case BuiltinType::Char8:
6980     case BuiltinType::Char_U:
6981     case BuiltinType::UChar:      return 'C';
6982     case BuiltinType::Char16:
6983     case BuiltinType::UShort:     return 'S';
6984     case BuiltinType::Char32:
6985     case BuiltinType::UInt:       return 'I';
6986     case BuiltinType::ULong:
6987         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6988     case BuiltinType::UInt128:    return 'T';
6989     case BuiltinType::ULongLong:  return 'Q';
6990     case BuiltinType::Char_S:
6991     case BuiltinType::SChar:      return 'c';
6992     case BuiltinType::Short:      return 's';
6993     case BuiltinType::WChar_S:
6994     case BuiltinType::WChar_U:
6995     case BuiltinType::Int:        return 'i';
6996     case BuiltinType::Long:
6997       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6998     case BuiltinType::LongLong:   return 'q';
6999     case BuiltinType::Int128:     return 't';
7000     case BuiltinType::Float:      return 'f';
7001     case BuiltinType::Double:     return 'd';
7002     case BuiltinType::LongDouble: return 'D';
7003     case BuiltinType::NullPtr:    return '*'; // like char*
7004
7005     case BuiltinType::BFloat16:
7006     case BuiltinType::Float16:
7007     case BuiltinType::Float128:
7008     case BuiltinType::Half:
7009     case BuiltinType::ShortAccum:
7010     case BuiltinType::Accum:
7011     case BuiltinType::LongAccum:
7012     case BuiltinType::UShortAccum:
7013     case BuiltinType::UAccum:
7014     case BuiltinType::ULongAccum:
7015     case BuiltinType::ShortFract:
7016     case BuiltinType::Fract:
7017     case BuiltinType::LongFract:
7018     case BuiltinType::UShortFract:
7019     case BuiltinType::UFract:
7020     case BuiltinType::ULongFract:
7021     case BuiltinType::SatShortAccum:
7022     case BuiltinType::SatAccum:
7023     case BuiltinType::SatLongAccum:
7024     case BuiltinType::SatUShortAccum:
7025     case BuiltinType::SatUAccum:
7026     case BuiltinType::SatULongAccum:
7027     case BuiltinType::SatShortFract:
7028     case BuiltinType::SatFract:
7029     case BuiltinType::SatLongFract:
7030     case BuiltinType::SatUShortFract:
7031     case BuiltinType::SatUFract:
7032     case BuiltinType::SatULongFract:
7033       // FIXME: potentially need @encodes for these!
7034       return ' ';
7035
7036 #define SVE_TYPE(Name, Id, SingletonId) \
7037     case BuiltinType::Id:
7038 #include "clang/Basic/AArch64SVEACLETypes.def"
7039     {
7040       DiagnosticsEngine &Diags = C->getDiagnostics();
7041       unsigned DiagID = Diags.getCustomDiagID(
7042           DiagnosticsEngine::Error, "cannot yet @encode type %0");
7043       Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7044       return ' ';
7045     }
7046
7047     case BuiltinType::ObjCId:
7048     case BuiltinType::ObjCClass:
7049     case BuiltinType::ObjCSel:
7050       llvm_unreachable("@encoding ObjC primitive type");
7051
7052     // OpenCL and placeholder types don't need @encodings.
7053 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7054     case BuiltinType::Id:
7055 #include "clang/Basic/OpenCLImageTypes.def"
7056 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7057     case BuiltinType::Id:
7058 #include "clang/Basic/OpenCLExtensionTypes.def"
7059     case BuiltinType::OCLEvent:
7060     case BuiltinType::OCLClkEvent:
7061     case BuiltinType::OCLQueue:
7062     case BuiltinType::OCLReserveID:
7063     case BuiltinType::OCLSampler:
7064     case BuiltinType::Dependent:
7065 #define BUILTIN_TYPE(KIND, ID)
7066 #define PLACEHOLDER_TYPE(KIND, ID) \
7067     case BuiltinType::KIND:
7068 #include "clang/AST/BuiltinTypes.def"
7069       llvm_unreachable("invalid builtin type for @encode");
7070     }
7071     llvm_unreachable("invalid BuiltinType::Kind value");
7072 }
7073
7074 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7075   EnumDecl *Enum = ET->getDecl();
7076
7077   // The encoding of an non-fixed enum type is always 'i', regardless of size.
7078   if (!Enum->isFixed())
7079     return 'i';
7080
7081   // The encoding of a fixed enum type matches its fixed underlying type.
7082   const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7083   return getObjCEncodingForPrimitiveType(C, BT);
7084 }
7085
7086 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7087                            QualType T, const FieldDecl *FD) {
7088   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7089   S += 'b';
7090   // The NeXT runtime encodes bit fields as b followed by the number of bits.
7091   // The GNU runtime requires more information; bitfields are encoded as b,
7092   // then the offset (in bits) of the first element, then the type of the
7093   // bitfield, then the size in bits.  For example, in this structure:
7094   //
7095   // struct
7096   // {
7097   //    int integer;
7098   //    int flags:2;
7099   // };
7100   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7101   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
7102   // information is not especially sensible, but we're stuck with it for
7103   // compatibility with GCC, although providing it breaks anything that
7104   // actually uses runtime introspection and wants to work on both runtimes...
7105   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7106     uint64_t Offset;
7107
7108     if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7109       Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7110                                          IVD);
7111     } else {
7112       const RecordDecl *RD = FD->getParent();
7113       const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7114       Offset = RL.getFieldOffset(FD->getFieldIndex());
7115     }
7116
7117     S += llvm::utostr(Offset);
7118
7119     if (const auto *ET = T->getAs<EnumType>())
7120       S += ObjCEncodingForEnumType(Ctx, ET);
7121     else {
7122       const auto *BT = T->castAs<BuiltinType>();
7123       S += getObjCEncodingForPrimitiveType(Ctx, BT);
7124     }
7125   }
7126   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7127 }
7128
7129 // FIXME: Use SmallString for accumulating string.
7130 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7131                                             const ObjCEncOptions Options,
7132                                             const FieldDecl *FD,
7133                                             QualType *NotEncodedT) const {
7134   CanQualType CT = getCanonicalType(T);
7135   switch (CT->getTypeClass()) {
7136   case Type::Builtin:
7137   case Type::Enum:
7138     if (FD && FD->isBitField())
7139       return EncodeBitField(this, S, T, FD);
7140     if (const auto *BT = dyn_cast<BuiltinType>(CT))
7141       S += getObjCEncodingForPrimitiveType(this, BT);
7142     else
7143       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7144     return;
7145
7146   case Type::Complex:
7147     S += 'j';
7148     getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7149                                ObjCEncOptions(),
7150                                /*Field=*/nullptr);
7151     return;
7152
7153   case Type::Atomic:
7154     S += 'A';
7155     getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7156                                ObjCEncOptions(),
7157                                /*Field=*/nullptr);
7158     return;
7159
7160   // encoding for pointer or reference types.
7161   case Type::Pointer:
7162   case Type::LValueReference:
7163   case Type::RValueReference: {
7164     QualType PointeeTy;
7165     if (isa<PointerType>(CT)) {
7166       const auto *PT = T->castAs<PointerType>();
7167       if (PT->isObjCSelType()) {
7168         S += ':';
7169         return;
7170       }
7171       PointeeTy = PT->getPointeeType();
7172     } else {
7173       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7174     }
7175
7176     bool isReadOnly = false;
7177     // For historical/compatibility reasons, the read-only qualifier of the
7178     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
7179     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7180     // Also, do not emit the 'r' for anything but the outermost type!
7181     if (isa<TypedefType>(T.getTypePtr())) {
7182       if (Options.IsOutermostType() && T.isConstQualified()) {
7183         isReadOnly = true;
7184         S += 'r';
7185       }
7186     } else if (Options.IsOutermostType()) {
7187       QualType P = PointeeTy;
7188       while (auto PT = P->getAs<PointerType>())
7189         P = PT->getPointeeType();
7190       if (P.isConstQualified()) {
7191         isReadOnly = true;
7192         S += 'r';
7193       }
7194     }
7195     if (isReadOnly) {
7196       // Another legacy compatibility encoding. Some ObjC qualifier and type
7197       // combinations need to be rearranged.
7198       // Rewrite "in const" from "nr" to "rn"
7199       if (StringRef(S).endswith("nr"))
7200         S.replace(S.end()-2, S.end(), "rn");
7201     }
7202
7203     if (PointeeTy->isCharType()) {
7204       // char pointer types should be encoded as '*' unless it is a
7205       // type that has been typedef'd to 'BOOL'.
7206       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7207         S += '*';
7208         return;
7209       }
7210     } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7211       // GCC binary compat: Need to convert "struct objc_class *" to "#".
7212       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7213         S += '#';
7214         return;
7215       }
7216       // GCC binary compat: Need to convert "struct objc_object *" to "@".
7217       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7218         S += '@';
7219         return;
7220       }
7221       // fall through...
7222     }
7223     S += '^';
7224     getLegacyIntegralTypeEncoding(PointeeTy);
7225
7226     ObjCEncOptions NewOptions;
7227     if (Options.ExpandPointedToStructures())
7228       NewOptions.setExpandStructures();
7229     getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7230                                /*Field=*/nullptr, NotEncodedT);
7231     return;
7232   }
7233
7234   case Type::ConstantArray:
7235   case Type::IncompleteArray:
7236   case Type::VariableArray: {
7237     const auto *AT = cast<ArrayType>(CT);
7238
7239     if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7240       // Incomplete arrays are encoded as a pointer to the array element.
7241       S += '^';
7242
7243       getObjCEncodingForTypeImpl(
7244           AT->getElementType(), S,
7245           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7246     } else {
7247       S += '[';
7248
7249       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7250         S += llvm::utostr(CAT->getSize().getZExtValue());
7251       else {
7252         //Variable length arrays are encoded as a regular array with 0 elements.
7253         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7254                "Unknown array type!");
7255         S += '0';
7256       }
7257
7258       getObjCEncodingForTypeImpl(
7259           AT->getElementType(), S,
7260           Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7261           NotEncodedT);
7262       S += ']';
7263     }
7264     return;
7265   }
7266
7267   case Type::FunctionNoProto:
7268   case Type::FunctionProto:
7269     S += '?';
7270     return;
7271
7272   case Type::Record: {
7273     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7274     S += RDecl->isUnion() ? '(' : '{';
7275     // Anonymous structures print as '?'
7276     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7277       S += II->getName();
7278       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7279         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7280         llvm::raw_string_ostream OS(S);
7281         printTemplateArgumentList(OS, TemplateArgs.asArray(),
7282                                   getPrintingPolicy());
7283       }
7284     } else {
7285       S += '?';
7286     }
7287     if (Options.ExpandStructures()) {
7288       S += '=';
7289       if (!RDecl->isUnion()) {
7290         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7291       } else {
7292         for (const auto *Field : RDecl->fields()) {
7293           if (FD) {
7294             S += '"';
7295             S += Field->getNameAsString();
7296             S += '"';
7297           }
7298
7299           // Special case bit-fields.
7300           if (Field->isBitField()) {
7301             getObjCEncodingForTypeImpl(Field->getType(), S,
7302                                        ObjCEncOptions().setExpandStructures(),
7303                                        Field);
7304           } else {
7305             QualType qt = Field->getType();
7306             getLegacyIntegralTypeEncoding(qt);
7307             getObjCEncodingForTypeImpl(
7308                 qt, S,
7309                 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7310                 NotEncodedT);
7311           }
7312         }
7313       }
7314     }
7315     S += RDecl->isUnion() ? ')' : '}';
7316     return;
7317   }
7318
7319   case Type::BlockPointer: {
7320     const auto *BT = T->castAs<BlockPointerType>();
7321     S += "@?"; // Unlike a pointer-to-function, which is "^?".
7322     if (Options.EncodeBlockParameters()) {
7323       const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7324
7325       S += '<';
7326       // Block return type
7327       getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7328                                  Options.forComponentType(), FD, NotEncodedT);
7329       // Block self
7330       S += "@?";
7331       // Block parameters
7332       if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7333         for (const auto &I : FPT->param_types())
7334           getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7335                                      NotEncodedT);
7336       }
7337       S += '>';
7338     }
7339     return;
7340   }
7341
7342   case Type::ObjCObject: {
7343     // hack to match legacy encoding of *id and *Class
7344     QualType Ty = getObjCObjectPointerType(CT);
7345     if (Ty->isObjCIdType()) {
7346       S += "{objc_object=}";
7347       return;
7348     }
7349     else if (Ty->isObjCClassType()) {
7350       S += "{objc_class=}";
7351       return;
7352     }
7353     // TODO: Double check to make sure this intentionally falls through.
7354     LLVM_FALLTHROUGH;
7355   }
7356
7357   case Type::ObjCInterface: {
7358     // Ignore protocol qualifiers when mangling at this level.
7359     // @encode(class_name)
7360     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7361     S += '{';
7362     S += OI->getObjCRuntimeNameAsString();
7363     if (Options.ExpandStructures()) {
7364       S += '=';
7365       SmallVector<const ObjCIvarDecl*, 32> Ivars;
7366       DeepCollectObjCIvars(OI, true, Ivars);
7367       for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7368         const FieldDecl *Field = Ivars[i];
7369         if (Field->isBitField())
7370           getObjCEncodingForTypeImpl(Field->getType(), S,
7371                                      ObjCEncOptions().setExpandStructures(),
7372                                      Field);
7373         else
7374           getObjCEncodingForTypeImpl(Field->getType(), S,
7375                                      ObjCEncOptions().setExpandStructures(), FD,
7376                                      NotEncodedT);
7377       }
7378     }
7379     S += '}';
7380     return;
7381   }
7382
7383   case Type::ObjCObjectPointer: {
7384     const auto *OPT = T->castAs<ObjCObjectPointerType>();
7385     if (OPT->isObjCIdType()) {
7386       S += '@';
7387       return;
7388     }
7389
7390     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7391       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7392       // Since this is a binary compatibility issue, need to consult with
7393       // runtime folks. Fortunately, this is a *very* obscure construct.
7394       S += '#';
7395       return;
7396     }
7397
7398     if (OPT->isObjCQualifiedIdType()) {
7399       getObjCEncodingForTypeImpl(
7400           getObjCIdType(), S,
7401           Options.keepingOnly(ObjCEncOptions()
7402                                   .setExpandPointedToStructures()
7403                                   .setExpandStructures()),
7404           FD);
7405       if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7406         // Note that we do extended encoding of protocol qualifer list
7407         // Only when doing ivar or property encoding.
7408         S += '"';
7409         for (const auto *I : OPT->quals()) {
7410           S += '<';
7411           S += I->getObjCRuntimeNameAsString();
7412           S += '>';
7413         }
7414         S += '"';
7415       }
7416       return;
7417     }
7418
7419     S += '@';
7420     if (OPT->getInterfaceDecl() &&
7421         (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7422       S += '"';
7423       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7424       for (const auto *I : OPT->quals()) {
7425         S += '<';
7426         S += I->getObjCRuntimeNameAsString();
7427         S += '>';
7428       }
7429       S += '"';
7430     }
7431     return;
7432   }
7433
7434   // gcc just blithely ignores member pointers.
7435   // FIXME: we should do better than that.  'M' is available.
7436   case Type::MemberPointer:
7437   // This matches gcc's encoding, even though technically it is insufficient.
7438   //FIXME. We should do a better job than gcc.
7439   case Type::Vector:
7440   case Type::ExtVector:
7441   // Until we have a coherent encoding of these three types, issue warning.
7442     if (NotEncodedT)
7443       *NotEncodedT = T;
7444     return;
7445
7446   case Type::ConstantMatrix:
7447     if (NotEncodedT)
7448       *NotEncodedT = T;
7449     return;
7450
7451   // We could see an undeduced auto type here during error recovery.
7452   // Just ignore it.
7453   case Type::Auto:
7454   case Type::DeducedTemplateSpecialization:
7455     return;
7456
7457   case Type::Pipe:
7458   case Type::ExtInt:
7459 #define ABSTRACT_TYPE(KIND, BASE)
7460 #define TYPE(KIND, BASE)
7461 #define DEPENDENT_TYPE(KIND, BASE) \
7462   case Type::KIND:
7463 #define NON_CANONICAL_TYPE(KIND, BASE) \
7464   case Type::KIND:
7465 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7466   case Type::KIND:
7467 #include "clang/AST/TypeNodes.inc"
7468     llvm_unreachable("@encode for dependent type!");
7469   }
7470   llvm_unreachable("bad type kind!");
7471 }
7472
7473 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7474                                                  std::string &S,
7475                                                  const FieldDecl *FD,
7476                                                  bool includeVBases,
7477                                                  QualType *NotEncodedT) const {
7478   assert(RDecl && "Expected non-null RecordDecl");
7479   assert(!RDecl->isUnion() && "Should not be called for unions");
7480   if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7481     return;
7482
7483   const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7484   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7485   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7486
7487   if (CXXRec) {
7488     for (const auto &BI : CXXRec->bases()) {
7489       if (!BI.isVirtual()) {
7490         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7491         if (base->isEmpty())
7492           continue;
7493         uint64_t offs = toBits(layout.getBaseClassOffset(base));
7494         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7495                                   std::make_pair(offs, base));
7496       }
7497     }
7498   }
7499
7500   unsigned i = 0;
7501   for (auto *Field : RDecl->fields()) {
7502     uint64_t offs = layout.getFieldOffset(i);
7503     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7504                               std::make_pair(offs, Field));
7505     ++i;
7506   }
7507
7508   if (CXXRec && includeVBases) {
7509     for (const auto &BI : CXXRec->vbases()) {
7510       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7511       if (base->isEmpty())
7512         continue;
7513       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7514       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7515           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7516         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7517                                   std::make_pair(offs, base));
7518     }
7519   }
7520
7521   CharUnits size;
7522   if (CXXRec) {
7523     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7524   } else {
7525     size = layout.getSize();
7526   }
7527
7528 #ifndef NDEBUG
7529   uint64_t CurOffs = 0;
7530 #endif
7531   std::multimap<uint64_t, NamedDecl *>::iterator
7532     CurLayObj = FieldOrBaseOffsets.begin();
7533
7534   if (CXXRec && CXXRec->isDynamicClass() &&
7535       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7536     if (FD) {
7537       S += "\"_vptr$";
7538       std::string recname = CXXRec->getNameAsString();
7539       if (recname.empty()) recname = "?";
7540       S += recname;
7541       S += '"';
7542     }
7543     S += "^^?";
7544 #ifndef NDEBUG
7545     CurOffs += getTypeSize(VoidPtrTy);
7546 #endif
7547   }
7548
7549   if (!RDecl->hasFlexibleArrayMember()) {
7550     // Mark the end of the structure.
7551     uint64_t offs = toBits(size);
7552     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7553                               std::make_pair(offs, nullptr));
7554   }
7555
7556   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7557 #ifndef NDEBUG
7558     assert(CurOffs <= CurLayObj->first);
7559     if (CurOffs < CurLayObj->first) {
7560       uint64_t padding = CurLayObj->first - CurOffs;
7561       // FIXME: There doesn't seem to be a way to indicate in the encoding that
7562       // packing/alignment of members is different that normal, in which case
7563       // the encoding will be out-of-sync with the real layout.
7564       // If the runtime switches to just consider the size of types without
7565       // taking into account alignment, we could make padding explicit in the
7566       // encoding (e.g. using arrays of chars). The encoding strings would be
7567       // longer then though.
7568       CurOffs += padding;
7569     }
7570 #endif
7571
7572     NamedDecl *dcl = CurLayObj->second;
7573     if (!dcl)
7574       break; // reached end of structure.
7575
7576     if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7577       // We expand the bases without their virtual bases since those are going
7578       // in the initial structure. Note that this differs from gcc which
7579       // expands virtual bases each time one is encountered in the hierarchy,
7580       // making the encoding type bigger than it really is.
7581       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7582                                       NotEncodedT);
7583       assert(!base->isEmpty());
7584 #ifndef NDEBUG
7585       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7586 #endif
7587     } else {
7588       const auto *field = cast<FieldDecl>(dcl);
7589       if (FD) {
7590         S += '"';
7591         S += field->getNameAsString();
7592         S += '"';
7593       }
7594
7595       if (field->isBitField()) {
7596         EncodeBitField(this, S, field->getType(), field);
7597 #ifndef NDEBUG
7598         CurOffs += field->getBitWidthValue(*this);
7599 #endif
7600       } else {
7601         QualType qt = field->getType();
7602         getLegacyIntegralTypeEncoding(qt);
7603         getObjCEncodingForTypeImpl(
7604             qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7605             FD, NotEncodedT);
7606 #ifndef NDEBUG
7607         CurOffs += getTypeSize(field->getType());
7608 #endif
7609       }
7610     }
7611   }
7612 }
7613
7614 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7615                                                  std::string& S) const {
7616   if (QT & Decl::OBJC_TQ_In)
7617     S += 'n';
7618   if (QT & Decl::OBJC_TQ_Inout)
7619     S += 'N';
7620   if (QT & Decl::OBJC_TQ_Out)
7621     S += 'o';
7622   if (QT & Decl::OBJC_TQ_Bycopy)
7623     S += 'O';
7624   if (QT & Decl::OBJC_TQ_Byref)
7625     S += 'R';
7626   if (QT & Decl::OBJC_TQ_Oneway)
7627     S += 'V';
7628 }
7629
7630 TypedefDecl *ASTContext::getObjCIdDecl() const {
7631   if (!ObjCIdDecl) {
7632     QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7633     T = getObjCObjectPointerType(T);
7634     ObjCIdDecl = buildImplicitTypedef(T, "id");
7635   }
7636   return ObjCIdDecl;
7637 }
7638
7639 TypedefDecl *ASTContext::getObjCSelDecl() const {
7640   if (!ObjCSelDecl) {
7641     QualType T = getPointerType(ObjCBuiltinSelTy);
7642     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7643   }
7644   return ObjCSelDecl;
7645 }
7646
7647 TypedefDecl *ASTContext::getObjCClassDecl() const {
7648   if (!ObjCClassDecl) {
7649     QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7650     T = getObjCObjectPointerType(T);
7651     ObjCClassDecl = buildImplicitTypedef(T, "Class");
7652   }
7653   return ObjCClassDecl;
7654 }
7655
7656 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7657   if (!ObjCProtocolClassDecl) {
7658     ObjCProtocolClassDecl
7659       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7660                                   SourceLocation(),
7661                                   &Idents.get("Protocol"),
7662                                   /*typeParamList=*/nullptr,
7663                                   /*PrevDecl=*/nullptr,
7664                                   SourceLocation(), true);
7665   }
7666
7667   return ObjCProtocolClassDecl;
7668 }
7669
7670 //===----------------------------------------------------------------------===//
7671 // __builtin_va_list Construction Functions
7672 //===----------------------------------------------------------------------===//
7673
7674 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7675                                                  StringRef Name) {
7676   // typedef char* __builtin[_ms]_va_list;
7677   QualType T = Context->getPointerType(Context->CharTy);
7678   return Context->buildImplicitTypedef(T, Name);
7679 }
7680
7681 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7682   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7683 }
7684
7685 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7686   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7687 }
7688
7689 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7690   // typedef void* __builtin_va_list;
7691   QualType T = Context->getPointerType(Context->VoidTy);
7692   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7693 }
7694
7695 static TypedefDecl *
7696 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7697   // struct __va_list
7698   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7699   if (Context->getLangOpts().CPlusPlus) {
7700     // namespace std { struct __va_list {
7701     NamespaceDecl *NS;
7702     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7703                                Context->getTranslationUnitDecl(),
7704                                /*Inline*/ false, SourceLocation(),
7705                                SourceLocation(), &Context->Idents.get("std"),
7706                                /*PrevDecl*/ nullptr);
7707     NS->setImplicit();
7708     VaListTagDecl->setDeclContext(NS);
7709   }
7710
7711   VaListTagDecl->startDefinition();
7712
7713   const size_t NumFields = 5;
7714   QualType FieldTypes[NumFields];
7715   const char *FieldNames[NumFields];
7716
7717   // void *__stack;
7718   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7719   FieldNames[0] = "__stack";
7720
7721   // void *__gr_top;
7722   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7723   FieldNames[1] = "__gr_top";
7724
7725   // void *__vr_top;
7726   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7727   FieldNames[2] = "__vr_top";
7728
7729   // int __gr_offs;
7730   FieldTypes[3] = Context->IntTy;
7731   FieldNames[3] = "__gr_offs";
7732
7733   // int __vr_offs;
7734   FieldTypes[4] = Context->IntTy;
7735   FieldNames[4] = "__vr_offs";
7736
7737   // Create fields
7738   for (unsigned i = 0; i < NumFields; ++i) {
7739     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7740                                          VaListTagDecl,
7741                                          SourceLocation(),
7742                                          SourceLocation(),
7743                                          &Context->Idents.get(FieldNames[i]),
7744                                          FieldTypes[i], /*TInfo=*/nullptr,
7745                                          /*BitWidth=*/nullptr,
7746                                          /*Mutable=*/false,
7747                                          ICIS_NoInit);
7748     Field->setAccess(AS_public);
7749     VaListTagDecl->addDecl(Field);
7750   }
7751   VaListTagDecl->completeDefinition();
7752   Context->VaListTagDecl = VaListTagDecl;
7753   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7754
7755   // } __builtin_va_list;
7756   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7757 }
7758
7759 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7760   // typedef struct __va_list_tag {
7761   RecordDecl *VaListTagDecl;
7762
7763   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7764   VaListTagDecl->startDefinition();
7765
7766   const size_t NumFields = 5;
7767   QualType FieldTypes[NumFields];
7768   const char *FieldNames[NumFields];
7769
7770   //   unsigned char gpr;
7771   FieldTypes[0] = Context->UnsignedCharTy;
7772   FieldNames[0] = "gpr";
7773
7774   //   unsigned char fpr;
7775   FieldTypes[1] = Context->UnsignedCharTy;
7776   FieldNames[1] = "fpr";
7777
7778   //   unsigned short reserved;
7779   FieldTypes[2] = Context->UnsignedShortTy;
7780   FieldNames[2] = "reserved";
7781
7782   //   void* overflow_arg_area;
7783   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7784   FieldNames[3] = "overflow_arg_area";
7785
7786   //   void* reg_save_area;
7787   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7788   FieldNames[4] = "reg_save_area";
7789
7790   // Create fields
7791   for (unsigned i = 0; i < NumFields; ++i) {
7792     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7793                                          SourceLocation(),
7794                                          SourceLocation(),
7795                                          &Context->Idents.get(FieldNames[i]),
7796                                          FieldTypes[i], /*TInfo=*/nullptr,
7797                                          /*BitWidth=*/nullptr,
7798                                          /*Mutable=*/false,
7799                                          ICIS_NoInit);
7800     Field->setAccess(AS_public);
7801     VaListTagDecl->addDecl(Field);
7802   }
7803   VaListTagDecl->completeDefinition();
7804   Context->VaListTagDecl = VaListTagDecl;
7805   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7806
7807   // } __va_list_tag;
7808   TypedefDecl *VaListTagTypedefDecl =
7809       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7810
7811   QualType VaListTagTypedefType =
7812     Context->getTypedefType(VaListTagTypedefDecl);
7813
7814   // typedef __va_list_tag __builtin_va_list[1];
7815   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7816   QualType VaListTagArrayType
7817     = Context->getConstantArrayType(VaListTagTypedefType,
7818                                     Size, nullptr, ArrayType::Normal, 0);
7819   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7820 }
7821
7822 static TypedefDecl *
7823 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
7824   // struct __va_list_tag {
7825   RecordDecl *VaListTagDecl;
7826   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7827   VaListTagDecl->startDefinition();
7828
7829   const size_t NumFields = 4;
7830   QualType FieldTypes[NumFields];
7831   const char *FieldNames[NumFields];
7832
7833   //   unsigned gp_offset;
7834   FieldTypes[0] = Context->UnsignedIntTy;
7835   FieldNames[0] = "gp_offset";
7836
7837   //   unsigned fp_offset;
7838   FieldTypes[1] = Context->UnsignedIntTy;
7839   FieldNames[1] = "fp_offset";
7840
7841   //   void* overflow_arg_area;
7842   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7843   FieldNames[2] = "overflow_arg_area";
7844
7845   //   void* reg_save_area;
7846   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7847   FieldNames[3] = "reg_save_area";
7848
7849   // Create fields
7850   for (unsigned i = 0; i < NumFields; ++i) {
7851     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7852                                          VaListTagDecl,
7853                                          SourceLocation(),
7854                                          SourceLocation(),
7855                                          &Context->Idents.get(FieldNames[i]),
7856                                          FieldTypes[i], /*TInfo=*/nullptr,
7857                                          /*BitWidth=*/nullptr,
7858                                          /*Mutable=*/false,
7859                                          ICIS_NoInit);
7860     Field->setAccess(AS_public);
7861     VaListTagDecl->addDecl(Field);
7862   }
7863   VaListTagDecl->completeDefinition();
7864   Context->VaListTagDecl = VaListTagDecl;
7865   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7866
7867   // };
7868
7869   // typedef struct __va_list_tag __builtin_va_list[1];
7870   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7871   QualType VaListTagArrayType = Context->getConstantArrayType(
7872       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7873   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7874 }
7875
7876 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7877   // typedef int __builtin_va_list[4];
7878   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7879   QualType IntArrayType = Context->getConstantArrayType(
7880       Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
7881   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7882 }
7883
7884 static TypedefDecl *
7885 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
7886   // struct __va_list
7887   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7888   if (Context->getLangOpts().CPlusPlus) {
7889     // namespace std { struct __va_list {
7890     NamespaceDecl *NS;
7891     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7892                                Context->getTranslationUnitDecl(),
7893                                /*Inline*/false, SourceLocation(),
7894                                SourceLocation(), &Context->Idents.get("std"),
7895                                /*PrevDecl*/ nullptr);
7896     NS->setImplicit();
7897     VaListDecl->setDeclContext(NS);
7898   }
7899
7900   VaListDecl->startDefinition();
7901
7902   // void * __ap;
7903   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7904                                        VaListDecl,
7905                                        SourceLocation(),
7906                                        SourceLocation(),
7907                                        &Context->Idents.get("__ap"),
7908                                        Context->getPointerType(Context->VoidTy),
7909                                        /*TInfo=*/nullptr,
7910                                        /*BitWidth=*/nullptr,
7911                                        /*Mutable=*/false,
7912                                        ICIS_NoInit);
7913   Field->setAccess(AS_public);
7914   VaListDecl->addDecl(Field);
7915
7916   // };
7917   VaListDecl->completeDefinition();
7918   Context->VaListTagDecl = VaListDecl;
7919
7920   // typedef struct __va_list __builtin_va_list;
7921   QualType T = Context->getRecordType(VaListDecl);
7922   return Context->buildImplicitTypedef(T, "__builtin_va_list");
7923 }
7924
7925 static TypedefDecl *
7926 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
7927   // struct __va_list_tag {
7928   RecordDecl *VaListTagDecl;
7929   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7930   VaListTagDecl->startDefinition();
7931
7932   const size_t NumFields = 4;
7933   QualType FieldTypes[NumFields];
7934   const char *FieldNames[NumFields];
7935
7936   //   long __gpr;
7937   FieldTypes[0] = Context->LongTy;
7938   FieldNames[0] = "__gpr";
7939
7940   //   long __fpr;
7941   FieldTypes[1] = Context->LongTy;
7942   FieldNames[1] = "__fpr";
7943
7944   //   void *__overflow_arg_area;
7945   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7946   FieldNames[2] = "__overflow_arg_area";
7947
7948   //   void *__reg_save_area;
7949   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7950   FieldNames[3] = "__reg_save_area";
7951
7952   // Create fields
7953   for (unsigned i = 0; i < NumFields; ++i) {
7954     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7955                                          VaListTagDecl,
7956                                          SourceLocation(),
7957                                          SourceLocation(),
7958                                          &Context->Idents.get(FieldNames[i]),
7959                                          FieldTypes[i], /*TInfo=*/nullptr,
7960                                          /*BitWidth=*/nullptr,
7961                                          /*Mutable=*/false,
7962                                          ICIS_NoInit);
7963     Field->setAccess(AS_public);
7964     VaListTagDecl->addDecl(Field);
7965   }
7966   VaListTagDecl->completeDefinition();
7967   Context->VaListTagDecl = VaListTagDecl;
7968   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7969
7970   // };
7971
7972   // typedef __va_list_tag __builtin_va_list[1];
7973   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7974   QualType VaListTagArrayType = Context->getConstantArrayType(
7975       VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7976
7977   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7978 }
7979
7980 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
7981   // typedef struct __va_list_tag {
7982   RecordDecl *VaListTagDecl;
7983   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7984   VaListTagDecl->startDefinition();
7985
7986   const size_t NumFields = 3;
7987   QualType FieldTypes[NumFields];
7988   const char *FieldNames[NumFields];
7989
7990   //   void *CurrentSavedRegisterArea;
7991   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7992   FieldNames[0] = "__current_saved_reg_area_pointer";
7993
7994   //   void *SavedRegAreaEnd;
7995   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7996   FieldNames[1] = "__saved_reg_area_end_pointer";
7997
7998   //   void *OverflowArea;
7999   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8000   FieldNames[2] = "__overflow_area_pointer";
8001
8002   // Create fields
8003   for (unsigned i = 0; i < NumFields; ++i) {
8004     FieldDecl *Field = FieldDecl::Create(
8005         const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8006         SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8007         /*TInfo=*/0,
8008         /*BitWidth=*/0,
8009         /*Mutable=*/false, ICIS_NoInit);
8010     Field->setAccess(AS_public);
8011     VaListTagDecl->addDecl(Field);
8012   }
8013   VaListTagDecl->completeDefinition();
8014   Context->VaListTagDecl = VaListTagDecl;
8015   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8016
8017   // } __va_list_tag;
8018   TypedefDecl *VaListTagTypedefDecl =
8019       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8020
8021   QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8022
8023   // typedef __va_list_tag __builtin_va_list[1];
8024   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8025   QualType VaListTagArrayType = Context->getConstantArrayType(
8026       VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8027
8028   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8029 }
8030
8031 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8032                                      TargetInfo::BuiltinVaListKind Kind) {
8033   switch (Kind) {
8034   case TargetInfo::CharPtrBuiltinVaList:
8035     return CreateCharPtrBuiltinVaListDecl(Context);
8036   case TargetInfo::VoidPtrBuiltinVaList:
8037     return CreateVoidPtrBuiltinVaListDecl(Context);
8038   case TargetInfo::AArch64ABIBuiltinVaList:
8039     return CreateAArch64ABIBuiltinVaListDecl(Context);
8040   case TargetInfo::PowerABIBuiltinVaList:
8041     return CreatePowerABIBuiltinVaListDecl(Context);
8042   case TargetInfo::X86_64ABIBuiltinVaList:
8043     return CreateX86_64ABIBuiltinVaListDecl(Context);
8044   case TargetInfo::PNaClABIBuiltinVaList:
8045     return CreatePNaClABIBuiltinVaListDecl(Context);
8046   case TargetInfo::AAPCSABIBuiltinVaList:
8047     return CreateAAPCSABIBuiltinVaListDecl(Context);
8048   case TargetInfo::SystemZBuiltinVaList:
8049     return CreateSystemZBuiltinVaListDecl(Context);
8050   case TargetInfo::HexagonBuiltinVaList:
8051     return CreateHexagonBuiltinVaListDecl(Context);
8052   }
8053
8054   llvm_unreachable("Unhandled __builtin_va_list type kind");
8055 }
8056
8057 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8058   if (!BuiltinVaListDecl) {
8059     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8060     assert(BuiltinVaListDecl->isImplicit());
8061   }
8062
8063   return BuiltinVaListDecl;
8064 }
8065
8066 Decl *ASTContext::getVaListTagDecl() const {
8067   // Force the creation of VaListTagDecl by building the __builtin_va_list
8068   // declaration.
8069   if (!VaListTagDecl)
8070     (void)getBuiltinVaListDecl();
8071
8072   return VaListTagDecl;
8073 }
8074
8075 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8076   if (!BuiltinMSVaListDecl)
8077     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8078
8079   return BuiltinMSVaListDecl;
8080 }
8081
8082 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8083   return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8084 }
8085
8086 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8087   assert(ObjCConstantStringType.isNull() &&
8088          "'NSConstantString' type already set!");
8089
8090   ObjCConstantStringType = getObjCInterfaceType(Decl);
8091 }
8092
8093 /// Retrieve the template name that corresponds to a non-empty
8094 /// lookup.
8095 TemplateName
8096 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8097                                       UnresolvedSetIterator End) const {
8098   unsigned size = End - Begin;
8099   assert(size > 1 && "set is not overloaded!");
8100
8101   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8102                           size * sizeof(FunctionTemplateDecl*));
8103   auto *OT = new (memory) OverloadedTemplateStorage(size);
8104
8105   NamedDecl **Storage = OT->getStorage();
8106   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8107     NamedDecl *D = *I;
8108     assert(isa<FunctionTemplateDecl>(D) ||
8109            isa<UnresolvedUsingValueDecl>(D) ||
8110            (isa<UsingShadowDecl>(D) &&
8111             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8112     *Storage++ = D;
8113   }
8114
8115   return TemplateName(OT);
8116 }
8117
8118 /// Retrieve a template name representing an unqualified-id that has been
8119 /// assumed to name a template for ADL purposes.
8120 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8121   auto *OT = new (*this) AssumedTemplateStorage(Name);
8122   return TemplateName(OT);
8123 }
8124
8125 /// Retrieve the template name that represents a qualified
8126 /// template name such as \c std::vector.
8127 TemplateName
8128 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8129                                      bool TemplateKeyword,
8130                                      TemplateDecl *Template) const {
8131   assert(NNS && "Missing nested-name-specifier in qualified template name");
8132
8133   // FIXME: Canonicalization?
8134   llvm::FoldingSetNodeID ID;
8135   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8136
8137   void *InsertPos = nullptr;
8138   QualifiedTemplateName *QTN =
8139     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8140   if (!QTN) {
8141     QTN = new (*this, alignof(QualifiedTemplateName))
8142         QualifiedTemplateName(NNS, TemplateKeyword, Template);
8143     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8144   }
8145
8146   return TemplateName(QTN);
8147 }
8148
8149 /// Retrieve the template name that represents a dependent
8150 /// template name such as \c MetaFun::template apply.
8151 TemplateName
8152 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8153                                      const IdentifierInfo *Name) const {
8154   assert((!NNS || NNS->isDependent()) &&
8155          "Nested name specifier must be dependent");
8156
8157   llvm::FoldingSetNodeID ID;
8158   DependentTemplateName::Profile(ID, NNS, Name);
8159
8160   void *InsertPos = nullptr;
8161   DependentTemplateName *QTN =
8162     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8163
8164   if (QTN)
8165     return TemplateName(QTN);
8166
8167   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8168   if (CanonNNS == NNS) {
8169     QTN = new (*this, alignof(DependentTemplateName))
8170         DependentTemplateName(NNS, Name);
8171   } else {
8172     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8173     QTN = new (*this, alignof(DependentTemplateName))
8174         DependentTemplateName(NNS, Name, Canon);
8175     DependentTemplateName *CheckQTN =
8176       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8177     assert(!CheckQTN && "Dependent type name canonicalization broken");
8178     (void)CheckQTN;
8179   }
8180
8181   DependentTemplateNames.InsertNode(QTN, InsertPos);
8182   return TemplateName(QTN);
8183 }
8184
8185 /// Retrieve the template name that represents a dependent
8186 /// template name such as \c MetaFun::template operator+.
8187 TemplateName
8188 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8189                                      OverloadedOperatorKind Operator) const {
8190   assert((!NNS || NNS->isDependent()) &&
8191          "Nested name specifier must be dependent");
8192
8193   llvm::FoldingSetNodeID ID;
8194   DependentTemplateName::Profile(ID, NNS, Operator);
8195
8196   void *InsertPos = nullptr;
8197   DependentTemplateName *QTN
8198     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8199
8200   if (QTN)
8201     return TemplateName(QTN);
8202
8203   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8204   if (CanonNNS == NNS) {
8205     QTN = new (*this, alignof(DependentTemplateName))
8206         DependentTemplateName(NNS, Operator);
8207   } else {
8208     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8209     QTN = new (*this, alignof(DependentTemplateName))
8210         DependentTemplateName(NNS, Operator, Canon);
8211
8212     DependentTemplateName *CheckQTN
8213       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8214     assert(!CheckQTN && "Dependent template name canonicalization broken");
8215     (void)CheckQTN;
8216   }
8217
8218   DependentTemplateNames.InsertNode(QTN, InsertPos);
8219   return TemplateName(QTN);
8220 }
8221
8222 TemplateName
8223 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8224                                          TemplateName replacement) const {
8225   llvm::FoldingSetNodeID ID;
8226   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8227
8228   void *insertPos = nullptr;
8229   SubstTemplateTemplateParmStorage *subst
8230     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8231
8232   if (!subst) {
8233     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8234     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8235   }
8236
8237   return TemplateName(subst);
8238 }
8239
8240 TemplateName
8241 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8242                                        const TemplateArgument &ArgPack) const {
8243   auto &Self = const_cast<ASTContext &>(*this);
8244   llvm::FoldingSetNodeID ID;
8245   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8246
8247   void *InsertPos = nullptr;
8248   SubstTemplateTemplateParmPackStorage *Subst
8249     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8250
8251   if (!Subst) {
8252     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8253                                                            ArgPack.pack_size(),
8254                                                          ArgPack.pack_begin());
8255     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8256   }
8257
8258   return TemplateName(Subst);
8259 }
8260
8261 /// getFromTargetType - Given one of the integer types provided by
8262 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8263 /// is actually a value of type @c TargetInfo::IntType.
8264 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8265   switch (Type) {
8266   case TargetInfo::NoInt: return {};
8267   case TargetInfo::SignedChar: return SignedCharTy;
8268   case TargetInfo::UnsignedChar: return UnsignedCharTy;
8269   case TargetInfo::SignedShort: return ShortTy;
8270   case TargetInfo::UnsignedShort: return UnsignedShortTy;
8271   case TargetInfo::SignedInt: return IntTy;
8272   case TargetInfo::UnsignedInt: return UnsignedIntTy;
8273   case TargetInfo::SignedLong: return LongTy;
8274   case TargetInfo::UnsignedLong: return UnsignedLongTy;
8275   case TargetInfo::SignedLongLong: return LongLongTy;
8276   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8277   }
8278
8279   llvm_unreachable("Unhandled TargetInfo::IntType value");
8280 }
8281
8282 //===----------------------------------------------------------------------===//
8283 //                        Type Predicates.
8284 //===----------------------------------------------------------------------===//
8285
8286 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8287 /// garbage collection attribute.
8288 ///
8289 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8290   if (getLangOpts().getGC() == LangOptions::NonGC)
8291     return Qualifiers::GCNone;
8292
8293   assert(getLangOpts().ObjC);
8294   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8295
8296   // Default behaviour under objective-C's gc is for ObjC pointers
8297   // (or pointers to them) be treated as though they were declared
8298   // as __strong.
8299   if (GCAttrs == Qualifiers::GCNone) {
8300     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8301       return Qualifiers::Strong;
8302     else if (Ty->isPointerType())
8303       return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8304   } else {
8305     // It's not valid to set GC attributes on anything that isn't a
8306     // pointer.
8307 #ifndef NDEBUG
8308     QualType CT = Ty->getCanonicalTypeInternal();
8309     while (const auto *AT = dyn_cast<ArrayType>(CT))
8310       CT = AT->getElementType();
8311     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8312 #endif
8313   }
8314   return GCAttrs;
8315 }
8316
8317 //===----------------------------------------------------------------------===//
8318 //                        Type Compatibility Testing
8319 //===----------------------------------------------------------------------===//
8320
8321 /// areCompatVectorTypes - Return true if the two specified vector types are
8322 /// compatible.
8323 static bool areCompatVectorTypes(const VectorType *LHS,
8324                                  const VectorType *RHS) {
8325   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8326   return LHS->getElementType() == RHS->getElementType() &&
8327          LHS->getNumElements() == RHS->getNumElements();
8328 }
8329
8330 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8331 /// compatible.
8332 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8333                                  const ConstantMatrixType *RHS) {
8334   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8335   return LHS->getElementType() == RHS->getElementType() &&
8336          LHS->getNumRows() == RHS->getNumRows() &&
8337          LHS->getNumColumns() == RHS->getNumColumns();
8338 }
8339
8340 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8341                                           QualType SecondVec) {
8342   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8343   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8344
8345   if (hasSameUnqualifiedType(FirstVec, SecondVec))
8346     return true;
8347
8348   // Treat Neon vector types and most AltiVec vector types as if they are the
8349   // equivalent GCC vector types.
8350   const auto *First = FirstVec->castAs<VectorType>();
8351   const auto *Second = SecondVec->castAs<VectorType>();
8352   if (First->getNumElements() == Second->getNumElements() &&
8353       hasSameType(First->getElementType(), Second->getElementType()) &&
8354       First->getVectorKind() != VectorType::AltiVecPixel &&
8355       First->getVectorKind() != VectorType::AltiVecBool &&
8356       Second->getVectorKind() != VectorType::AltiVecPixel &&
8357       Second->getVectorKind() != VectorType::AltiVecBool)
8358     return true;
8359
8360   return false;
8361 }
8362
8363 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8364   while (true) {
8365     // __strong id
8366     if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8367       if (Attr->getAttrKind() == attr::ObjCOwnership)
8368         return true;
8369
8370       Ty = Attr->getModifiedType();
8371
8372     // X *__strong (...)
8373     } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8374       Ty = Paren->getInnerType();
8375
8376     // We do not want to look through typedefs, typeof(expr),
8377     // typeof(type), or any other way that the type is somehow
8378     // abstracted.
8379     } else {
8380       return false;
8381     }
8382   }
8383 }
8384
8385 //===----------------------------------------------------------------------===//
8386 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8387 //===----------------------------------------------------------------------===//
8388
8389 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8390 /// inheritance hierarchy of 'rProto'.
8391 bool
8392 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8393                                            ObjCProtocolDecl *rProto) const {
8394   if (declaresSameEntity(lProto, rProto))
8395     return true;
8396   for (auto *PI : rProto->protocols())
8397     if (ProtocolCompatibleWithProtocol(lProto, PI))
8398       return true;
8399   return false;
8400 }
8401
8402 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
8403 /// Class<pr1, ...>.
8404 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8405     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8406   for (auto *lhsProto : lhs->quals()) {
8407     bool match = false;
8408     for (auto *rhsProto : rhs->quals()) {
8409       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8410         match = true;
8411         break;
8412       }
8413     }
8414     if (!match)
8415       return false;
8416   }
8417   return true;
8418 }
8419
8420 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8421 /// ObjCQualifiedIDType.
8422 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8423     const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8424     bool compare) {
8425   // Allow id<P..> and an 'id' in all cases.
8426   if (lhs->isObjCIdType() || rhs->isObjCIdType())
8427     return true;
8428
8429   // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8430   if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8431       rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8432     return false;
8433
8434   if (lhs->isObjCQualifiedIdType()) {
8435     if (rhs->qual_empty()) {
8436       // If the RHS is a unqualified interface pointer "NSString*",
8437       // make sure we check the class hierarchy.
8438       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8439         for (auto *I : lhs->quals()) {
8440           // when comparing an id<P> on lhs with a static type on rhs,
8441           // see if static class implements all of id's protocols, directly or
8442           // through its super class and categories.
8443           if (!rhsID->ClassImplementsProtocol(I, true))
8444             return false;
8445         }
8446       }
8447       // If there are no qualifiers and no interface, we have an 'id'.
8448       return true;
8449     }
8450     // Both the right and left sides have qualifiers.
8451     for (auto *lhsProto : lhs->quals()) {
8452       bool match = false;
8453
8454       // when comparing an id<P> on lhs with a static type on rhs,
8455       // see if static class implements all of id's protocols, directly or
8456       // through its super class and categories.
8457       for (auto *rhsProto : rhs->quals()) {
8458         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8459             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8460           match = true;
8461           break;
8462         }
8463       }
8464       // If the RHS is a qualified interface pointer "NSString<P>*",
8465       // make sure we check the class hierarchy.
8466       if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8467         for (auto *I : lhs->quals()) {
8468           // when comparing an id<P> on lhs with a static type on rhs,
8469           // see if static class implements all of id's protocols, directly or
8470           // through its super class and categories.
8471           if (rhsID->ClassImplementsProtocol(I, true)) {
8472             match = true;
8473             break;
8474           }
8475         }
8476       }
8477       if (!match)
8478         return false;
8479     }
8480
8481     return true;
8482   }
8483
8484   assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8485
8486   if (lhs->getInterfaceType()) {
8487     // If both the right and left sides have qualifiers.
8488     for (auto *lhsProto : lhs->quals()) {
8489       bool match = false;
8490
8491       // when comparing an id<P> on rhs with a static type on lhs,
8492       // see if static class implements all of id's protocols, directly or
8493       // through its super class and categories.
8494       // First, lhs protocols in the qualifier list must be found, direct
8495       // or indirect in rhs's qualifier list or it is a mismatch.
8496       for (auto *rhsProto : rhs->quals()) {
8497         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8498             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8499           match = true;
8500           break;
8501         }
8502       }
8503       if (!match)
8504         return false;
8505     }
8506
8507     // Static class's protocols, or its super class or category protocols
8508     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8509     if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8510       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8511       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8512       // This is rather dubious but matches gcc's behavior. If lhs has
8513       // no type qualifier and its class has no static protocol(s)
8514       // assume that it is mismatch.
8515       if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8516         return false;
8517       for (auto *lhsProto : LHSInheritedProtocols) {
8518         bool match = false;
8519         for (auto *rhsProto : rhs->quals()) {
8520           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8521               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8522             match = true;
8523             break;
8524           }
8525         }
8526         if (!match)
8527           return false;
8528       }
8529     }
8530     return true;
8531   }
8532   return false;
8533 }
8534
8535 /// canAssignObjCInterfaces - Return true if the two interface types are
8536 /// compatible for assignment from RHS to LHS.  This handles validation of any
8537 /// protocol qualifiers on the LHS or RHS.
8538 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8539                                          const ObjCObjectPointerType *RHSOPT) {
8540   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8541   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8542
8543   // If either type represents the built-in 'id' type, return true.
8544   if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8545     return true;
8546
8547   // Function object that propagates a successful result or handles
8548   // __kindof types.
8549   auto finish = [&](bool succeeded) -> bool {
8550     if (succeeded)
8551       return true;
8552
8553     if (!RHS->isKindOfType())
8554       return false;
8555
8556     // Strip off __kindof and protocol qualifiers, then check whether
8557     // we can assign the other way.
8558     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8559                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8560   };
8561
8562   // Casts from or to id<P> are allowed when the other side has compatible
8563   // protocols.
8564   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8565     return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8566   }
8567
8568   // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8569   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8570     return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8571   }
8572
8573   // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8574   if (LHS->isObjCClass() && RHS->isObjCClass()) {
8575     return true;
8576   }
8577
8578   // If we have 2 user-defined types, fall into that path.
8579   if (LHS->getInterface() && RHS->getInterface()) {
8580     return finish(canAssignObjCInterfaces(LHS, RHS));
8581   }
8582
8583   return false;
8584 }
8585
8586 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8587 /// for providing type-safety for objective-c pointers used to pass/return
8588 /// arguments in block literals. When passed as arguments, passing 'A*' where
8589 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8590 /// not OK. For the return type, the opposite is not OK.
8591 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8592                                          const ObjCObjectPointerType *LHSOPT,
8593                                          const ObjCObjectPointerType *RHSOPT,
8594                                          bool BlockReturnType) {
8595
8596   // Function object that propagates a successful result or handles
8597   // __kindof types.
8598   auto finish = [&](bool succeeded) -> bool {
8599     if (succeeded)
8600       return true;
8601
8602     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8603     if (!Expected->isKindOfType())
8604       return false;
8605
8606     // Strip off __kindof and protocol qualifiers, then check whether
8607     // we can assign the other way.
8608     return canAssignObjCInterfacesInBlockPointer(
8609              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8610              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8611              BlockReturnType);
8612   };
8613
8614   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8615     return true;
8616
8617   if (LHSOPT->isObjCBuiltinType()) {
8618     return finish(RHSOPT->isObjCBuiltinType() ||
8619                   RHSOPT->isObjCQualifiedIdType());
8620   }
8621
8622   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8623     if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8624       // Use for block parameters previous type checking for compatibility.
8625       return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8626                     // Or corrected type checking as in non-compat mode.
8627                     (!BlockReturnType &&
8628                      ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8629     else
8630       return finish(ObjCQualifiedIdTypesAreCompatible(
8631           (BlockReturnType ? LHSOPT : RHSOPT),
8632           (BlockReturnType ? RHSOPT : LHSOPT), false));
8633   }
8634
8635   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8636   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8637   if (LHS && RHS)  { // We have 2 user-defined types.
8638     if (LHS != RHS) {
8639       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8640         return finish(BlockReturnType);
8641       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8642         return finish(!BlockReturnType);
8643     }
8644     else
8645       return true;
8646   }
8647   return false;
8648 }
8649
8650 /// Comparison routine for Objective-C protocols to be used with
8651 /// llvm::array_pod_sort.
8652 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8653                                       ObjCProtocolDecl * const *rhs) {
8654   return (*lhs)->getName().compare((*rhs)->getName());
8655 }
8656
8657 /// getIntersectionOfProtocols - This routine finds the intersection of set
8658 /// of protocols inherited from two distinct objective-c pointer objects with
8659 /// the given common base.
8660 /// It is used to build composite qualifier list of the composite type of
8661 /// the conditional expression involving two objective-c pointer objects.
8662 static
8663 void getIntersectionOfProtocols(ASTContext &Context,
8664                                 const ObjCInterfaceDecl *CommonBase,
8665                                 const ObjCObjectPointerType *LHSOPT,
8666                                 const ObjCObjectPointerType *RHSOPT,
8667       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8668
8669   const ObjCObjectType* LHS = LHSOPT->getObjectType();
8670   const ObjCObjectType* RHS = RHSOPT->getObjectType();
8671   assert(LHS->getInterface() && "LHS must have an interface base");
8672   assert(RHS->getInterface() && "RHS must have an interface base");
8673
8674   // Add all of the protocols for the LHS.
8675   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8676
8677   // Start with the protocol qualifiers.
8678   for (auto proto : LHS->quals()) {
8679     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8680   }
8681
8682   // Also add the protocols associated with the LHS interface.
8683   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8684
8685   // Add all of the protocols for the RHS.
8686   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8687
8688   // Start with the protocol qualifiers.
8689   for (auto proto : RHS->quals()) {
8690     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8691   }
8692
8693   // Also add the protocols associated with the RHS interface.
8694   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8695
8696   // Compute the intersection of the collected protocol sets.
8697   for (auto proto : LHSProtocolSet) {
8698     if (RHSProtocolSet.count(proto))
8699       IntersectionSet.push_back(proto);
8700   }
8701
8702   // Compute the set of protocols that is implied by either the common type or
8703   // the protocols within the intersection.
8704   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8705   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8706
8707   // Remove any implied protocols from the list of inherited protocols.
8708   if (!ImpliedProtocols.empty()) {
8709     IntersectionSet.erase(
8710       std::remove_if(IntersectionSet.begin(),
8711                      IntersectionSet.end(),
8712                      [&](ObjCProtocolDecl *proto) -> bool {
8713                        return ImpliedProtocols.count(proto) > 0;
8714                      }),
8715       IntersectionSet.end());
8716   }
8717
8718   // Sort the remaining protocols by name.
8719   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8720                        compareObjCProtocolsByName);
8721 }
8722
8723 /// Determine whether the first type is a subtype of the second.
8724 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8725                                      QualType rhs) {
8726   // Common case: two object pointers.
8727   const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8728   const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8729   if (lhsOPT && rhsOPT)
8730     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8731
8732   // Two block pointers.
8733   const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8734   const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8735   if (lhsBlock && rhsBlock)
8736     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8737
8738   // If either is an unqualified 'id' and the other is a block, it's
8739   // acceptable.
8740   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8741       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8742     return true;
8743
8744   return false;
8745 }
8746
8747 // Check that the given Objective-C type argument lists are equivalent.
8748 static bool sameObjCTypeArgs(ASTContext &ctx,
8749                              const ObjCInterfaceDecl *iface,
8750                              ArrayRef<QualType> lhsArgs,
8751                              ArrayRef<QualType> rhsArgs,
8752                              bool stripKindOf) {
8753   if (lhsArgs.size() != rhsArgs.size())
8754     return false;
8755
8756   ObjCTypeParamList *typeParams = iface->getTypeParamList();
8757   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8758     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8759       continue;
8760
8761     switch (typeParams->begin()[i]->getVariance()) {
8762     case ObjCTypeParamVariance::Invariant:
8763       if (!stripKindOf ||
8764           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8765                            rhsArgs[i].stripObjCKindOfType(ctx))) {
8766         return false;
8767       }
8768       break;
8769
8770     case ObjCTypeParamVariance::Covariant:
8771       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8772         return false;
8773       break;
8774
8775     case ObjCTypeParamVariance::Contravariant:
8776       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8777         return false;
8778       break;
8779     }
8780   }
8781
8782   return true;
8783 }
8784
8785 QualType ASTContext::areCommonBaseCompatible(
8786            const ObjCObjectPointerType *Lptr,
8787            const ObjCObjectPointerType *Rptr) {
8788   const ObjCObjectType *LHS = Lptr->getObjectType();
8789   const ObjCObjectType *RHS = Rptr->getObjectType();
8790   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8791   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8792
8793   if (!LDecl || !RDecl)
8794     return {};
8795
8796   // When either LHS or RHS is a kindof type, we should return a kindof type.
8797   // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8798   // kindof(A).
8799   bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8800
8801   // Follow the left-hand side up the class hierarchy until we either hit a
8802   // root or find the RHS. Record the ancestors in case we don't find it.
8803   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8804     LHSAncestors;
8805   while (true) {
8806     // Record this ancestor. We'll need this if the common type isn't in the
8807     // path from the LHS to the root.
8808     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8809
8810     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8811       // Get the type arguments.
8812       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8813       bool anyChanges = false;
8814       if (LHS->isSpecialized() && RHS->isSpecialized()) {
8815         // Both have type arguments, compare them.
8816         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8817                               LHS->getTypeArgs(), RHS->getTypeArgs(),
8818                               /*stripKindOf=*/true))
8819           return {};
8820       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8821         // If only one has type arguments, the result will not have type
8822         // arguments.
8823         LHSTypeArgs = {};
8824         anyChanges = true;
8825       }
8826
8827       // Compute the intersection of protocols.
8828       SmallVector<ObjCProtocolDecl *, 8> Protocols;
8829       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8830                                  Protocols);
8831       if (!Protocols.empty())
8832         anyChanges = true;
8833
8834       // If anything in the LHS will have changed, build a new result type.
8835       // If we need to return a kindof type but LHS is not a kindof type, we
8836       // build a new result type.
8837       if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8838         QualType Result = getObjCInterfaceType(LHS->getInterface());
8839         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8840                                    anyKindOf || LHS->isKindOfType());
8841         return getObjCObjectPointerType(Result);
8842       }
8843
8844       return getObjCObjectPointerType(QualType(LHS, 0));
8845     }
8846
8847     // Find the superclass.
8848     QualType LHSSuperType = LHS->getSuperClassType();
8849     if (LHSSuperType.isNull())
8850       break;
8851
8852     LHS = LHSSuperType->castAs<ObjCObjectType>();
8853   }
8854
8855   // We didn't find anything by following the LHS to its root; now check
8856   // the RHS against the cached set of ancestors.
8857   while (true) {
8858     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8859     if (KnownLHS != LHSAncestors.end()) {
8860       LHS = KnownLHS->second;
8861
8862       // Get the type arguments.
8863       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8864       bool anyChanges = false;
8865       if (LHS->isSpecialized() && RHS->isSpecialized()) {
8866         // Both have type arguments, compare them.
8867         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8868                               LHS->getTypeArgs(), RHS->getTypeArgs(),
8869                               /*stripKindOf=*/true))
8870           return {};
8871       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8872         // If only one has type arguments, the result will not have type
8873         // arguments.
8874         RHSTypeArgs = {};
8875         anyChanges = true;
8876       }
8877
8878       // Compute the intersection of protocols.
8879       SmallVector<ObjCProtocolDecl *, 8> Protocols;
8880       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8881                                  Protocols);
8882       if (!Protocols.empty())
8883         anyChanges = true;
8884
8885       // If we need to return a kindof type but RHS is not a kindof type, we
8886       // build a new result type.
8887       if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8888         QualType Result = getObjCInterfaceType(RHS->getInterface());
8889         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8890                                    anyKindOf || RHS->isKindOfType());
8891         return getObjCObjectPointerType(Result);
8892       }
8893
8894       return getObjCObjectPointerType(QualType(RHS, 0));
8895     }
8896
8897     // Find the superclass of the RHS.
8898     QualType RHSSuperType = RHS->getSuperClassType();
8899     if (RHSSuperType.isNull())
8900       break;
8901
8902     RHS = RHSSuperType->castAs<ObjCObjectType>();
8903   }
8904
8905   return {};
8906 }
8907
8908 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8909                                          const ObjCObjectType *RHS) {
8910   assert(LHS->getInterface() && "LHS is not an interface type");
8911   assert(RHS->getInterface() && "RHS is not an interface type");
8912
8913   // Verify that the base decls are compatible: the RHS must be a subclass of
8914   // the LHS.
8915   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8916   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8917   if (!IsSuperClass)
8918     return false;
8919
8920   // If the LHS has protocol qualifiers, determine whether all of them are
8921   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8922   // LHS).
8923   if (LHS->getNumProtocols() > 0) {
8924     // OK if conversion of LHS to SuperClass results in narrowing of types
8925     // ; i.e., SuperClass may implement at least one of the protocols
8926     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8927     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8928     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8929     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8930     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8931     // qualifiers.
8932     for (auto *RHSPI : RHS->quals())
8933       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8934     // If there is no protocols associated with RHS, it is not a match.
8935     if (SuperClassInheritedProtocols.empty())
8936       return false;
8937
8938     for (const auto *LHSProto : LHS->quals()) {
8939       bool SuperImplementsProtocol = false;
8940       for (auto *SuperClassProto : SuperClassInheritedProtocols)
8941         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8942           SuperImplementsProtocol = true;
8943           break;
8944         }
8945       if (!SuperImplementsProtocol)
8946         return false;
8947     }
8948   }
8949
8950   // If the LHS is specialized, we may need to check type arguments.
8951   if (LHS->isSpecialized()) {
8952     // Follow the superclass chain until we've matched the LHS class in the
8953     // hierarchy. This substitutes type arguments through.
8954     const ObjCObjectType *RHSSuper = RHS;
8955     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8956       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8957
8958     // If the RHS is specializd, compare type arguments.
8959     if (RHSSuper->isSpecialized() &&
8960         !sameObjCTypeArgs(*this, LHS->getInterface(),
8961                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8962                           /*stripKindOf=*/true)) {
8963       return false;
8964     }
8965   }
8966
8967   return true;
8968 }
8969
8970 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8971   // get the "pointed to" types
8972   const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8973   const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8974
8975   if (!LHSOPT || !RHSOPT)
8976     return false;
8977
8978   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8979          canAssignObjCInterfaces(RHSOPT, LHSOPT);
8980 }
8981
8982 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8983   return canAssignObjCInterfaces(
8984       getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
8985       getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
8986 }
8987
8988 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8989 /// both shall have the identically qualified version of a compatible type.
8990 /// C99 6.2.7p1: Two types have compatible types if their types are the
8991 /// same. See 6.7.[2,3,5] for additional rules.
8992 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8993                                     bool CompareUnqualified) {
8994   if (getLangOpts().CPlusPlus)
8995     return hasSameType(LHS, RHS);
8996
8997   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
8998 }
8999
9000 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9001   return typesAreCompatible(LHS, RHS);
9002 }
9003
9004 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9005   return !mergeTypes(LHS, RHS, true).isNull();
9006 }
9007
9008 /// mergeTransparentUnionType - if T is a transparent union type and a member
9009 /// of T is compatible with SubType, return the merged type, else return
9010 /// QualType()
9011 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9012                                                bool OfBlockPointer,
9013                                                bool Unqualified) {
9014   if (const RecordType *UT = T->getAsUnionType()) {
9015     RecordDecl *UD = UT->getDecl();
9016     if (UD->hasAttr<TransparentUnionAttr>()) {
9017       for (const auto *I : UD->fields()) {
9018         QualType ET = I->getType().getUnqualifiedType();
9019         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9020         if (!MT.isNull())
9021           return MT;
9022       }
9023     }
9024   }
9025
9026   return {};
9027 }
9028
9029 /// mergeFunctionParameterTypes - merge two types which appear as function
9030 /// parameter types
9031 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9032                                                  bool OfBlockPointer,
9033                                                  bool Unqualified) {
9034   // GNU extension: two types are compatible if they appear as a function
9035   // argument, one of the types is a transparent union type and the other
9036   // type is compatible with a union member
9037   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9038                                               Unqualified);
9039   if (!lmerge.isNull())
9040     return lmerge;
9041
9042   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9043                                               Unqualified);
9044   if (!rmerge.isNull())
9045     return rmerge;
9046
9047   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9048 }
9049
9050 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9051                                         bool OfBlockPointer, bool Unqualified,
9052                                         bool AllowCXX) {
9053   const auto *lbase = lhs->castAs<FunctionType>();
9054   const auto *rbase = rhs->castAs<FunctionType>();
9055   const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9056   const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9057   bool allLTypes = true;
9058   bool allRTypes = true;
9059
9060   // Check return type
9061   QualType retType;
9062   if (OfBlockPointer) {
9063     QualType RHS = rbase->getReturnType();
9064     QualType LHS = lbase->getReturnType();
9065     bool UnqualifiedResult = Unqualified;
9066     if (!UnqualifiedResult)
9067       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9068     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9069   }
9070   else
9071     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9072                          Unqualified);
9073   if (retType.isNull())
9074     return {};
9075
9076   if (Unqualified)
9077     retType = retType.getUnqualifiedType();
9078
9079   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9080   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9081   if (Unqualified) {
9082     LRetType = LRetType.getUnqualifiedType();
9083     RRetType = RRetType.getUnqualifiedType();
9084   }
9085
9086   if (getCanonicalType(retType) != LRetType)
9087     allLTypes = false;
9088   if (getCanonicalType(retType) != RRetType)
9089     allRTypes = false;
9090
9091   // FIXME: double check this
9092   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9093   //                           rbase->getRegParmAttr() != 0 &&
9094   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9095   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9096   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9097
9098   // Compatible functions must have compatible calling conventions
9099   if (lbaseInfo.getCC() != rbaseInfo.getCC())
9100     return {};
9101
9102   // Regparm is part of the calling convention.
9103   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9104     return {};
9105   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9106     return {};
9107
9108   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9109     return {};
9110   if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9111     return {};
9112   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9113     return {};
9114
9115   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9116   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9117
9118   if (lbaseInfo.getNoReturn() != NoReturn)
9119     allLTypes = false;
9120   if (rbaseInfo.getNoReturn() != NoReturn)
9121     allRTypes = false;
9122
9123   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9124
9125   if (lproto && rproto) { // two C99 style function prototypes
9126     assert((AllowCXX ||
9127             (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9128            "C++ shouldn't be here");
9129     // Compatible functions must have the same number of parameters
9130     if (lproto->getNumParams() != rproto->getNumParams())
9131       return {};
9132
9133     // Variadic and non-variadic functions aren't compatible
9134     if (lproto->isVariadic() != rproto->isVariadic())
9135       return {};
9136
9137     if (lproto->getMethodQuals() != rproto->getMethodQuals())
9138       return {};
9139
9140     SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9141     bool canUseLeft, canUseRight;
9142     if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9143                                newParamInfos))
9144       return {};
9145
9146     if (!canUseLeft)
9147       allLTypes = false;
9148     if (!canUseRight)
9149       allRTypes = false;
9150
9151     // Check parameter type compatibility
9152     SmallVector<QualType, 10> types;
9153     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9154       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9155       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9156       QualType paramType = mergeFunctionParameterTypes(
9157           lParamType, rParamType, OfBlockPointer, Unqualified);
9158       if (paramType.isNull())
9159         return {};
9160
9161       if (Unqualified)
9162         paramType = paramType.getUnqualifiedType();
9163
9164       types.push_back(paramType);
9165       if (Unqualified) {
9166         lParamType = lParamType.getUnqualifiedType();
9167         rParamType = rParamType.getUnqualifiedType();
9168       }
9169
9170       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9171         allLTypes = false;
9172       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9173         allRTypes = false;
9174     }
9175
9176     if (allLTypes) return lhs;
9177     if (allRTypes) return rhs;
9178
9179     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9180     EPI.ExtInfo = einfo;
9181     EPI.ExtParameterInfos =
9182         newParamInfos.empty() ? nullptr : newParamInfos.data();
9183     return getFunctionType(retType, types, EPI);
9184   }
9185
9186   if (lproto) allRTypes = false;
9187   if (rproto) allLTypes = false;
9188
9189   const FunctionProtoType *proto = lproto ? lproto : rproto;
9190   if (proto) {
9191     assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9192     if (proto->isVariadic())
9193       return {};
9194     // Check that the types are compatible with the types that
9195     // would result from default argument promotions (C99 6.7.5.3p15).
9196     // The only types actually affected are promotable integer
9197     // types and floats, which would be passed as a different
9198     // type depending on whether the prototype is visible.
9199     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9200       QualType paramTy = proto->getParamType(i);
9201
9202       // Look at the converted type of enum types, since that is the type used
9203       // to pass enum values.
9204       if (const auto *Enum = paramTy->getAs<EnumType>()) {
9205         paramTy = Enum->getDecl()->getIntegerType();
9206         if (paramTy.isNull())
9207           return {};
9208       }
9209
9210       if (paramTy->isPromotableIntegerType() ||
9211           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9212         return {};
9213     }
9214
9215     if (allLTypes) return lhs;
9216     if (allRTypes) return rhs;
9217
9218     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9219     EPI.ExtInfo = einfo;
9220     return getFunctionType(retType, proto->getParamTypes(), EPI);
9221   }
9222
9223   if (allLTypes) return lhs;
9224   if (allRTypes) return rhs;
9225   return getFunctionNoProtoType(retType, einfo);
9226 }
9227
9228 /// Given that we have an enum type and a non-enum type, try to merge them.
9229 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9230                                      QualType other, bool isBlockReturnType) {
9231   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9232   // a signed integer type, or an unsigned integer type.
9233   // Compatibility is based on the underlying type, not the promotion
9234   // type.
9235   QualType underlyingType = ET->getDecl()->getIntegerType();
9236   if (underlyingType.isNull())
9237     return {};
9238   if (Context.hasSameType(underlyingType, other))
9239     return other;
9240
9241   // In block return types, we're more permissive and accept any
9242   // integral type of the same size.
9243   if (isBlockReturnType && other->isIntegerType() &&
9244       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9245     return other;
9246
9247   return {};
9248 }
9249
9250 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9251                                 bool OfBlockPointer,
9252                                 bool Unqualified, bool BlockReturnType) {
9253   // C++ [expr]: If an expression initially has the type "reference to T", the
9254   // type is adjusted to "T" prior to any further analysis, the expression
9255   // designates the object or function denoted by the reference, and the
9256   // expression is an lvalue unless the reference is an rvalue reference and
9257   // the expression is a function call (possibly inside parentheses).
9258   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
9259   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
9260
9261   if (Unqualified) {
9262     LHS = LHS.getUnqualifiedType();
9263     RHS = RHS.getUnqualifiedType();
9264   }
9265
9266   QualType LHSCan = getCanonicalType(LHS),
9267            RHSCan = getCanonicalType(RHS);
9268
9269   // If two types are identical, they are compatible.
9270   if (LHSCan == RHSCan)
9271     return LHS;
9272
9273   // If the qualifiers are different, the types aren't compatible... mostly.
9274   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9275   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9276   if (LQuals != RQuals) {
9277     // If any of these qualifiers are different, we have a type
9278     // mismatch.
9279     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9280         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9281         LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9282         LQuals.hasUnaligned() != RQuals.hasUnaligned())
9283       return {};
9284
9285     // Exactly one GC qualifier difference is allowed: __strong is
9286     // okay if the other type has no GC qualifier but is an Objective
9287     // C object pointer (i.e. implicitly strong by default).  We fix
9288     // this by pretending that the unqualified type was actually
9289     // qualified __strong.
9290     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9291     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9292     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9293
9294     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9295       return {};
9296
9297     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9298       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9299     }
9300     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9301       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9302     }
9303     return {};
9304   }
9305
9306   // Okay, qualifiers are equal.
9307
9308   Type::TypeClass LHSClass = LHSCan->getTypeClass();
9309   Type::TypeClass RHSClass = RHSCan->getTypeClass();
9310
9311   // We want to consider the two function types to be the same for these
9312   // comparisons, just force one to the other.
9313   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9314   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9315
9316   // Same as above for arrays
9317   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9318     LHSClass = Type::ConstantArray;
9319   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9320     RHSClass = Type::ConstantArray;
9321
9322   // ObjCInterfaces are just specialized ObjCObjects.
9323   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9324   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9325
9326   // Canonicalize ExtVector -> Vector.
9327   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9328   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9329
9330   // If the canonical type classes don't match.
9331   if (LHSClass != RHSClass) {
9332     // Note that we only have special rules for turning block enum
9333     // returns into block int returns, not vice-versa.
9334     if (const auto *ETy = LHS->getAs<EnumType>()) {
9335       return mergeEnumWithInteger(*this, ETy, RHS, false);
9336     }
9337     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9338       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9339     }
9340     // allow block pointer type to match an 'id' type.
9341     if (OfBlockPointer && !BlockReturnType) {
9342        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9343          return LHS;
9344       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9345         return RHS;
9346     }
9347
9348     return {};
9349   }
9350
9351   // The canonical type classes match.
9352   switch (LHSClass) {
9353 #define TYPE(Class, Base)
9354 #define ABSTRACT_TYPE(Class, Base)
9355 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9356 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9357 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9358 #include "clang/AST/TypeNodes.inc"
9359     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9360
9361   case Type::Auto:
9362   case Type::DeducedTemplateSpecialization:
9363   case Type::LValueReference:
9364   case Type::RValueReference:
9365   case Type::MemberPointer:
9366     llvm_unreachable("C++ should never be in mergeTypes");
9367
9368   case Type::ObjCInterface:
9369   case Type::IncompleteArray:
9370   case Type::VariableArray:
9371   case Type::FunctionProto:
9372   case Type::ExtVector:
9373     llvm_unreachable("Types are eliminated above");
9374
9375   case Type::Pointer:
9376   {
9377     // Merge two pointer types, while trying to preserve typedef info
9378     QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9379     QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9380     if (Unqualified) {
9381       LHSPointee = LHSPointee.getUnqualifiedType();
9382       RHSPointee = RHSPointee.getUnqualifiedType();
9383     }
9384     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9385                                      Unqualified);
9386     if (ResultType.isNull())
9387       return {};
9388     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9389       return LHS;
9390     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9391       return RHS;
9392     return getPointerType(ResultType);
9393   }
9394   case Type::BlockPointer:
9395   {
9396     // Merge two block pointer types, while trying to preserve typedef info
9397     QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9398     QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9399     if (Unqualified) {
9400       LHSPointee = LHSPointee.getUnqualifiedType();
9401       RHSPointee = RHSPointee.getUnqualifiedType();
9402     }
9403     if (getLangOpts().OpenCL) {
9404       Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9405       Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9406       // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9407       // 6.12.5) thus the following check is asymmetric.
9408       if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9409         return {};
9410       LHSPteeQual.removeAddressSpace();
9411       RHSPteeQual.removeAddressSpace();
9412       LHSPointee =
9413           QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9414       RHSPointee =
9415           QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9416     }
9417     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9418                                      Unqualified);
9419     if (ResultType.isNull())
9420       return {};
9421     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9422       return LHS;
9423     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9424       return RHS;
9425     return getBlockPointerType(ResultType);
9426   }
9427   case Type::Atomic:
9428   {
9429     // Merge two pointer types, while trying to preserve typedef info
9430     QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9431     QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9432     if (Unqualified) {
9433       LHSValue = LHSValue.getUnqualifiedType();
9434       RHSValue = RHSValue.getUnqualifiedType();
9435     }
9436     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9437                                      Unqualified);
9438     if (ResultType.isNull())
9439       return {};
9440     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9441       return LHS;
9442     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9443       return RHS;
9444     return getAtomicType(ResultType);
9445   }
9446   case Type::ConstantArray:
9447   {
9448     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9449     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9450     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9451       return {};
9452
9453     QualType LHSElem = getAsArrayType(LHS)->getElementType();
9454     QualType RHSElem = getAsArrayType(RHS)->getElementType();
9455     if (Unqualified) {
9456       LHSElem = LHSElem.getUnqualifiedType();
9457       RHSElem = RHSElem.getUnqualifiedType();
9458     }
9459
9460     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9461     if (ResultType.isNull())
9462       return {};
9463
9464     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9465     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9466
9467     // If either side is a variable array, and both are complete, check whether
9468     // the current dimension is definite.
9469     if (LVAT || RVAT) {
9470       auto SizeFetch = [this](const VariableArrayType* VAT,
9471           const ConstantArrayType* CAT)
9472           -> std::pair<bool,llvm::APInt> {
9473         if (VAT) {
9474           llvm::APSInt TheInt;
9475           Expr *E = VAT->getSizeExpr();
9476           if (E && E->isIntegerConstantExpr(TheInt, *this))
9477             return std::make_pair(true, TheInt);
9478           else
9479             return std::make_pair(false, TheInt);
9480         } else if (CAT) {
9481             return std::make_pair(true, CAT->getSize());
9482         } else {
9483             return std::make_pair(false, llvm::APInt());
9484         }
9485       };
9486
9487       bool HaveLSize, HaveRSize;
9488       llvm::APInt LSize, RSize;
9489       std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9490       std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9491       if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9492         return {}; // Definite, but unequal, array dimension
9493     }
9494
9495     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9496       return LHS;
9497     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9498       return RHS;
9499     if (LCAT)
9500       return getConstantArrayType(ResultType, LCAT->getSize(),
9501                                   LCAT->getSizeExpr(),
9502                                   ArrayType::ArraySizeModifier(), 0);
9503     if (RCAT)
9504       return getConstantArrayType(ResultType, RCAT->getSize(),
9505                                   RCAT->getSizeExpr(),
9506                                   ArrayType::ArraySizeModifier(), 0);
9507     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9508       return LHS;
9509     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9510       return RHS;
9511     if (LVAT) {
9512       // FIXME: This isn't correct! But tricky to implement because
9513       // the array's size has to be the size of LHS, but the type
9514       // has to be different.
9515       return LHS;
9516     }
9517     if (RVAT) {
9518       // FIXME: This isn't correct! But tricky to implement because
9519       // the array's size has to be the size of RHS, but the type
9520       // has to be different.
9521       return RHS;
9522     }
9523     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9524     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9525     return getIncompleteArrayType(ResultType,
9526                                   ArrayType::ArraySizeModifier(), 0);
9527   }
9528   case Type::FunctionNoProto:
9529     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9530   case Type::Record:
9531   case Type::Enum:
9532     return {};
9533   case Type::Builtin:
9534     // Only exactly equal builtin types are compatible, which is tested above.
9535     return {};
9536   case Type::Complex:
9537     // Distinct complex types are incompatible.
9538     return {};
9539   case Type::Vector:
9540     // FIXME: The merged type should be an ExtVector!
9541     if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9542                              RHSCan->castAs<VectorType>()))
9543       return LHS;
9544     return {};
9545   case Type::ConstantMatrix:
9546     if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9547                              RHSCan->castAs<ConstantMatrixType>()))
9548       return LHS;
9549     return {};
9550   case Type::ObjCObject: {
9551     // Check if the types are assignment compatible.
9552     // FIXME: This should be type compatibility, e.g. whether
9553     // "LHS x; RHS x;" at global scope is legal.
9554     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9555                                 RHS->castAs<ObjCObjectType>()))
9556       return LHS;
9557     return {};
9558   }
9559   case Type::ObjCObjectPointer:
9560     if (OfBlockPointer) {
9561       if (canAssignObjCInterfacesInBlockPointer(
9562               LHS->castAs<ObjCObjectPointerType>(),
9563               RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9564         return LHS;
9565       return {};
9566     }
9567     if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9568                                 RHS->castAs<ObjCObjectPointerType>()))
9569       return LHS;
9570     return {};
9571   case Type::Pipe:
9572     assert(LHS != RHS &&
9573            "Equivalent pipe types should have already been handled!");
9574     return {};
9575   case Type::ExtInt: {
9576     // Merge two ext-int types, while trying to preserve typedef info.
9577     bool LHSUnsigned  = LHS->castAs<ExtIntType>()->isUnsigned();
9578     bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9579     unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9580     unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9581
9582     // Like unsigned/int, shouldn't have a type if they dont match.
9583     if (LHSUnsigned != RHSUnsigned)
9584       return {};
9585
9586     if (LHSBits != RHSBits)
9587       return {};
9588     return LHS;
9589   }
9590   }
9591
9592   llvm_unreachable("Invalid Type::Class!");
9593 }
9594
9595 bool ASTContext::mergeExtParameterInfo(
9596     const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9597     bool &CanUseFirst, bool &CanUseSecond,
9598     SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9599   assert(NewParamInfos.empty() && "param info list not empty");
9600   CanUseFirst = CanUseSecond = true;
9601   bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9602   bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9603
9604   // Fast path: if the first type doesn't have ext parameter infos,
9605   // we match if and only if the second type also doesn't have them.
9606   if (!FirstHasInfo && !SecondHasInfo)
9607     return true;
9608
9609   bool NeedParamInfo = false;
9610   size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9611                           : SecondFnType->getExtParameterInfos().size();
9612
9613   for (size_t I = 0; I < E; ++I) {
9614     FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9615     if (FirstHasInfo)
9616       FirstParam = FirstFnType->getExtParameterInfo(I);
9617     if (SecondHasInfo)
9618       SecondParam = SecondFnType->getExtParameterInfo(I);
9619
9620     // Cannot merge unless everything except the noescape flag matches.
9621     if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9622       return false;
9623
9624     bool FirstNoEscape = FirstParam.isNoEscape();
9625     bool SecondNoEscape = SecondParam.isNoEscape();
9626     bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9627     NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9628     if (NewParamInfos.back().getOpaqueValue())
9629       NeedParamInfo = true;
9630     if (FirstNoEscape != IsNoEscape)
9631       CanUseFirst = false;
9632     if (SecondNoEscape != IsNoEscape)
9633       CanUseSecond = false;
9634   }
9635
9636   if (!NeedParamInfo)
9637     NewParamInfos.clear();
9638
9639   return true;
9640 }
9641
9642 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9643   ObjCLayouts[CD] = nullptr;
9644 }
9645
9646 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9647 /// 'RHS' attributes and returns the merged version; including for function
9648 /// return types.
9649 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9650   QualType LHSCan = getCanonicalType(LHS),
9651   RHSCan = getCanonicalType(RHS);
9652   // If two types are identical, they are compatible.
9653   if (LHSCan == RHSCan)
9654     return LHS;
9655   if (RHSCan->isFunctionType()) {
9656     if (!LHSCan->isFunctionType())
9657       return {};
9658     QualType OldReturnType =
9659         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9660     QualType NewReturnType =
9661         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9662     QualType ResReturnType =
9663       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9664     if (ResReturnType.isNull())
9665       return {};
9666     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9667       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9668       // In either case, use OldReturnType to build the new function type.
9669       const auto *F = LHS->castAs<FunctionType>();
9670       if (const auto *FPT = cast<FunctionProtoType>(F)) {
9671         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9672         EPI.ExtInfo = getFunctionExtInfo(LHS);
9673         QualType ResultType =
9674             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9675         return ResultType;
9676       }
9677     }
9678     return {};
9679   }
9680
9681   // If the qualifiers are different, the types can still be merged.
9682   Qualifiers LQuals = LHSCan.getLocalQualifiers();
9683   Qualifiers RQuals = RHSCan.getLocalQualifiers();
9684   if (LQuals != RQuals) {
9685     // If any of these qualifiers are different, we have a type mismatch.
9686     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9687         LQuals.getAddressSpace() != RQuals.getAddressSpace())
9688       return {};
9689
9690     // Exactly one GC qualifier difference is allowed: __strong is
9691     // okay if the other type has no GC qualifier but is an Objective
9692     // C object pointer (i.e. implicitly strong by default).  We fix
9693     // this by pretending that the unqualified type was actually
9694     // qualified __strong.
9695     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9696     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9697     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9698
9699     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9700       return {};
9701
9702     if (GC_L == Qualifiers::Strong)
9703       return LHS;
9704     if (GC_R == Qualifiers::Strong)
9705       return RHS;
9706     return {};
9707   }
9708
9709   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9710     QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9711     QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9712     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9713     if (ResQT == LHSBaseQT)
9714       return LHS;
9715     if (ResQT == RHSBaseQT)
9716       return RHS;
9717   }
9718   return {};
9719 }
9720
9721 //===----------------------------------------------------------------------===//
9722 //                         Integer Predicates
9723 //===----------------------------------------------------------------------===//
9724
9725 unsigned ASTContext::getIntWidth(QualType T) const {
9726   if (const auto *ET = T->getAs<EnumType>())
9727     T = ET->getDecl()->getIntegerType();
9728   if (T->isBooleanType())
9729     return 1;
9730   if(const auto *EIT = T->getAs<ExtIntType>())
9731     return EIT->getNumBits();
9732   // For builtin types, just use the standard type sizing method
9733   return (unsigned)getTypeSize(T);
9734 }
9735
9736 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
9737   assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9738          "Unexpected type");
9739
9740   // Turn <4 x signed int> -> <4 x unsigned int>
9741   if (const auto *VTy = T->getAs<VectorType>())
9742     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9743                          VTy->getNumElements(), VTy->getVectorKind());
9744
9745   // For enums, we return the unsigned version of the base type.
9746   if (const auto *ETy = T->getAs<EnumType>())
9747     T = ETy->getDecl()->getIntegerType();
9748
9749   switch (T->castAs<BuiltinType>()->getKind()) {
9750   case BuiltinType::Char_S:
9751   case BuiltinType::SChar:
9752     return UnsignedCharTy;
9753   case BuiltinType::Short:
9754     return UnsignedShortTy;
9755   case BuiltinType::Int:
9756     return UnsignedIntTy;
9757   case BuiltinType::Long:
9758     return UnsignedLongTy;
9759   case BuiltinType::LongLong:
9760     return UnsignedLongLongTy;
9761   case BuiltinType::Int128:
9762     return UnsignedInt128Ty;
9763
9764   case BuiltinType::ShortAccum:
9765     return UnsignedShortAccumTy;
9766   case BuiltinType::Accum:
9767     return UnsignedAccumTy;
9768   case BuiltinType::LongAccum:
9769     return UnsignedLongAccumTy;
9770   case BuiltinType::SatShortAccum:
9771     return SatUnsignedShortAccumTy;
9772   case BuiltinType::SatAccum:
9773     return SatUnsignedAccumTy;
9774   case BuiltinType::SatLongAccum:
9775     return SatUnsignedLongAccumTy;
9776   case BuiltinType::ShortFract:
9777     return UnsignedShortFractTy;
9778   case BuiltinType::Fract:
9779     return UnsignedFractTy;
9780   case BuiltinType::LongFract:
9781     return UnsignedLongFractTy;
9782   case BuiltinType::SatShortFract:
9783     return SatUnsignedShortFractTy;
9784   case BuiltinType::SatFract:
9785     return SatUnsignedFractTy;
9786   case BuiltinType::SatLongFract:
9787     return SatUnsignedLongFractTy;
9788   default:
9789     llvm_unreachable("Unexpected signed integer or fixed point type");
9790   }
9791 }
9792
9793 ASTMutationListener::~ASTMutationListener() = default;
9794
9795 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9796                                             QualType ReturnType) {}
9797
9798 //===----------------------------------------------------------------------===//
9799 //                          Builtin Type Computation
9800 //===----------------------------------------------------------------------===//
9801
9802 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9803 /// pointer over the consumed characters.  This returns the resultant type.  If
9804 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9805 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
9806 /// a vector of "i*".
9807 ///
9808 /// RequiresICE is filled in on return to indicate whether the value is required
9809 /// to be an Integer Constant Expression.
9810 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9811                                   ASTContext::GetBuiltinTypeError &Error,
9812                                   bool &RequiresICE,
9813                                   bool AllowTypeModifiers) {
9814   // Modifiers.
9815   int HowLong = 0;
9816   bool Signed = false, Unsigned = false;
9817   RequiresICE = false;
9818
9819   // Read the prefixed modifiers first.
9820   bool Done = false;
9821   #ifndef NDEBUG
9822   bool IsSpecial = false;
9823   #endif
9824   while (!Done) {
9825     switch (*Str++) {
9826     default: Done = true; --Str; break;
9827     case 'I':
9828       RequiresICE = true;
9829       break;
9830     case 'S':
9831       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9832       assert(!Signed && "Can't use 'S' modifier multiple times!");
9833       Signed = true;
9834       break;
9835     case 'U':
9836       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9837       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9838       Unsigned = true;
9839       break;
9840     case 'L':
9841       assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9842       assert(HowLong <= 2 && "Can't have LLLL modifier");
9843       ++HowLong;
9844       break;
9845     case 'N':
9846       // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9847       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9848       assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9849       #ifndef NDEBUG
9850       IsSpecial = true;
9851       #endif
9852       if (Context.getTargetInfo().getLongWidth() == 32)
9853         ++HowLong;
9854       break;
9855     case 'W':
9856       // This modifier represents int64 type.
9857       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9858       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9859       #ifndef NDEBUG
9860       IsSpecial = true;
9861       #endif
9862       switch (Context.getTargetInfo().getInt64Type()) {
9863       default:
9864         llvm_unreachable("Unexpected integer type");
9865       case TargetInfo::SignedLong:
9866         HowLong = 1;
9867         break;
9868       case TargetInfo::SignedLongLong:
9869         HowLong = 2;
9870         break;
9871       }
9872       break;
9873     case 'Z':
9874       // This modifier represents int32 type.
9875       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9876       assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9877       #ifndef NDEBUG
9878       IsSpecial = true;
9879       #endif
9880       switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9881       default:
9882         llvm_unreachable("Unexpected integer type");
9883       case TargetInfo::SignedInt:
9884         HowLong = 0;
9885         break;
9886       case TargetInfo::SignedLong:
9887         HowLong = 1;
9888         break;
9889       case TargetInfo::SignedLongLong:
9890         HowLong = 2;
9891         break;
9892       }
9893       break;
9894     case 'O':
9895       assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9896       assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9897       #ifndef NDEBUG
9898       IsSpecial = true;
9899       #endif
9900       if (Context.getLangOpts().OpenCL)
9901         HowLong = 1;
9902       else
9903         HowLong = 2;
9904       break;
9905     }
9906   }
9907
9908   QualType Type;
9909
9910   // Read the base type.
9911   switch (*Str++) {
9912   default: llvm_unreachable("Unknown builtin type letter!");
9913   case 'y':
9914     assert(HowLong == 0 && !Signed && !Unsigned &&
9915            "Bad modifiers used with 'y'!");
9916     Type = Context.BFloat16Ty;
9917     break;
9918   case 'v':
9919     assert(HowLong == 0 && !Signed && !Unsigned &&
9920            "Bad modifiers used with 'v'!");
9921     Type = Context.VoidTy;
9922     break;
9923   case 'h':
9924     assert(HowLong == 0 && !Signed && !Unsigned &&
9925            "Bad modifiers used with 'h'!");
9926     Type = Context.HalfTy;
9927     break;
9928   case 'f':
9929     assert(HowLong == 0 && !Signed && !Unsigned &&
9930            "Bad modifiers used with 'f'!");
9931     Type = Context.FloatTy;
9932     break;
9933   case 'd':
9934     assert(HowLong < 3 && !Signed && !Unsigned &&
9935            "Bad modifiers used with 'd'!");
9936     if (HowLong == 1)
9937       Type = Context.LongDoubleTy;
9938     else if (HowLong == 2)
9939       Type = Context.Float128Ty;
9940     else
9941       Type = Context.DoubleTy;
9942     break;
9943   case 's':
9944     assert(HowLong == 0 && "Bad modifiers used with 's'!");
9945     if (Unsigned)
9946       Type = Context.UnsignedShortTy;
9947     else
9948       Type = Context.ShortTy;
9949     break;
9950   case 'i':
9951     if (HowLong == 3)
9952       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9953     else if (HowLong == 2)
9954       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9955     else if (HowLong == 1)
9956       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9957     else
9958       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9959     break;
9960   case 'c':
9961     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9962     if (Signed)
9963       Type = Context.SignedCharTy;
9964     else if (Unsigned)
9965       Type = Context.UnsignedCharTy;
9966     else
9967       Type = Context.CharTy;
9968     break;
9969   case 'b': // boolean
9970     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9971     Type = Context.BoolTy;
9972     break;
9973   case 'z':  // size_t.
9974     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9975     Type = Context.getSizeType();
9976     break;
9977   case 'w':  // wchar_t.
9978     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9979     Type = Context.getWideCharType();
9980     break;
9981   case 'F':
9982     Type = Context.getCFConstantStringType();
9983     break;
9984   case 'G':
9985     Type = Context.getObjCIdType();
9986     break;
9987   case 'H':
9988     Type = Context.getObjCSelType();
9989     break;
9990   case 'M':
9991     Type = Context.getObjCSuperType();
9992     break;
9993   case 'a':
9994     Type = Context.getBuiltinVaListType();
9995     assert(!Type.isNull() && "builtin va list type not initialized!");
9996     break;
9997   case 'A':
9998     // This is a "reference" to a va_list; however, what exactly
9999     // this means depends on how va_list is defined. There are two
10000     // different kinds of va_list: ones passed by value, and ones
10001     // passed by reference.  An example of a by-value va_list is
10002     // x86, where va_list is a char*. An example of by-ref va_list
10003     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10004     // we want this argument to be a char*&; for x86-64, we want
10005     // it to be a __va_list_tag*.
10006     Type = Context.getBuiltinVaListType();
10007     assert(!Type.isNull() && "builtin va list type not initialized!");
10008     if (Type->isArrayType())
10009       Type = Context.getArrayDecayedType(Type);
10010     else
10011       Type = Context.getLValueReferenceType(Type);
10012     break;
10013   case 'q': {
10014     char *End;
10015     unsigned NumElements = strtoul(Str, &End, 10);
10016     assert(End != Str && "Missing vector size");
10017     Str = End;
10018
10019     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10020                                              RequiresICE, false);
10021     assert(!RequiresICE && "Can't require vector ICE");
10022
10023     Type = Context.getScalableVectorType(ElementType, NumElements);
10024     break;
10025   }
10026   case 'V': {
10027     char *End;
10028     unsigned NumElements = strtoul(Str, &End, 10);
10029     assert(End != Str && "Missing vector size");
10030     Str = End;
10031
10032     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10033                                              RequiresICE, false);
10034     assert(!RequiresICE && "Can't require vector ICE");
10035
10036     // TODO: No way to make AltiVec vectors in builtins yet.
10037     Type = Context.getVectorType(ElementType, NumElements,
10038                                  VectorType::GenericVector);
10039     break;
10040   }
10041   case 'E': {
10042     char *End;
10043
10044     unsigned NumElements = strtoul(Str, &End, 10);
10045     assert(End != Str && "Missing vector size");
10046
10047     Str = End;
10048
10049     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10050                                              false);
10051     Type = Context.getExtVectorType(ElementType, NumElements);
10052     break;
10053   }
10054   case 'X': {
10055     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10056                                              false);
10057     assert(!RequiresICE && "Can't require complex ICE");
10058     Type = Context.getComplexType(ElementType);
10059     break;
10060   }
10061   case 'Y':
10062     Type = Context.getPointerDiffType();
10063     break;
10064   case 'P':
10065     Type = Context.getFILEType();
10066     if (Type.isNull()) {
10067       Error = ASTContext::GE_Missing_stdio;
10068       return {};
10069     }
10070     break;
10071   case 'J':
10072     if (Signed)
10073       Type = Context.getsigjmp_bufType();
10074     else
10075       Type = Context.getjmp_bufType();
10076
10077     if (Type.isNull()) {
10078       Error = ASTContext::GE_Missing_setjmp;
10079       return {};
10080     }
10081     break;
10082   case 'K':
10083     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10084     Type = Context.getucontext_tType();
10085
10086     if (Type.isNull()) {
10087       Error = ASTContext::GE_Missing_ucontext;
10088       return {};
10089     }
10090     break;
10091   case 'p':
10092     Type = Context.getProcessIDType();
10093     break;
10094   }
10095
10096   // If there are modifiers and if we're allowed to parse them, go for it.
10097   Done = !AllowTypeModifiers;
10098   while (!Done) {
10099     switch (char c = *Str++) {
10100     default: Done = true; --Str; break;
10101     case '*':
10102     case '&': {
10103       // Both pointers and references can have their pointee types
10104       // qualified with an address space.
10105       char *End;
10106       unsigned AddrSpace = strtoul(Str, &End, 10);
10107       if (End != Str) {
10108         // Note AddrSpace == 0 is not the same as an unspecified address space.
10109         Type = Context.getAddrSpaceQualType(
10110           Type,
10111           Context.getLangASForBuiltinAddressSpace(AddrSpace));
10112         Str = End;
10113       }
10114       if (c == '*')
10115         Type = Context.getPointerType(Type);
10116       else
10117         Type = Context.getLValueReferenceType(Type);
10118       break;
10119     }
10120     // FIXME: There's no way to have a built-in with an rvalue ref arg.
10121     case 'C':
10122       Type = Type.withConst();
10123       break;
10124     case 'D':
10125       Type = Context.getVolatileType(Type);
10126       break;
10127     case 'R':
10128       Type = Type.withRestrict();
10129       break;
10130     }
10131   }
10132
10133   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10134          "Integer constant 'I' type must be an integer");
10135
10136   return Type;
10137 }
10138
10139 /// GetBuiltinType - Return the type for the specified builtin.
10140 QualType ASTContext::GetBuiltinType(unsigned Id,
10141                                     GetBuiltinTypeError &Error,
10142                                     unsigned *IntegerConstantArgs) const {
10143   const char *TypeStr = BuiltinInfo.getTypeString(Id);
10144   if (TypeStr[0] == '\0') {
10145     Error = GE_Missing_type;
10146     return {};
10147   }
10148
10149   SmallVector<QualType, 8> ArgTypes;
10150
10151   bool RequiresICE = false;
10152   Error = GE_None;
10153   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10154                                        RequiresICE, true);
10155   if (Error != GE_None)
10156     return {};
10157
10158   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10159
10160   while (TypeStr[0] && TypeStr[0] != '.') {
10161     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10162     if (Error != GE_None)
10163       return {};
10164
10165     // If this argument is required to be an IntegerConstantExpression and the
10166     // caller cares, fill in the bitmask we return.
10167     if (RequiresICE && IntegerConstantArgs)
10168       *IntegerConstantArgs |= 1 << ArgTypes.size();
10169
10170     // Do array -> pointer decay.  The builtin should use the decayed type.
10171     if (Ty->isArrayType())
10172       Ty = getArrayDecayedType(Ty);
10173
10174     ArgTypes.push_back(Ty);
10175   }
10176
10177   if (Id == Builtin::BI__GetExceptionInfo)
10178     return {};
10179
10180   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10181          "'.' should only occur at end of builtin type list!");
10182
10183   bool Variadic = (TypeStr[0] == '.');
10184
10185   FunctionType::ExtInfo EI(getDefaultCallingConvention(
10186       Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10187   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10188
10189
10190   // We really shouldn't be making a no-proto type here.
10191   if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10192     return getFunctionNoProtoType(ResType, EI);
10193
10194   FunctionProtoType::ExtProtoInfo EPI;
10195   EPI.ExtInfo = EI;
10196   EPI.Variadic = Variadic;
10197   if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10198     EPI.ExceptionSpec.Type =
10199         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10200
10201   return getFunctionType(ResType, ArgTypes, EPI);
10202 }
10203
10204 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10205                                              const FunctionDecl *FD) {
10206   if (!FD->isExternallyVisible())
10207     return GVA_Internal;
10208
10209   // Non-user-provided functions get emitted as weak definitions with every
10210   // use, no matter whether they've been explicitly instantiated etc.
10211   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10212     if (!MD->isUserProvided())
10213       return GVA_DiscardableODR;
10214
10215   GVALinkage External;
10216   switch (FD->getTemplateSpecializationKind()) {
10217   case TSK_Undeclared:
10218   case TSK_ExplicitSpecialization:
10219     External = GVA_StrongExternal;
10220     break;
10221
10222   case TSK_ExplicitInstantiationDefinition:
10223     return GVA_StrongODR;
10224
10225   // C++11 [temp.explicit]p10:
10226   //   [ Note: The intent is that an inline function that is the subject of
10227   //   an explicit instantiation declaration will still be implicitly
10228   //   instantiated when used so that the body can be considered for
10229   //   inlining, but that no out-of-line copy of the inline function would be
10230   //   generated in the translation unit. -- end note ]
10231   case TSK_ExplicitInstantiationDeclaration:
10232     return GVA_AvailableExternally;
10233
10234   case TSK_ImplicitInstantiation:
10235     External = GVA_DiscardableODR;
10236     break;
10237   }
10238
10239   if (!FD->isInlined())
10240     return External;
10241
10242   if ((!Context.getLangOpts().CPlusPlus &&
10243        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10244        !FD->hasAttr<DLLExportAttr>()) ||
10245       FD->hasAttr<GNUInlineAttr>()) {
10246     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10247
10248     // GNU or C99 inline semantics. Determine whether this symbol should be
10249     // externally visible.
10250     if (FD->isInlineDefinitionExternallyVisible())
10251       return External;
10252
10253     // C99 inline semantics, where the symbol is not externally visible.
10254     return GVA_AvailableExternally;
10255   }
10256
10257   // Functions specified with extern and inline in -fms-compatibility mode
10258   // forcibly get emitted.  While the body of the function cannot be later
10259   // replaced, the function definition cannot be discarded.
10260   if (FD->isMSExternInline())
10261     return GVA_StrongODR;
10262
10263   return GVA_DiscardableODR;
10264 }
10265
10266 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10267                                                 const Decl *D, GVALinkage L) {
10268   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10269   // dllexport/dllimport on inline functions.
10270   if (D->hasAttr<DLLImportAttr>()) {
10271     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10272       return GVA_AvailableExternally;
10273   } else if (D->hasAttr<DLLExportAttr>()) {
10274     if (L == GVA_DiscardableODR)
10275       return GVA_StrongODR;
10276   } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
10277              D->hasAttr<CUDAGlobalAttr>()) {
10278     // Device-side functions with __global__ attribute must always be
10279     // visible externally so they can be launched from host.
10280     if (L == GVA_DiscardableODR || L == GVA_Internal)
10281       return GVA_StrongODR;
10282   }
10283   return L;
10284 }
10285
10286 /// Adjust the GVALinkage for a declaration based on what an external AST source
10287 /// knows about whether there can be other definitions of this declaration.
10288 static GVALinkage
10289 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10290                                           GVALinkage L) {
10291   ExternalASTSource *Source = Ctx.getExternalSource();
10292   if (!Source)
10293     return L;
10294
10295   switch (Source->hasExternalDefinitions(D)) {
10296   case ExternalASTSource::EK_Never:
10297     // Other translation units rely on us to provide the definition.
10298     if (L == GVA_DiscardableODR)
10299       return GVA_StrongODR;
10300     break;
10301
10302   case ExternalASTSource::EK_Always:
10303     return GVA_AvailableExternally;
10304
10305   case ExternalASTSource::EK_ReplyHazy:
10306     break;
10307   }
10308   return L;
10309 }
10310
10311 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10312   return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10313            adjustGVALinkageForAttributes(*this, FD,
10314              basicGVALinkageForFunction(*this, FD)));
10315 }
10316
10317 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10318                                              const VarDecl *VD) {
10319   if (!VD->isExternallyVisible())
10320     return GVA_Internal;
10321
10322   if (VD->isStaticLocal()) {
10323     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10324     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10325       LexicalContext = LexicalContext->getLexicalParent();
10326
10327     // ObjC Blocks can create local variables that don't have a FunctionDecl
10328     // LexicalContext.
10329     if (!LexicalContext)
10330       return GVA_DiscardableODR;
10331
10332     // Otherwise, let the static local variable inherit its linkage from the
10333     // nearest enclosing function.
10334     auto StaticLocalLinkage =
10335         Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10336
10337     // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10338     // be emitted in any object with references to the symbol for the object it
10339     // contains, whether inline or out-of-line."
10340     // Similar behavior is observed with MSVC. An alternative ABI could use
10341     // StrongODR/AvailableExternally to match the function, but none are
10342     // known/supported currently.
10343     if (StaticLocalLinkage == GVA_StrongODR ||
10344         StaticLocalLinkage == GVA_AvailableExternally)
10345       return GVA_DiscardableODR;
10346     return StaticLocalLinkage;
10347   }
10348
10349   // MSVC treats in-class initialized static data members as definitions.
10350   // By giving them non-strong linkage, out-of-line definitions won't
10351   // cause link errors.
10352   if (Context.isMSStaticDataMemberInlineDefinition(VD))
10353     return GVA_DiscardableODR;
10354
10355   // Most non-template variables have strong linkage; inline variables are
10356   // linkonce_odr or (occasionally, for compatibility) weak_odr.
10357   GVALinkage StrongLinkage;
10358   switch (Context.getInlineVariableDefinitionKind(VD)) {
10359   case ASTContext::InlineVariableDefinitionKind::None:
10360     StrongLinkage = GVA_StrongExternal;
10361     break;
10362   case ASTContext::InlineVariableDefinitionKind::Weak:
10363   case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10364     StrongLinkage = GVA_DiscardableODR;
10365     break;
10366   case ASTContext::InlineVariableDefinitionKind::Strong:
10367     StrongLinkage = GVA_StrongODR;
10368     break;
10369   }
10370
10371   switch (VD->getTemplateSpecializationKind()) {
10372   case TSK_Undeclared:
10373     return StrongLinkage;
10374
10375   case TSK_ExplicitSpecialization:
10376     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10377                    VD->isStaticDataMember()
10378                ? GVA_StrongODR
10379                : StrongLinkage;
10380
10381   case TSK_ExplicitInstantiationDefinition:
10382     return GVA_StrongODR;
10383
10384   case TSK_ExplicitInstantiationDeclaration:
10385     return GVA_AvailableExternally;
10386
10387   case TSK_ImplicitInstantiation:
10388     return GVA_DiscardableODR;
10389   }
10390
10391   llvm_unreachable("Invalid Linkage!");
10392 }
10393
10394 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10395   return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10396            adjustGVALinkageForAttributes(*this, VD,
10397              basicGVALinkageForVariable(*this, VD)));
10398 }
10399
10400 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10401   if (const auto *VD = dyn_cast<VarDecl>(D)) {
10402     if (!VD->isFileVarDecl())
10403       return false;
10404     // Global named register variables (GNU extension) are never emitted.
10405     if (VD->getStorageClass() == SC_Register)
10406       return false;
10407     if (VD->getDescribedVarTemplate() ||
10408         isa<VarTemplatePartialSpecializationDecl>(VD))
10409       return false;
10410   } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10411     // We never need to emit an uninstantiated function template.
10412     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10413       return false;
10414   } else if (isa<PragmaCommentDecl>(D))
10415     return true;
10416   else if (isa<PragmaDetectMismatchDecl>(D))
10417     return true;
10418   else if (isa<OMPRequiresDecl>(D))
10419     return true;
10420   else if (isa<OMPThreadPrivateDecl>(D))
10421     return !D->getDeclContext()->isDependentContext();
10422   else if (isa<OMPAllocateDecl>(D))
10423     return !D->getDeclContext()->isDependentContext();
10424   else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10425     return !D->getDeclContext()->isDependentContext();
10426   else if (isa<ImportDecl>(D))
10427     return true;
10428   else
10429     return false;
10430
10431   if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10432     assert(getExternalSource() && "It's from an AST file; must have a source.");
10433     // On Windows, PCH files are built together with an object file. If this
10434     // declaration comes from such a PCH and DeclMustBeEmitted would return
10435     // true, it would have returned true and the decl would have been emitted
10436     // into that object file, so it doesn't need to be emitted here.
10437     // Note that decls are still emitted if they're referenced, as usual;
10438     // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10439     // if it's not referenced.
10440     //
10441     // Explicit template instantiation definitions are tricky. If there was an
10442     // explicit template instantiation decl in the PCH before, it will look like
10443     // the definition comes from there, even if that was just the declaration.
10444     // (Explicit instantiation defs of variable templates always get emitted.)
10445     bool IsExpInstDef =
10446         isa<FunctionDecl>(D) &&
10447         cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10448             TSK_ExplicitInstantiationDefinition;
10449
10450     // Implicit member function definitions, such as operator= might not be
10451     // marked as template specializations, since they're not coming from a
10452     // template but synthesized directly on the class.
10453     IsExpInstDef |=
10454         isa<CXXMethodDecl>(D) &&
10455         cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10456             TSK_ExplicitInstantiationDefinition;
10457
10458     if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10459       return false;
10460   }
10461
10462   // If this is a member of a class template, we do not need to emit it.
10463   if (D->getDeclContext()->isDependentContext())
10464     return false;
10465
10466   // Weak references don't produce any output by themselves.
10467   if (D->hasAttr<WeakRefAttr>())
10468     return false;
10469
10470   // Aliases and used decls are required.
10471   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10472     return true;
10473
10474   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10475     // Forward declarations aren't required.
10476     if (!FD->doesThisDeclarationHaveABody())
10477       return FD->doesDeclarationForceExternallyVisibleDefinition();
10478
10479     // Constructors and destructors are required.
10480     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10481       return true;
10482
10483     // The key function for a class is required.  This rule only comes
10484     // into play when inline functions can be key functions, though.
10485     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10486       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10487         const CXXRecordDecl *RD = MD->getParent();
10488         if (MD->isOutOfLine() && RD->isDynamicClass()) {
10489           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10490           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10491             return true;
10492         }
10493       }
10494     }
10495
10496     GVALinkage Linkage = GetGVALinkageForFunction(FD);
10497
10498     // static, static inline, always_inline, and extern inline functions can
10499     // always be deferred.  Normal inline functions can be deferred in C99/C++.
10500     // Implicit template instantiations can also be deferred in C++.
10501     return !isDiscardableGVALinkage(Linkage);
10502   }
10503
10504   const auto *VD = cast<VarDecl>(D);
10505   assert(VD->isFileVarDecl() && "Expected file scoped var");
10506
10507   // If the decl is marked as `declare target to`, it should be emitted for the
10508   // host and for the device.
10509   if (LangOpts.OpenMP &&
10510       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10511     return true;
10512
10513   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10514       !isMSStaticDataMemberInlineDefinition(VD))
10515     return false;
10516
10517   // Variables that can be needed in other TUs are required.
10518   auto Linkage = GetGVALinkageForVariable(VD);
10519   if (!isDiscardableGVALinkage(Linkage))
10520     return true;
10521
10522   // We never need to emit a variable that is available in another TU.
10523   if (Linkage == GVA_AvailableExternally)
10524     return false;
10525
10526   // Variables that have destruction with side-effects are required.
10527   if (VD->needsDestruction(*this))
10528     return true;
10529
10530   // Variables that have initialization with side-effects are required.
10531   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10532       // We can get a value-dependent initializer during error recovery.
10533       (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10534     return true;
10535
10536   // Likewise, variables with tuple-like bindings are required if their
10537   // bindings have side-effects.
10538   if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10539     for (const auto *BD : DD->bindings())
10540       if (const auto *BindingVD = BD->getHoldingVar())
10541         if (DeclMustBeEmitted(BindingVD))
10542           return true;
10543
10544   return false;
10545 }
10546
10547 void ASTContext::forEachMultiversionedFunctionVersion(
10548     const FunctionDecl *FD,
10549     llvm::function_ref<void(FunctionDecl *)> Pred) const {
10550   assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10551   llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10552   FD = FD->getMostRecentDecl();
10553   for (auto *CurDecl :
10554        FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10555     FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10556     if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10557         std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10558       SeenDecls.insert(CurFD);
10559       Pred(CurFD);
10560     }
10561   }
10562 }
10563
10564 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10565                                                     bool IsCXXMethod,
10566                                                     bool IsBuiltin) const {
10567   // Pass through to the C++ ABI object
10568   if (IsCXXMethod)
10569     return ABI->getDefaultMethodCallConv(IsVariadic);
10570
10571   // Builtins ignore user-specified default calling convention and remain the
10572   // Target's default calling convention.
10573   if (!IsBuiltin) {
10574     switch (LangOpts.getDefaultCallingConv()) {
10575     case LangOptions::DCC_None:
10576       break;
10577     case LangOptions::DCC_CDecl:
10578       return CC_C;
10579     case LangOptions::DCC_FastCall:
10580       if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10581         return CC_X86FastCall;
10582       break;
10583     case LangOptions::DCC_StdCall:
10584       if (!IsVariadic)
10585         return CC_X86StdCall;
10586       break;
10587     case LangOptions::DCC_VectorCall:
10588       // __vectorcall cannot be applied to variadic functions.
10589       if (!IsVariadic)
10590         return CC_X86VectorCall;
10591       break;
10592     case LangOptions::DCC_RegCall:
10593       // __regcall cannot be applied to variadic functions.
10594       if (!IsVariadic)
10595         return CC_X86RegCall;
10596       break;
10597     }
10598   }
10599   return Target->getDefaultCallingConv();
10600 }
10601
10602 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10603   // Pass through to the C++ ABI object
10604   return ABI->isNearlyEmpty(RD);
10605 }
10606
10607 VTableContextBase *ASTContext::getVTableContext() {
10608   if (!VTContext.get()) {
10609     auto ABI = Target->getCXXABI();
10610     if (ABI.isMicrosoft())
10611       VTContext.reset(new MicrosoftVTableContext(*this));
10612     else {
10613       auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10614                                  ? ItaniumVTableContext::Relative
10615                                  : ItaniumVTableContext::Pointer;
10616       VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10617     }
10618   }
10619   return VTContext.get();
10620 }
10621
10622 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10623   if (!T)
10624     T = Target;
10625   switch (T->getCXXABI().getKind()) {
10626   case TargetCXXABI::Fuchsia:
10627   case TargetCXXABI::GenericAArch64:
10628   case TargetCXXABI::GenericItanium:
10629   case TargetCXXABI::GenericARM:
10630   case TargetCXXABI::GenericMIPS:
10631   case TargetCXXABI::iOS:
10632   case TargetCXXABI::iOS64:
10633   case TargetCXXABI::WebAssembly:
10634   case TargetCXXABI::WatchOS:
10635   case TargetCXXABI::XL:
10636     return ItaniumMangleContext::create(*this, getDiagnostics());
10637   case TargetCXXABI::Microsoft:
10638     return MicrosoftMangleContext::create(*this, getDiagnostics());
10639   }
10640   llvm_unreachable("Unsupported ABI");
10641 }
10642
10643 CXXABI::~CXXABI() = default;
10644
10645 size_t ASTContext::getSideTableAllocatedMemory() const {
10646   return ASTRecordLayouts.getMemorySize() +
10647          llvm::capacity_in_bytes(ObjCLayouts) +
10648          llvm::capacity_in_bytes(KeyFunctions) +
10649          llvm::capacity_in_bytes(ObjCImpls) +
10650          llvm::capacity_in_bytes(BlockVarCopyInits) +
10651          llvm::capacity_in_bytes(DeclAttrs) +
10652          llvm::capacity_in_bytes(TemplateOrInstantiation) +
10653          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10654          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10655          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10656          llvm::capacity_in_bytes(OverriddenMethods) +
10657          llvm::capacity_in_bytes(Types) +
10658          llvm::capacity_in_bytes(VariableArrayTypes);
10659 }
10660
10661 /// getIntTypeForBitwidth -
10662 /// sets integer QualTy according to specified details:
10663 /// bitwidth, signed/unsigned.
10664 /// Returns empty type if there is no appropriate target types.
10665 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10666                                            unsigned Signed) const {
10667   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10668   CanQualType QualTy = getFromTargetType(Ty);
10669   if (!QualTy && DestWidth == 128)
10670     return Signed ? Int128Ty : UnsignedInt128Ty;
10671   return QualTy;
10672 }
10673
10674 /// getRealTypeForBitwidth -
10675 /// sets floating point QualTy according to specified bitwidth.
10676 /// Returns empty type if there is no appropriate target types.
10677 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
10678                                             bool ExplicitIEEE) const {
10679   TargetInfo::RealType Ty =
10680       getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
10681   switch (Ty) {
10682   case TargetInfo::Float:
10683     return FloatTy;
10684   case TargetInfo::Double:
10685     return DoubleTy;
10686   case TargetInfo::LongDouble:
10687     return LongDoubleTy;
10688   case TargetInfo::Float128:
10689     return Float128Ty;
10690   case TargetInfo::NoFloat:
10691     return {};
10692   }
10693
10694   llvm_unreachable("Unhandled TargetInfo::RealType value");
10695 }
10696
10697 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10698   if (Number > 1)
10699     MangleNumbers[ND] = Number;
10700 }
10701
10702 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10703   auto I = MangleNumbers.find(ND);
10704   return I != MangleNumbers.end() ? I->second : 1;
10705 }
10706
10707 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10708   if (Number > 1)
10709     StaticLocalNumbers[VD] = Number;
10710 }
10711
10712 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10713   auto I = StaticLocalNumbers.find(VD);
10714   return I != StaticLocalNumbers.end() ? I->second : 1;
10715 }
10716
10717 MangleNumberingContext &
10718 ASTContext::getManglingNumberContext(const DeclContext *DC) {
10719   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
10720   std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10721   if (!MCtx)
10722     MCtx = createMangleNumberingContext();
10723   return *MCtx;
10724 }
10725
10726 MangleNumberingContext &
10727 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10728   assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10729   std::unique_ptr<MangleNumberingContext> &MCtx =
10730       ExtraMangleNumberingContexts[D];
10731   if (!MCtx)
10732     MCtx = createMangleNumberingContext();
10733   return *MCtx;
10734 }
10735
10736 std::unique_ptr<MangleNumberingContext>
10737 ASTContext::createMangleNumberingContext() const {
10738   return ABI->createMangleNumberingContext();
10739 }
10740
10741 const CXXConstructorDecl *
10742 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10743   return ABI->getCopyConstructorForExceptionObject(
10744       cast<CXXRecordDecl>(RD->getFirstDecl()));
10745 }
10746
10747 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10748                                                       CXXConstructorDecl *CD) {
10749   return ABI->addCopyConstructorForExceptionObject(
10750       cast<CXXRecordDecl>(RD->getFirstDecl()),
10751       cast<CXXConstructorDecl>(CD->getFirstDecl()));
10752 }
10753
10754 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10755                                                  TypedefNameDecl *DD) {
10756   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10757 }
10758
10759 TypedefNameDecl *
10760 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10761   return ABI->getTypedefNameForUnnamedTagDecl(TD);
10762 }
10763
10764 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10765                                                 DeclaratorDecl *DD) {
10766   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10767 }
10768
10769 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10770   return ABI->getDeclaratorForUnnamedTagDecl(TD);
10771 }
10772
10773 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10774   ParamIndices[D] = index;
10775 }
10776
10777 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10778   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10779   assert(I != ParamIndices.end() &&
10780          "ParmIndices lacks entry set by ParmVarDecl");
10781   return I->second;
10782 }
10783
10784 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10785                                                unsigned Length) const {
10786   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10787   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10788     EltTy = EltTy.withConst();
10789
10790   EltTy = adjustStringLiteralBaseType(EltTy);
10791
10792   // Get an array type for the string, according to C99 6.4.5. This includes
10793   // the null terminator character.
10794   return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
10795                               ArrayType::Normal, /*IndexTypeQuals*/ 0);
10796 }
10797
10798 StringLiteral *
10799 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10800   StringLiteral *&Result = StringLiteralCache[Key];
10801   if (!Result)
10802     Result = StringLiteral::Create(
10803         *this, Key, StringLiteral::Ascii,
10804         /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10805         SourceLocation());
10806   return Result;
10807 }
10808
10809 MSGuidDecl *
10810 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
10811   assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
10812
10813   llvm::FoldingSetNodeID ID;
10814   MSGuidDecl::Profile(ID, Parts);
10815
10816   void *InsertPos;
10817   if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
10818     return Existing;
10819
10820   QualType GUIDType = getMSGuidType().withConst();
10821   MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
10822   MSGuidDecls.InsertNode(New, InsertPos);
10823   return New;
10824 }
10825
10826 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10827   const llvm::Triple &T = getTargetInfo().getTriple();
10828   if (!T.isOSDarwin())
10829     return false;
10830
10831   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10832       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10833     return false;
10834
10835   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10836   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10837   uint64_t Size = sizeChars.getQuantity();
10838   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10839   unsigned Align = alignChars.getQuantity();
10840   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10841   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10842 }
10843
10844 bool
10845 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10846                                 const ObjCMethodDecl *MethodImpl) {
10847   // No point trying to match an unavailable/deprecated mothod.
10848   if (MethodDecl->hasAttr<UnavailableAttr>()
10849       || MethodDecl->hasAttr<DeprecatedAttr>())
10850     return false;
10851   if (MethodDecl->getObjCDeclQualifier() !=
10852       MethodImpl->getObjCDeclQualifier())
10853     return false;
10854   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10855     return false;
10856
10857   if (MethodDecl->param_size() != MethodImpl->param_size())
10858     return false;
10859
10860   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10861        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10862        EF = MethodDecl->param_end();
10863        IM != EM && IF != EF; ++IM, ++IF) {
10864     const ParmVarDecl *DeclVar = (*IF);
10865     const ParmVarDecl *ImplVar = (*IM);
10866     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10867       return false;
10868     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10869       return false;
10870   }
10871
10872   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10873 }
10874
10875 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
10876   LangAS AS;
10877   if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
10878     AS = LangAS::Default;
10879   else
10880     AS = QT->getPointeeType().getAddressSpace();
10881
10882   return getTargetInfo().getNullPointerValue(AS);
10883 }
10884
10885 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10886   if (isTargetAddressSpace(AS))
10887     return toTargetAddressSpace(AS);
10888   else
10889     return (*AddrSpaceMap)[(unsigned)AS];
10890 }
10891
10892 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10893   assert(Ty->isFixedPointType());
10894
10895   if (Ty->isSaturatedFixedPointType()) return Ty;
10896
10897   switch (Ty->castAs<BuiltinType>()->getKind()) {
10898     default:
10899       llvm_unreachable("Not a fixed point type!");
10900     case BuiltinType::ShortAccum:
10901       return SatShortAccumTy;
10902     case BuiltinType::Accum:
10903       return SatAccumTy;
10904     case BuiltinType::LongAccum:
10905       return SatLongAccumTy;
10906     case BuiltinType::UShortAccum:
10907       return SatUnsignedShortAccumTy;
10908     case BuiltinType::UAccum:
10909       return SatUnsignedAccumTy;
10910     case BuiltinType::ULongAccum:
10911       return SatUnsignedLongAccumTy;
10912     case BuiltinType::ShortFract:
10913       return SatShortFractTy;
10914     case BuiltinType::Fract:
10915       return SatFractTy;
10916     case BuiltinType::LongFract:
10917       return SatLongFractTy;
10918     case BuiltinType::UShortFract:
10919       return SatUnsignedShortFractTy;
10920     case BuiltinType::UFract:
10921       return SatUnsignedFractTy;
10922     case BuiltinType::ULongFract:
10923       return SatUnsignedLongFractTy;
10924   }
10925 }
10926
10927 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10928   if (LangOpts.OpenCL)
10929     return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10930
10931   if (LangOpts.CUDA)
10932     return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10933
10934   return getLangASFromTargetAS(AS);
10935 }
10936
10937 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10938 // doesn't include ASTContext.h
10939 template
10940 clang::LazyGenerationalUpdatePtr<
10941     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10942 clang::LazyGenerationalUpdatePtr<
10943     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10944         const clang::ASTContext &Ctx, Decl *Value);
10945
10946 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10947   assert(Ty->isFixedPointType());
10948
10949   const TargetInfo &Target = getTargetInfo();
10950   switch (Ty->castAs<BuiltinType>()->getKind()) {
10951     default:
10952       llvm_unreachable("Not a fixed point type!");
10953     case BuiltinType::ShortAccum:
10954     case BuiltinType::SatShortAccum:
10955       return Target.getShortAccumScale();
10956     case BuiltinType::Accum:
10957     case BuiltinType::SatAccum:
10958       return Target.getAccumScale();
10959     case BuiltinType::LongAccum:
10960     case BuiltinType::SatLongAccum:
10961       return Target.getLongAccumScale();
10962     case BuiltinType::UShortAccum:
10963     case BuiltinType::SatUShortAccum:
10964       return Target.getUnsignedShortAccumScale();
10965     case BuiltinType::UAccum:
10966     case BuiltinType::SatUAccum:
10967       return Target.getUnsignedAccumScale();
10968     case BuiltinType::ULongAccum:
10969     case BuiltinType::SatULongAccum:
10970       return Target.getUnsignedLongAccumScale();
10971     case BuiltinType::ShortFract:
10972     case BuiltinType::SatShortFract:
10973       return Target.getShortFractScale();
10974     case BuiltinType::Fract:
10975     case BuiltinType::SatFract:
10976       return Target.getFractScale();
10977     case BuiltinType::LongFract:
10978     case BuiltinType::SatLongFract:
10979       return Target.getLongFractScale();
10980     case BuiltinType::UShortFract:
10981     case BuiltinType::SatUShortFract:
10982       return Target.getUnsignedShortFractScale();
10983     case BuiltinType::UFract:
10984     case BuiltinType::SatUFract:
10985       return Target.getUnsignedFractScale();
10986     case BuiltinType::ULongFract:
10987     case BuiltinType::SatULongFract:
10988       return Target.getUnsignedLongFractScale();
10989   }
10990 }
10991
10992 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10993   assert(Ty->isFixedPointType());
10994
10995   const TargetInfo &Target = getTargetInfo();
10996   switch (Ty->castAs<BuiltinType>()->getKind()) {
10997     default:
10998       llvm_unreachable("Not a fixed point type!");
10999     case BuiltinType::ShortAccum:
11000     case BuiltinType::SatShortAccum:
11001       return Target.getShortAccumIBits();
11002     case BuiltinType::Accum:
11003     case BuiltinType::SatAccum:
11004       return Target.getAccumIBits();
11005     case BuiltinType::LongAccum:
11006     case BuiltinType::SatLongAccum:
11007       return Target.getLongAccumIBits();
11008     case BuiltinType::UShortAccum:
11009     case BuiltinType::SatUShortAccum:
11010       return Target.getUnsignedShortAccumIBits();
11011     case BuiltinType::UAccum:
11012     case BuiltinType::SatUAccum:
11013       return Target.getUnsignedAccumIBits();
11014     case BuiltinType::ULongAccum:
11015     case BuiltinType::SatULongAccum:
11016       return Target.getUnsignedLongAccumIBits();
11017     case BuiltinType::ShortFract:
11018     case BuiltinType::SatShortFract:
11019     case BuiltinType::Fract:
11020     case BuiltinType::SatFract:
11021     case BuiltinType::LongFract:
11022     case BuiltinType::SatLongFract:
11023     case BuiltinType::UShortFract:
11024     case BuiltinType::SatUShortFract:
11025     case BuiltinType::UFract:
11026     case BuiltinType::SatUFract:
11027     case BuiltinType::ULongFract:
11028     case BuiltinType::SatULongFract:
11029       return 0;
11030   }
11031 }
11032
11033 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
11034   assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11035          "Can only get the fixed point semantics for a "
11036          "fixed point or integer type.");
11037   if (Ty->isIntegerType())
11038     return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
11039                                                     Ty->isSignedIntegerType());
11040
11041   bool isSigned = Ty->isSignedFixedPointType();
11042   return FixedPointSemantics(
11043       static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11044       Ty->isSaturatedFixedPointType(),
11045       !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11046 }
11047
11048 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11049   assert(Ty->isFixedPointType());
11050   return APFixedPoint::getMax(getFixedPointSemantics(Ty));
11051 }
11052
11053 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11054   assert(Ty->isFixedPointType());
11055   return APFixedPoint::getMin(getFixedPointSemantics(Ty));
11056 }
11057
11058 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11059   assert(Ty->isUnsignedFixedPointType() &&
11060          "Expected unsigned fixed point type");
11061
11062   switch (Ty->castAs<BuiltinType>()->getKind()) {
11063   case BuiltinType::UShortAccum:
11064     return ShortAccumTy;
11065   case BuiltinType::UAccum:
11066     return AccumTy;
11067   case BuiltinType::ULongAccum:
11068     return LongAccumTy;
11069   case BuiltinType::SatUShortAccum:
11070     return SatShortAccumTy;
11071   case BuiltinType::SatUAccum:
11072     return SatAccumTy;
11073   case BuiltinType::SatULongAccum:
11074     return SatLongAccumTy;
11075   case BuiltinType::UShortFract:
11076     return ShortFractTy;
11077   case BuiltinType::UFract:
11078     return FractTy;
11079   case BuiltinType::ULongFract:
11080     return LongFractTy;
11081   case BuiltinType::SatUShortFract:
11082     return SatShortFractTy;
11083   case BuiltinType::SatUFract:
11084     return SatFractTy;
11085   case BuiltinType::SatULongFract:
11086     return SatLongFractTy;
11087   default:
11088     llvm_unreachable("Unexpected unsigned fixed point type");
11089   }
11090 }
11091
11092 ParsedTargetAttr
11093 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11094   assert(TD != nullptr);
11095   ParsedTargetAttr ParsedAttr = TD->parse();
11096
11097   ParsedAttr.Features.erase(
11098       llvm::remove_if(ParsedAttr.Features,
11099                       [&](const std::string &Feat) {
11100                         return !Target->isValidFeatureName(
11101                             StringRef{Feat}.substr(1));
11102                       }),
11103       ParsedAttr.Features.end());
11104   return ParsedAttr;
11105 }
11106
11107 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11108                                        const FunctionDecl *FD) const {
11109   if (FD)
11110     getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11111   else
11112     Target->initFeatureMap(FeatureMap, getDiagnostics(),
11113                            Target->getTargetOpts().CPU,
11114                            Target->getTargetOpts().Features);
11115 }
11116
11117 // Fills in the supplied string map with the set of target features for the
11118 // passed in function.
11119 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11120                                        GlobalDecl GD) const {
11121   StringRef TargetCPU = Target->getTargetOpts().CPU;
11122   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11123   if (const auto *TD = FD->getAttr<TargetAttr>()) {
11124     ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11125
11126     // Make a copy of the features as passed on the command line into the
11127     // beginning of the additional features from the function to override.
11128     ParsedAttr.Features.insert(
11129         ParsedAttr.Features.begin(),
11130         Target->getTargetOpts().FeaturesAsWritten.begin(),
11131         Target->getTargetOpts().FeaturesAsWritten.end());
11132
11133     if (ParsedAttr.Architecture != "" &&
11134         Target->isValidCPUName(ParsedAttr.Architecture))
11135       TargetCPU = ParsedAttr.Architecture;
11136
11137     // Now populate the feature map, first with the TargetCPU which is either
11138     // the default or a new one from the target attribute string. Then we'll use
11139     // the passed in features (FeaturesAsWritten) along with the new ones from
11140     // the attribute.
11141     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11142                            ParsedAttr.Features);
11143   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11144     llvm::SmallVector<StringRef, 32> FeaturesTmp;
11145     Target->getCPUSpecificCPUDispatchFeatures(
11146         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11147     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11148     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11149   } else {
11150     Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11151                            Target->getTargetOpts().Features);
11152   }
11153 }
11154
11155 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11156   OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11157   return *OMPTraitInfoVector.back();
11158 }
11159
11160 const DiagnosticBuilder &
11161 clang::operator<<(const DiagnosticBuilder &DB,
11162                   const ASTContext::SectionInfo &Section) {
11163   if (Section.Decl)
11164     return DB << Section.Decl;
11165   return DB << "a prior #pragma section";
11166 }