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