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