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