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