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