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