clang API Documentation

ASTContext.cpp
Go to the documentation of this file.
00001 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the ASTContext interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/ASTContext.h"
00015 #include "CXXABI.h"
00016 #include "clang/AST/ASTMutationListener.h"
00017 #include "clang/AST/Attr.h"
00018 #include "clang/AST/CharUnits.h"
00019 #include "clang/AST/Comment.h"
00020 #include "clang/AST/CommentCommandTraits.h"
00021 #include "clang/AST/DeclCXX.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/DeclTemplate.h"
00024 #include "clang/AST/Expr.h"
00025 #include "clang/AST/ExprCXX.h"
00026 #include "clang/AST/ExternalASTSource.h"
00027 #include "clang/AST/Mangle.h"
00028 #include "clang/AST/MangleNumberingContext.h"
00029 #include "clang/AST/RecordLayout.h"
00030 #include "clang/AST/RecursiveASTVisitor.h"
00031 #include "clang/AST/TypeLoc.h"
00032 #include "clang/AST/VTableBuilder.h"
00033 #include "clang/Basic/Builtins.h"
00034 #include "clang/Basic/SourceManager.h"
00035 #include "clang/Basic/TargetInfo.h"
00036 #include "llvm/ADT/SmallString.h"
00037 #include "llvm/ADT/StringExtras.h"
00038 #include "llvm/ADT/Triple.h"
00039 #include "llvm/Support/Capacity.h"
00040 #include "llvm/Support/MathExtras.h"
00041 #include "llvm/Support/raw_ostream.h"
00042 #include <map>
00043 
00044 using namespace clang;
00045 
00046 unsigned ASTContext::NumImplicitDefaultConstructors;
00047 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
00048 unsigned ASTContext::NumImplicitCopyConstructors;
00049 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
00050 unsigned ASTContext::NumImplicitMoveConstructors;
00051 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
00052 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
00053 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
00054 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
00055 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
00056 unsigned ASTContext::NumImplicitDestructors;
00057 unsigned ASTContext::NumImplicitDestructorsDeclared;
00058 
00059 enum FloatingRank {
00060   HalfRank, FloatRank, DoubleRank, LongDoubleRank
00061 };
00062 
00063 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
00064   if (!CommentsLoaded && ExternalSource) {
00065     ExternalSource->ReadComments();
00066 
00067 #ifndef NDEBUG
00068     ArrayRef<RawComment *> RawComments = Comments.getComments();
00069     assert(std::is_sorted(RawComments.begin(), RawComments.end(),
00070                           BeforeThanCompare<RawComment>(SourceMgr)));
00071 #endif
00072 
00073     CommentsLoaded = true;
00074   }
00075 
00076   assert(D);
00077 
00078   // User can not attach documentation to implicit declarations.
00079   if (D->isImplicit())
00080     return nullptr;
00081 
00082   // User can not attach documentation to implicit instantiations.
00083   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00084     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
00085       return nullptr;
00086   }
00087 
00088   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00089     if (VD->isStaticDataMember() &&
00090         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
00091       return nullptr;
00092   }
00093 
00094   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
00095     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
00096       return nullptr;
00097   }
00098 
00099   if (const ClassTemplateSpecializationDecl *CTSD =
00100           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
00101     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
00102     if (TSK == TSK_ImplicitInstantiation ||
00103         TSK == TSK_Undeclared)
00104       return nullptr;
00105   }
00106 
00107   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
00108     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
00109       return nullptr;
00110   }
00111   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
00112     // When tag declaration (but not definition!) is part of the
00113     // decl-specifier-seq of some other declaration, it doesn't get comment
00114     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
00115       return nullptr;
00116   }
00117   // TODO: handle comments for function parameters properly.
00118   if (isa<ParmVarDecl>(D))
00119     return nullptr;
00120 
00121   // TODO: we could look up template parameter documentation in the template
00122   // documentation.
00123   if (isa<TemplateTypeParmDecl>(D) ||
00124       isa<NonTypeTemplateParmDecl>(D) ||
00125       isa<TemplateTemplateParmDecl>(D))
00126     return nullptr;
00127 
00128   ArrayRef<RawComment *> RawComments = Comments.getComments();
00129 
00130   // If there are no comments anywhere, we won't find anything.
00131   if (RawComments.empty())
00132     return nullptr;
00133 
00134   // Find declaration location.
00135   // For Objective-C declarations we generally don't expect to have multiple
00136   // declarators, thus use declaration starting location as the "declaration
00137   // location".
00138   // For all other declarations multiple declarators are used quite frequently,
00139   // so we use the location of the identifier as the "declaration location".
00140   SourceLocation DeclLoc;
00141   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
00142       isa<ObjCPropertyDecl>(D) ||
00143       isa<RedeclarableTemplateDecl>(D) ||
00144       isa<ClassTemplateSpecializationDecl>(D))
00145     DeclLoc = D->getLocStart();
00146   else {
00147     DeclLoc = D->getLocation();
00148     if (DeclLoc.isMacroID()) {
00149       if (isa<TypedefDecl>(D)) {
00150         // If location of the typedef name is in a macro, it is because being
00151         // declared via a macro. Try using declaration's starting location as
00152         // the "declaration location".
00153         DeclLoc = D->getLocStart();
00154       } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
00155         // If location of the tag decl is inside a macro, but the spelling of
00156         // the tag name comes from a macro argument, it looks like a special
00157         // macro like NS_ENUM is being used to define the tag decl.  In that
00158         // case, adjust the source location to the expansion loc so that we can
00159         // attach the comment to the tag decl.
00160         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
00161             TD->isCompleteDefinition())
00162           DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
00163       }
00164     }
00165   }
00166 
00167   // If the declaration doesn't map directly to a location in a file, we
00168   // can't find the comment.
00169   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
00170     return nullptr;
00171 
00172   // Find the comment that occurs just after this declaration.
00173   ArrayRef<RawComment *>::iterator Comment;
00174   {
00175     // When searching for comments during parsing, the comment we are looking
00176     // for is usually among the last two comments we parsed -- check them
00177     // first.
00178     RawComment CommentAtDeclLoc(
00179         SourceMgr, SourceRange(DeclLoc), false,
00180         LangOpts.CommentOpts.ParseAllComments);
00181     BeforeThanCompare<RawComment> Compare(SourceMgr);
00182     ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
00183     bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
00184     if (!Found && RawComments.size() >= 2) {
00185       MaybeBeforeDecl--;
00186       Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
00187     }
00188 
00189     if (Found) {
00190       Comment = MaybeBeforeDecl + 1;
00191       assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
00192                                          &CommentAtDeclLoc, Compare));
00193     } else {
00194       // Slow path.
00195       Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
00196                                  &CommentAtDeclLoc, Compare);
00197     }
00198   }
00199 
00200   // Decompose the location for the declaration and find the beginning of the
00201   // file buffer.
00202   std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
00203 
00204   // First check whether we have a trailing comment.
00205   if (Comment != RawComments.end() &&
00206       (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
00207       (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
00208        isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
00209     std::pair<FileID, unsigned> CommentBeginDecomp
00210       = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
00211     // Check that Doxygen trailing comment comes after the declaration, starts
00212     // on the same line and in the same file as the declaration.
00213     if (DeclLocDecomp.first == CommentBeginDecomp.first &&
00214         SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
00215           == SourceMgr.getLineNumber(CommentBeginDecomp.first,
00216                                      CommentBeginDecomp.second)) {
00217       return *Comment;
00218     }
00219   }
00220 
00221   // The comment just after the declaration was not a trailing comment.
00222   // Let's look at the previous comment.
00223   if (Comment == RawComments.begin())
00224     return nullptr;
00225   --Comment;
00226 
00227   // Check that we actually have a non-member Doxygen comment.
00228   if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
00229     return nullptr;
00230 
00231   // Decompose the end of the comment.
00232   std::pair<FileID, unsigned> CommentEndDecomp
00233     = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
00234 
00235   // If the comment and the declaration aren't in the same file, then they
00236   // aren't related.
00237   if (DeclLocDecomp.first != CommentEndDecomp.first)
00238     return nullptr;
00239 
00240   // Get the corresponding buffer.
00241   bool Invalid = false;
00242   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
00243                                                &Invalid).data();
00244   if (Invalid)
00245     return nullptr;
00246 
00247   // Extract text between the comment and declaration.
00248   StringRef Text(Buffer + CommentEndDecomp.second,
00249                  DeclLocDecomp.second - CommentEndDecomp.second);
00250 
00251   // There should be no other declarations or preprocessor directives between
00252   // comment and declaration.
00253   if (Text.find_first_of(";{}#@") != StringRef::npos)
00254     return nullptr;
00255 
00256   return *Comment;
00257 }
00258 
00259 namespace {
00260 /// If we have a 'templated' declaration for a template, adjust 'D' to
00261 /// refer to the actual template.
00262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
00263 const Decl *adjustDeclToTemplate(const Decl *D) {
00264   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
00265     // Is this function declaration part of a function template?
00266     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
00267       return FTD;
00268 
00269     // Nothing to do if function is not an implicit instantiation.
00270     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
00271       return D;
00272 
00273     // Function is an implicit instantiation of a function template?
00274     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
00275       return FTD;
00276 
00277     // Function is instantiated from a member definition of a class template?
00278     if (const FunctionDecl *MemberDecl =
00279             FD->getInstantiatedFromMemberFunction())
00280       return MemberDecl;
00281 
00282     return D;
00283   }
00284   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00285     // Static data member is instantiated from a member definition of a class
00286     // template?
00287     if (VD->isStaticDataMember())
00288       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
00289         return MemberDecl;
00290 
00291     return D;
00292   }
00293   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
00294     // Is this class declaration part of a class template?
00295     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
00296       return CTD;
00297 
00298     // Class is an implicit instantiation of a class template or partial
00299     // specialization?
00300     if (const ClassTemplateSpecializationDecl *CTSD =
00301             dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
00302       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
00303         return D;
00304       llvm::PointerUnion<ClassTemplateDecl *,
00305                          ClassTemplatePartialSpecializationDecl *>
00306           PU = CTSD->getSpecializedTemplateOrPartial();
00307       return PU.is<ClassTemplateDecl*>() ?
00308           static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
00309           static_cast<const Decl*>(
00310               PU.get<ClassTemplatePartialSpecializationDecl *>());
00311     }
00312 
00313     // Class is instantiated from a member definition of a class template?
00314     if (const MemberSpecializationInfo *Info =
00315                    CRD->getMemberSpecializationInfo())
00316       return Info->getInstantiatedFrom();
00317 
00318     return D;
00319   }
00320   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
00321     // Enum is instantiated from a member definition of a class template?
00322     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
00323       return MemberDecl;
00324 
00325     return D;
00326   }
00327   // FIXME: Adjust alias templates?
00328   return D;
00329 }
00330 } // unnamed namespace
00331 
00332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
00333                                                 const Decl *D,
00334                                                 const Decl **OriginalDecl) const {
00335   D = adjustDeclToTemplate(D);
00336 
00337   // Check whether we have cached a comment for this declaration already.
00338   {
00339     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
00340         RedeclComments.find(D);
00341     if (Pos != RedeclComments.end()) {
00342       const RawCommentAndCacheFlags &Raw = Pos->second;
00343       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
00344         if (OriginalDecl)
00345           *OriginalDecl = Raw.getOriginalDecl();
00346         return Raw.getRaw();
00347       }
00348     }
00349   }
00350 
00351   // Search for comments attached to declarations in the redeclaration chain.
00352   const RawComment *RC = nullptr;
00353   const Decl *OriginalDeclForRC = nullptr;
00354   for (auto I : D->redecls()) {
00355     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
00356         RedeclComments.find(I);
00357     if (Pos != RedeclComments.end()) {
00358       const RawCommentAndCacheFlags &Raw = Pos->second;
00359       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
00360         RC = Raw.getRaw();
00361         OriginalDeclForRC = Raw.getOriginalDecl();
00362         break;
00363       }
00364     } else {
00365       RC = getRawCommentForDeclNoCache(I);
00366       OriginalDeclForRC = I;
00367       RawCommentAndCacheFlags Raw;
00368       if (RC) {
00369         Raw.setRaw(RC);
00370         Raw.setKind(RawCommentAndCacheFlags::FromDecl);
00371       } else
00372         Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
00373       Raw.setOriginalDecl(I);
00374       RedeclComments[I] = Raw;
00375       if (RC)
00376         break;
00377     }
00378   }
00379 
00380   // If we found a comment, it should be a documentation comment.
00381   assert(!RC || RC->isDocumentation());
00382 
00383   if (OriginalDecl)
00384     *OriginalDecl = OriginalDeclForRC;
00385 
00386   // Update cache for every declaration in the redeclaration chain.
00387   RawCommentAndCacheFlags Raw;
00388   Raw.setRaw(RC);
00389   Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
00390   Raw.setOriginalDecl(OriginalDeclForRC);
00391 
00392   for (auto I : D->redecls()) {
00393     RawCommentAndCacheFlags &R = RedeclComments[I];
00394     if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
00395       R = Raw;
00396   }
00397 
00398   return RC;
00399 }
00400 
00401 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
00402                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
00403   const DeclContext *DC = ObjCMethod->getDeclContext();
00404   if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
00405     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
00406     if (!ID)
00407       return;
00408     // Add redeclared method here.
00409     for (const auto *Ext : ID->known_extensions()) {
00410       if (ObjCMethodDecl *RedeclaredMethod =
00411             Ext->getMethod(ObjCMethod->getSelector(),
00412                                   ObjCMethod->isInstanceMethod()))
00413         Redeclared.push_back(RedeclaredMethod);
00414     }
00415   }
00416 }
00417 
00418 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
00419                                                     const Decl *D) const {
00420   comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
00421   ThisDeclInfo->CommentDecl = D;
00422   ThisDeclInfo->IsFilled = false;
00423   ThisDeclInfo->fill();
00424   ThisDeclInfo->CommentDecl = FC->getDecl();
00425   if (!ThisDeclInfo->TemplateParameters)
00426     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
00427   comments::FullComment *CFC =
00428     new (*this) comments::FullComment(FC->getBlocks(),
00429                                       ThisDeclInfo);
00430   return CFC;
00431   
00432 }
00433 
00434 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
00435   const RawComment *RC = getRawCommentForDeclNoCache(D);
00436   return RC ? RC->parse(*this, nullptr, D) : nullptr;
00437 }
00438 
00439 comments::FullComment *ASTContext::getCommentForDecl(
00440                                               const Decl *D,
00441                                               const Preprocessor *PP) const {
00442   if (D->isInvalidDecl())
00443     return nullptr;
00444   D = adjustDeclToTemplate(D);
00445   
00446   const Decl *Canonical = D->getCanonicalDecl();
00447   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
00448       ParsedComments.find(Canonical);
00449   
00450   if (Pos != ParsedComments.end()) {
00451     if (Canonical != D) {
00452       comments::FullComment *FC = Pos->second;
00453       comments::FullComment *CFC = cloneFullComment(FC, D);
00454       return CFC;
00455     }
00456     return Pos->second;
00457   }
00458   
00459   const Decl *OriginalDecl;
00460   
00461   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
00462   if (!RC) {
00463     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
00464       SmallVector<const NamedDecl*, 8> Overridden;
00465       const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
00466       if (OMD && OMD->isPropertyAccessor())
00467         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
00468           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
00469             return cloneFullComment(FC, D);
00470       if (OMD)
00471         addRedeclaredMethods(OMD, Overridden);
00472       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
00473       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
00474         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
00475           return cloneFullComment(FC, D);
00476     }
00477     else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
00478       // Attach any tag type's documentation to its typedef if latter
00479       // does not have one of its own.
00480       QualType QT = TD->getUnderlyingType();
00481       if (const TagType *TT = QT->getAs<TagType>())
00482         if (const Decl *TD = TT->getDecl())
00483           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
00484             return cloneFullComment(FC, D);
00485     }
00486     else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
00487       while (IC->getSuperClass()) {
00488         IC = IC->getSuperClass();
00489         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
00490           return cloneFullComment(FC, D);
00491       }
00492     }
00493     else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
00494       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
00495         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
00496           return cloneFullComment(FC, D);
00497     }
00498     else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
00499       if (!(RD = RD->getDefinition()))
00500         return nullptr;
00501       // Check non-virtual bases.
00502       for (const auto &I : RD->bases()) {
00503         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
00504           continue;
00505         QualType Ty = I.getType();
00506         if (Ty.isNull())
00507           continue;
00508         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
00509           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
00510             continue;
00511         
00512           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
00513             return cloneFullComment(FC, D);
00514         }
00515       }
00516       // Check virtual bases.
00517       for (const auto &I : RD->vbases()) {
00518         if (I.getAccessSpecifier() != AS_public)
00519           continue;
00520         QualType Ty = I.getType();
00521         if (Ty.isNull())
00522           continue;
00523         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
00524           if (!(VirtualBase= VirtualBase->getDefinition()))
00525             continue;
00526           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
00527             return cloneFullComment(FC, D);
00528         }
00529       }
00530     }
00531     return nullptr;
00532   }
00533   
00534   // If the RawComment was attached to other redeclaration of this Decl, we
00535   // should parse the comment in context of that other Decl.  This is important
00536   // because comments can contain references to parameter names which can be
00537   // different across redeclarations.
00538   if (D != OriginalDecl)
00539     return getCommentForDecl(OriginalDecl, PP);
00540 
00541   comments::FullComment *FC = RC->parse(*this, PP, D);
00542   ParsedComments[Canonical] = FC;
00543   return FC;
00544 }
00545 
00546 void 
00547 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 
00548                                                TemplateTemplateParmDecl *Parm) {
00549   ID.AddInteger(Parm->getDepth());
00550   ID.AddInteger(Parm->getPosition());
00551   ID.AddBoolean(Parm->isParameterPack());
00552 
00553   TemplateParameterList *Params = Parm->getTemplateParameters();
00554   ID.AddInteger(Params->size());
00555   for (TemplateParameterList::const_iterator P = Params->begin(), 
00556                                           PEnd = Params->end();
00557        P != PEnd; ++P) {
00558     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
00559       ID.AddInteger(0);
00560       ID.AddBoolean(TTP->isParameterPack());
00561       continue;
00562     }
00563     
00564     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
00565       ID.AddInteger(1);
00566       ID.AddBoolean(NTTP->isParameterPack());
00567       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
00568       if (NTTP->isExpandedParameterPack()) {
00569         ID.AddBoolean(true);
00570         ID.AddInteger(NTTP->getNumExpansionTypes());
00571         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
00572           QualType T = NTTP->getExpansionType(I);
00573           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
00574         }
00575       } else 
00576         ID.AddBoolean(false);
00577       continue;
00578     }
00579     
00580     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
00581     ID.AddInteger(2);
00582     Profile(ID, TTP);
00583   }
00584 }
00585 
00586 TemplateTemplateParmDecl *
00587 ASTContext::getCanonicalTemplateTemplateParmDecl(
00588                                           TemplateTemplateParmDecl *TTP) const {
00589   // Check if we already have a canonical template template parameter.
00590   llvm::FoldingSetNodeID ID;
00591   CanonicalTemplateTemplateParm::Profile(ID, TTP);
00592   void *InsertPos = nullptr;
00593   CanonicalTemplateTemplateParm *Canonical
00594     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
00595   if (Canonical)
00596     return Canonical->getParam();
00597   
00598   // Build a canonical template parameter list.
00599   TemplateParameterList *Params = TTP->getTemplateParameters();
00600   SmallVector<NamedDecl *, 4> CanonParams;
00601   CanonParams.reserve(Params->size());
00602   for (TemplateParameterList::const_iterator P = Params->begin(), 
00603                                           PEnd = Params->end();
00604        P != PEnd; ++P) {
00605     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
00606       CanonParams.push_back(
00607                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 
00608                                                SourceLocation(),
00609                                                SourceLocation(),
00610                                                TTP->getDepth(),
00611                                                TTP->getIndex(), nullptr, false,
00612                                                TTP->isParameterPack()));
00613     else if (NonTypeTemplateParmDecl *NTTP
00614              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
00615       QualType T = getCanonicalType(NTTP->getType());
00616       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
00617       NonTypeTemplateParmDecl *Param;
00618       if (NTTP->isExpandedParameterPack()) {
00619         SmallVector<QualType, 2> ExpandedTypes;
00620         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
00621         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
00622           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
00623           ExpandedTInfos.push_back(
00624                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
00625         }
00626         
00627         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
00628                                                 SourceLocation(),
00629                                                 SourceLocation(),
00630                                                 NTTP->getDepth(),
00631                                                 NTTP->getPosition(), nullptr,
00632                                                 T,
00633                                                 TInfo,
00634                                                 ExpandedTypes.data(),
00635                                                 ExpandedTypes.size(),
00636                                                 ExpandedTInfos.data());
00637       } else {
00638         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
00639                                                 SourceLocation(),
00640                                                 SourceLocation(),
00641                                                 NTTP->getDepth(),
00642                                                 NTTP->getPosition(), nullptr,
00643                                                 T,
00644                                                 NTTP->isParameterPack(),
00645                                                 TInfo);
00646       }
00647       CanonParams.push_back(Param);
00648 
00649     } else
00650       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
00651                                            cast<TemplateTemplateParmDecl>(*P)));
00652   }
00653 
00654   TemplateTemplateParmDecl *CanonTTP
00655     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 
00656                                        SourceLocation(), TTP->getDepth(),
00657                                        TTP->getPosition(), 
00658                                        TTP->isParameterPack(),
00659                                        nullptr,
00660                          TemplateParameterList::Create(*this, SourceLocation(),
00661                                                        SourceLocation(),
00662                                                        CanonParams.data(),
00663                                                        CanonParams.size(),
00664                                                        SourceLocation()));
00665 
00666   // Get the new insert position for the node we care about.
00667   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
00668   assert(!Canonical && "Shouldn't be in the map!");
00669   (void)Canonical;
00670 
00671   // Create the canonical template template parameter entry.
00672   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
00673   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
00674   return CanonTTP;
00675 }
00676 
00677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
00678   if (!LangOpts.CPlusPlus) return nullptr;
00679 
00680   switch (T.getCXXABI().getKind()) {
00681   case TargetCXXABI::GenericARM: // Same as Itanium at this level
00682   case TargetCXXABI::iOS:
00683   case TargetCXXABI::iOS64:
00684   case TargetCXXABI::GenericAArch64:
00685   case TargetCXXABI::GenericItanium:
00686     return CreateItaniumCXXABI(*this);
00687   case TargetCXXABI::Microsoft:
00688     return CreateMicrosoftCXXABI(*this);
00689   }
00690   llvm_unreachable("Invalid CXXABI type!");
00691 }
00692 
00693 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
00694                                              const LangOptions &LOpts) {
00695   if (LOpts.FakeAddressSpaceMap) {
00696     // The fake address space map must have a distinct entry for each
00697     // language-specific address space.
00698     static const unsigned FakeAddrSpaceMap[] = {
00699       1, // opencl_global
00700       2, // opencl_local
00701       3, // opencl_constant
00702       4, // cuda_device
00703       5, // cuda_constant
00704       6  // cuda_shared
00705     };
00706     return &FakeAddrSpaceMap;
00707   } else {
00708     return &T.getAddressSpaceMap();
00709   }
00710 }
00711 
00712 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
00713                                           const LangOptions &LangOpts) {
00714   switch (LangOpts.getAddressSpaceMapMangling()) {
00715   case LangOptions::ASMM_Target:
00716     return TI.useAddressSpaceMapMangling();
00717   case LangOptions::ASMM_On:
00718     return true;
00719   case LangOptions::ASMM_Off:
00720     return false;
00721   }
00722   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
00723 }
00724 
00725 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
00726                        IdentifierTable &idents, SelectorTable &sels,
00727                        Builtin::Context &builtins)
00728     : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
00729       DependentTemplateSpecializationTypes(this_()),
00730       SubstTemplateTemplateParmPacks(this_()),
00731       GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
00732       UInt128Decl(nullptr), Float128StubDecl(nullptr),
00733       BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
00734       ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
00735       CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
00736       FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
00737       ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
00738       BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
00739       NullTypeSourceInfo(QualType()), FirstLocalImport(), LastLocalImport(),
00740       SourceMgr(SM), LangOpts(LOpts),
00741       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)),
00742       AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
00743       Idents(idents), Selectors(sels), BuiltinInfo(builtins),
00744       DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
00745       Comments(SM), CommentsLoaded(false),
00746       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
00747   TUDecl = TranslationUnitDecl::Create(*this);
00748 }
00749 
00750 ASTContext::~ASTContext() {
00751   ReleaseParentMapEntries();
00752 
00753   // Release the DenseMaps associated with DeclContext objects.
00754   // FIXME: Is this the ideal solution?
00755   ReleaseDeclContextMaps();
00756 
00757   // Call all of the deallocation functions on all of their targets.
00758   for (DeallocationMap::const_iterator I = Deallocations.begin(),
00759            E = Deallocations.end(); I != E; ++I)
00760     for (unsigned J = 0, N = I->second.size(); J != N; ++J)
00761       (I->first)((I->second)[J]);
00762 
00763   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
00764   // because they can contain DenseMaps.
00765   for (llvm::DenseMap<const ObjCContainerDecl*,
00766        const ASTRecordLayout*>::iterator
00767        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
00768     // Increment in loop to prevent using deallocated memory.
00769     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
00770       R->Destroy(*this);
00771 
00772   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
00773        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
00774     // Increment in loop to prevent using deallocated memory.
00775     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
00776       R->Destroy(*this);
00777   }
00778   
00779   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
00780                                                     AEnd = DeclAttrs.end();
00781        A != AEnd; ++A)
00782     A->second->~AttrVec();
00783 
00784   llvm::DeleteContainerSeconds(MangleNumberingContexts);
00785 }
00786 
00787 void ASTContext::ReleaseParentMapEntries() {
00788   if (!AllParents) return;
00789   for (const auto &Entry : *AllParents) {
00790     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
00791       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
00792     } else {
00793       assert(Entry.second.is<ParentVector *>());
00794       delete Entry.second.get<ParentVector *>();
00795     }
00796   }
00797 }
00798 
00799 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
00800   Deallocations[Callback].push_back(Data);
00801 }
00802 
00803 void
00804 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
00805   ExternalSource = Source;
00806 }
00807 
00808 void ASTContext::PrintStats() const {
00809   llvm::errs() << "\n*** AST Context Stats:\n";
00810   llvm::errs() << "  " << Types.size() << " types total.\n";
00811 
00812   unsigned counts[] = {
00813 #define TYPE(Name, Parent) 0,
00814 #define ABSTRACT_TYPE(Name, Parent)
00815 #include "clang/AST/TypeNodes.def"
00816     0 // Extra
00817   };
00818 
00819   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
00820     Type *T = Types[i];
00821     counts[(unsigned)T->getTypeClass()]++;
00822   }
00823 
00824   unsigned Idx = 0;
00825   unsigned TotalBytes = 0;
00826 #define TYPE(Name, Parent)                                              \
00827   if (counts[Idx])                                                      \
00828     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
00829                  << " types\n";                                         \
00830   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
00831   ++Idx;
00832 #define ABSTRACT_TYPE(Name, Parent)
00833 #include "clang/AST/TypeNodes.def"
00834 
00835   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
00836 
00837   // Implicit special member functions.
00838   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
00839                << NumImplicitDefaultConstructors
00840                << " implicit default constructors created\n";
00841   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
00842                << NumImplicitCopyConstructors
00843                << " implicit copy constructors created\n";
00844   if (getLangOpts().CPlusPlus)
00845     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
00846                  << NumImplicitMoveConstructors
00847                  << " implicit move constructors created\n";
00848   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
00849                << NumImplicitCopyAssignmentOperators
00850                << " implicit copy assignment operators created\n";
00851   if (getLangOpts().CPlusPlus)
00852     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
00853                  << NumImplicitMoveAssignmentOperators
00854                  << " implicit move assignment operators created\n";
00855   llvm::errs() << NumImplicitDestructorsDeclared << "/"
00856                << NumImplicitDestructors
00857                << " implicit destructors created\n";
00858 
00859   if (ExternalSource) {
00860     llvm::errs() << "\n";
00861     ExternalSource->PrintStats();
00862   }
00863 
00864   BumpAlloc.PrintStats();
00865 }
00866 
00867 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
00868                                             RecordDecl::TagKind TK) const {
00869   SourceLocation Loc;
00870   RecordDecl *NewDecl;
00871   if (getLangOpts().CPlusPlus)
00872     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
00873                                     Loc, &Idents.get(Name));
00874   else
00875     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
00876                                  &Idents.get(Name));
00877   NewDecl->setImplicit();
00878   return NewDecl;
00879 }
00880 
00881 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
00882                                               StringRef Name) const {
00883   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
00884   TypedefDecl *NewDecl = TypedefDecl::Create(
00885       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
00886       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
00887   NewDecl->setImplicit();
00888   return NewDecl;
00889 }
00890 
00891 TypedefDecl *ASTContext::getInt128Decl() const {
00892   if (!Int128Decl)
00893     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
00894   return Int128Decl;
00895 }
00896 
00897 TypedefDecl *ASTContext::getUInt128Decl() const {
00898   if (!UInt128Decl)
00899     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
00900   return UInt128Decl;
00901 }
00902 
00903 TypeDecl *ASTContext::getFloat128StubType() const {
00904   assert(LangOpts.CPlusPlus && "should only be called for c++");
00905   if (!Float128StubDecl)
00906     Float128StubDecl = buildImplicitRecord("__float128");
00907 
00908   return Float128StubDecl;
00909 }
00910 
00911 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
00912   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
00913   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
00914   Types.push_back(Ty);
00915 }
00916 
00917 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
00918   assert((!this->Target || this->Target == &Target) &&
00919          "Incorrect target reinitialization");
00920   assert(VoidTy.isNull() && "Context reinitialized?");
00921 
00922   this->Target = &Target;
00923   
00924   ABI.reset(createCXXABI(Target));
00925   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
00926   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
00927   
00928   // C99 6.2.5p19.
00929   InitBuiltinType(VoidTy,              BuiltinType::Void);
00930 
00931   // C99 6.2.5p2.
00932   InitBuiltinType(BoolTy,              BuiltinType::Bool);
00933   // C99 6.2.5p3.
00934   if (LangOpts.CharIsSigned)
00935     InitBuiltinType(CharTy,            BuiltinType::Char_S);
00936   else
00937     InitBuiltinType(CharTy,            BuiltinType::Char_U);
00938   // C99 6.2.5p4.
00939   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
00940   InitBuiltinType(ShortTy,             BuiltinType::Short);
00941   InitBuiltinType(IntTy,               BuiltinType::Int);
00942   InitBuiltinType(LongTy,              BuiltinType::Long);
00943   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
00944 
00945   // C99 6.2.5p6.
00946   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
00947   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
00948   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
00949   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
00950   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
00951 
00952   // C99 6.2.5p10.
00953   InitBuiltinType(FloatTy,             BuiltinType::Float);
00954   InitBuiltinType(DoubleTy,            BuiltinType::Double);
00955   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
00956 
00957   // GNU extension, 128-bit integers.
00958   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
00959   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
00960 
00961   // C++ 3.9.1p5
00962   if (TargetInfo::isTypeSigned(Target.getWCharType()))
00963     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
00964   else  // -fshort-wchar makes wchar_t be unsigned.
00965     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
00966   if (LangOpts.CPlusPlus && LangOpts.WChar)
00967     WideCharTy = WCharTy;
00968   else {
00969     // C99 (or C++ using -fno-wchar).
00970     WideCharTy = getFromTargetType(Target.getWCharType());
00971   }
00972 
00973   WIntTy = getFromTargetType(Target.getWIntType());
00974 
00975   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
00976     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
00977   else // C99
00978     Char16Ty = getFromTargetType(Target.getChar16Type());
00979 
00980   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
00981     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
00982   else // C99
00983     Char32Ty = getFromTargetType(Target.getChar32Type());
00984 
00985   // Placeholder type for type-dependent expressions whose type is
00986   // completely unknown. No code should ever check a type against
00987   // DependentTy and users should never see it; however, it is here to
00988   // help diagnose failures to properly check for type-dependent
00989   // expressions.
00990   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
00991 
00992   // Placeholder type for functions.
00993   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
00994 
00995   // Placeholder type for bound members.
00996   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
00997 
00998   // Placeholder type for pseudo-objects.
00999   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
01000 
01001   // "any" type; useful for debugger-like clients.
01002   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
01003 
01004   // Placeholder type for unbridged ARC casts.
01005   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
01006 
01007   // Placeholder type for builtin functions.
01008   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
01009 
01010   // C99 6.2.5p11.
01011   FloatComplexTy      = getComplexType(FloatTy);
01012   DoubleComplexTy     = getComplexType(DoubleTy);
01013   LongDoubleComplexTy = getComplexType(LongDoubleTy);
01014 
01015   // Builtin types for 'id', 'Class', and 'SEL'.
01016   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
01017   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
01018   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
01019 
01020   if (LangOpts.OpenCL) { 
01021     InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
01022     InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
01023     InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
01024     InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
01025     InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
01026     InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
01027 
01028     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
01029     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
01030   }
01031   
01032   // Builtin type for __objc_yes and __objc_no
01033   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
01034                        SignedCharTy : BoolTy);
01035   
01036   ObjCConstantStringType = QualType();
01037   
01038   ObjCSuperType = QualType();
01039 
01040   // void * type
01041   VoidPtrTy = getPointerType(VoidTy);
01042 
01043   // nullptr type (C++0x 2.14.7)
01044   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
01045 
01046   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
01047   InitBuiltinType(HalfTy, BuiltinType::Half);
01048 
01049   // Builtin type used to help define __builtin_va_list.
01050   VaListTagTy = QualType();
01051 }
01052 
01053 DiagnosticsEngine &ASTContext::getDiagnostics() const {
01054   return SourceMgr.getDiagnostics();
01055 }
01056 
01057 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
01058   AttrVec *&Result = DeclAttrs[D];
01059   if (!Result) {
01060     void *Mem = Allocate(sizeof(AttrVec));
01061     Result = new (Mem) AttrVec;
01062   }
01063     
01064   return *Result;
01065 }
01066 
01067 /// \brief Erase the attributes corresponding to the given declaration.
01068 void ASTContext::eraseDeclAttrs(const Decl *D) { 
01069   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
01070   if (Pos != DeclAttrs.end()) {
01071     Pos->second->~AttrVec();
01072     DeclAttrs.erase(Pos);
01073   }
01074 }
01075 
01076 // FIXME: Remove ?
01077 MemberSpecializationInfo *
01078 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
01079   assert(Var->isStaticDataMember() && "Not a static data member");
01080   return getTemplateOrSpecializationInfo(Var)
01081       .dyn_cast<MemberSpecializationInfo *>();
01082 }
01083 
01084 ASTContext::TemplateOrSpecializationInfo
01085 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
01086   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
01087       TemplateOrInstantiation.find(Var);
01088   if (Pos == TemplateOrInstantiation.end())
01089     return TemplateOrSpecializationInfo();
01090 
01091   return Pos->second;
01092 }
01093 
01094 void
01095 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
01096                                                 TemplateSpecializationKind TSK,
01097                                           SourceLocation PointOfInstantiation) {
01098   assert(Inst->isStaticDataMember() && "Not a static data member");
01099   assert(Tmpl->isStaticDataMember() && "Not a static data member");
01100   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
01101                                             Tmpl, TSK, PointOfInstantiation));
01102 }
01103 
01104 void
01105 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
01106                                             TemplateOrSpecializationInfo TSI) {
01107   assert(!TemplateOrInstantiation[Inst] &&
01108          "Already noted what the variable was instantiated from");
01109   TemplateOrInstantiation[Inst] = TSI;
01110 }
01111 
01112 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
01113                                                      const FunctionDecl *FD){
01114   assert(FD && "Specialization is 0");
01115   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
01116     = ClassScopeSpecializationPattern.find(FD);
01117   if (Pos == ClassScopeSpecializationPattern.end())
01118     return nullptr;
01119 
01120   return Pos->second;
01121 }
01122 
01123 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
01124                                         FunctionDecl *Pattern) {
01125   assert(FD && "Specialization is 0");
01126   assert(Pattern && "Class scope specialization pattern is 0");
01127   ClassScopeSpecializationPattern[FD] = Pattern;
01128 }
01129 
01130 NamedDecl *
01131 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
01132   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
01133     = InstantiatedFromUsingDecl.find(UUD);
01134   if (Pos == InstantiatedFromUsingDecl.end())
01135     return nullptr;
01136 
01137   return Pos->second;
01138 }
01139 
01140 void
01141 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
01142   assert((isa<UsingDecl>(Pattern) ||
01143           isa<UnresolvedUsingValueDecl>(Pattern) ||
01144           isa<UnresolvedUsingTypenameDecl>(Pattern)) && 
01145          "pattern decl is not a using decl");
01146   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
01147   InstantiatedFromUsingDecl[Inst] = Pattern;
01148 }
01149 
01150 UsingShadowDecl *
01151 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
01152   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
01153     = InstantiatedFromUsingShadowDecl.find(Inst);
01154   if (Pos == InstantiatedFromUsingShadowDecl.end())
01155     return nullptr;
01156 
01157   return Pos->second;
01158 }
01159 
01160 void
01161 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
01162                                                UsingShadowDecl *Pattern) {
01163   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
01164   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
01165 }
01166 
01167 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
01168   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
01169     = InstantiatedFromUnnamedFieldDecl.find(Field);
01170   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
01171     return nullptr;
01172 
01173   return Pos->second;
01174 }
01175 
01176 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
01177                                                      FieldDecl *Tmpl) {
01178   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
01179   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
01180   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
01181          "Already noted what unnamed field was instantiated from");
01182 
01183   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
01184 }
01185 
01186 ASTContext::overridden_cxx_method_iterator
01187 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
01188   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
01189     = OverriddenMethods.find(Method->getCanonicalDecl());
01190   if (Pos == OverriddenMethods.end())
01191     return nullptr;
01192 
01193   return Pos->second.begin();
01194 }
01195 
01196 ASTContext::overridden_cxx_method_iterator
01197 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
01198   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
01199     = OverriddenMethods.find(Method->getCanonicalDecl());
01200   if (Pos == OverriddenMethods.end())
01201     return nullptr;
01202 
01203   return Pos->second.end();
01204 }
01205 
01206 unsigned
01207 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
01208   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
01209     = OverriddenMethods.find(Method->getCanonicalDecl());
01210   if (Pos == OverriddenMethods.end())
01211     return 0;
01212 
01213   return Pos->second.size();
01214 }
01215 
01216 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 
01217                                      const CXXMethodDecl *Overridden) {
01218   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
01219   OverriddenMethods[Method].push_back(Overridden);
01220 }
01221 
01222 void ASTContext::getOverriddenMethods(
01223                       const NamedDecl *D,
01224                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
01225   assert(D);
01226 
01227   if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
01228     Overridden.append(overridden_methods_begin(CXXMethod),
01229                       overridden_methods_end(CXXMethod));
01230     return;
01231   }
01232 
01233   const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
01234   if (!Method)
01235     return;
01236 
01237   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
01238   Method->getOverriddenMethods(OverDecls);
01239   Overridden.append(OverDecls.begin(), OverDecls.end());
01240 }
01241 
01242 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
01243   assert(!Import->NextLocalImport && "Import declaration already in the chain");
01244   assert(!Import->isFromASTFile() && "Non-local import declaration");
01245   if (!FirstLocalImport) {
01246     FirstLocalImport = Import;
01247     LastLocalImport = Import;
01248     return;
01249   }
01250   
01251   LastLocalImport->NextLocalImport = Import;
01252   LastLocalImport = Import;
01253 }
01254 
01255 //===----------------------------------------------------------------------===//
01256 //                         Type Sizing and Analysis
01257 //===----------------------------------------------------------------------===//
01258 
01259 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
01260 /// scalar floating point type.
01261 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
01262   const BuiltinType *BT = T->getAs<BuiltinType>();
01263   assert(BT && "Not a floating point type!");
01264   switch (BT->getKind()) {
01265   default: llvm_unreachable("Not a floating point type!");
01266   case BuiltinType::Half:       return Target->getHalfFormat();
01267   case BuiltinType::Float:      return Target->getFloatFormat();
01268   case BuiltinType::Double:     return Target->getDoubleFormat();
01269   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
01270   }
01271 }
01272 
01273 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
01274   unsigned Align = Target->getCharWidth();
01275 
01276   bool UseAlignAttrOnly = false;
01277   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
01278     Align = AlignFromAttr;
01279 
01280     // __attribute__((aligned)) can increase or decrease alignment
01281     // *except* on a struct or struct member, where it only increases
01282     // alignment unless 'packed' is also specified.
01283     //
01284     // It is an error for alignas to decrease alignment, so we can
01285     // ignore that possibility;  Sema should diagnose it.
01286     if (isa<FieldDecl>(D)) {
01287       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
01288         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
01289     } else {
01290       UseAlignAttrOnly = true;
01291     }
01292   }
01293   else if (isa<FieldDecl>(D))
01294       UseAlignAttrOnly = 
01295         D->hasAttr<PackedAttr>() ||
01296         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
01297 
01298   // If we're using the align attribute only, just ignore everything
01299   // else about the declaration and its type.
01300   if (UseAlignAttrOnly) {
01301     // do nothing
01302 
01303   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
01304     QualType T = VD->getType();
01305     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
01306       if (ForAlignof)
01307         T = RT->getPointeeType();
01308       else
01309         T = getPointerType(RT->getPointeeType());
01310     }
01311     QualType BaseT = getBaseElementType(T);
01312     if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
01313       // Adjust alignments of declarations with array type by the
01314       // large-array alignment on the target.
01315       if (const ArrayType *arrayType = getAsArrayType(T)) {
01316         unsigned MinWidth = Target->getLargeArrayMinWidth();
01317         if (!ForAlignof && MinWidth) {
01318           if (isa<VariableArrayType>(arrayType))
01319             Align = std::max(Align, Target->getLargeArrayAlign());
01320           else if (isa<ConstantArrayType>(arrayType) &&
01321                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
01322             Align = std::max(Align, Target->getLargeArrayAlign());
01323         }
01324       }
01325       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
01326       if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
01327         if (VD->hasGlobalStorage())
01328           Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
01329       }
01330     }
01331 
01332     // Fields can be subject to extra alignment constraints, like if
01333     // the field is packed, the struct is packed, or the struct has a
01334     // a max-field-alignment constraint (#pragma pack).  So calculate
01335     // the actual alignment of the field within the struct, and then
01336     // (as we're expected to) constrain that by the alignment of the type.
01337     if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
01338       const RecordDecl *Parent = Field->getParent();
01339       // We can only produce a sensible answer if the record is valid.
01340       if (!Parent->isInvalidDecl()) {
01341         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
01342 
01343         // Start with the record's overall alignment.
01344         unsigned FieldAlign = toBits(Layout.getAlignment());
01345 
01346         // Use the GCD of that and the offset within the record.
01347         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
01348         if (Offset > 0) {
01349           // Alignment is always a power of 2, so the GCD will be a power of 2,
01350           // which means we get to do this crazy thing instead of Euclid's.
01351           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
01352           if (LowBitOfOffset < FieldAlign)
01353             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
01354         }
01355 
01356         Align = std::min(Align, FieldAlign);
01357       }
01358     }
01359   }
01360 
01361   return toCharUnitsFromBits(Align);
01362 }
01363 
01364 // getTypeInfoDataSizeInChars - Return the size of a type, in
01365 // chars. If the type is a record, its data size is returned.  This is
01366 // the size of the memcpy that's performed when assigning this type
01367 // using a trivial copy/move assignment operator.
01368 std::pair<CharUnits, CharUnits>
01369 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
01370   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
01371 
01372   // In C++, objects can sometimes be allocated into the tail padding
01373   // of a base-class subobject.  We decide whether that's possible
01374   // during class layout, so here we can just trust the layout results.
01375   if (getLangOpts().CPlusPlus) {
01376     if (const RecordType *RT = T->getAs<RecordType>()) {
01377       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
01378       sizeAndAlign.first = layout.getDataSize();
01379     }
01380   }
01381 
01382   return sizeAndAlign;
01383 }
01384 
01385 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
01386 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
01387 std::pair<CharUnits, CharUnits>
01388 static getConstantArrayInfoInChars(const ASTContext &Context,
01389                                    const ConstantArrayType *CAT) {
01390   std::pair<CharUnits, CharUnits> EltInfo =
01391       Context.getTypeInfoInChars(CAT->getElementType());
01392   uint64_t Size = CAT->getSize().getZExtValue();
01393   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
01394               (uint64_t)(-1)/Size) &&
01395          "Overflow in array type char size evaluation");
01396   uint64_t Width = EltInfo.first.getQuantity() * Size;
01397   unsigned Align = EltInfo.second.getQuantity();
01398   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
01399       Context.getTargetInfo().getPointerWidth(0) == 64)
01400     Width = llvm::RoundUpToAlignment(Width, Align);
01401   return std::make_pair(CharUnits::fromQuantity(Width),
01402                         CharUnits::fromQuantity(Align));
01403 }
01404 
01405 std::pair<CharUnits, CharUnits>
01406 ASTContext::getTypeInfoInChars(const Type *T) const {
01407   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
01408     return getConstantArrayInfoInChars(*this, CAT);
01409   TypeInfo Info = getTypeInfo(T);
01410   return std::make_pair(toCharUnitsFromBits(Info.Width),
01411                         toCharUnitsFromBits(Info.Align));
01412 }
01413 
01414 std::pair<CharUnits, CharUnits>
01415 ASTContext::getTypeInfoInChars(QualType T) const {
01416   return getTypeInfoInChars(T.getTypePtr());
01417 }
01418 
01419 bool ASTContext::isAlignmentRequired(const Type *T) const {
01420   return getTypeInfo(T).AlignIsRequired;
01421 }
01422 
01423 bool ASTContext::isAlignmentRequired(QualType T) const {
01424   return isAlignmentRequired(T.getTypePtr());
01425 }
01426 
01427 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
01428   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
01429   if (I != MemoizedTypeInfo.end())
01430     return I->second;
01431 
01432   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
01433   TypeInfo TI = getTypeInfoImpl(T);
01434   MemoizedTypeInfo[T] = TI;
01435   return TI;
01436 }
01437 
01438 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
01439 /// method does not work on incomplete types.
01440 ///
01441 /// FIXME: Pointers into different addr spaces could have different sizes and
01442 /// alignment requirements: getPointerInfo should take an AddrSpace, this
01443 /// should take a QualType, &c.
01444 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
01445   uint64_t Width = 0;
01446   unsigned Align = 8;
01447   bool AlignIsRequired = false;
01448   switch (T->getTypeClass()) {
01449 #define TYPE(Class, Base)
01450 #define ABSTRACT_TYPE(Class, Base)
01451 #define NON_CANONICAL_TYPE(Class, Base)
01452 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
01453 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
01454   case Type::Class:                                                            \
01455   assert(!T->isDependentType() && "should not see dependent types here");      \
01456   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
01457 #include "clang/AST/TypeNodes.def"
01458     llvm_unreachable("Should not see dependent types");
01459 
01460   case Type::FunctionNoProto:
01461   case Type::FunctionProto:
01462     // GCC extension: alignof(function) = 32 bits
01463     Width = 0;
01464     Align = 32;
01465     break;
01466 
01467   case Type::IncompleteArray:
01468   case Type::VariableArray:
01469     Width = 0;
01470     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
01471     break;
01472 
01473   case Type::ConstantArray: {
01474     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
01475 
01476     TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
01477     uint64_t Size = CAT->getSize().getZExtValue();
01478     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
01479            "Overflow in array type bit size evaluation");
01480     Width = EltInfo.Width * Size;
01481     Align = EltInfo.Align;
01482     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
01483         getTargetInfo().getPointerWidth(0) == 64)
01484       Width = llvm::RoundUpToAlignment(Width, Align);
01485     break;
01486   }
01487   case Type::ExtVector:
01488   case Type::Vector: {
01489     const VectorType *VT = cast<VectorType>(T);
01490     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
01491     Width = EltInfo.Width * VT->getNumElements();
01492     Align = Width;
01493     // If the alignment is not a power of 2, round up to the next power of 2.
01494     // This happens for non-power-of-2 length vectors.
01495     if (Align & (Align-1)) {
01496       Align = llvm::NextPowerOf2(Align);
01497       Width = llvm::RoundUpToAlignment(Width, Align);
01498     }
01499     // Adjust the alignment based on the target max.
01500     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
01501     if (TargetVectorAlign && TargetVectorAlign < Align)
01502       Align = TargetVectorAlign;
01503     break;
01504   }
01505 
01506   case Type::Builtin:
01507     switch (cast<BuiltinType>(T)->getKind()) {
01508     default: llvm_unreachable("Unknown builtin type!");
01509     case BuiltinType::Void:
01510       // GCC extension: alignof(void) = 8 bits.
01511       Width = 0;
01512       Align = 8;
01513       break;
01514 
01515     case BuiltinType::Bool:
01516       Width = Target->getBoolWidth();
01517       Align = Target->getBoolAlign();
01518       break;
01519     case BuiltinType::Char_S:
01520     case BuiltinType::Char_U:
01521     case BuiltinType::UChar:
01522     case BuiltinType::SChar:
01523       Width = Target->getCharWidth();
01524       Align = Target->getCharAlign();
01525       break;
01526     case BuiltinType::WChar_S:
01527     case BuiltinType::WChar_U:
01528       Width = Target->getWCharWidth();
01529       Align = Target->getWCharAlign();
01530       break;
01531     case BuiltinType::Char16:
01532       Width = Target->getChar16Width();
01533       Align = Target->getChar16Align();
01534       break;
01535     case BuiltinType::Char32:
01536       Width = Target->getChar32Width();
01537       Align = Target->getChar32Align();
01538       break;
01539     case BuiltinType::UShort:
01540     case BuiltinType::Short:
01541       Width = Target->getShortWidth();
01542       Align = Target->getShortAlign();
01543       break;
01544     case BuiltinType::UInt:
01545     case BuiltinType::Int:
01546       Width = Target->getIntWidth();
01547       Align = Target->getIntAlign();
01548       break;
01549     case BuiltinType::ULong:
01550     case BuiltinType::Long:
01551       Width = Target->getLongWidth();
01552       Align = Target->getLongAlign();
01553       break;
01554     case BuiltinType::ULongLong:
01555     case BuiltinType::LongLong:
01556       Width = Target->getLongLongWidth();
01557       Align = Target->getLongLongAlign();
01558       break;
01559     case BuiltinType::Int128:
01560     case BuiltinType::UInt128:
01561       Width = 128;
01562       Align = 128; // int128_t is 128-bit aligned on all targets.
01563       break;
01564     case BuiltinType::Half:
01565       Width = Target->getHalfWidth();
01566       Align = Target->getHalfAlign();
01567       break;
01568     case BuiltinType::Float:
01569       Width = Target->getFloatWidth();
01570       Align = Target->getFloatAlign();
01571       break;
01572     case BuiltinType::Double:
01573       Width = Target->getDoubleWidth();
01574       Align = Target->getDoubleAlign();
01575       break;
01576     case BuiltinType::LongDouble:
01577       Width = Target->getLongDoubleWidth();
01578       Align = Target->getLongDoubleAlign();
01579       break;
01580     case BuiltinType::NullPtr:
01581       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
01582       Align = Target->getPointerAlign(0); //   == sizeof(void*)
01583       break;
01584     case BuiltinType::ObjCId:
01585     case BuiltinType::ObjCClass:
01586     case BuiltinType::ObjCSel:
01587       Width = Target->getPointerWidth(0); 
01588       Align = Target->getPointerAlign(0);
01589       break;
01590     case BuiltinType::OCLSampler:
01591       // Samplers are modeled as integers.
01592       Width = Target->getIntWidth();
01593       Align = Target->getIntAlign();
01594       break;
01595     case BuiltinType::OCLEvent:
01596     case BuiltinType::OCLImage1d:
01597     case BuiltinType::OCLImage1dArray:
01598     case BuiltinType::OCLImage1dBuffer:
01599     case BuiltinType::OCLImage2d:
01600     case BuiltinType::OCLImage2dArray:
01601     case BuiltinType::OCLImage3d:
01602       // Currently these types are pointers to opaque types.
01603       Width = Target->getPointerWidth(0);
01604       Align = Target->getPointerAlign(0);
01605       break;
01606     }
01607     break;
01608   case Type::ObjCObjectPointer:
01609     Width = Target->getPointerWidth(0);
01610     Align = Target->getPointerAlign(0);
01611     break;
01612   case Type::BlockPointer: {
01613     unsigned AS = getTargetAddressSpace(
01614         cast<BlockPointerType>(T)->getPointeeType());
01615     Width = Target->getPointerWidth(AS);
01616     Align = Target->getPointerAlign(AS);
01617     break;
01618   }
01619   case Type::LValueReference:
01620   case Type::RValueReference: {
01621     // alignof and sizeof should never enter this code path here, so we go
01622     // the pointer route.
01623     unsigned AS = getTargetAddressSpace(
01624         cast<ReferenceType>(T)->getPointeeType());
01625     Width = Target->getPointerWidth(AS);
01626     Align = Target->getPointerAlign(AS);
01627     break;
01628   }
01629   case Type::Pointer: {
01630     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
01631     Width = Target->getPointerWidth(AS);
01632     Align = Target->getPointerAlign(AS);
01633     break;
01634   }
01635   case Type::MemberPointer: {
01636     const MemberPointerType *MPT = cast<MemberPointerType>(T);
01637     std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
01638     break;
01639   }
01640   case Type::Complex: {
01641     // Complex types have the same alignment as their elements, but twice the
01642     // size.
01643     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
01644     Width = EltInfo.Width * 2;
01645     Align = EltInfo.Align;
01646     break;
01647   }
01648   case Type::ObjCObject:
01649     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
01650   case Type::Adjusted:
01651   case Type::Decayed:
01652     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
01653   case Type::ObjCInterface: {
01654     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
01655     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
01656     Width = toBits(Layout.getSize());
01657     Align = toBits(Layout.getAlignment());
01658     break;
01659   }
01660   case Type::Record:
01661   case Type::Enum: {
01662     const TagType *TT = cast<TagType>(T);
01663 
01664     if (TT->getDecl()->isInvalidDecl()) {
01665       Width = 8;
01666       Align = 8;
01667       break;
01668     }
01669 
01670     if (const EnumType *ET = dyn_cast<EnumType>(TT))
01671       return getTypeInfo(ET->getDecl()->getIntegerType());
01672 
01673     const RecordType *RT = cast<RecordType>(TT);
01674     const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
01675     Width = toBits(Layout.getSize());
01676     Align = toBits(Layout.getAlignment());
01677     break;
01678   }
01679 
01680   case Type::SubstTemplateTypeParm:
01681     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
01682                        getReplacementType().getTypePtr());
01683 
01684   case Type::Auto: {
01685     const AutoType *A = cast<AutoType>(T);
01686     assert(!A->getDeducedType().isNull() &&
01687            "cannot request the size of an undeduced or dependent auto type");
01688     return getTypeInfo(A->getDeducedType().getTypePtr());
01689   }
01690 
01691   case Type::Paren:
01692     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
01693 
01694   case Type::Typedef: {
01695     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
01696     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
01697     // If the typedef has an aligned attribute on it, it overrides any computed
01698     // alignment we have.  This violates the GCC documentation (which says that
01699     // attribute(aligned) can only round up) but matches its implementation.
01700     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
01701       Align = AttrAlign;
01702       AlignIsRequired = true;
01703     } else {
01704       Align = Info.Align;
01705       AlignIsRequired = Info.AlignIsRequired;
01706     }
01707     Width = Info.Width;
01708     break;
01709   }
01710 
01711   case Type::Elaborated:
01712     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
01713 
01714   case Type::Attributed:
01715     return getTypeInfo(
01716                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
01717 
01718   case Type::Atomic: {
01719     // Start with the base type information.
01720     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
01721     Width = Info.Width;
01722     Align = Info.Align;
01723 
01724     // If the size of the type doesn't exceed the platform's max
01725     // atomic promotion width, make the size and alignment more
01726     // favorable to atomic operations:
01727     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
01728       // Round the size up to a power of 2.
01729       if (!llvm::isPowerOf2_64(Width))
01730         Width = llvm::NextPowerOf2(Width);
01731 
01732       // Set the alignment equal to the size.
01733       Align = static_cast<unsigned>(Width);
01734     }
01735   }
01736 
01737   }
01738 
01739   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
01740   return TypeInfo(Width, Align, AlignIsRequired);
01741 }
01742 
01743 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
01744 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
01745   return CharUnits::fromQuantity(BitSize / getCharWidth());
01746 }
01747 
01748 /// toBits - Convert a size in characters to a size in characters.
01749 int64_t ASTContext::toBits(CharUnits CharSize) const {
01750   return CharSize.getQuantity() * getCharWidth();
01751 }
01752 
01753 /// getTypeSizeInChars - Return the size of the specified type, in characters.
01754 /// This method does not work on incomplete types.
01755 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
01756   return getTypeInfoInChars(T).first;
01757 }
01758 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
01759   return getTypeInfoInChars(T).first;
01760 }
01761 
01762 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 
01763 /// characters. This method does not work on incomplete types.
01764 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
01765   return toCharUnitsFromBits(getTypeAlign(T));
01766 }
01767 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
01768   return toCharUnitsFromBits(getTypeAlign(T));
01769 }
01770 
01771 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
01772 /// type for the current target in bits.  This can be different than the ABI
01773 /// alignment in cases where it is beneficial for performance to overalign
01774 /// a data type.
01775 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
01776   TypeInfo TI = getTypeInfo(T);
01777   unsigned ABIAlign = TI.Align;
01778 
01779   if (Target->getTriple().getArch() == llvm::Triple::xcore)
01780     return ABIAlign;  // Never overalign on XCore.
01781 
01782   // Double and long long should be naturally aligned if possible.
01783   T = T->getBaseElementTypeUnsafe();
01784   if (const ComplexType *CT = T->getAs<ComplexType>())
01785     T = CT->getElementType().getTypePtr();
01786   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
01787       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
01788       T->isSpecificBuiltinType(BuiltinType::ULongLong))
01789     // Don't increase the alignment if an alignment attribute was specified on a
01790     // typedef declaration.
01791     if (!TI.AlignIsRequired)
01792       return std::max(ABIAlign, (unsigned)getTypeSize(T));
01793 
01794   return ABIAlign;
01795 }
01796 
01797 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
01798 /// to a global variable of the specified type.
01799 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
01800   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
01801 }
01802 
01803 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
01804 /// should be given to a global variable of the specified type.
01805 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
01806   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
01807 }
01808 
01809 /// DeepCollectObjCIvars -
01810 /// This routine first collects all declared, but not synthesized, ivars in
01811 /// super class and then collects all ivars, including those synthesized for
01812 /// current class. This routine is used for implementation of current class
01813 /// when all ivars, declared and synthesized are known.
01814 ///
01815 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
01816                                       bool leafClass,
01817                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
01818   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
01819     DeepCollectObjCIvars(SuperClass, false, Ivars);
01820   if (!leafClass) {
01821     for (const auto *I : OI->ivars())
01822       Ivars.push_back(I);
01823   } else {
01824     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
01825     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 
01826          Iv= Iv->getNextIvar())
01827       Ivars.push_back(Iv);
01828   }
01829 }
01830 
01831 /// CollectInheritedProtocols - Collect all protocols in current class and
01832 /// those inherited by it.
01833 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
01834                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
01835   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
01836     // We can use protocol_iterator here instead of
01837     // all_referenced_protocol_iterator since we are walking all categories.    
01838     for (auto *Proto : OI->all_referenced_protocols()) {
01839       Protocols.insert(Proto->getCanonicalDecl());
01840       for (auto *P : Proto->protocols()) {
01841         Protocols.insert(P->getCanonicalDecl());
01842         CollectInheritedProtocols(P, Protocols);
01843       }
01844     }
01845     
01846     // Categories of this Interface.
01847     for (const auto *Cat : OI->visible_categories())
01848       CollectInheritedProtocols(Cat, Protocols);
01849 
01850     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
01851       while (SD) {
01852         CollectInheritedProtocols(SD, Protocols);
01853         SD = SD->getSuperClass();
01854       }
01855   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01856     for (auto *Proto : OC->protocols()) {
01857       Protocols.insert(Proto->getCanonicalDecl());
01858       for (const auto *P : Proto->protocols())
01859         CollectInheritedProtocols(P, Protocols);
01860     }
01861   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
01862     for (auto *Proto : OP->protocols()) {
01863       Protocols.insert(Proto->getCanonicalDecl());
01864       for (const auto *P : Proto->protocols())
01865         CollectInheritedProtocols(P, Protocols);
01866     }
01867   }
01868 }
01869 
01870 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
01871   unsigned count = 0;  
01872   // Count ivars declared in class extension.
01873   for (const auto *Ext : OI->known_extensions())
01874     count += Ext->ivar_size();
01875   
01876   // Count ivar defined in this class's implementation.  This
01877   // includes synthesized ivars.
01878   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
01879     count += ImplDecl->ivar_size();
01880 
01881   return count;
01882 }
01883 
01884 bool ASTContext::isSentinelNullExpr(const Expr *E) {
01885   if (!E)
01886     return false;
01887 
01888   // nullptr_t is always treated as null.
01889   if (E->getType()->isNullPtrType()) return true;
01890 
01891   if (E->getType()->isAnyPointerType() &&
01892       E->IgnoreParenCasts()->isNullPointerConstant(*this,
01893                                                 Expr::NPC_ValueDependentIsNull))
01894     return true;
01895 
01896   // Unfortunately, __null has type 'int'.
01897   if (isa<GNUNullExpr>(E)) return true;
01898 
01899   return false;
01900 }
01901 
01902 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
01903 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
01904   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
01905     I = ObjCImpls.find(D);
01906   if (I != ObjCImpls.end())
01907     return cast<ObjCImplementationDecl>(I->second);
01908   return nullptr;
01909 }
01910 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
01911 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
01912   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
01913     I = ObjCImpls.find(D);
01914   if (I != ObjCImpls.end())
01915     return cast<ObjCCategoryImplDecl>(I->second);
01916   return nullptr;
01917 }
01918 
01919 /// \brief Set the implementation of ObjCInterfaceDecl.
01920 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
01921                            ObjCImplementationDecl *ImplD) {
01922   assert(IFaceD && ImplD && "Passed null params");
01923   ObjCImpls[IFaceD] = ImplD;
01924 }
01925 /// \brief Set the implementation of ObjCCategoryDecl.
01926 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
01927                            ObjCCategoryImplDecl *ImplD) {
01928   assert(CatD && ImplD && "Passed null params");
01929   ObjCImpls[CatD] = ImplD;
01930 }
01931 
01932 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
01933                                               const NamedDecl *ND) const {
01934   if (const ObjCInterfaceDecl *ID =
01935           dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
01936     return ID;
01937   if (const ObjCCategoryDecl *CD =
01938           dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
01939     return CD->getClassInterface();
01940   if (const ObjCImplDecl *IMD =
01941           dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
01942     return IMD->getClassInterface();
01943 
01944   return nullptr;
01945 }
01946 
01947 /// \brief Get the copy initialization expression of VarDecl,or NULL if 
01948 /// none exists.
01949 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
01950   assert(VD && "Passed null params");
01951   assert(VD->hasAttr<BlocksAttr>() && 
01952          "getBlockVarCopyInits - not __block var");
01953   llvm::DenseMap<const VarDecl*, Expr*>::iterator
01954     I = BlockVarCopyInits.find(VD);
01955   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
01956 }
01957 
01958 /// \brief Set the copy inialization expression of a block var decl.
01959 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
01960   assert(VD && Init && "Passed null params");
01961   assert(VD->hasAttr<BlocksAttr>() && 
01962          "setBlockVarCopyInits - not __block var");
01963   BlockVarCopyInits[VD] = Init;
01964 }
01965 
01966 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
01967                                                  unsigned DataSize) const {
01968   if (!DataSize)
01969     DataSize = TypeLoc::getFullDataSizeForType(T);
01970   else
01971     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
01972            "incorrect data size provided to CreateTypeSourceInfo!");
01973 
01974   TypeSourceInfo *TInfo =
01975     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
01976   new (TInfo) TypeSourceInfo(T);
01977   return TInfo;
01978 }
01979 
01980 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
01981                                                      SourceLocation L) const {
01982   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
01983   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
01984   return DI;
01985 }
01986 
01987 const ASTRecordLayout &
01988 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
01989   return getObjCLayout(D, nullptr);
01990 }
01991 
01992 const ASTRecordLayout &
01993 ASTContext::getASTObjCImplementationLayout(
01994                                         const ObjCImplementationDecl *D) const {
01995   return getObjCLayout(D->getClassInterface(), D);
01996 }
01997 
01998 //===----------------------------------------------------------------------===//
01999 //                   Type creation/memoization methods
02000 //===----------------------------------------------------------------------===//
02001 
02002 QualType
02003 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
02004   unsigned fastQuals = quals.getFastQualifiers();
02005   quals.removeFastQualifiers();
02006 
02007   // Check if we've already instantiated this type.
02008   llvm::FoldingSetNodeID ID;
02009   ExtQuals::Profile(ID, baseType, quals);
02010   void *insertPos = nullptr;
02011   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
02012     assert(eq->getQualifiers() == quals);
02013     return QualType(eq, fastQuals);
02014   }
02015 
02016   // If the base type is not canonical, make the appropriate canonical type.
02017   QualType canon;
02018   if (!baseType->isCanonicalUnqualified()) {
02019     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
02020     canonSplit.Quals.addConsistentQualifiers(quals);
02021     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
02022 
02023     // Re-find the insert position.
02024     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
02025   }
02026 
02027   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
02028   ExtQualNodes.InsertNode(eq, insertPos);
02029   return QualType(eq, fastQuals);
02030 }
02031 
02032 QualType
02033 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
02034   QualType CanT = getCanonicalType(T);
02035   if (CanT.getAddressSpace() == AddressSpace)
02036     return T;
02037 
02038   // If we are composing extended qualifiers together, merge together
02039   // into one ExtQuals node.
02040   QualifierCollector Quals;
02041   const Type *TypeNode = Quals.strip(T);
02042 
02043   // If this type already has an address space specified, it cannot get
02044   // another one.
02045   assert(!Quals.hasAddressSpace() &&
02046          "Type cannot be in multiple addr spaces!");
02047   Quals.addAddressSpace(AddressSpace);
02048 
02049   return getExtQualType(TypeNode, Quals);
02050 }
02051 
02052 QualType ASTContext::getObjCGCQualType(QualType T,
02053                                        Qualifiers::GC GCAttr) const {
02054   QualType CanT = getCanonicalType(T);
02055   if (CanT.getObjCGCAttr() == GCAttr)
02056     return T;
02057 
02058   if (const PointerType *ptr = T->getAs<PointerType>()) {
02059     QualType Pointee = ptr->getPointeeType();
02060     if (Pointee->isAnyPointerType()) {
02061       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
02062       return getPointerType(ResultType);
02063     }
02064   }
02065 
02066   // If we are composing extended qualifiers together, merge together
02067   // into one ExtQuals node.
02068   QualifierCollector Quals;
02069   const Type *TypeNode = Quals.strip(T);
02070 
02071   // If this type already has an ObjCGC specified, it cannot get
02072   // another one.
02073   assert(!Quals.hasObjCGCAttr() &&
02074          "Type cannot have multiple ObjCGCs!");
02075   Quals.addObjCGCAttr(GCAttr);
02076 
02077   return getExtQualType(TypeNode, Quals);
02078 }
02079 
02080 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
02081                                                    FunctionType::ExtInfo Info) {
02082   if (T->getExtInfo() == Info)
02083     return T;
02084 
02085   QualType Result;
02086   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
02087     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
02088   } else {
02089     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
02090     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
02091     EPI.ExtInfo = Info;
02092     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
02093   }
02094 
02095   return cast<FunctionType>(Result.getTypePtr());
02096 }
02097 
02098 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
02099                                                  QualType ResultType) {
02100   FD = FD->getMostRecentDecl();
02101   while (true) {
02102     const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
02103     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
02104     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
02105     if (FunctionDecl *Next = FD->getPreviousDecl())
02106       FD = Next;
02107     else
02108       break;
02109   }
02110   if (ASTMutationListener *L = getASTMutationListener())
02111     L->DeducedReturnType(FD, ResultType);
02112 }
02113 
02114 /// Get a function type and produce the equivalent function type with the
02115 /// specified exception specification. Type sugar that can be present on a
02116 /// declaration of a function with an exception specification is permitted
02117 /// and preserved. Other type sugar (for instance, typedefs) is not.
02118 static QualType getFunctionTypeWithExceptionSpec(
02119     ASTContext &Context, QualType Orig,
02120     const FunctionProtoType::ExceptionSpecInfo &ESI) {
02121   // Might have some parens.
02122   if (auto *PT = dyn_cast<ParenType>(Orig))
02123     return Context.getParenType(
02124         getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
02125 
02126   // Might have a calling-convention attribute.
02127   if (auto *AT = dyn_cast<AttributedType>(Orig))
02128     return Context.getAttributedType(
02129         AT->getAttrKind(),
02130         getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
02131         getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
02132                                          ESI));
02133 
02134   // Anything else must be a function type. Rebuild it with the new exception
02135   // specification.
02136   const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
02137   return Context.getFunctionType(
02138       Proto->getReturnType(), Proto->getParamTypes(),
02139       Proto->getExtProtoInfo().withExceptionSpec(ESI));
02140 }
02141 
02142 void ASTContext::adjustExceptionSpec(
02143     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
02144     bool AsWritten) {
02145   // Update the type.
02146   QualType Updated =
02147       getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
02148   FD->setType(Updated);
02149 
02150   if (!AsWritten)
02151     return;
02152 
02153   // Update the type in the type source information too.
02154   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
02155     // If the type and the type-as-written differ, we may need to update
02156     // the type-as-written too.
02157     if (TSInfo->getType() != FD->getType())
02158       Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
02159 
02160     // FIXME: When we get proper type location information for exceptions,
02161     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
02162     // up the TypeSourceInfo;
02163     assert(TypeLoc::getFullDataSizeForType(Updated) ==
02164                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
02165            "TypeLoc size mismatch from updating exception specification");
02166     TSInfo->overrideType(Updated);
02167   }
02168 }
02169 
02170 /// getComplexType - Return the uniqued reference to the type for a complex
02171 /// number with the specified element type.
02172 QualType ASTContext::getComplexType(QualType T) const {
02173   // Unique pointers, to guarantee there is only one pointer of a particular
02174   // structure.
02175   llvm::FoldingSetNodeID ID;
02176   ComplexType::Profile(ID, T);
02177 
02178   void *InsertPos = nullptr;
02179   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
02180     return QualType(CT, 0);
02181 
02182   // If the pointee type isn't canonical, this won't be a canonical type either,
02183   // so fill in the canonical type field.
02184   QualType Canonical;
02185   if (!T.isCanonical()) {
02186     Canonical = getComplexType(getCanonicalType(T));
02187 
02188     // Get the new insert position for the node we care about.
02189     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
02190     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02191   }
02192   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
02193   Types.push_back(New);
02194   ComplexTypes.InsertNode(New, InsertPos);
02195   return QualType(New, 0);
02196 }
02197 
02198 /// getPointerType - Return the uniqued reference to the type for a pointer to
02199 /// the specified type.
02200 QualType ASTContext::getPointerType(QualType T) const {
02201   // Unique pointers, to guarantee there is only one pointer of a particular
02202   // structure.
02203   llvm::FoldingSetNodeID ID;
02204   PointerType::Profile(ID, T);
02205 
02206   void *InsertPos = nullptr;
02207   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
02208     return QualType(PT, 0);
02209 
02210   // If the pointee type isn't canonical, this won't be a canonical type either,
02211   // so fill in the canonical type field.
02212   QualType Canonical;
02213   if (!T.isCanonical()) {
02214     Canonical = getPointerType(getCanonicalType(T));
02215 
02216     // Get the new insert position for the node we care about.
02217     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
02218     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02219   }
02220   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
02221   Types.push_back(New);
02222   PointerTypes.InsertNode(New, InsertPos);
02223   return QualType(New, 0);
02224 }
02225 
02226 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
02227   llvm::FoldingSetNodeID ID;
02228   AdjustedType::Profile(ID, Orig, New);
02229   void *InsertPos = nullptr;
02230   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
02231   if (AT)
02232     return QualType(AT, 0);
02233 
02234   QualType Canonical = getCanonicalType(New);
02235 
02236   // Get the new insert position for the node we care about.
02237   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
02238   assert(!AT && "Shouldn't be in the map!");
02239 
02240   AT = new (*this, TypeAlignment)
02241       AdjustedType(Type::Adjusted, Orig, New, Canonical);
02242   Types.push_back(AT);
02243   AdjustedTypes.InsertNode(AT, InsertPos);
02244   return QualType(AT, 0);
02245 }
02246 
02247 QualType ASTContext::getDecayedType(QualType T) const {
02248   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
02249 
02250   QualType Decayed;
02251 
02252   // C99 6.7.5.3p7:
02253   //   A declaration of a parameter as "array of type" shall be
02254   //   adjusted to "qualified pointer to type", where the type
02255   //   qualifiers (if any) are those specified within the [ and ] of
02256   //   the array type derivation.
02257   if (T->isArrayType())
02258     Decayed = getArrayDecayedType(T);
02259 
02260   // C99 6.7.5.3p8:
02261   //   A declaration of a parameter as "function returning type"
02262   //   shall be adjusted to "pointer to function returning type", as
02263   //   in 6.3.2.1.
02264   if (T->isFunctionType())
02265     Decayed = getPointerType(T);
02266 
02267   llvm::FoldingSetNodeID ID;
02268   AdjustedType::Profile(ID, T, Decayed);
02269   void *InsertPos = nullptr;
02270   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
02271   if (AT)
02272     return QualType(AT, 0);
02273 
02274   QualType Canonical = getCanonicalType(Decayed);
02275 
02276   // Get the new insert position for the node we care about.
02277   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
02278   assert(!AT && "Shouldn't be in the map!");
02279 
02280   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
02281   Types.push_back(AT);
02282   AdjustedTypes.InsertNode(AT, InsertPos);
02283   return QualType(AT, 0);
02284 }
02285 
02286 /// getBlockPointerType - Return the uniqued reference to the type for
02287 /// a pointer to the specified block.
02288 QualType ASTContext::getBlockPointerType(QualType T) const {
02289   assert(T->isFunctionType() && "block of function types only");
02290   // Unique pointers, to guarantee there is only one block of a particular
02291   // structure.
02292   llvm::FoldingSetNodeID ID;
02293   BlockPointerType::Profile(ID, T);
02294 
02295   void *InsertPos = nullptr;
02296   if (BlockPointerType *PT =
02297         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
02298     return QualType(PT, 0);
02299 
02300   // If the block pointee type isn't canonical, this won't be a canonical
02301   // type either so fill in the canonical type field.
02302   QualType Canonical;
02303   if (!T.isCanonical()) {
02304     Canonical = getBlockPointerType(getCanonicalType(T));
02305 
02306     // Get the new insert position for the node we care about.
02307     BlockPointerType *NewIP =
02308       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
02309     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02310   }
02311   BlockPointerType *New
02312     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
02313   Types.push_back(New);
02314   BlockPointerTypes.InsertNode(New, InsertPos);
02315   return QualType(New, 0);
02316 }
02317 
02318 /// getLValueReferenceType - Return the uniqued reference to the type for an
02319 /// lvalue reference to the specified type.
02320 QualType
02321 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
02322   assert(getCanonicalType(T) != OverloadTy && 
02323          "Unresolved overloaded function type");
02324   
02325   // Unique pointers, to guarantee there is only one pointer of a particular
02326   // structure.
02327   llvm::FoldingSetNodeID ID;
02328   ReferenceType::Profile(ID, T, SpelledAsLValue);
02329 
02330   void *InsertPos = nullptr;
02331   if (LValueReferenceType *RT =
02332         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
02333     return QualType(RT, 0);
02334 
02335   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
02336 
02337   // If the referencee type isn't canonical, this won't be a canonical type
02338   // either, so fill in the canonical type field.
02339   QualType Canonical;
02340   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
02341     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
02342     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
02343 
02344     // Get the new insert position for the node we care about.
02345     LValueReferenceType *NewIP =
02346       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
02347     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02348   }
02349 
02350   LValueReferenceType *New
02351     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
02352                                                      SpelledAsLValue);
02353   Types.push_back(New);
02354   LValueReferenceTypes.InsertNode(New, InsertPos);
02355 
02356   return QualType(New, 0);
02357 }
02358 
02359 /// getRValueReferenceType - Return the uniqued reference to the type for an
02360 /// rvalue reference to the specified type.
02361 QualType ASTContext::getRValueReferenceType(QualType T) const {
02362   // Unique pointers, to guarantee there is only one pointer of a particular
02363   // structure.
02364   llvm::FoldingSetNodeID ID;
02365   ReferenceType::Profile(ID, T, false);
02366 
02367   void *InsertPos = nullptr;
02368   if (RValueReferenceType *RT =
02369         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
02370     return QualType(RT, 0);
02371 
02372   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
02373 
02374   // If the referencee type isn't canonical, this won't be a canonical type
02375   // either, so fill in the canonical type field.
02376   QualType Canonical;
02377   if (InnerRef || !T.isCanonical()) {
02378     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
02379     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
02380 
02381     // Get the new insert position for the node we care about.
02382     RValueReferenceType *NewIP =
02383       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
02384     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02385   }
02386 
02387   RValueReferenceType *New
02388     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
02389   Types.push_back(New);
02390   RValueReferenceTypes.InsertNode(New, InsertPos);
02391   return QualType(New, 0);
02392 }
02393 
02394 /// getMemberPointerType - Return the uniqued reference to the type for a
02395 /// member pointer to the specified type, in the specified class.
02396 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
02397   // Unique pointers, to guarantee there is only one pointer of a particular
02398   // structure.
02399   llvm::FoldingSetNodeID ID;
02400   MemberPointerType::Profile(ID, T, Cls);
02401 
02402   void *InsertPos = nullptr;
02403   if (MemberPointerType *PT =
02404       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
02405     return QualType(PT, 0);
02406 
02407   // If the pointee or class type isn't canonical, this won't be a canonical
02408   // type either, so fill in the canonical type field.
02409   QualType Canonical;
02410   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
02411     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
02412 
02413     // Get the new insert position for the node we care about.
02414     MemberPointerType *NewIP =
02415       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
02416     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02417   }
02418   MemberPointerType *New
02419     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
02420   Types.push_back(New);
02421   MemberPointerTypes.InsertNode(New, InsertPos);
02422   return QualType(New, 0);
02423 }
02424 
02425 /// getConstantArrayType - Return the unique reference to the type for an
02426 /// array of the specified element type.
02427 QualType ASTContext::getConstantArrayType(QualType EltTy,
02428                                           const llvm::APInt &ArySizeIn,
02429                                           ArrayType::ArraySizeModifier ASM,
02430                                           unsigned IndexTypeQuals) const {
02431   assert((EltTy->isDependentType() ||
02432           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
02433          "Constant array of VLAs is illegal!");
02434 
02435   // Convert the array size into a canonical width matching the pointer size for
02436   // the target.
02437   llvm::APInt ArySize(ArySizeIn);
02438   ArySize =
02439     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
02440 
02441   llvm::FoldingSetNodeID ID;
02442   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
02443 
02444   void *InsertPos = nullptr;
02445   if (ConstantArrayType *ATP =
02446       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
02447     return QualType(ATP, 0);
02448 
02449   // If the element type isn't canonical or has qualifiers, this won't
02450   // be a canonical type either, so fill in the canonical type field.
02451   QualType Canon;
02452   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
02453     SplitQualType canonSplit = getCanonicalType(EltTy).split();
02454     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
02455                                  ASM, IndexTypeQuals);
02456     Canon = getQualifiedType(Canon, canonSplit.Quals);
02457 
02458     // Get the new insert position for the node we care about.
02459     ConstantArrayType *NewIP =
02460       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
02461     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02462   }
02463 
02464   ConstantArrayType *New = new(*this,TypeAlignment)
02465     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
02466   ConstantArrayTypes.InsertNode(New, InsertPos);
02467   Types.push_back(New);
02468   return QualType(New, 0);
02469 }
02470 
02471 /// getVariableArrayDecayedType - Turns the given type, which may be
02472 /// variably-modified, into the corresponding type with all the known
02473 /// sizes replaced with [*].
02474 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
02475   // Vastly most common case.
02476   if (!type->isVariablyModifiedType()) return type;
02477 
02478   QualType result;
02479 
02480   SplitQualType split = type.getSplitDesugaredType();
02481   const Type *ty = split.Ty;
02482   switch (ty->getTypeClass()) {
02483 #define TYPE(Class, Base)
02484 #define ABSTRACT_TYPE(Class, Base)
02485 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
02486 #include "clang/AST/TypeNodes.def"
02487     llvm_unreachable("didn't desugar past all non-canonical types?");
02488 
02489   // These types should never be variably-modified.
02490   case Type::Builtin:
02491   case Type::Complex:
02492   case Type::Vector:
02493   case Type::ExtVector:
02494   case Type::DependentSizedExtVector:
02495   case Type::ObjCObject:
02496   case Type::ObjCInterface:
02497   case Type::ObjCObjectPointer:
02498   case Type::Record:
02499   case Type::Enum:
02500   case Type::UnresolvedUsing:
02501   case Type::TypeOfExpr:
02502   case Type::TypeOf:
02503   case Type::Decltype:
02504   case Type::UnaryTransform:
02505   case Type::DependentName:
02506   case Type::InjectedClassName:
02507   case Type::TemplateSpecialization:
02508   case Type::DependentTemplateSpecialization:
02509   case Type::TemplateTypeParm:
02510   case Type::SubstTemplateTypeParmPack:
02511   case Type::Auto:
02512   case Type::PackExpansion:
02513     llvm_unreachable("type should never be variably-modified");
02514 
02515   // These types can be variably-modified but should never need to
02516   // further decay.
02517   case Type::FunctionNoProto:
02518   case Type::FunctionProto:
02519   case Type::BlockPointer:
02520   case Type::MemberPointer:
02521     return type;
02522 
02523   // These types can be variably-modified.  All these modifications
02524   // preserve structure except as noted by comments.
02525   // TODO: if we ever care about optimizing VLAs, there are no-op
02526   // optimizations available here.
02527   case Type::Pointer:
02528     result = getPointerType(getVariableArrayDecayedType(
02529                               cast<PointerType>(ty)->getPointeeType()));
02530     break;
02531 
02532   case Type::LValueReference: {
02533     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
02534     result = getLValueReferenceType(
02535                  getVariableArrayDecayedType(lv->getPointeeType()),
02536                                     lv->isSpelledAsLValue());
02537     break;
02538   }
02539 
02540   case Type::RValueReference: {
02541     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
02542     result = getRValueReferenceType(
02543                  getVariableArrayDecayedType(lv->getPointeeType()));
02544     break;
02545   }
02546 
02547   case Type::Atomic: {
02548     const AtomicType *at = cast<AtomicType>(ty);
02549     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
02550     break;
02551   }
02552 
02553   case Type::ConstantArray: {
02554     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
02555     result = getConstantArrayType(
02556                  getVariableArrayDecayedType(cat->getElementType()),
02557                                   cat->getSize(),
02558                                   cat->getSizeModifier(),
02559                                   cat->getIndexTypeCVRQualifiers());
02560     break;
02561   }
02562 
02563   case Type::DependentSizedArray: {
02564     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
02565     result = getDependentSizedArrayType(
02566                  getVariableArrayDecayedType(dat->getElementType()),
02567                                         dat->getSizeExpr(),
02568                                         dat->getSizeModifier(),
02569                                         dat->getIndexTypeCVRQualifiers(),
02570                                         dat->getBracketsRange());
02571     break;
02572   }
02573 
02574   // Turn incomplete types into [*] types.
02575   case Type::IncompleteArray: {
02576     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
02577     result = getVariableArrayType(
02578                  getVariableArrayDecayedType(iat->getElementType()),
02579                                   /*size*/ nullptr,
02580                                   ArrayType::Normal,
02581                                   iat->getIndexTypeCVRQualifiers(),
02582                                   SourceRange());
02583     break;
02584   }
02585 
02586   // Turn VLA types into [*] types.
02587   case Type::VariableArray: {
02588     const VariableArrayType *vat = cast<VariableArrayType>(ty);
02589     result = getVariableArrayType(
02590                  getVariableArrayDecayedType(vat->getElementType()),
02591                                   /*size*/ nullptr,
02592                                   ArrayType::Star,
02593                                   vat->getIndexTypeCVRQualifiers(),
02594                                   vat->getBracketsRange());
02595     break;
02596   }
02597   }
02598 
02599   // Apply the top-level qualifiers from the original.
02600   return getQualifiedType(result, split.Quals);
02601 }
02602 
02603 /// getVariableArrayType - Returns a non-unique reference to the type for a
02604 /// variable array of the specified element type.
02605 QualType ASTContext::getVariableArrayType(QualType EltTy,
02606                                           Expr *NumElts,
02607                                           ArrayType::ArraySizeModifier ASM,
02608                                           unsigned IndexTypeQuals,
02609                                           SourceRange Brackets) const {
02610   // Since we don't unique expressions, it isn't possible to unique VLA's
02611   // that have an expression provided for their size.
02612   QualType Canon;
02613   
02614   // Be sure to pull qualifiers off the element type.
02615   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
02616     SplitQualType canonSplit = getCanonicalType(EltTy).split();
02617     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
02618                                  IndexTypeQuals, Brackets);
02619     Canon = getQualifiedType(Canon, canonSplit.Quals);
02620   }
02621   
02622   VariableArrayType *New = new(*this, TypeAlignment)
02623     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
02624 
02625   VariableArrayTypes.push_back(New);
02626   Types.push_back(New);
02627   return QualType(New, 0);
02628 }
02629 
02630 /// getDependentSizedArrayType - Returns a non-unique reference to
02631 /// the type for a dependently-sized array of the specified element
02632 /// type.
02633 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
02634                                                 Expr *numElements,
02635                                                 ArrayType::ArraySizeModifier ASM,
02636                                                 unsigned elementTypeQuals,
02637                                                 SourceRange brackets) const {
02638   assert((!numElements || numElements->isTypeDependent() || 
02639           numElements->isValueDependent()) &&
02640          "Size must be type- or value-dependent!");
02641 
02642   // Dependently-sized array types that do not have a specified number
02643   // of elements will have their sizes deduced from a dependent
02644   // initializer.  We do no canonicalization here at all, which is okay
02645   // because they can't be used in most locations.
02646   if (!numElements) {
02647     DependentSizedArrayType *newType
02648       = new (*this, TypeAlignment)
02649           DependentSizedArrayType(*this, elementType, QualType(),
02650                                   numElements, ASM, elementTypeQuals,
02651                                   brackets);
02652     Types.push_back(newType);
02653     return QualType(newType, 0);
02654   }
02655 
02656   // Otherwise, we actually build a new type every time, but we
02657   // also build a canonical type.
02658 
02659   SplitQualType canonElementType = getCanonicalType(elementType).split();
02660 
02661   void *insertPos = nullptr;
02662   llvm::FoldingSetNodeID ID;
02663   DependentSizedArrayType::Profile(ID, *this,
02664                                    QualType(canonElementType.Ty, 0),
02665                                    ASM, elementTypeQuals, numElements);
02666 
02667   // Look for an existing type with these properties.
02668   DependentSizedArrayType *canonTy =
02669     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
02670 
02671   // If we don't have one, build one.
02672   if (!canonTy) {
02673     canonTy = new (*this, TypeAlignment)
02674       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
02675                               QualType(), numElements, ASM, elementTypeQuals,
02676                               brackets);
02677     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
02678     Types.push_back(canonTy);
02679   }
02680 
02681   // Apply qualifiers from the element type to the array.
02682   QualType canon = getQualifiedType(QualType(canonTy,0),
02683                                     canonElementType.Quals);
02684 
02685   // If we didn't need extra canonicalization for the element type,
02686   // then just use that as our result.
02687   if (QualType(canonElementType.Ty, 0) == elementType)
02688     return canon;
02689 
02690   // Otherwise, we need to build a type which follows the spelling
02691   // of the element type.
02692   DependentSizedArrayType *sugaredType
02693     = new (*this, TypeAlignment)
02694         DependentSizedArrayType(*this, elementType, canon, numElements,
02695                                 ASM, elementTypeQuals, brackets);
02696   Types.push_back(sugaredType);
02697   return QualType(sugaredType, 0);
02698 }
02699 
02700 QualType ASTContext::getIncompleteArrayType(QualType elementType,
02701                                             ArrayType::ArraySizeModifier ASM,
02702                                             unsigned elementTypeQuals) const {
02703   llvm::FoldingSetNodeID ID;
02704   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
02705 
02706   void *insertPos = nullptr;
02707   if (IncompleteArrayType *iat =
02708        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
02709     return QualType(iat, 0);
02710 
02711   // If the element type isn't canonical, this won't be a canonical type
02712   // either, so fill in the canonical type field.  We also have to pull
02713   // qualifiers off the element type.
02714   QualType canon;
02715 
02716   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
02717     SplitQualType canonSplit = getCanonicalType(elementType).split();
02718     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
02719                                    ASM, elementTypeQuals);
02720     canon = getQualifiedType(canon, canonSplit.Quals);
02721 
02722     // Get the new insert position for the node we care about.
02723     IncompleteArrayType *existing =
02724       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
02725     assert(!existing && "Shouldn't be in the map!"); (void) existing;
02726   }
02727 
02728   IncompleteArrayType *newType = new (*this, TypeAlignment)
02729     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
02730 
02731   IncompleteArrayTypes.InsertNode(newType, insertPos);
02732   Types.push_back(newType);
02733   return QualType(newType, 0);
02734 }
02735 
02736 /// getVectorType - Return the unique reference to a vector type of
02737 /// the specified element type and size. VectorType must be a built-in type.
02738 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
02739                                    VectorType::VectorKind VecKind) const {
02740   assert(vecType->isBuiltinType());
02741 
02742   // Check if we've already instantiated a vector of this type.
02743   llvm::FoldingSetNodeID ID;
02744   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
02745 
02746   void *InsertPos = nullptr;
02747   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
02748     return QualType(VTP, 0);
02749 
02750   // If the element type isn't canonical, this won't be a canonical type either,
02751   // so fill in the canonical type field.
02752   QualType Canonical;
02753   if (!vecType.isCanonical()) {
02754     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
02755 
02756     // Get the new insert position for the node we care about.
02757     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02758     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02759   }
02760   VectorType *New = new (*this, TypeAlignment)
02761     VectorType(vecType, NumElts, Canonical, VecKind);
02762   VectorTypes.InsertNode(New, InsertPos);
02763   Types.push_back(New);
02764   return QualType(New, 0);
02765 }
02766 
02767 /// getExtVectorType - Return the unique reference to an extended vector type of
02768 /// the specified element type and size. VectorType must be a built-in type.
02769 QualType
02770 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
02771   assert(vecType->isBuiltinType() || vecType->isDependentType());
02772 
02773   // Check if we've already instantiated a vector of this type.
02774   llvm::FoldingSetNodeID ID;
02775   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
02776                       VectorType::GenericVector);
02777   void *InsertPos = nullptr;
02778   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
02779     return QualType(VTP, 0);
02780 
02781   // If the element type isn't canonical, this won't be a canonical type either,
02782   // so fill in the canonical type field.
02783   QualType Canonical;
02784   if (!vecType.isCanonical()) {
02785     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
02786 
02787     // Get the new insert position for the node we care about.
02788     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02789     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02790   }
02791   ExtVectorType *New = new (*this, TypeAlignment)
02792     ExtVectorType(vecType, NumElts, Canonical);
02793   VectorTypes.InsertNode(New, InsertPos);
02794   Types.push_back(New);
02795   return QualType(New, 0);
02796 }
02797 
02798 QualType
02799 ASTContext::getDependentSizedExtVectorType(QualType vecType,
02800                                            Expr *SizeExpr,
02801                                            SourceLocation AttrLoc) const {
02802   llvm::FoldingSetNodeID ID;
02803   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
02804                                        SizeExpr);
02805 
02806   void *InsertPos = nullptr;
02807   DependentSizedExtVectorType *Canon
02808     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02809   DependentSizedExtVectorType *New;
02810   if (Canon) {
02811     // We already have a canonical version of this array type; use it as
02812     // the canonical type for a newly-built type.
02813     New = new (*this, TypeAlignment)
02814       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
02815                                   SizeExpr, AttrLoc);
02816   } else {
02817     QualType CanonVecTy = getCanonicalType(vecType);
02818     if (CanonVecTy == vecType) {
02819       New = new (*this, TypeAlignment)
02820         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
02821                                     AttrLoc);
02822 
02823       DependentSizedExtVectorType *CanonCheck
02824         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
02825       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
02826       (void)CanonCheck;
02827       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
02828     } else {
02829       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
02830                                                       SourceLocation());
02831       New = new (*this, TypeAlignment) 
02832         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
02833     }
02834   }
02835 
02836   Types.push_back(New);
02837   return QualType(New, 0);
02838 }
02839 
02840 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
02841 ///
02842 QualType
02843 ASTContext::getFunctionNoProtoType(QualType ResultTy,
02844                                    const FunctionType::ExtInfo &Info) const {
02845   const CallingConv CallConv = Info.getCC();
02846 
02847   // Unique functions, to guarantee there is only one function of a particular
02848   // structure.
02849   llvm::FoldingSetNodeID ID;
02850   FunctionNoProtoType::Profile(ID, ResultTy, Info);
02851 
02852   void *InsertPos = nullptr;
02853   if (FunctionNoProtoType *FT =
02854         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
02855     return QualType(FT, 0);
02856 
02857   QualType Canonical;
02858   if (!ResultTy.isCanonical()) {
02859     Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
02860 
02861     // Get the new insert position for the node we care about.
02862     FunctionNoProtoType *NewIP =
02863       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
02864     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02865   }
02866 
02867   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
02868   FunctionNoProtoType *New = new (*this, TypeAlignment)
02869     FunctionNoProtoType(ResultTy, Canonical, newInfo);
02870   Types.push_back(New);
02871   FunctionNoProtoTypes.InsertNode(New, InsertPos);
02872   return QualType(New, 0);
02873 }
02874 
02875 /// \brief Determine whether \p T is canonical as the result type of a function.
02876 static bool isCanonicalResultType(QualType T) {
02877   return T.isCanonical() &&
02878          (T.getObjCLifetime() == Qualifiers::OCL_None ||
02879           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
02880 }
02881 
02882 QualType
02883 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
02884                             const FunctionProtoType::ExtProtoInfo &EPI) const {
02885   size_t NumArgs = ArgArray.size();
02886 
02887   // Unique functions, to guarantee there is only one function of a particular
02888   // structure.
02889   llvm::FoldingSetNodeID ID;
02890   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
02891                              *this);
02892 
02893   void *InsertPos = nullptr;
02894   if (FunctionProtoType *FTP =
02895         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
02896     return QualType(FTP, 0);
02897 
02898   // Determine whether the type being created is already canonical or not.
02899   bool isCanonical =
02900     EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
02901     !EPI.HasTrailingReturn;
02902   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
02903     if (!ArgArray[i].isCanonicalAsParam())
02904       isCanonical = false;
02905 
02906   // If this type isn't canonical, get the canonical version of it.
02907   // The exception spec is not part of the canonical type.
02908   QualType Canonical;
02909   if (!isCanonical) {
02910     SmallVector<QualType, 16> CanonicalArgs;
02911     CanonicalArgs.reserve(NumArgs);
02912     for (unsigned i = 0; i != NumArgs; ++i)
02913       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
02914 
02915     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
02916     CanonicalEPI.HasTrailingReturn = false;
02917     CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
02918 
02919     // Result types do not have ARC lifetime qualifiers.
02920     QualType CanResultTy = getCanonicalType(ResultTy);
02921     if (ResultTy.getQualifiers().hasObjCLifetime()) {
02922       Qualifiers Qs = CanResultTy.getQualifiers();
02923       Qs.removeObjCLifetime();
02924       CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
02925     }
02926 
02927     Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
02928 
02929     // Get the new insert position for the node we care about.
02930     FunctionProtoType *NewIP =
02931       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
02932     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
02933   }
02934 
02935   // FunctionProtoType objects are allocated with extra bytes after
02936   // them for three variable size arrays at the end:
02937   //  - parameter types
02938   //  - exception types
02939   //  - consumed-arguments flags
02940   // Instead of the exception types, there could be a noexcept
02941   // expression, or information used to resolve the exception
02942   // specification.
02943   size_t Size = sizeof(FunctionProtoType) +
02944                 NumArgs * sizeof(QualType);
02945   if (EPI.ExceptionSpec.Type == EST_Dynamic) {
02946     Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
02947   } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
02948     Size += sizeof(Expr*);
02949   } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
02950     Size += 2 * sizeof(FunctionDecl*);
02951   } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
02952     Size += sizeof(FunctionDecl*);
02953   }
02954   if (EPI.ConsumedParameters)
02955     Size += NumArgs * sizeof(bool);
02956 
02957   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
02958   FunctionProtoType::ExtProtoInfo newEPI = EPI;
02959   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
02960   Types.push_back(FTP);
02961   FunctionProtoTypes.InsertNode(FTP, InsertPos);
02962   return QualType(FTP, 0);
02963 }
02964 
02965 #ifndef NDEBUG
02966 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
02967   if (!isa<CXXRecordDecl>(D)) return false;
02968   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
02969   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
02970     return true;
02971   if (RD->getDescribedClassTemplate() &&
02972       !isa<ClassTemplateSpecializationDecl>(RD))
02973     return true;
02974   return false;
02975 }
02976 #endif
02977 
02978 /// getInjectedClassNameType - Return the unique reference to the
02979 /// injected class name type for the specified templated declaration.
02980 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
02981                                               QualType TST) const {
02982   assert(NeedsInjectedClassNameType(Decl));
02983   if (Decl->TypeForDecl) {
02984     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
02985   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
02986     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
02987     Decl->TypeForDecl = PrevDecl->TypeForDecl;
02988     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
02989   } else {
02990     Type *newType =
02991       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
02992     Decl->TypeForDecl = newType;
02993     Types.push_back(newType);
02994   }
02995   return QualType(Decl->TypeForDecl, 0);
02996 }
02997 
02998 /// getTypeDeclType - Return the unique reference to the type for the
02999 /// specified type declaration.
03000 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
03001   assert(Decl && "Passed null for Decl param");
03002   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
03003 
03004   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
03005     return getTypedefType(Typedef);
03006 
03007   assert(!isa<TemplateTypeParmDecl>(Decl) &&
03008          "Template type parameter types are always available.");
03009 
03010   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
03011     assert(Record->isFirstDecl() && "struct/union has previous declaration");
03012     assert(!NeedsInjectedClassNameType(Record));
03013     return getRecordType(Record);
03014   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
03015     assert(Enum->isFirstDecl() && "enum has previous declaration");
03016     return getEnumType(Enum);
03017   } else if (const UnresolvedUsingTypenameDecl *Using =
03018                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
03019     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
03020     Decl->TypeForDecl = newType;
03021     Types.push_back(newType);
03022   } else
03023     llvm_unreachable("TypeDecl without a type?");
03024 
03025   return QualType(Decl->TypeForDecl, 0);
03026 }
03027 
03028 /// getTypedefType - Return the unique reference to the type for the
03029 /// specified typedef name decl.
03030 QualType
03031 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
03032                            QualType Canonical) const {
03033   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
03034 
03035   if (Canonical.isNull())
03036     Canonical = getCanonicalType(Decl->getUnderlyingType());
03037   TypedefType *newType = new(*this, TypeAlignment)
03038     TypedefType(Type::Typedef, Decl, Canonical);
03039   Decl->TypeForDecl = newType;
03040   Types.push_back(newType);
03041   return QualType(newType, 0);
03042 }
03043 
03044 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
03045   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
03046 
03047   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
03048     if (PrevDecl->TypeForDecl)
03049       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 
03050 
03051   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
03052   Decl->TypeForDecl = newType;
03053   Types.push_back(newType);
03054   return QualType(newType, 0);
03055 }
03056 
03057 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
03058   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
03059 
03060   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
03061     if (PrevDecl->TypeForDecl)
03062       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 
03063 
03064   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
03065   Decl->TypeForDecl = newType;
03066   Types.push_back(newType);
03067   return QualType(newType, 0);
03068 }
03069 
03070 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
03071                                        QualType modifiedType,
03072                                        QualType equivalentType) {
03073   llvm::FoldingSetNodeID id;
03074   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
03075 
03076   void *insertPos = nullptr;
03077   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
03078   if (type) return QualType(type, 0);
03079 
03080   QualType canon = getCanonicalType(equivalentType);
03081   type = new (*this, TypeAlignment)
03082            AttributedType(canon, attrKind, modifiedType, equivalentType);
03083 
03084   Types.push_back(type);
03085   AttributedTypes.InsertNode(type, insertPos);
03086 
03087   return QualType(type, 0);
03088 }
03089 
03090 
03091 /// \brief Retrieve a substitution-result type.
03092 QualType
03093 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
03094                                          QualType Replacement) const {
03095   assert(Replacement.isCanonical()
03096          && "replacement types must always be canonical");
03097 
03098   llvm::FoldingSetNodeID ID;
03099   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
03100   void *InsertPos = nullptr;
03101   SubstTemplateTypeParmType *SubstParm
03102     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
03103 
03104   if (!SubstParm) {
03105     SubstParm = new (*this, TypeAlignment)
03106       SubstTemplateTypeParmType(Parm, Replacement);
03107     Types.push_back(SubstParm);
03108     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
03109   }
03110 
03111   return QualType(SubstParm, 0);
03112 }
03113 
03114 /// \brief Retrieve a 
03115 QualType ASTContext::getSubstTemplateTypeParmPackType(
03116                                           const TemplateTypeParmType *Parm,
03117                                               const TemplateArgument &ArgPack) {
03118 #ifndef NDEBUG
03119   for (const auto &P : ArgPack.pack_elements()) {
03120     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
03121     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
03122   }
03123 #endif
03124   
03125   llvm::FoldingSetNodeID ID;
03126   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
03127   void *InsertPos = nullptr;
03128   if (SubstTemplateTypeParmPackType *SubstParm
03129         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
03130     return QualType(SubstParm, 0);
03131   
03132   QualType Canon;
03133   if (!Parm->isCanonicalUnqualified()) {
03134     Canon = getCanonicalType(QualType(Parm, 0));
03135     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
03136                                              ArgPack);
03137     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
03138   }
03139 
03140   SubstTemplateTypeParmPackType *SubstParm
03141     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
03142                                                                ArgPack);
03143   Types.push_back(SubstParm);
03144   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
03145   return QualType(SubstParm, 0);  
03146 }
03147 
03148 /// \brief Retrieve the template type parameter type for a template
03149 /// parameter or parameter pack with the given depth, index, and (optionally)
03150 /// name.
03151 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
03152                                              bool ParameterPack,
03153                                              TemplateTypeParmDecl *TTPDecl) const {
03154   llvm::FoldingSetNodeID ID;
03155   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
03156   void *InsertPos = nullptr;
03157   TemplateTypeParmType *TypeParm
03158     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
03159 
03160   if (TypeParm)
03161     return QualType(TypeParm, 0);
03162 
03163   if (TTPDecl) {
03164     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
03165     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
03166 
03167     TemplateTypeParmType *TypeCheck 
03168       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
03169     assert(!TypeCheck && "Template type parameter canonical type broken");
03170     (void)TypeCheck;
03171   } else
03172     TypeParm = new (*this, TypeAlignment)
03173       TemplateTypeParmType(Depth, Index, ParameterPack);
03174 
03175   Types.push_back(TypeParm);
03176   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
03177 
03178   return QualType(TypeParm, 0);
03179 }
03180 
03181 TypeSourceInfo *
03182 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
03183                                               SourceLocation NameLoc,
03184                                         const TemplateArgumentListInfo &Args,
03185                                               QualType Underlying) const {
03186   assert(!Name.getAsDependentTemplateName() && 
03187          "No dependent template names here!");
03188   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
03189 
03190   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
03191   TemplateSpecializationTypeLoc TL =
03192       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
03193   TL.setTemplateKeywordLoc(SourceLocation());
03194   TL.setTemplateNameLoc(NameLoc);
03195   TL.setLAngleLoc(Args.getLAngleLoc());
03196   TL.setRAngleLoc(Args.getRAngleLoc());
03197   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
03198     TL.setArgLocInfo(i, Args[i].getLocInfo());
03199   return DI;
03200 }
03201 
03202 QualType
03203 ASTContext::getTemplateSpecializationType(TemplateName Template,
03204                                           const TemplateArgumentListInfo &Args,
03205                                           QualType Underlying) const {
03206   assert(!Template.getAsDependentTemplateName() && 
03207          "No dependent template names here!");
03208   
03209   unsigned NumArgs = Args.size();
03210 
03211   SmallVector<TemplateArgument, 4> ArgVec;
03212   ArgVec.reserve(NumArgs);
03213   for (unsigned i = 0; i != NumArgs; ++i)
03214     ArgVec.push_back(Args[i].getArgument());
03215 
03216   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
03217                                        Underlying);
03218 }
03219 
03220 #ifndef NDEBUG
03221 static bool hasAnyPackExpansions(const TemplateArgument *Args,
03222                                  unsigned NumArgs) {
03223   for (unsigned I = 0; I != NumArgs; ++I)
03224     if (Args[I].isPackExpansion())
03225       return true;
03226   
03227   return true;
03228 }
03229 #endif
03230 
03231 QualType
03232 ASTContext::getTemplateSpecializationType(TemplateName Template,
03233                                           const TemplateArgument *Args,
03234                                           unsigned NumArgs,
03235                                           QualType Underlying) const {
03236   assert(!Template.getAsDependentTemplateName() && 
03237          "No dependent template names here!");
03238   // Look through qualified template names.
03239   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
03240     Template = TemplateName(QTN->getTemplateDecl());
03241   
03242   bool IsTypeAlias = 
03243     Template.getAsTemplateDecl() &&
03244     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
03245   QualType CanonType;
03246   if (!Underlying.isNull())
03247     CanonType = getCanonicalType(Underlying);
03248   else {
03249     // We can get here with an alias template when the specialization contains
03250     // a pack expansion that does not match up with a parameter pack.
03251     assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
03252            "Caller must compute aliased type");
03253     IsTypeAlias = false;
03254     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
03255                                                        NumArgs);
03256   }
03257 
03258   // Allocate the (non-canonical) template specialization type, but don't
03259   // try to unique it: these types typically have location information that
03260   // we don't unique and don't want to lose.
03261   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
03262                        sizeof(TemplateArgument) * NumArgs +
03263                        (IsTypeAlias? sizeof(QualType) : 0),
03264                        TypeAlignment);
03265   TemplateSpecializationType *Spec
03266     = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
03267                                          IsTypeAlias ? Underlying : QualType());
03268 
03269   Types.push_back(Spec);
03270   return QualType(Spec, 0);
03271 }
03272 
03273 QualType
03274 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
03275                                                    const TemplateArgument *Args,
03276                                                    unsigned NumArgs) const {
03277   assert(!Template.getAsDependentTemplateName() && 
03278          "No dependent template names here!");
03279 
03280   // Look through qualified template names.
03281   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
03282     Template = TemplateName(QTN->getTemplateDecl());
03283   
03284   // Build the canonical template specialization type.
03285   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
03286   SmallVector<TemplateArgument, 4> CanonArgs;
03287   CanonArgs.reserve(NumArgs);
03288   for (unsigned I = 0; I != NumArgs; ++I)
03289     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
03290 
03291   // Determine whether this canonical template specialization type already
03292   // exists.
03293   llvm::FoldingSetNodeID ID;
03294   TemplateSpecializationType::Profile(ID, CanonTemplate,
03295                                       CanonArgs.data(), NumArgs, *this);
03296 
03297   void *InsertPos = nullptr;
03298   TemplateSpecializationType *Spec
03299     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
03300 
03301   if (!Spec) {
03302     // Allocate a new canonical template specialization type.
03303     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
03304                           sizeof(TemplateArgument) * NumArgs),
03305                          TypeAlignment);
03306     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
03307                                                 CanonArgs.data(), NumArgs,
03308                                                 QualType(), QualType());
03309     Types.push_back(Spec);
03310     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
03311   }
03312 
03313   assert(Spec->isDependentType() &&
03314          "Non-dependent template-id type must have a canonical type");
03315   return QualType(Spec, 0);
03316 }
03317 
03318 QualType
03319 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
03320                               NestedNameSpecifier *NNS,
03321                               QualType NamedType) const {
03322   llvm::FoldingSetNodeID ID;
03323   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
03324 
03325   void *InsertPos = nullptr;
03326   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
03327   if (T)
03328     return QualType(T, 0);
03329 
03330   QualType Canon = NamedType;
03331   if (!Canon.isCanonical()) {
03332     Canon = getCanonicalType(NamedType);
03333     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
03334     assert(!CheckT && "Elaborated canonical type broken");
03335     (void)CheckT;
03336   }
03337 
03338   T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
03339   Types.push_back(T);
03340   ElaboratedTypes.InsertNode(T, InsertPos);
03341   return QualType(T, 0);
03342 }
03343 
03344 QualType
03345 ASTContext::getParenType(QualType InnerType) const {
03346   llvm::FoldingSetNodeID ID;
03347   ParenType::Profile(ID, InnerType);
03348 
03349   void *InsertPos = nullptr;
03350   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
03351   if (T)
03352     return QualType(T, 0);
03353 
03354   QualType Canon = InnerType;
03355   if (!Canon.isCanonical()) {
03356     Canon = getCanonicalType(InnerType);
03357     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
03358     assert(!CheckT && "Paren canonical type broken");
03359     (void)CheckT;
03360   }
03361 
03362   T = new (*this) ParenType(InnerType, Canon);
03363   Types.push_back(T);
03364   ParenTypes.InsertNode(T, InsertPos);
03365   return QualType(T, 0);
03366 }
03367 
03368 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
03369                                           NestedNameSpecifier *NNS,
03370                                           const IdentifierInfo *Name,
03371                                           QualType Canon) const {
03372   if (Canon.isNull()) {
03373     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
03374     ElaboratedTypeKeyword CanonKeyword = Keyword;
03375     if (Keyword == ETK_None)
03376       CanonKeyword = ETK_Typename;
03377     
03378     if (CanonNNS != NNS || CanonKeyword != Keyword)
03379       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
03380   }
03381 
03382   llvm::FoldingSetNodeID ID;
03383   DependentNameType::Profile(ID, Keyword, NNS, Name);
03384 
03385   void *InsertPos = nullptr;
03386   DependentNameType *T
03387     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
03388   if (T)
03389     return QualType(T, 0);
03390 
03391   T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
03392   Types.push_back(T);
03393   DependentNameTypes.InsertNode(T, InsertPos);
03394   return QualType(T, 0);
03395 }
03396 
03397 QualType
03398 ASTContext::getDependentTemplateSpecializationType(
03399                                  ElaboratedTypeKeyword Keyword,
03400                                  NestedNameSpecifier *NNS,
03401                                  const IdentifierInfo *Name,
03402                                  const TemplateArgumentListInfo &Args) const {
03403   // TODO: avoid this copy
03404   SmallVector<TemplateArgument, 16> ArgCopy;
03405   for (unsigned I = 0, E = Args.size(); I != E; ++I)
03406     ArgCopy.push_back(Args[I].getArgument());
03407   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
03408                                                 ArgCopy.size(),
03409                                                 ArgCopy.data());
03410 }
03411 
03412 QualType
03413 ASTContext::getDependentTemplateSpecializationType(
03414                                  ElaboratedTypeKeyword Keyword,
03415                                  NestedNameSpecifier *NNS,
03416                                  const IdentifierInfo *Name,
03417                                  unsigned NumArgs,
03418                                  const TemplateArgument *Args) const {
03419   assert((!NNS || NNS->isDependent()) && 
03420          "nested-name-specifier must be dependent");
03421 
03422   llvm::FoldingSetNodeID ID;
03423   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
03424                                                Name, NumArgs, Args);
03425 
03426   void *InsertPos = nullptr;
03427   DependentTemplateSpecializationType *T
03428     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
03429   if (T)
03430     return QualType(T, 0);
03431 
03432   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
03433 
03434   ElaboratedTypeKeyword CanonKeyword = Keyword;
03435   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
03436 
03437   bool AnyNonCanonArgs = false;
03438   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
03439   for (unsigned I = 0; I != NumArgs; ++I) {
03440     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
03441     if (!CanonArgs[I].structurallyEquals(Args[I]))
03442       AnyNonCanonArgs = true;
03443   }
03444 
03445   QualType Canon;
03446   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
03447     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
03448                                                    Name, NumArgs,
03449                                                    CanonArgs.data());
03450 
03451     // Find the insert position again.
03452     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
03453   }
03454 
03455   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
03456                         sizeof(TemplateArgument) * NumArgs),
03457                        TypeAlignment);
03458   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
03459                                                     Name, NumArgs, Args, Canon);
03460   Types.push_back(T);
03461   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
03462   return QualType(T, 0);
03463 }
03464 
03465 QualType ASTContext::getPackExpansionType(QualType Pattern,
03466                                           Optional<unsigned> NumExpansions) {
03467   llvm::FoldingSetNodeID ID;
03468   PackExpansionType::Profile(ID, Pattern, NumExpansions);
03469 
03470   assert(Pattern->containsUnexpandedParameterPack() &&
03471          "Pack expansions must expand one or more parameter packs");
03472   void *InsertPos = nullptr;
03473   PackExpansionType *T
03474     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
03475   if (T)
03476     return QualType(T, 0);
03477 
03478   QualType Canon;
03479   if (!Pattern.isCanonical()) {
03480     Canon = getCanonicalType(Pattern);
03481     // The canonical type might not contain an unexpanded parameter pack, if it
03482     // contains an alias template specialization which ignores one of its
03483     // parameters.
03484     if (Canon->containsUnexpandedParameterPack()) {
03485       Canon = getPackExpansionType(Canon, NumExpansions);
03486 
03487       // Find the insert position again, in case we inserted an element into
03488       // PackExpansionTypes and invalidated our insert position.
03489       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
03490     }
03491   }
03492 
03493   T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
03494   Types.push_back(T);
03495   PackExpansionTypes.InsertNode(T, InsertPos);
03496   return QualType(T, 0);
03497 }
03498 
03499 /// CmpProtocolNames - Comparison predicate for sorting protocols
03500 /// alphabetically.
03501 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
03502                             const ObjCProtocolDecl *RHS) {
03503   return LHS->getDeclName() < RHS->getDeclName();
03504 }
03505 
03506 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
03507                                 unsigned NumProtocols) {
03508   if (NumProtocols == 0) return true;
03509 
03510   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
03511     return false;
03512   
03513   for (unsigned i = 1; i != NumProtocols; ++i)
03514     if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
03515         Protocols[i]->getCanonicalDecl() != Protocols[i])
03516       return false;
03517   return true;
03518 }
03519 
03520 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
03521                                    unsigned &NumProtocols) {
03522   ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
03523 
03524   // Sort protocols, keyed by name.
03525   std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
03526 
03527   // Canonicalize.
03528   for (unsigned I = 0, N = NumProtocols; I != N; ++I)
03529     Protocols[I] = Protocols[I]->getCanonicalDecl();
03530   
03531   // Remove duplicates.
03532   ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
03533   NumProtocols = ProtocolsEnd-Protocols;
03534 }
03535 
03536 QualType ASTContext::getObjCObjectType(QualType BaseType,
03537                                        ObjCProtocolDecl * const *Protocols,
03538                                        unsigned NumProtocols) const {
03539   // If the base type is an interface and there aren't any protocols
03540   // to add, then the interface type will do just fine.
03541   if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
03542     return BaseType;
03543 
03544   // Look in the folding set for an existing type.
03545   llvm::FoldingSetNodeID ID;
03546   ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
03547   void *InsertPos = nullptr;
03548   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
03549     return QualType(QT, 0);
03550 
03551   // Build the canonical type, which has the canonical base type and
03552   // a sorted-and-uniqued list of protocols.
03553   QualType Canonical;
03554   bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
03555   if (!ProtocolsSorted || !BaseType.isCanonical()) {
03556     if (!ProtocolsSorted) {
03557       SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
03558                                                      Protocols + NumProtocols);
03559       unsigned UniqueCount = NumProtocols;
03560 
03561       SortAndUniqueProtocols(&Sorted[0], UniqueCount);
03562       Canonical = getObjCObjectType(getCanonicalType(BaseType),
03563                                     &Sorted[0], UniqueCount);
03564     } else {
03565       Canonical = getObjCObjectType(getCanonicalType(BaseType),
03566                                     Protocols, NumProtocols);
03567     }
03568 
03569     // Regenerate InsertPos.
03570     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
03571   }
03572 
03573   unsigned Size = sizeof(ObjCObjectTypeImpl);
03574   Size += NumProtocols * sizeof(ObjCProtocolDecl *);
03575   void *Mem = Allocate(Size, TypeAlignment);
03576   ObjCObjectTypeImpl *T =
03577     new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
03578 
03579   Types.push_back(T);
03580   ObjCObjectTypes.InsertNode(T, InsertPos);
03581   return QualType(T, 0);
03582 }
03583 
03584 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
03585 /// protocol list adopt all protocols in QT's qualified-id protocol
03586 /// list.
03587 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
03588                                                 ObjCInterfaceDecl *IC) {
03589   if (!QT->isObjCQualifiedIdType())
03590     return false;
03591   
03592   if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
03593     // If both the right and left sides have qualifiers.
03594     for (auto *Proto : OPT->quals()) {
03595       if (!IC->ClassImplementsProtocol(Proto, false))
03596         return false;
03597     }
03598     return true;
03599   }
03600   return false;
03601 }
03602 
03603 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
03604 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
03605 /// of protocols.
03606 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
03607                                                 ObjCInterfaceDecl *IDecl) {
03608   if (!QT->isObjCQualifiedIdType())
03609     return false;
03610   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
03611   if (!OPT)
03612     return false;
03613   if (!IDecl->hasDefinition())
03614     return false;
03615   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
03616   CollectInheritedProtocols(IDecl, InheritedProtocols);
03617   if (InheritedProtocols.empty())
03618     return false;
03619   // Check that if every protocol in list of id<plist> conforms to a protcol
03620   // of IDecl's, then bridge casting is ok.
03621   bool Conforms = false;
03622   for (auto *Proto : OPT->quals()) {
03623     Conforms = false;
03624     for (auto *PI : InheritedProtocols) {
03625       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
03626         Conforms = true;
03627         break;
03628       }
03629     }
03630     if (!Conforms)
03631       break;
03632   }
03633   if (Conforms)
03634     return true;
03635   
03636   for (auto *PI : InheritedProtocols) {
03637     // If both the right and left sides have qualifiers.
03638     bool Adopts = false;
03639     for (auto *Proto : OPT->quals()) {
03640       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
03641       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
03642         break;
03643     }
03644     if (!Adopts)
03645       return false;
03646   }
03647   return true;
03648 }
03649 
03650 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
03651 /// the given object type.
03652 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
03653   llvm::FoldingSetNodeID ID;
03654   ObjCObjectPointerType::Profile(ID, ObjectT);
03655 
03656   void *InsertPos = nullptr;
03657   if (ObjCObjectPointerType *QT =
03658               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
03659     return QualType(QT, 0);
03660 
03661   // Find the canonical object type.
03662   QualType Canonical;
03663   if (!ObjectT.isCanonical()) {
03664     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
03665 
03666     // Regenerate InsertPos.
03667     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
03668   }
03669 
03670   // No match.
03671   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
03672   ObjCObjectPointerType *QType =
03673     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
03674 
03675   Types.push_back(QType);
03676   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
03677   return QualType(QType, 0);
03678 }
03679 
03680 /// getObjCInterfaceType - Return the unique reference to the type for the
03681 /// specified ObjC interface decl. The list of protocols is optional.
03682 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
03683                                           ObjCInterfaceDecl *PrevDecl) const {
03684   if (Decl->TypeForDecl)
03685     return QualType(Decl->TypeForDecl, 0);
03686 
03687   if (PrevDecl) {
03688     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
03689     Decl->TypeForDecl = PrevDecl->TypeForDecl;
03690     return QualType(PrevDecl->TypeForDecl, 0);
03691   }
03692 
03693   // Prefer the definition, if there is one.
03694   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
03695     Decl = Def;
03696   
03697   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
03698   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
03699   Decl->TypeForDecl = T;
03700   Types.push_back(T);
03701   return QualType(T, 0);
03702 }
03703 
03704 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
03705 /// TypeOfExprType AST's (since expression's are never shared). For example,
03706 /// multiple declarations that refer to "typeof(x)" all contain different
03707 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
03708 /// on canonical type's (which are always unique).
03709 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
03710   TypeOfExprType *toe;
03711   if (tofExpr->isTypeDependent()) {
03712     llvm::FoldingSetNodeID ID;
03713     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
03714 
03715     void *InsertPos = nullptr;
03716     DependentTypeOfExprType *Canon
03717       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
03718     if (Canon) {
03719       // We already have a "canonical" version of an identical, dependent
03720       // typeof(expr) type. Use that as our canonical type.
03721       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
03722                                           QualType((TypeOfExprType*)Canon, 0));
03723     } else {
03724       // Build a new, canonical typeof(expr) type.
03725       Canon
03726         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
03727       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
03728       toe = Canon;
03729     }
03730   } else {
03731     QualType Canonical = getCanonicalType(tofExpr->getType());
03732     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
03733   }
03734   Types.push_back(toe);
03735   return QualType(toe, 0);
03736 }
03737 
03738 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
03739 /// TypeOfType nodes. The only motivation to unique these nodes would be
03740 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
03741 /// an issue. This doesn't affect the type checker, since it operates
03742 /// on canonical types (which are always unique).
03743 QualType ASTContext::getTypeOfType(QualType tofType) const {
03744   QualType Canonical = getCanonicalType(tofType);
03745   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
03746   Types.push_back(tot);
03747   return QualType(tot, 0);
03748 }
03749 
03750 
03751 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
03752 /// nodes. This would never be helpful, since each such type has its own
03753 /// expression, and would not give a significant memory saving, since there
03754 /// is an Expr tree under each such type.
03755 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
03756   DecltypeType *dt;
03757 
03758   // C++11 [temp.type]p2:
03759   //   If an expression e involves a template parameter, decltype(e) denotes a
03760   //   unique dependent type. Two such decltype-specifiers refer to the same
03761   //   type only if their expressions are equivalent (14.5.6.1).
03762   if (e->isInstantiationDependent()) {
03763     llvm::FoldingSetNodeID ID;
03764     DependentDecltypeType::Profile(ID, *this, e);
03765 
03766     void *InsertPos = nullptr;
03767     DependentDecltypeType *Canon
03768       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
03769     if (!Canon) {
03770       // Build a new, canonical typeof(expr) type.
03771       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
03772       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
03773     }
03774     dt = new (*this, TypeAlignment)
03775         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
03776   } else {
03777     dt = new (*this, TypeAlignment)
03778         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
03779   }
03780   Types.push_back(dt);
03781   return QualType(dt, 0);
03782 }
03783 
03784 /// getUnaryTransformationType - We don't unique these, since the memory
03785 /// savings are minimal and these are rare.
03786 QualType ASTContext::getUnaryTransformType(QualType BaseType,
03787                                            QualType UnderlyingType,
03788                                            UnaryTransformType::UTTKind Kind)
03789     const {
03790   UnaryTransformType *Ty =
03791     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 
03792                                                    Kind,
03793                                  UnderlyingType->isDependentType() ?
03794                                  QualType() : getCanonicalType(UnderlyingType));
03795   Types.push_back(Ty);
03796   return QualType(Ty, 0);
03797 }
03798 
03799 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
03800 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
03801 /// canonical deduced-but-dependent 'auto' type.
03802 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
03803                                  bool IsDependent) const {
03804   if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
03805     return getAutoDeductType();
03806 
03807   // Look in the folding set for an existing type.
03808   void *InsertPos = nullptr;
03809   llvm::FoldingSetNodeID ID;
03810   AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
03811   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
03812     return QualType(AT, 0);
03813 
03814   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
03815                                                      IsDecltypeAuto,
03816                                                      IsDependent);
03817   Types.push_back(AT);
03818   if (InsertPos)
03819     AutoTypes.InsertNode(AT, InsertPos);
03820   return QualType(AT, 0);
03821 }
03822 
03823 /// getAtomicType - Return the uniqued reference to the atomic type for
03824 /// the given value type.
03825 QualType ASTContext::getAtomicType(QualType T) const {
03826   // Unique pointers, to guarantee there is only one pointer of a particular
03827   // structure.
03828   llvm::FoldingSetNodeID ID;
03829   AtomicType::Profile(ID, T);
03830 
03831   void *InsertPos = nullptr;
03832   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
03833     return QualType(AT, 0);
03834 
03835   // If the atomic value type isn't canonical, this won't be a canonical type
03836   // either, so fill in the canonical type field.
03837   QualType Canonical;
03838   if (!T.isCanonical()) {
03839     Canonical = getAtomicType(getCanonicalType(T));
03840 
03841     // Get the new insert position for the node we care about.
03842     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
03843     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
03844   }
03845   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
03846   Types.push_back(New);
03847   AtomicTypes.InsertNode(New, InsertPos);
03848   return QualType(New, 0);
03849 }
03850 
03851 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
03852 QualType ASTContext::getAutoDeductType() const {
03853   if (AutoDeductTy.isNull())
03854     AutoDeductTy = QualType(
03855       new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
03856                                           /*dependent*/false),
03857       0);
03858   return AutoDeductTy;
03859 }
03860 
03861 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
03862 QualType ASTContext::getAutoRRefDeductType() const {
03863   if (AutoRRefDeductTy.isNull())
03864     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
03865   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
03866   return AutoRRefDeductTy;
03867 }
03868 
03869 /// getTagDeclType - Return the unique reference to the type for the
03870 /// specified TagDecl (struct/union/class/enum) decl.
03871 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
03872   assert (Decl);
03873   // FIXME: What is the design on getTagDeclType when it requires casting
03874   // away const?  mutable?
03875   return getTypeDeclType(const_cast<TagDecl*>(Decl));
03876 }
03877 
03878 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
03879 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
03880 /// needs to agree with the definition in <stddef.h>.
03881 CanQualType ASTContext::getSizeType() const {
03882   return getFromTargetType(Target->getSizeType());
03883 }
03884 
03885 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
03886 CanQualType ASTContext::getIntMaxType() const {
03887   return getFromTargetType(Target->getIntMaxType());
03888 }
03889 
03890 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
03891 CanQualType ASTContext::getUIntMaxType() const {
03892   return getFromTargetType(Target->getUIntMaxType());
03893 }
03894 
03895 /// getSignedWCharType - Return the type of "signed wchar_t".
03896 /// Used when in C++, as a GCC extension.
03897 QualType ASTContext::getSignedWCharType() const {
03898   // FIXME: derive from "Target" ?
03899   return WCharTy;
03900 }
03901 
03902 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
03903 /// Used when in C++, as a GCC extension.
03904 QualType ASTContext::getUnsignedWCharType() const {
03905   // FIXME: derive from "Target" ?
03906   return UnsignedIntTy;
03907 }
03908 
03909 QualType ASTContext::getIntPtrType() const {
03910   return getFromTargetType(Target->getIntPtrType());
03911 }
03912 
03913 QualType ASTContext::getUIntPtrType() const {
03914   return getCorrespondingUnsignedType(getIntPtrType());
03915 }
03916 
03917 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
03918 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
03919 QualType ASTContext::getPointerDiffType() const {
03920   return getFromTargetType(Target->getPtrDiffType(0));
03921 }
03922 
03923 /// \brief Return the unique type for "pid_t" defined in
03924 /// <sys/types.h>. We need this to compute the correct type for vfork().
03925 QualType ASTContext::getProcessIDType() const {
03926   return getFromTargetType(Target->getProcessIDType());
03927 }
03928 
03929 //===----------------------------------------------------------------------===//
03930 //                              Type Operators
03931 //===----------------------------------------------------------------------===//
03932 
03933 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
03934   // Push qualifiers into arrays, and then discard any remaining
03935   // qualifiers.
03936   T = getCanonicalType(T);
03937   T = getVariableArrayDecayedType(T);
03938   const Type *Ty = T.getTypePtr();
03939   QualType Result;
03940   if (isa<ArrayType>(Ty)) {
03941     Result = getArrayDecayedType(QualType(Ty,0));
03942   } else if (isa<FunctionType>(Ty)) {
03943     Result = getPointerType(QualType(Ty, 0));
03944   } else {
03945     Result = QualType(Ty, 0);
03946   }
03947 
03948   return CanQualType::CreateUnsafe(Result);
03949 }
03950 
03951 QualType ASTContext::getUnqualifiedArrayType(QualType type,
03952                                              Qualifiers &quals) {
03953   SplitQualType splitType = type.getSplitUnqualifiedType();
03954 
03955   // FIXME: getSplitUnqualifiedType() actually walks all the way to
03956   // the unqualified desugared type and then drops it on the floor.
03957   // We then have to strip that sugar back off with
03958   // getUnqualifiedDesugaredType(), which is silly.
03959   const ArrayType *AT =
03960     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
03961 
03962   // If we don't have an array, just use the results in splitType.
03963   if (!AT) {
03964     quals = splitType.Quals;
03965     return QualType(splitType.Ty, 0);
03966   }
03967 
03968   // Otherwise, recurse on the array's element type.
03969   QualType elementType = AT->getElementType();
03970   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
03971 
03972   // If that didn't change the element type, AT has no qualifiers, so we
03973   // can just use the results in splitType.
03974   if (elementType == unqualElementType) {
03975     assert(quals.empty()); // from the recursive call
03976     quals = splitType.Quals;
03977     return QualType(splitType.Ty, 0);
03978   }
03979 
03980   // Otherwise, add in the qualifiers from the outermost type, then
03981   // build the type back up.
03982   quals.addConsistentQualifiers(splitType.Quals);
03983 
03984   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
03985     return getConstantArrayType(unqualElementType, CAT->getSize(),
03986                                 CAT->getSizeModifier(), 0);
03987   }
03988 
03989   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
03990     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
03991   }
03992 
03993   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
03994     return getVariableArrayType(unqualElementType,
03995                                 VAT->getSizeExpr(),
03996                                 VAT->getSizeModifier(),
03997                                 VAT->getIndexTypeCVRQualifiers(),
03998                                 VAT->getBracketsRange());
03999   }
04000 
04001   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
04002   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
04003                                     DSAT->getSizeModifier(), 0,
04004                                     SourceRange());
04005 }
04006 
04007 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
04008 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
04009 /// they point to and return true. If T1 and T2 aren't pointer types
04010 /// or pointer-to-member types, or if they are not similar at this
04011 /// level, returns false and leaves T1 and T2 unchanged. Top-level
04012 /// qualifiers on T1 and T2 are ignored. This function will typically
04013 /// be called in a loop that successively "unwraps" pointer and
04014 /// pointer-to-member types to compare them at each level.
04015 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
04016   const PointerType *T1PtrType = T1->getAs<PointerType>(),
04017                     *T2PtrType = T2->getAs<PointerType>();
04018   if (T1PtrType && T2PtrType) {
04019     T1 = T1PtrType->getPointeeType();
04020     T2 = T2PtrType->getPointeeType();
04021     return true;
04022   }
04023   
04024   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
04025                           *T2MPType = T2->getAs<MemberPointerType>();
04026   if (T1MPType && T2MPType && 
04027       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 
04028                              QualType(T2MPType->getClass(), 0))) {
04029     T1 = T1MPType->getPointeeType();
04030     T2 = T2MPType->getPointeeType();
04031     return true;
04032   }
04033   
04034   if (getLangOpts().ObjC1) {
04035     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
04036                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
04037     if (T1OPType && T2OPType) {
04038       T1 = T1OPType->getPointeeType();
04039       T2 = T2OPType->getPointeeType();
04040       return true;
04041     }
04042   }
04043   
04044   // FIXME: Block pointers, too?
04045   
04046   return false;
04047 }
04048 
04049 DeclarationNameInfo
04050 ASTContext::getNameForTemplate(TemplateName Name,
04051                                SourceLocation NameLoc) const {
04052   switch (Name.getKind()) {
04053   case TemplateName::QualifiedTemplate:
04054   case TemplateName::Template:
04055     // DNInfo work in progress: CHECKME: what about DNLoc?
04056     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
04057                                NameLoc);
04058 
04059   case TemplateName::OverloadedTemplate: {
04060     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
04061     // DNInfo work in progress: CHECKME: what about DNLoc?
04062     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
04063   }
04064 
04065   case TemplateName::DependentTemplate: {
04066     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
04067     DeclarationName DName;
04068     if (DTN->isIdentifier()) {
04069       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
04070       return DeclarationNameInfo(DName, NameLoc);
04071     } else {
04072       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
04073       // DNInfo work in progress: FIXME: source locations?
04074       DeclarationNameLoc DNLoc;
04075       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
04076       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
04077       return DeclarationNameInfo(DName, NameLoc, DNLoc);
04078     }
04079   }
04080 
04081   case TemplateName::SubstTemplateTemplateParm: {
04082     SubstTemplateTemplateParmStorage *subst
04083       = Name.getAsSubstTemplateTemplateParm();
04084     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
04085                                NameLoc);
04086   }
04087 
04088   case TemplateName::SubstTemplateTemplateParmPack: {
04089     SubstTemplateTemplateParmPackStorage *subst
04090       = Name.getAsSubstTemplateTemplateParmPack();
04091     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
04092                                NameLoc);
04093   }
04094   }
04095 
04096   llvm_unreachable("bad template name kind!");
04097 }
04098 
04099 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
04100   switch (Name.getKind()) {
04101   case TemplateName::QualifiedTemplate:
04102   case TemplateName::Template: {
04103     TemplateDecl *Template = Name.getAsTemplateDecl();
04104     if (TemplateTemplateParmDecl *TTP 
04105           = dyn_cast<TemplateTemplateParmDecl>(Template))
04106       Template = getCanonicalTemplateTemplateParmDecl(TTP);
04107   
04108     // The canonical template name is the canonical template declaration.
04109     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
04110   }
04111 
04112   case TemplateName::OverloadedTemplate:
04113     llvm_unreachable("cannot canonicalize overloaded template");
04114 
04115   case TemplateName::DependentTemplate: {
04116     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
04117     assert(DTN && "Non-dependent template names must refer to template decls.");
04118     return DTN->CanonicalTemplateName;
04119   }
04120 
04121   case TemplateName::SubstTemplateTemplateParm: {
04122     SubstTemplateTemplateParmStorage *subst
04123       = Name.getAsSubstTemplateTemplateParm();
04124     return getCanonicalTemplateName(subst->getReplacement());
04125   }
04126 
04127   case TemplateName::SubstTemplateTemplateParmPack: {
04128     SubstTemplateTemplateParmPackStorage *subst
04129                                   = Name.getAsSubstTemplateTemplateParmPack();
04130     TemplateTemplateParmDecl *canonParameter
04131       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
04132     TemplateArgument canonArgPack
04133       = getCanonicalTemplateArgument(subst->getArgumentPack());
04134     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
04135   }
04136   }
04137 
04138   llvm_unreachable("bad template name!");
04139 }
04140 
04141 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
04142   X = getCanonicalTemplateName(X);
04143   Y = getCanonicalTemplateName(Y);
04144   return X.getAsVoidPointer() == Y.getAsVoidPointer();
04145 }
04146 
04147 TemplateArgument
04148 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
04149   switch (Arg.getKind()) {
04150     case TemplateArgument::Null:
04151       return Arg;
04152 
04153     case TemplateArgument::Expression:
04154       return Arg;
04155 
04156     case TemplateArgument::Declaration: {
04157       ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
04158       return TemplateArgument(D, Arg.getParamTypeForDecl());
04159     }
04160 
04161     case TemplateArgument::NullPtr:
04162       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
04163                               /*isNullPtr*/true);
04164 
04165     case TemplateArgument::Template:
04166       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
04167 
04168     case TemplateArgument::TemplateExpansion:
04169       return TemplateArgument(getCanonicalTemplateName(
04170                                          Arg.getAsTemplateOrTemplatePattern()),
04171                               Arg.getNumTemplateExpansions());
04172 
04173     case TemplateArgument::Integral:
04174       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
04175 
04176     case TemplateArgument::Type:
04177       return TemplateArgument(getCanonicalType(Arg.getAsType()));
04178 
04179     case TemplateArgument::Pack: {
04180       if (Arg.pack_size() == 0)
04181         return Arg;
04182       
04183       TemplateArgument *CanonArgs
04184         = new (*this) TemplateArgument[Arg.pack_size()];
04185       unsigned Idx = 0;
04186       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
04187                                         AEnd = Arg.pack_end();
04188            A != AEnd; (void)++A, ++Idx)
04189         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
04190 
04191       return TemplateArgument(CanonArgs, Arg.pack_size());
04192     }
04193   }
04194 
04195   // Silence GCC warning
04196   llvm_unreachable("Unhandled template argument kind");
04197 }
04198 
04199 NestedNameSpecifier *
04200 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
04201   if (!NNS)
04202     return nullptr;
04203 
04204   switch (NNS->getKind()) {
04205   case NestedNameSpecifier::Identifier:
04206     // Canonicalize the prefix but keep the identifier the same.
04207     return NestedNameSpecifier::Create(*this,
04208                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
04209                                        NNS->getAsIdentifier());
04210 
04211   case NestedNameSpecifier::Namespace:
04212     // A namespace is canonical; build a nested-name-specifier with
04213     // this namespace and no prefix.
04214     return NestedNameSpecifier::Create(*this, nullptr,
04215                                  NNS->getAsNamespace()->getOriginalNamespace());
04216 
04217   case NestedNameSpecifier::NamespaceAlias:
04218     // A namespace is canonical; build a nested-name-specifier with
04219     // this namespace and no prefix.
04220     return NestedNameSpecifier::Create(*this, nullptr,
04221                                     NNS->getAsNamespaceAlias()->getNamespace()
04222                                                       ->getOriginalNamespace());
04223 
04224   case NestedNameSpecifier::TypeSpec:
04225   case NestedNameSpecifier::TypeSpecWithTemplate: {
04226     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
04227     
04228     // If we have some kind of dependent-named type (e.g., "typename T::type"),
04229     // break it apart into its prefix and identifier, then reconsititute those
04230     // as the canonical nested-name-specifier. This is required to canonicalize
04231     // a dependent nested-name-specifier involving typedefs of dependent-name
04232     // types, e.g.,
04233     //   typedef typename T::type T1;
04234     //   typedef typename T1::type T2;
04235     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
04236       return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 
04237                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
04238 
04239     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
04240     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
04241     // first place?
04242     return NestedNameSpecifier::Create(*this, nullptr, false,
04243                                        const_cast<Type *>(T.getTypePtr()));
04244   }
04245 
04246   case NestedNameSpecifier::Global:
04247   case NestedNameSpecifier::Super:
04248     // The global specifier and __super specifer are canonical and unique.
04249     return NNS;
04250   }
04251 
04252   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
04253 }
04254 
04255 
04256 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
04257   // Handle the non-qualified case efficiently.
04258   if (!T.hasLocalQualifiers()) {
04259     // Handle the common positive case fast.
04260     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
04261       return AT;
04262   }
04263 
04264   // Handle the common negative case fast.
04265   if (!isa<ArrayType>(T.getCanonicalType()))
04266     return nullptr;
04267 
04268   // Apply any qualifiers from the array type to the element type.  This
04269   // implements C99 6.7.3p8: "If the specification of an array type includes
04270   // any type qualifiers, the element type is so qualified, not the array type."
04271 
04272   // If we get here, we either have type qualifiers on the type, or we have
04273   // sugar such as a typedef in the way.  If we have type qualifiers on the type
04274   // we must propagate them down into the element type.
04275 
04276   SplitQualType split = T.getSplitDesugaredType();
04277   Qualifiers qs = split.Quals;
04278 
04279   // If we have a simple case, just return now.
04280   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
04281   if (!ATy || qs.empty())
04282     return ATy;
04283 
04284   // Otherwise, we have an array and we have qualifiers on it.  Push the
04285   // qualifiers into the array element type and return a new array type.
04286   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
04287 
04288   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
04289     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
04290                                                 CAT->getSizeModifier(),
04291                                            CAT->getIndexTypeCVRQualifiers()));
04292   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
04293     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
04294                                                   IAT->getSizeModifier(),
04295                                            IAT->getIndexTypeCVRQualifiers()));
04296 
04297   if (const DependentSizedArrayType *DSAT
04298         = dyn_cast<DependentSizedArrayType>(ATy))
04299     return cast<ArrayType>(
04300                      getDependentSizedArrayType(NewEltTy,
04301                                                 DSAT->getSizeExpr(),
04302                                                 DSAT->getSizeModifier(),
04303                                               DSAT->getIndexTypeCVRQualifiers(),
04304                                                 DSAT->getBracketsRange()));
04305 
04306   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
04307   return cast<ArrayType>(getVariableArrayType(NewEltTy,
04308                                               VAT->getSizeExpr(),
04309                                               VAT->getSizeModifier(),
04310                                               VAT->getIndexTypeCVRQualifiers(),
04311                                               VAT->getBracketsRange()));
04312 }
04313 
04314 QualType ASTContext::getAdjustedParameterType(QualType T) const {
04315   if (T->isArrayType() || T->isFunctionType())
04316     return getDecayedType(T);
04317   return T;
04318 }
04319 
04320 QualType ASTContext::getSignatureParameterType(QualType T) const {
04321   T = getVariableArrayDecayedType(T);
04322   T = getAdjustedParameterType(T);
04323   return T.getUnqualifiedType();
04324 }
04325 
04326 /// getArrayDecayedType - Return the properly qualified result of decaying the
04327 /// specified array type to a pointer.  This operation is non-trivial when
04328 /// handling typedefs etc.  The canonical type of "T" must be an array type,
04329 /// this returns a pointer to a properly qualified element of the array.
04330 ///
04331 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
04332 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
04333   // Get the element type with 'getAsArrayType' so that we don't lose any
04334   // typedefs in the element type of the array.  This also handles propagation
04335   // of type qualifiers from the array type into the element type if present
04336   // (C99 6.7.3p8).
04337   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
04338   assert(PrettyArrayType && "Not an array type!");
04339 
04340   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
04341 
04342   // int x[restrict 4] ->  int *restrict
04343   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
04344 }
04345 
04346 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
04347   return getBaseElementType(array->getElementType());
04348 }
04349 
04350 QualType ASTContext::getBaseElementType(QualType type) const {
04351   Qualifiers qs;
04352   while (true) {
04353     SplitQualType split = type.getSplitDesugaredType();
04354     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
04355     if (!array) break;
04356 
04357     type = array->getElementType();
04358     qs.addConsistentQualifiers(split.Quals);
04359   }
04360 
04361   return getQualifiedType(type, qs);
04362 }
04363 
04364 /// getConstantArrayElementCount - Returns number of constant array elements.
04365 uint64_t
04366 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
04367   uint64_t ElementCount = 1;
04368   do {
04369     ElementCount *= CA->getSize().getZExtValue();
04370     CA = dyn_cast_or_null<ConstantArrayType>(
04371       CA->getElementType()->getAsArrayTypeUnsafe());
04372   } while (CA);
04373   return ElementCount;
04374 }
04375 
04376 /// getFloatingRank - Return a relative rank for floating point types.
04377 /// This routine will assert if passed a built-in type that isn't a float.
04378 static FloatingRank getFloatingRank(QualType T) {
04379   if (const ComplexType *CT = T->getAs<ComplexType>())
04380     return getFloatingRank(CT->getElementType());
04381 
04382   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
04383   switch (T->getAs<BuiltinType>()->getKind()) {
04384   default: llvm_unreachable("getFloatingRank(): not a floating type");
04385   case BuiltinType::Half:       return HalfRank;
04386   case BuiltinType::Float:      return FloatRank;
04387   case BuiltinType::Double:     return DoubleRank;
04388   case BuiltinType::LongDouble: return LongDoubleRank;
04389   }
04390 }
04391 
04392 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
04393 /// point or a complex type (based on typeDomain/typeSize).
04394 /// 'typeDomain' is a real floating point or complex type.
04395 /// 'typeSize' is a real floating point or complex type.
04396 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
04397                                                        QualType Domain) const {
04398   FloatingRank EltRank = getFloatingRank(Size);
04399   if (Domain->isComplexType()) {
04400     switch (EltRank) {
04401     case HalfRank: llvm_unreachable("Complex half is not supported");
04402     case FloatRank:      return FloatComplexTy;
04403     case DoubleRank:     return DoubleComplexTy;
04404     case LongDoubleRank: return LongDoubleComplexTy;
04405     }
04406   }
04407 
04408   assert(Domain->isRealFloatingType() && "Unknown domain!");
04409   switch (EltRank) {
04410   case HalfRank:       return HalfTy;
04411   case FloatRank:      return FloatTy;
04412   case DoubleRank:     return DoubleTy;
04413   case LongDoubleRank: return LongDoubleTy;
04414   }
04415   llvm_unreachable("getFloatingRank(): illegal value for rank");
04416 }
04417 
04418 /// getFloatingTypeOrder - Compare the rank of the two specified floating
04419 /// point types, ignoring the domain of the type (i.e. 'double' ==
04420 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
04421 /// LHS < RHS, return -1.
04422 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
04423   FloatingRank LHSR = getFloatingRank(LHS);
04424   FloatingRank RHSR = getFloatingRank(RHS);
04425 
04426   if (LHSR == RHSR)
04427     return 0;
04428   if (LHSR > RHSR)
04429     return 1;
04430   return -1;
04431 }
04432 
04433 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
04434 /// routine will assert if passed a built-in type that isn't an integer or enum,
04435 /// or if it is not canonicalized.
04436 unsigned ASTContext::getIntegerRank(const Type *T) const {
04437   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
04438 
04439   switch (cast<BuiltinType>(T)->getKind()) {
04440   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
04441   case BuiltinType::Bool:
04442     return 1 + (getIntWidth(BoolTy) << 3);
04443   case BuiltinType::Char_S:
04444   case BuiltinType::Char_U:
04445   case BuiltinType::SChar:
04446   case BuiltinType::UChar:
04447     return 2 + (getIntWidth(CharTy) << 3);
04448   case BuiltinType::Short:
04449   case BuiltinType::UShort:
04450     return 3 + (getIntWidth(ShortTy) << 3);
04451   case BuiltinType::Int:
04452   case BuiltinType::UInt:
04453     return 4 + (getIntWidth(IntTy) << 3);
04454   case BuiltinType::Long:
04455   case BuiltinType::ULong:
04456     return 5 + (getIntWidth(LongTy) << 3);
04457   case BuiltinType::LongLong:
04458   case BuiltinType::ULongLong:
04459     return 6 + (getIntWidth(LongLongTy) << 3);
04460   case BuiltinType::Int128:
04461   case BuiltinType::UInt128:
04462     return 7 + (getIntWidth(Int128Ty) << 3);
04463   }
04464 }
04465 
04466 /// \brief Whether this is a promotable bitfield reference according
04467 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
04468 ///
04469 /// \returns the type this bit-field will promote to, or NULL if no
04470 /// promotion occurs.
04471 QualType ASTContext::isPromotableBitField(Expr *E) const {
04472   if (E->isTypeDependent() || E->isValueDependent())
04473     return QualType();
04474 
04475   // FIXME: We should not do this unless E->refersToBitField() is true. This
04476   // matters in C where getSourceBitField() will find bit-fields for various
04477   // cases where the source expression is not a bit-field designator.
04478 
04479   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
04480   if (!Field)
04481     return QualType();
04482 
04483   QualType FT = Field->getType();
04484 
04485   uint64_t BitWidth = Field->getBitWidthValue(*this);
04486   uint64_t IntSize = getTypeSize(IntTy);
04487   // C++ [conv.prom]p5:
04488   //   A prvalue for an integral bit-field can be converted to a prvalue of type
04489   //   int if int can represent all the values of the bit-field; otherwise, it
04490   //   can be converted to unsigned int if unsigned int can represent all the
04491   //   values of the bit-field. If the bit-field is larger yet, no integral
04492   //   promotion applies to it.
04493   // C11 6.3.1.1/2:
04494   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
04495   //   If an int can represent all values of the original type (as restricted by
04496   //   the width, for a bit-field), the value is converted to an int; otherwise,
04497   //   it is converted to an unsigned int.
04498   //
04499   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
04500   //        We perform that promotion here to match GCC and C++.
04501   if (BitWidth < IntSize)
04502     return IntTy;
04503 
04504   if (BitWidth == IntSize)
04505     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
04506 
04507   // Types bigger than int are not subject to promotions, and therefore act
04508   // like the base type. GCC has some weird bugs in this area that we
04509   // deliberately do not follow (GCC follows a pre-standard resolution to
04510   // C's DR315 which treats bit-width as being part of the type, and this leaks
04511   // into their semantics in some cases).
04512   return QualType();
04513 }
04514 
04515 /// getPromotedIntegerType - Returns the type that Promotable will
04516 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
04517 /// integer type.
04518 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
04519   assert(!Promotable.isNull());
04520   assert(Promotable->isPromotableIntegerType());
04521   if (const EnumType *ET = Promotable->getAs<EnumType>())
04522     return ET->getDecl()->getPromotionType();
04523 
04524   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
04525     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
04526     // (3.9.1) can be converted to a prvalue of the first of the following
04527     // types that can represent all the values of its underlying type:
04528     // int, unsigned int, long int, unsigned long int, long long int, or
04529     // unsigned long long int [...]
04530     // FIXME: Is there some better way to compute this?
04531     if (BT->getKind() == BuiltinType::WChar_S ||
04532         BT->getKind() == BuiltinType::WChar_U ||
04533         BT->getKind() == BuiltinType::Char16 ||
04534         BT->getKind() == BuiltinType::Char32) {
04535       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
04536       uint64_t FromSize = getTypeSize(BT);
04537       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
04538                                   LongLongTy, UnsignedLongLongTy };
04539       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
04540         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
04541         if (FromSize < ToSize ||
04542             (FromSize == ToSize &&
04543              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
04544           return PromoteTypes[Idx];
04545       }
04546       llvm_unreachable("char type should fit into long long");
04547     }
04548   }
04549 
04550   // At this point, we should have a signed or unsigned integer type.
04551   if (Promotable->isSignedIntegerType())
04552     return IntTy;
04553   uint64_t PromotableSize = getIntWidth(Promotable);
04554   uint64_t IntSize = getIntWidth(IntTy);
04555   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
04556   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
04557 }
04558 
04559 /// \brief Recurses in pointer/array types until it finds an objc retainable
04560 /// type and returns its ownership.
04561 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
04562   while (!T.isNull()) {
04563     if (T.getObjCLifetime() != Qualifiers::OCL_None)
04564       return T.getObjCLifetime();
04565     if (T->isArrayType())
04566       T = getBaseElementType(T);
04567     else if (const PointerType *PT = T->getAs<PointerType>())
04568       T = PT->getPointeeType();
04569     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
04570       T = RT->getPointeeType();
04571     else
04572       break;
04573   }
04574 
04575   return Qualifiers::OCL_None;
04576 }
04577 
04578 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
04579   // Incomplete enum types are not treated as integer types.
04580   // FIXME: In C++, enum types are never integer types.
04581   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
04582     return ET->getDecl()->getIntegerType().getTypePtr();
04583   return nullptr;
04584 }
04585 
04586 /// getIntegerTypeOrder - Returns the highest ranked integer type:
04587 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
04588 /// LHS < RHS, return -1.
04589 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
04590   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
04591   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
04592 
04593   // Unwrap enums to their underlying type.
04594   if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
04595     LHSC = getIntegerTypeForEnum(ET);
04596   if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
04597     RHSC = getIntegerTypeForEnum(ET);
04598 
04599   if (LHSC == RHSC) return 0;
04600 
04601   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
04602   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
04603 
04604   unsigned LHSRank = getIntegerRank(LHSC);
04605   unsigned RHSRank = getIntegerRank(RHSC);
04606 
04607   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
04608     if (LHSRank == RHSRank) return 0;
04609     return LHSRank > RHSRank ? 1 : -1;
04610   }
04611 
04612   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
04613   if (LHSUnsigned) {
04614     // If the unsigned [LHS] type is larger, return it.
04615     if (LHSRank >= RHSRank)
04616       return 1;
04617 
04618     // If the signed type can represent all values of the unsigned type, it
04619     // wins.  Because we are dealing with 2's complement and types that are
04620     // powers of two larger than each other, this is always safe.
04621     return -1;
04622   }
04623 
04624   // If the unsigned [RHS] type is larger, return it.
04625   if (RHSRank >= LHSRank)
04626     return -1;
04627 
04628   // If the signed type can represent all values of the unsigned type, it
04629   // wins.  Because we are dealing with 2's complement and types that are
04630   // powers of two larger than each other, this is always safe.
04631   return 1;
04632 }
04633 
04634 // getCFConstantStringType - Return the type used for constant CFStrings.
04635 QualType ASTContext::getCFConstantStringType() const {
04636   if (!CFConstantStringTypeDecl) {
04637     CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
04638     CFConstantStringTypeDecl->startDefinition();
04639 
04640     QualType FieldTypes[4];
04641 
04642     // const int *isa;
04643     FieldTypes[0] = getPointerType(IntTy.withConst());
04644     // int flags;
04645     FieldTypes[1] = IntTy;
04646     // const char *str;
04647     FieldTypes[2] = getPointerType(CharTy.withConst());
04648     // long length;
04649     FieldTypes[3] = LongTy;
04650 
04651     // Create fields
04652     for (unsigned i = 0; i < 4; ++i) {
04653       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
04654                                            SourceLocation(),
04655                                            SourceLocation(), nullptr,
04656                                            FieldTypes[i], /*TInfo=*/nullptr,
04657                                            /*BitWidth=*/nullptr,
04658                                            /*Mutable=*/false,
04659                                            ICIS_NoInit);
04660       Field->setAccess(AS_public);
04661       CFConstantStringTypeDecl->addDecl(Field);
04662     }
04663 
04664     CFConstantStringTypeDecl->completeDefinition();
04665   }
04666 
04667   return getTagDeclType(CFConstantStringTypeDecl);
04668 }
04669 
04670 QualType ASTContext::getObjCSuperType() const {
04671   if (ObjCSuperType.isNull()) {
04672     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
04673     TUDecl->addDecl(ObjCSuperTypeDecl);
04674     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
04675   }
04676   return ObjCSuperType;
04677 }
04678 
04679 void ASTContext::setCFConstantStringType(QualType T) {
04680   const RecordType *Rec = T->getAs<RecordType>();
04681   assert(Rec && "Invalid CFConstantStringType");
04682   CFConstantStringTypeDecl = Rec->getDecl();
04683 }
04684 
04685 QualType ASTContext::getBlockDescriptorType() const {
04686   if (BlockDescriptorType)
04687     return getTagDeclType(BlockDescriptorType);
04688 
04689   RecordDecl *RD;
04690   // FIXME: Needs the FlagAppleBlock bit.
04691   RD = buildImplicitRecord("__block_descriptor");
04692   RD->startDefinition();
04693 
04694   QualType FieldTypes[] = {
04695     UnsignedLongTy,
04696     UnsignedLongTy,
04697   };
04698 
04699   static const char *const FieldNames[] = {
04700     "reserved",
04701     "Size"
04702   };
04703 
04704   for (size_t i = 0; i < 2; ++i) {
04705     FieldDecl *Field = FieldDecl::Create(
04706         *this, RD, SourceLocation(), SourceLocation(),
04707         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
04708         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
04709     Field->setAccess(AS_public);
04710     RD->addDecl(Field);
04711   }
04712 
04713   RD->completeDefinition();
04714 
04715   BlockDescriptorType = RD;
04716 
04717   return getTagDeclType(BlockDescriptorType);
04718 }
04719 
04720 QualType ASTContext::getBlockDescriptorExtendedType() const {
04721   if (BlockDescriptorExtendedType)
04722     return getTagDeclType(BlockDescriptorExtendedType);
04723 
04724   RecordDecl *RD;
04725   // FIXME: Needs the FlagAppleBlock bit.
04726   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
04727   RD->startDefinition();
04728 
04729   QualType FieldTypes[] = {
04730     UnsignedLongTy,
04731     UnsignedLongTy,
04732     getPointerType(VoidPtrTy),
04733     getPointerType(VoidPtrTy)
04734   };
04735 
04736   static const char *const FieldNames[] = {
04737     "reserved",
04738     "Size",
04739     "CopyFuncPtr",
04740     "DestroyFuncPtr"
04741   };
04742 
04743   for (size_t i = 0; i < 4; ++i) {
04744     FieldDecl *Field = FieldDecl::Create(
04745         *this, RD, SourceLocation(), SourceLocation(),
04746         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
04747         /*BitWidth=*/nullptr,
04748         /*Mutable=*/false, ICIS_NoInit);
04749     Field->setAccess(AS_public);
04750     RD->addDecl(Field);
04751   }
04752 
04753   RD->completeDefinition();
04754 
04755   BlockDescriptorExtendedType = RD;
04756   return getTagDeclType(BlockDescriptorExtendedType);
04757 }
04758 
04759 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
04760 /// requires copy/dispose. Note that this must match the logic
04761 /// in buildByrefHelpers.
04762 bool ASTContext::BlockRequiresCopying(QualType Ty,
04763                                       const VarDecl *D) {
04764   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
04765     const Expr *copyExpr = getBlockVarCopyInits(D);
04766     if (!copyExpr && record->hasTrivialDestructor()) return false;
04767     
04768     return true;
04769   }
04770   
04771   if (!Ty->isObjCRetainableType()) return false;
04772   
04773   Qualifiers qs = Ty.getQualifiers();
04774   
04775   // If we have lifetime, that dominates.
04776   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
04777     assert(getLangOpts().ObjCAutoRefCount);
04778     
04779     switch (lifetime) {
04780       case Qualifiers::OCL_None: llvm_unreachable("impossible");
04781         
04782       // These are just bits as far as the runtime is concerned.
04783       case Qualifiers::OCL_ExplicitNone:
04784       case Qualifiers::OCL_Autoreleasing:
04785         return false;
04786         
04787       // Tell the runtime that this is ARC __weak, called by the
04788       // byref routines.
04789       case Qualifiers::OCL_Weak:
04790       // ARC __strong __block variables need to be retained.
04791       case Qualifiers::OCL_Strong:
04792         return true;
04793     }
04794     llvm_unreachable("fell out of lifetime switch!");
04795   }
04796   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
04797           Ty->isObjCObjectPointerType());
04798 }
04799 
04800 bool ASTContext::getByrefLifetime(QualType Ty,
04801                               Qualifiers::ObjCLifetime &LifeTime,
04802                               bool &HasByrefExtendedLayout) const {
04803   
04804   if (!getLangOpts().ObjC1 ||
04805       getLangOpts().getGC() != LangOptions::NonGC)
04806     return false;
04807   
04808   HasByrefExtendedLayout = false;
04809   if (Ty->isRecordType()) {
04810     HasByrefExtendedLayout = true;
04811     LifeTime = Qualifiers::OCL_None;
04812   }
04813   else if (getLangOpts().ObjCAutoRefCount)
04814     LifeTime = Ty.getObjCLifetime();
04815   // MRR.
04816   else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
04817     LifeTime = Qualifiers::OCL_ExplicitNone;
04818   else
04819     LifeTime = Qualifiers::OCL_None;
04820   return true;
04821 }
04822 
04823 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
04824   if (!ObjCInstanceTypeDecl)
04825     ObjCInstanceTypeDecl =
04826         buildImplicitTypedef(getObjCIdType(), "instancetype");
04827   return ObjCInstanceTypeDecl;
04828 }
04829 
04830 // This returns true if a type has been typedefed to BOOL:
04831 // typedef <type> BOOL;
04832 static bool isTypeTypedefedAsBOOL(QualType T) {
04833   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
04834     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
04835       return II->isStr("BOOL");
04836 
04837   return false;
04838 }
04839 
04840 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
04841 /// purpose.
04842 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
04843   if (!type->isIncompleteArrayType() && type->isIncompleteType())
04844     return CharUnits::Zero();
04845   
04846   CharUnits sz = getTypeSizeInChars(type);
04847 
04848   // Make all integer and enum types at least as large as an int
04849   if (sz.isPositive() && type->isIntegralOrEnumerationType())
04850     sz = std::max(sz, getTypeSizeInChars(IntTy));
04851   // Treat arrays as pointers, since that's how they're passed in.
04852   else if (type->isArrayType())
04853     sz = getTypeSizeInChars(VoidPtrTy);
04854   return sz;
04855 }
04856 
04857 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
04858   return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
04859          VD->getType()->isIntegralOrEnumerationType() &&
04860          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
04861 }
04862 
04863 static inline 
04864 std::string charUnitsToString(const CharUnits &CU) {
04865   return llvm::itostr(CU.getQuantity());
04866 }
04867 
04868 /// getObjCEncodingForBlock - Return the encoded type for this block
04869 /// declaration.
04870 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
04871   std::string S;
04872 
04873   const BlockDecl *Decl = Expr->getBlockDecl();
04874   QualType BlockTy =
04875       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
04876   // Encode result type.
04877   if (getLangOpts().EncodeExtendedBlockSig)
04878     getObjCEncodingForMethodParameter(
04879         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
04880         true /*Extended*/);
04881   else
04882     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
04883   // Compute size of all parameters.
04884   // Start with computing size of a pointer in number of bytes.
04885   // FIXME: There might(should) be a better way of doing this computation!
04886   SourceLocation Loc;
04887   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
04888   CharUnits ParmOffset = PtrSize;
04889   for (auto PI : Decl->params()) {
04890     QualType PType = PI->getType();
04891     CharUnits sz = getObjCEncodingTypeSize(PType);
04892     if (sz.isZero())
04893       continue;
04894     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
04895     ParmOffset += sz;
04896   }
04897   // Size of the argument frame
04898   S += charUnitsToString(ParmOffset);
04899   // Block pointer and offset.
04900   S += "@?0";
04901   
04902   // Argument types.
04903   ParmOffset = PtrSize;
04904   for (auto PVDecl : Decl->params()) {
04905     QualType PType = PVDecl->getOriginalType(); 
04906     if (const ArrayType *AT =
04907           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
04908       // Use array's original type only if it has known number of
04909       // elements.
04910       if (!isa<ConstantArrayType>(AT))
04911         PType = PVDecl->getType();
04912     } else if (PType->isFunctionType())
04913       PType = PVDecl->getType();
04914     if (getLangOpts().EncodeExtendedBlockSig)
04915       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
04916                                       S, true /*Extended*/);
04917     else
04918       getObjCEncodingForType(PType, S);
04919     S += charUnitsToString(ParmOffset);
04920     ParmOffset += getObjCEncodingTypeSize(PType);
04921   }
04922 
04923   return S;
04924 }
04925 
04926 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
04927                                                 std::string& S) {
04928   // Encode result type.
04929   getObjCEncodingForType(Decl->getReturnType(), S);
04930   CharUnits ParmOffset;
04931   // Compute size of all parameters.
04932   for (auto PI : Decl->params()) {
04933     QualType PType = PI->getType();
04934     CharUnits sz = getObjCEncodingTypeSize(PType);
04935     if (sz.isZero())
04936       continue;
04937  
04938     assert (sz.isPositive() && 
04939         "getObjCEncodingForFunctionDecl - Incomplete param type");
04940     ParmOffset += sz;
04941   }
04942   S += charUnitsToString(ParmOffset);
04943   ParmOffset = CharUnits::Zero();
04944 
04945   // Argument types.
04946   for (auto PVDecl : Decl->params()) {
04947     QualType PType = PVDecl->getOriginalType();
04948     if (const ArrayType *AT =
04949           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
04950       // Use array's original type only if it has known number of
04951       // elements.
04952       if (!isa<ConstantArrayType>(AT))
04953         PType = PVDecl->getType();
04954     } else if (PType->isFunctionType())
04955       PType = PVDecl->getType();
04956     getObjCEncodingForType(PType, S);
04957     S += charUnitsToString(ParmOffset);
04958     ParmOffset += getObjCEncodingTypeSize(PType);
04959   }
04960   
04961   return false;
04962 }
04963 
04964 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
04965 /// method parameter or return type. If Extended, include class names and 
04966 /// block object types.
04967 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
04968                                                    QualType T, std::string& S,
04969                                                    bool Extended) const {
04970   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
04971   getObjCEncodingForTypeQualifier(QT, S);
04972   // Encode parameter type.
04973   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
04974                              true     /*OutermostType*/,
04975                              false    /*EncodingProperty*/, 
04976                              false    /*StructField*/, 
04977                              Extended /*EncodeBlockParameters*/, 
04978                              Extended /*EncodeClassNames*/);
04979 }
04980 
04981 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
04982 /// declaration.
04983 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
04984                                               std::string& S, 
04985                                               bool Extended) const {
04986   // FIXME: This is not very efficient.
04987   // Encode return type.
04988   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
04989                                     Decl->getReturnType(), S, Extended);
04990   // Compute size of all parameters.
04991   // Start with computing size of a pointer in number of bytes.
04992   // FIXME: There might(should) be a better way of doing this computation!
04993   SourceLocation Loc;
04994   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
04995   // The first two arguments (self and _cmd) are pointers; account for
04996   // their size.
04997   CharUnits ParmOffset = 2 * PtrSize;
04998   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
04999        E = Decl->sel_param_end(); PI != E; ++PI) {
05000     QualType PType = (*PI)->getType();
05001     CharUnits sz = getObjCEncodingTypeSize(PType);
05002     if (sz.isZero())
05003       continue;
05004  
05005     assert (sz.isPositive() && 
05006         "getObjCEncodingForMethodDecl - Incomplete param type");
05007     ParmOffset += sz;
05008   }
05009   S += charUnitsToString(ParmOffset);
05010   S += "@0:";
05011   S += charUnitsToString(PtrSize);
05012 
05013   // Argument types.
05014   ParmOffset = 2 * PtrSize;
05015   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
05016        E = Decl->sel_param_end(); PI != E; ++PI) {
05017     const ParmVarDecl *PVDecl = *PI;
05018     QualType PType = PVDecl->getOriginalType();
05019     if (const ArrayType *AT =
05020           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
05021       // Use array's original type only if it has known number of
05022       // elements.
05023       if (!isa<ConstantArrayType>(AT))
05024         PType = PVDecl->getType();
05025     } else if (PType->isFunctionType())
05026       PType = PVDecl->getType();
05027     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 
05028                                       PType, S, Extended);
05029     S += charUnitsToString(ParmOffset);
05030     ParmOffset += getObjCEncodingTypeSize(PType);
05031   }
05032   
05033   return false;
05034 }
05035 
05036 ObjCPropertyImplDecl *
05037 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
05038                                       const ObjCPropertyDecl *PD,
05039                                       const Decl *Container) const {
05040   if (!Container)
05041     return nullptr;
05042   if (const ObjCCategoryImplDecl *CID =
05043       dyn_cast<ObjCCategoryImplDecl>(Container)) {
05044     for (auto *PID : CID->property_impls())
05045       if (PID->getPropertyDecl() == PD)
05046         return PID;
05047   } else {
05048     const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
05049     for (auto *PID : OID->property_impls())
05050       if (PID->getPropertyDecl() == PD)
05051         return PID;
05052   }
05053   return nullptr;
05054 }
05055 
05056 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
05057 /// property declaration. If non-NULL, Container must be either an
05058 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
05059 /// NULL when getting encodings for protocol properties.
05060 /// Property attributes are stored as a comma-delimited C string. The simple
05061 /// attributes readonly and bycopy are encoded as single characters. The
05062 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
05063 /// encoded as single characters, followed by an identifier. Property types
05064 /// are also encoded as a parametrized attribute. The characters used to encode
05065 /// these attributes are defined by the following enumeration:
05066 /// @code
05067 /// enum PropertyAttributes {
05068 /// kPropertyReadOnly = 'R',   // property is read-only.
05069 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
05070 /// kPropertyByref = '&',  // property is a reference to the value last assigned
05071 /// kPropertyDynamic = 'D',    // property is dynamic
05072 /// kPropertyGetter = 'G',     // followed by getter selector name
05073 /// kPropertySetter = 'S',     // followed by setter selector name
05074 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
05075 /// kPropertyType = 'T'              // followed by old-style type encoding.
05076 /// kPropertyWeak = 'W'              // 'weak' property
05077 /// kPropertyStrong = 'P'            // property GC'able
05078 /// kPropertyNonAtomic = 'N'         // property non-atomic
05079 /// };
05080 /// @endcode
05081 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
05082                                                 const Decl *Container,
05083                                                 std::string& S) const {
05084   // Collect information from the property implementation decl(s).
05085   bool Dynamic = false;
05086   ObjCPropertyImplDecl *SynthesizePID = nullptr;
05087 
05088   if (ObjCPropertyImplDecl *PropertyImpDecl =
05089       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
05090     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
05091       Dynamic = true;
05092     else
05093       SynthesizePID = PropertyImpDecl;
05094   }
05095 
05096   // FIXME: This is not very efficient.
05097   S = "T";
05098 
05099   // Encode result type.
05100   // GCC has some special rules regarding encoding of properties which
05101   // closely resembles encoding of ivars.
05102   getObjCEncodingForPropertyType(PD->getType(), S);
05103 
05104   if (PD->isReadOnly()) {
05105     S += ",R";
05106     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
05107       S += ",C";
05108     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
05109       S += ",&";
05110     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
05111       S += ",W";
05112   } else {
05113     switch (PD->getSetterKind()) {
05114     case ObjCPropertyDecl::Assign: break;
05115     case ObjCPropertyDecl::Copy:   S += ",C"; break;
05116     case ObjCPropertyDecl::Retain: S += ",&"; break;
05117     case ObjCPropertyDecl::Weak:   S += ",W"; break;
05118     }
05119   }
05120 
05121   // It really isn't clear at all what this means, since properties
05122   // are "dynamic by default".
05123   if (Dynamic)
05124     S += ",D";
05125 
05126   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
05127     S += ",N";
05128 
05129   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
05130     S += ",G";
05131     S += PD->getGetterName().getAsString();
05132   }
05133 
05134   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
05135     S += ",S";
05136     S += PD->getSetterName().getAsString();
05137   }
05138 
05139   if (SynthesizePID) {
05140     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
05141     S += ",V";
05142     S += OID->getNameAsString();
05143   }
05144 
05145   // FIXME: OBJCGC: weak & strong
05146 }
05147 
05148 /// getLegacyIntegralTypeEncoding -
05149 /// Another legacy compatibility encoding: 32-bit longs are encoded as
05150 /// 'l' or 'L' , but not always.  For typedefs, we need to use
05151 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
05152 ///
05153 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
05154   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
05155     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
05156       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
05157         PointeeTy = UnsignedIntTy;
05158       else
05159         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
05160           PointeeTy = IntTy;
05161     }
05162   }
05163 }
05164 
05165 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
05166                                         const FieldDecl *Field,
05167                                         QualType *NotEncodedT) const {
05168   // We follow the behavior of gcc, expanding structures which are
05169   // directly pointed to, and expanding embedded structures. Note that
05170   // these rules are sufficient to prevent recursive encoding of the
05171   // same type.
05172   getObjCEncodingForTypeImpl(T, S, true, true, Field,
05173                              true /* outermost type */, false, false,
05174                              false, false, false, NotEncodedT);
05175 }
05176 
05177 void ASTContext::getObjCEncodingForPropertyType(QualType T,
05178                                                 std::string& S) const {
05179   // Encode result type.
05180   // GCC has some special rules regarding encoding of properties which
05181   // closely resembles encoding of ivars.
05182   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
05183                              true /* outermost type */,
05184                              true /* encoding property */);
05185 }
05186 
05187 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
05188                                             BuiltinType::Kind kind) {
05189     switch (kind) {
05190     case BuiltinType::Void:       return 'v';
05191     case BuiltinType::Bool:       return 'B';
05192     case BuiltinType::Char_U:
05193     case BuiltinType::UChar:      return 'C';
05194     case BuiltinType::Char16:
05195     case BuiltinType::UShort:     return 'S';
05196     case BuiltinType::Char32:
05197     case BuiltinType::UInt:       return 'I';
05198     case BuiltinType::ULong:
05199         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
05200     case BuiltinType::UInt128:    return 'T';
05201     case BuiltinType::ULongLong:  return 'Q';
05202     case BuiltinType::Char_S:
05203     case BuiltinType::SChar:      return 'c';
05204     case BuiltinType::Short:      return 's';
05205     case BuiltinType::WChar_S:
05206     case BuiltinType::WChar_U:
05207     case BuiltinType::Int:        return 'i';
05208     case BuiltinType::Long:
05209       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
05210     case BuiltinType::LongLong:   return 'q';
05211     case BuiltinType::Int128:     return 't';
05212     case BuiltinType::Float:      return 'f';
05213     case BuiltinType::Double:     return 'd';
05214     case BuiltinType::LongDouble: return 'D';
05215     case BuiltinType::NullPtr:    return '*'; // like char*
05216 
05217     case BuiltinType::Half:
05218       // FIXME: potentially need @encodes for these!
05219       return ' ';
05220 
05221     case BuiltinType::ObjCId:
05222     case BuiltinType::ObjCClass:
05223     case BuiltinType::ObjCSel:
05224       llvm_unreachable("@encoding ObjC primitive type");
05225 
05226     // OpenCL and placeholder types don't need @encodings.
05227     case BuiltinType::OCLImage1d:
05228     case BuiltinType::OCLImage1dArray:
05229     case BuiltinType::OCLImage1dBuffer:
05230     case BuiltinType::OCLImage2d:
05231     case BuiltinType::OCLImage2dArray:
05232     case BuiltinType::OCLImage3d:
05233     case BuiltinType::OCLEvent:
05234     case BuiltinType::OCLSampler:
05235     case BuiltinType::Dependent:
05236 #define BUILTIN_TYPE(KIND, ID)
05237 #define PLACEHOLDER_TYPE(KIND, ID) \
05238     case BuiltinType::KIND:
05239 #include "clang/AST/BuiltinTypes.def"
05240       llvm_unreachable("invalid builtin type for @encode");
05241     }
05242     llvm_unreachable("invalid BuiltinType::Kind value");
05243 }
05244 
05245 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
05246   EnumDecl *Enum = ET->getDecl();
05247   
05248   // The encoding of an non-fixed enum type is always 'i', regardless of size.
05249   if (!Enum->isFixed())
05250     return 'i';
05251   
05252   // The encoding of a fixed enum type matches its fixed underlying type.
05253   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
05254   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
05255 }
05256 
05257 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
05258                            QualType T, const FieldDecl *FD) {
05259   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
05260   S += 'b';
05261   // The NeXT runtime encodes bit fields as b followed by the number of bits.
05262   // The GNU runtime requires more information; bitfields are encoded as b,
05263   // then the offset (in bits) of the first element, then the type of the
05264   // bitfield, then the size in bits.  For example, in this structure:
05265   //
05266   // struct
05267   // {
05268   //    int integer;
05269   //    int flags:2;
05270   // };
05271   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
05272   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
05273   // information is not especially sensible, but we're stuck with it for
05274   // compatibility with GCC, although providing it breaks anything that
05275   // actually uses runtime introspection and wants to work on both runtimes...
05276   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
05277     const RecordDecl *RD = FD->getParent();
05278     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
05279     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
05280     if (const EnumType *ET = T->getAs<EnumType>())
05281       S += ObjCEncodingForEnumType(Ctx, ET);
05282     else {
05283       const BuiltinType *BT = T->castAs<BuiltinType>();
05284       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
05285     }
05286   }
05287   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
05288 }
05289 
05290 // FIXME: Use SmallString for accumulating string.
05291 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
05292                                             bool ExpandPointedToStructures,
05293                                             bool ExpandStructures,
05294                                             const FieldDecl *FD,
05295                                             bool OutermostType,
05296                                             bool EncodingProperty,
05297                                             bool StructField,
05298                                             bool EncodeBlockParameters,
05299                                             bool EncodeClassNames,
05300                                             bool EncodePointerToObjCTypedef,
05301                                             QualType *NotEncodedT) const {
05302   CanQualType CT = getCanonicalType(T);
05303   switch (CT->getTypeClass()) {
05304   case Type::Builtin:
05305   case Type::Enum:
05306     if (FD && FD->isBitField())
05307       return EncodeBitField(this, S, T, FD);
05308     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
05309       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
05310     else
05311       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
05312     return;
05313 
05314   case Type::Complex: {
05315     const ComplexType *CT = T->castAs<ComplexType>();
05316     S += 'j';
05317     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
05318     return;
05319   }
05320 
05321   case Type::Atomic: {
05322     const AtomicType *AT = T->castAs<AtomicType>();
05323     S += 'A';
05324     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
05325     return;
05326   }
05327 
05328   // encoding for pointer or reference types.
05329   case Type::Pointer:
05330   case Type::LValueReference:
05331   case Type::RValueReference: {
05332     QualType PointeeTy;
05333     if (isa<PointerType>(CT)) {
05334       const PointerType *PT = T->castAs<PointerType>();
05335       if (PT->isObjCSelType()) {
05336         S += ':';
05337         return;
05338       }
05339       PointeeTy = PT->getPointeeType();
05340     } else {
05341       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
05342     }
05343 
05344     bool isReadOnly = false;
05345     // For historical/compatibility reasons, the read-only qualifier of the
05346     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
05347     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
05348     // Also, do not emit the 'r' for anything but the outermost type!
05349     if (isa<TypedefType>(T.getTypePtr())) {
05350       if (OutermostType && T.isConstQualified()) {
05351         isReadOnly = true;
05352         S += 'r';
05353       }
05354     } else if (OutermostType) {
05355       QualType P = PointeeTy;
05356       while (P->getAs<PointerType>())
05357         P = P->getAs<PointerType>()->getPointeeType();
05358       if (P.isConstQualified()) {
05359         isReadOnly = true;
05360         S += 'r';
05361       }
05362     }
05363     if (isReadOnly) {
05364       // Another legacy compatibility encoding. Some ObjC qualifier and type
05365       // combinations need to be rearranged.
05366       // Rewrite "in const" from "nr" to "rn"
05367       if (StringRef(S).endswith("nr"))
05368         S.replace(S.end()-2, S.end(), "rn");
05369     }
05370 
05371     if (PointeeTy->isCharType()) {
05372       // char pointer types should be encoded as '*' unless it is a
05373       // type that has been typedef'd to 'BOOL'.
05374       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
05375         S += '*';
05376         return;
05377       }
05378     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
05379       // GCC binary compat: Need to convert "struct objc_class *" to "#".
05380       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
05381         S += '#';
05382         return;
05383       }
05384       // GCC binary compat: Need to convert "struct objc_object *" to "@".
05385       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
05386         S += '@';
05387         return;
05388       }
05389       // fall through...
05390     }
05391     S += '^';
05392     getLegacyIntegralTypeEncoding(PointeeTy);
05393 
05394     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
05395                                nullptr, false, false, false, false, false, false,
05396                                NotEncodedT);
05397     return;
05398   }
05399 
05400   case Type::ConstantArray:
05401   case Type::IncompleteArray:
05402   case Type::VariableArray: {
05403     const ArrayType *AT = cast<ArrayType>(CT);
05404 
05405     if (isa<IncompleteArrayType>(AT) && !StructField) {
05406       // Incomplete arrays are encoded as a pointer to the array element.
05407       S += '^';
05408 
05409       getObjCEncodingForTypeImpl(AT->getElementType(), S,
05410                                  false, ExpandStructures, FD);
05411     } else {
05412       S += '[';
05413 
05414       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
05415         S += llvm::utostr(CAT->getSize().getZExtValue());
05416       else {
05417         //Variable length arrays are encoded as a regular array with 0 elements.
05418         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
05419                "Unknown array type!");
05420         S += '0';
05421       }
05422 
05423       getObjCEncodingForTypeImpl(AT->getElementType(), S,
05424                                  false, ExpandStructures, FD,
05425                                  false, false, false, false, false, false,
05426                                  NotEncodedT);
05427       S += ']';
05428     }
05429     return;
05430   }
05431 
05432   case Type::FunctionNoProto:
05433   case Type::FunctionProto:
05434     S += '?';
05435     return;
05436 
05437   case Type::Record: {
05438     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
05439     S += RDecl->isUnion() ? '(' : '{';
05440     // Anonymous structures print as '?'
05441     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
05442       S += II->getName();
05443       if (ClassTemplateSpecializationDecl *Spec
05444           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
05445         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
05446         llvm::raw_string_ostream OS(S);
05447         TemplateSpecializationType::PrintTemplateArgumentList(OS,
05448                                             TemplateArgs.data(),
05449                                             TemplateArgs.size(),
05450                                             (*this).getPrintingPolicy());
05451       }
05452     } else {
05453       S += '?';
05454     }
05455     if (ExpandStructures) {
05456       S += '=';
05457       if (!RDecl->isUnion()) {
05458         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
05459       } else {
05460         for (const auto *Field : RDecl->fields()) {
05461           if (FD) {
05462             S += '"';
05463             S += Field->getNameAsString();
05464             S += '"';
05465           }
05466 
05467           // Special case bit-fields.
05468           if (Field->isBitField()) {
05469             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
05470                                        Field);
05471           } else {
05472             QualType qt = Field->getType();
05473             getLegacyIntegralTypeEncoding(qt);
05474             getObjCEncodingForTypeImpl(qt, S, false, true,
05475                                        FD, /*OutermostType*/false,
05476                                        /*EncodingProperty*/false,
05477                                        /*StructField*/true,
05478                                        false, false, false, NotEncodedT);
05479           }
05480         }
05481       }
05482     }
05483     S += RDecl->isUnion() ? ')' : '}';
05484     return;
05485   }
05486 
05487   case Type::BlockPointer: {
05488     const BlockPointerType *BT = T->castAs<BlockPointerType>();
05489     S += "@?"; // Unlike a pointer-to-function, which is "^?".
05490     if (EncodeBlockParameters) {
05491       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
05492       
05493       S += '<';
05494       // Block return type
05495       getObjCEncodingForTypeImpl(
05496           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
05497           FD, false /* OutermostType */, EncodingProperty,
05498           false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
05499                                  NotEncodedT);
05500       // Block self
05501       S += "@?";
05502       // Block parameters
05503       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
05504         for (const auto &I : FPT->param_types())
05505           getObjCEncodingForTypeImpl(
05506               I, S, ExpandPointedToStructures, ExpandStructures, FD,
05507               false /* OutermostType */, EncodingProperty,
05508               false /* StructField */, EncodeBlockParameters, EncodeClassNames,
05509                                      false, NotEncodedT);
05510       }
05511       S += '>';
05512     }
05513     return;
05514   }
05515 
05516   case Type::ObjCObject: {
05517     // hack to match legacy encoding of *id and *Class
05518     QualType Ty = getObjCObjectPointerType(CT);
05519     if (Ty->isObjCIdType()) {
05520       S += "{objc_object=}";
05521       return;
05522     }
05523     else if (Ty->isObjCClassType()) {
05524       S += "{objc_class=}";
05525       return;
05526     }
05527   }
05528   
05529   case Type::ObjCInterface: {
05530     // Ignore protocol qualifiers when mangling at this level.
05531     T = T->castAs<ObjCObjectType>()->getBaseType();
05532 
05533     // The assumption seems to be that this assert will succeed
05534     // because nested levels will have filtered out 'id' and 'Class'.
05535     const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
05536     // @encode(class_name)
05537     ObjCInterfaceDecl *OI = OIT->getDecl();
05538     S += '{';
05539     const IdentifierInfo *II = OI->getIdentifier();
05540     S += II->getName();
05541     S += '=';
05542     SmallVector<const ObjCIvarDecl*, 32> Ivars;
05543     DeepCollectObjCIvars(OI, true, Ivars);
05544     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
05545       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
05546       if (Field->isBitField())
05547         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
05548       else
05549         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
05550                                    false, false, false, false, false,
05551                                    EncodePointerToObjCTypedef,
05552                                    NotEncodedT);
05553     }
05554     S += '}';
05555     return;
05556   }
05557 
05558   case Type::ObjCObjectPointer: {
05559     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
05560     if (OPT->isObjCIdType()) {
05561       S += '@';
05562       return;
05563     }
05564 
05565     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
05566       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
05567       // Since this is a binary compatibility issue, need to consult with runtime
05568       // folks. Fortunately, this is a *very* obsure construct.
05569       S += '#';
05570       return;
05571     }
05572 
05573     if (OPT->isObjCQualifiedIdType()) {
05574       getObjCEncodingForTypeImpl(getObjCIdType(), S,
05575                                  ExpandPointedToStructures,
05576                                  ExpandStructures, FD);
05577       if (FD || EncodingProperty || EncodeClassNames) {
05578         // Note that we do extended encoding of protocol qualifer list
05579         // Only when doing ivar or property encoding.
05580         S += '"';
05581         for (const auto *I : OPT->quals()) {
05582           S += '<';
05583           S += I->getNameAsString();
05584           S += '>';
05585         }
05586         S += '"';
05587       }
05588       return;
05589     }
05590 
05591     QualType PointeeTy = OPT->getPointeeType();
05592     if (!EncodingProperty &&
05593         isa<TypedefType>(PointeeTy.getTypePtr()) &&
05594         !EncodePointerToObjCTypedef) {
05595       // Another historical/compatibility reason.
05596       // We encode the underlying type which comes out as
05597       // {...};
05598       S += '^';
05599       if (FD && OPT->getInterfaceDecl()) {
05600         // Prevent recursive encoding of fields in some rare cases.
05601         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
05602         SmallVector<const ObjCIvarDecl*, 32> Ivars;
05603         DeepCollectObjCIvars(OI, true, Ivars);
05604         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
05605           if (cast<FieldDecl>(Ivars[i]) == FD) {
05606             S += '{';
05607             S += OI->getIdentifier()->getName();
05608             S += '}';
05609             return;
05610           }
05611         }
05612       }
05613       getObjCEncodingForTypeImpl(PointeeTy, S,
05614                                  false, ExpandPointedToStructures,
05615                                  nullptr,
05616                                  false, false, false, false, false,
05617                                  /*EncodePointerToObjCTypedef*/true);
05618       return;
05619     }
05620 
05621     S += '@';
05622     if (OPT->getInterfaceDecl() && 
05623         (FD || EncodingProperty || EncodeClassNames)) {
05624       S += '"';
05625       S += OPT->getInterfaceDecl()->getIdentifier()->getName();
05626       for (const auto *I : OPT->quals()) {
05627         S += '<';
05628         S += I->getNameAsString();
05629         S += '>';
05630       }
05631       S += '"';
05632     }
05633     return;
05634   }
05635 
05636   // gcc just blithely ignores member pointers.
05637   // FIXME: we shoul do better than that.  'M' is available.
05638   case Type::MemberPointer:
05639   // This matches gcc's encoding, even though technically it is insufficient.
05640   //FIXME. We should do a better job than gcc.
05641   case Type::Vector:
05642   case Type::ExtVector:
05643   // Until we have a coherent encoding of these three types, issue warning.
05644     { if (NotEncodedT)
05645         *NotEncodedT = T;
05646       return;
05647     }
05648       
05649   // We could see an undeduced auto type here during error recovery.
05650   // Just ignore it.
05651   case Type::Auto:
05652     return;
05653   
05654 
05655 #define ABSTRACT_TYPE(KIND, BASE)
05656 #define TYPE(KIND, BASE)
05657 #define DEPENDENT_TYPE(KIND, BASE) \
05658   case Type::KIND:
05659 #define NON_CANONICAL_TYPE(KIND, BASE) \
05660   case Type::KIND:
05661 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
05662   case Type::KIND:
05663 #include "clang/AST/TypeNodes.def"
05664     llvm_unreachable("@encode for dependent type!");
05665   }
05666   llvm_unreachable("bad type kind!");
05667 }
05668 
05669 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
05670                                                  std::string &S,
05671                                                  const FieldDecl *FD,
05672                                                  bool includeVBases,
05673                                                  QualType *NotEncodedT) const {
05674   assert(RDecl && "Expected non-null RecordDecl");
05675   assert(!RDecl->isUnion() && "Should not be called for unions");
05676   if (!RDecl->getDefinition())
05677     return;
05678 
05679   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
05680   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
05681   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
05682 
05683   if (CXXRec) {
05684     for (const auto &BI : CXXRec->bases()) {
05685       if (!BI.isVirtual()) {
05686         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
05687         if (base->isEmpty())
05688           continue;
05689         uint64_t offs = toBits(layout.getBaseClassOffset(base));
05690         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
05691                                   std::make_pair(offs, base));
05692       }
05693     }
05694   }
05695   
05696   unsigned i = 0;
05697   for (auto *Field : RDecl->fields()) {
05698     uint64_t offs = layout.getFieldOffset(i);
05699     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
05700                               std::make_pair(offs, Field));
05701     ++i;
05702   }
05703 
05704   if (CXXRec && includeVBases) {
05705     for (const auto &BI : CXXRec->vbases()) {
05706       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
05707       if (base->isEmpty())
05708         continue;
05709       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
05710       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
05711           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
05712         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
05713                                   std::make_pair(offs, base));
05714     }
05715   }
05716 
05717   CharUnits size;
05718   if (CXXRec) {
05719     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
05720   } else {
05721     size = layout.getSize();
05722   }
05723 
05724 #ifndef NDEBUG
05725   uint64_t CurOffs = 0;
05726 #endif
05727   std::multimap<uint64_t, NamedDecl *>::iterator
05728     CurLayObj = FieldOrBaseOffsets.begin();
05729 
05730   if (CXXRec && CXXRec->isDynamicClass() &&
05731       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
05732     if (FD) {
05733       S += "\"_vptr$";
05734       std::string recname = CXXRec->getNameAsString();
05735       if (recname.empty()) recname = "?";
05736       S += recname;
05737       S += '"';
05738     }
05739     S += "^^?";
05740 #ifndef NDEBUG
05741     CurOffs += getTypeSize(VoidPtrTy);
05742 #endif
05743   }
05744 
05745   if (!RDecl->hasFlexibleArrayMember()) {
05746     // Mark the end of the structure.
05747     uint64_t offs = toBits(size);
05748     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
05749                               std::make_pair(offs, nullptr));
05750   }
05751 
05752   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
05753 #ifndef NDEBUG
05754     assert(CurOffs <= CurLayObj->first);
05755     if (CurOffs < CurLayObj->first) {
05756       uint64_t padding = CurLayObj->first - CurOffs; 
05757       // FIXME: There doesn't seem to be a way to indicate in the encoding that
05758       // packing/alignment of members is different that normal, in which case
05759       // the encoding will be out-of-sync with the real layout.
05760       // If the runtime switches to just consider the size of types without
05761       // taking into account alignment, we could make padding explicit in the
05762       // encoding (e.g. using arrays of chars). The encoding strings would be
05763       // longer then though.
05764       CurOffs += padding;
05765     }
05766 #endif
05767 
05768     NamedDecl *dcl = CurLayObj->second;
05769     if (!dcl)
05770       break; // reached end of structure.
05771 
05772     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
05773       // We expand the bases without their virtual bases since those are going
05774       // in the initial structure. Note that this differs from gcc which
05775       // expands virtual bases each time one is encountered in the hierarchy,
05776       // making the encoding type bigger than it really is.
05777       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
05778                                       NotEncodedT);
05779       assert(!base->isEmpty());
05780 #ifndef NDEBUG
05781       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
05782 #endif
05783     } else {
05784       FieldDecl *field = cast<FieldDecl>(dcl);
05785       if (FD) {
05786         S += '"';
05787         S += field->getNameAsString();
05788         S += '"';
05789       }
05790 
05791       if (field->isBitField()) {
05792         EncodeBitField(this, S, field->getType(), field);
05793 #ifndef NDEBUG
05794         CurOffs += field->getBitWidthValue(*this);
05795 #endif
05796       } else {
05797         QualType qt = field->getType();
05798         getLegacyIntegralTypeEncoding(qt);
05799         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
05800                                    /*OutermostType*/false,
05801                                    /*EncodingProperty*/false,
05802                                    /*StructField*/true,
05803                                    false, false, false, NotEncodedT);
05804 #ifndef NDEBUG
05805         CurOffs += getTypeSize(field->getType());
05806 #endif
05807       }
05808     }
05809   }
05810 }
05811 
05812 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
05813                                                  std::string& S) const {
05814   if (QT & Decl::OBJC_TQ_In)
05815     S += 'n';
05816   if (QT & Decl::OBJC_TQ_Inout)
05817     S += 'N';
05818   if (QT & Decl::OBJC_TQ_Out)
05819     S += 'o';
05820   if (QT & Decl::OBJC_TQ_Bycopy)
05821     S += 'O';
05822   if (QT & Decl::OBJC_TQ_Byref)
05823     S += 'R';
05824   if (QT & Decl::OBJC_TQ_Oneway)
05825     S += 'V';
05826 }
05827 
05828 TypedefDecl *ASTContext::getObjCIdDecl() const {
05829   if (!ObjCIdDecl) {
05830     QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
05831     T = getObjCObjectPointerType(T);
05832     ObjCIdDecl = buildImplicitTypedef(T, "id");
05833   }
05834   return ObjCIdDecl;
05835 }
05836 
05837 TypedefDecl *ASTContext::getObjCSelDecl() const {
05838   if (!ObjCSelDecl) {
05839     QualType T = getPointerType(ObjCBuiltinSelTy);
05840     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
05841   }
05842   return ObjCSelDecl;
05843 }
05844 
05845 TypedefDecl *ASTContext::getObjCClassDecl() const {
05846   if (!ObjCClassDecl) {
05847     QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
05848     T = getObjCObjectPointerType(T);
05849     ObjCClassDecl = buildImplicitTypedef(T, "Class");
05850   }
05851   return ObjCClassDecl;
05852 }
05853 
05854 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
05855   if (!ObjCProtocolClassDecl) {
05856     ObjCProtocolClassDecl 
05857       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 
05858                                   SourceLocation(),
05859                                   &Idents.get("Protocol"),
05860                                   /*PrevDecl=*/nullptr,
05861                                   SourceLocation(), true);    
05862   }
05863   
05864   return ObjCProtocolClassDecl;
05865 }
05866 
05867 //===----------------------------------------------------------------------===//
05868 // __builtin_va_list Construction Functions
05869 //===----------------------------------------------------------------------===//
05870 
05871 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
05872   // typedef char* __builtin_va_list;
05873   QualType T = Context->getPointerType(Context->CharTy);
05874   return Context->buildImplicitTypedef(T, "__builtin_va_list");
05875 }
05876 
05877 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
05878   // typedef void* __builtin_va_list;
05879   QualType T = Context->getPointerType(Context->VoidTy);
05880   return Context->buildImplicitTypedef(T, "__builtin_va_list");
05881 }
05882 
05883 static TypedefDecl *
05884 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
05885   // struct __va_list
05886   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
05887   if (Context->getLangOpts().CPlusPlus) {
05888     // namespace std { struct __va_list {
05889     NamespaceDecl *NS;
05890     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
05891                                Context->getTranslationUnitDecl(),
05892                                /*Inline*/ false, SourceLocation(),
05893                                SourceLocation(), &Context->Idents.get("std"),
05894                                /*PrevDecl*/ nullptr);
05895     NS->setImplicit();
05896     VaListTagDecl->setDeclContext(NS);
05897   }
05898 
05899   VaListTagDecl->startDefinition();
05900 
05901   const size_t NumFields = 5;
05902   QualType FieldTypes[NumFields];
05903   const char *FieldNames[NumFields];
05904 
05905   // void *__stack;
05906   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
05907   FieldNames[0] = "__stack";
05908 
05909   // void *__gr_top;
05910   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
05911   FieldNames[1] = "__gr_top";
05912 
05913   // void *__vr_top;
05914   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
05915   FieldNames[2] = "__vr_top";
05916 
05917   // int __gr_offs;
05918   FieldTypes[3] = Context->IntTy;
05919   FieldNames[3] = "__gr_offs";
05920 
05921   // int __vr_offs;
05922   FieldTypes[4] = Context->IntTy;
05923   FieldNames[4] = "__vr_offs";
05924 
05925   // Create fields
05926   for (unsigned i = 0; i < NumFields; ++i) {
05927     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
05928                                          VaListTagDecl,
05929                                          SourceLocation(),
05930                                          SourceLocation(),
05931                                          &Context->Idents.get(FieldNames[i]),
05932                                          FieldTypes[i], /*TInfo=*/nullptr,
05933                                          /*BitWidth=*/nullptr,
05934                                          /*Mutable=*/false,
05935                                          ICIS_NoInit);
05936     Field->setAccess(AS_public);
05937     VaListTagDecl->addDecl(Field);
05938   }
05939   VaListTagDecl->completeDefinition();
05940   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
05941   Context->VaListTagTy = VaListTagType;
05942 
05943   // } __builtin_va_list;
05944   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
05945 }
05946 
05947 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
05948   // typedef struct __va_list_tag {
05949   RecordDecl *VaListTagDecl;
05950 
05951   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
05952   VaListTagDecl->startDefinition();
05953 
05954   const size_t NumFields = 5;
05955   QualType FieldTypes[NumFields];
05956   const char *FieldNames[NumFields];
05957 
05958   //   unsigned char gpr;
05959   FieldTypes[0] = Context->UnsignedCharTy;
05960   FieldNames[0] = "gpr";
05961 
05962   //   unsigned char fpr;
05963   FieldTypes[1] = Context->UnsignedCharTy;
05964   FieldNames[1] = "fpr";
05965 
05966   //   unsigned short reserved;
05967   FieldTypes[2] = Context->UnsignedShortTy;
05968   FieldNames[2] = "reserved";
05969 
05970   //   void* overflow_arg_area;
05971   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
05972   FieldNames[3] = "overflow_arg_area";
05973 
05974   //   void* reg_save_area;
05975   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
05976   FieldNames[4] = "reg_save_area";
05977 
05978   // Create fields
05979   for (unsigned i = 0; i < NumFields; ++i) {
05980     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
05981                                          SourceLocation(),
05982                                          SourceLocation(),
05983                                          &Context->Idents.get(FieldNames[i]),
05984                                          FieldTypes[i], /*TInfo=*/nullptr,
05985                                          /*BitWidth=*/nullptr,
05986                                          /*Mutable=*/false,
05987                                          ICIS_NoInit);
05988     Field->setAccess(AS_public);
05989     VaListTagDecl->addDecl(Field);
05990   }
05991   VaListTagDecl->completeDefinition();
05992   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
05993   Context->VaListTagTy = VaListTagType;
05994 
05995   // } __va_list_tag;
05996   TypedefDecl *VaListTagTypedefDecl =
05997       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
05998 
05999   QualType VaListTagTypedefType =
06000     Context->getTypedefType(VaListTagTypedefDecl);
06001 
06002   // typedef __va_list_tag __builtin_va_list[1];
06003   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
06004   QualType VaListTagArrayType
06005     = Context->getConstantArrayType(VaListTagTypedefType,
06006                                     Size, ArrayType::Normal, 0);
06007   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
06008 }
06009 
06010 static TypedefDecl *
06011 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
06012   // typedef struct __va_list_tag {
06013   RecordDecl *VaListTagDecl;
06014   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
06015   VaListTagDecl->startDefinition();
06016 
06017   const size_t NumFields = 4;
06018   QualType FieldTypes[NumFields];
06019   const char *FieldNames[NumFields];
06020 
06021   //   unsigned gp_offset;
06022   FieldTypes[0] = Context->UnsignedIntTy;
06023   FieldNames[0] = "gp_offset";
06024 
06025   //   unsigned fp_offset;
06026   FieldTypes[1] = Context->UnsignedIntTy;
06027   FieldNames[1] = "fp_offset";
06028 
06029   //   void* overflow_arg_area;
06030   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
06031   FieldNames[2] = "overflow_arg_area";
06032 
06033   //   void* reg_save_area;
06034   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
06035   FieldNames[3] = "reg_save_area";
06036 
06037   // Create fields
06038   for (unsigned i = 0; i < NumFields; ++i) {
06039     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
06040                                          VaListTagDecl,
06041                                          SourceLocation(),
06042                                          SourceLocation(),
06043                                          &Context->Idents.get(FieldNames[i]),
06044                                          FieldTypes[i], /*TInfo=*/nullptr,
06045                                          /*BitWidth=*/nullptr,
06046                                          /*Mutable=*/false,
06047                                          ICIS_NoInit);
06048     Field->setAccess(AS_public);
06049     VaListTagDecl->addDecl(Field);
06050   }
06051   VaListTagDecl->completeDefinition();
06052   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
06053   Context->VaListTagTy = VaListTagType;
06054 
06055   // } __va_list_tag;
06056   TypedefDecl *VaListTagTypedefDecl =
06057       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
06058 
06059   QualType VaListTagTypedefType =
06060     Context->getTypedefType(VaListTagTypedefDecl);
06061 
06062   // typedef __va_list_tag __builtin_va_list[1];
06063   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
06064   QualType VaListTagArrayType
06065     = Context->getConstantArrayType(VaListTagTypedefType,
06066                                       Size, ArrayType::Normal,0);
06067   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
06068 }
06069 
06070 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
06071   // typedef int __builtin_va_list[4];
06072   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
06073   QualType IntArrayType
06074     = Context->getConstantArrayType(Context->IntTy,
06075             Size, ArrayType::Normal, 0);
06076   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
06077 }
06078 
06079 static TypedefDecl *
06080 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
06081   // struct __va_list
06082   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
06083   if (Context->getLangOpts().CPlusPlus) {
06084     // namespace std { struct __va_list {
06085     NamespaceDecl *NS;
06086     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
06087                                Context->getTranslationUnitDecl(),
06088                                /*Inline*/false, SourceLocation(),
06089                                SourceLocation(), &Context->Idents.get("std"),
06090                                /*PrevDecl*/ nullptr);
06091     NS->setImplicit();
06092     VaListDecl->setDeclContext(NS);
06093   }
06094 
06095   VaListDecl->startDefinition();
06096 
06097   // void * __ap;
06098   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
06099                                        VaListDecl,
06100                                        SourceLocation(),
06101                                        SourceLocation(),
06102                                        &Context->Idents.get("__ap"),
06103                                        Context->getPointerType(Context->VoidTy),
06104                                        /*TInfo=*/nullptr,
06105                                        /*BitWidth=*/nullptr,
06106                                        /*Mutable=*/false,
06107                                        ICIS_NoInit);
06108   Field->setAccess(AS_public);
06109   VaListDecl->addDecl(Field);
06110 
06111   // };
06112   VaListDecl->completeDefinition();
06113 
06114   // typedef struct __va_list __builtin_va_list;
06115   QualType T = Context->getRecordType(VaListDecl);
06116   return Context->buildImplicitTypedef(T, "__builtin_va_list");
06117 }
06118 
06119 static TypedefDecl *
06120 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
06121   // typedef struct __va_list_tag {
06122   RecordDecl *VaListTagDecl;
06123   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
06124   VaListTagDecl->startDefinition();
06125 
06126   const size_t NumFields = 4;
06127   QualType FieldTypes[NumFields];
06128   const char *FieldNames[NumFields];
06129 
06130   //   long __gpr;
06131   FieldTypes[0] = Context->LongTy;
06132   FieldNames[0] = "__gpr";
06133 
06134   //   long __fpr;
06135   FieldTypes[1] = Context->LongTy;
06136   FieldNames[1] = "__fpr";
06137 
06138   //   void *__overflow_arg_area;
06139   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
06140   FieldNames[2] = "__overflow_arg_area";
06141 
06142   //   void *__reg_save_area;
06143   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
06144   FieldNames[3] = "__reg_save_area";
06145 
06146   // Create fields
06147   for (unsigned i = 0; i < NumFields; ++i) {
06148     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
06149                                          VaListTagDecl,
06150                                          SourceLocation(),
06151                                          SourceLocation(),
06152                                          &Context->Idents.get(FieldNames[i]),
06153                                          FieldTypes[i], /*TInfo=*/nullptr,
06154                                          /*BitWidth=*/nullptr,
06155                                          /*Mutable=*/false,
06156                                          ICIS_NoInit);
06157     Field->setAccess(AS_public);
06158     VaListTagDecl->addDecl(Field);
06159   }
06160   VaListTagDecl->completeDefinition();
06161   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
06162   Context->VaListTagTy = VaListTagType;
06163 
06164   // } __va_list_tag;
06165   TypedefDecl *VaListTagTypedefDecl =
06166       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
06167   QualType VaListTagTypedefType =
06168     Context->getTypedefType(VaListTagTypedefDecl);
06169 
06170   // typedef __va_list_tag __builtin_va_list[1];
06171   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
06172   QualType VaListTagArrayType
06173     = Context->getConstantArrayType(VaListTagTypedefType,
06174                                       Size, ArrayType::Normal,0);
06175 
06176   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
06177 }
06178 
06179 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
06180                                      TargetInfo::BuiltinVaListKind Kind) {
06181   switch (Kind) {
06182   case TargetInfo::CharPtrBuiltinVaList:
06183     return CreateCharPtrBuiltinVaListDecl(Context);
06184   case TargetInfo::VoidPtrBuiltinVaList:
06185     return CreateVoidPtrBuiltinVaListDecl(Context);
06186   case TargetInfo::AArch64ABIBuiltinVaList:
06187     return CreateAArch64ABIBuiltinVaListDecl(Context);
06188   case TargetInfo::PowerABIBuiltinVaList:
06189     return CreatePowerABIBuiltinVaListDecl(Context);
06190   case TargetInfo::X86_64ABIBuiltinVaList:
06191     return CreateX86_64ABIBuiltinVaListDecl(Context);
06192   case TargetInfo::PNaClABIBuiltinVaList:
06193     return CreatePNaClABIBuiltinVaListDecl(Context);
06194   case TargetInfo::AAPCSABIBuiltinVaList:
06195     return CreateAAPCSABIBuiltinVaListDecl(Context);
06196   case TargetInfo::SystemZBuiltinVaList:
06197     return CreateSystemZBuiltinVaListDecl(Context);
06198   }
06199 
06200   llvm_unreachable("Unhandled __builtin_va_list type kind");
06201 }
06202 
06203 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
06204   if (!BuiltinVaListDecl) {
06205     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
06206     assert(BuiltinVaListDecl->isImplicit());
06207   }
06208 
06209   return BuiltinVaListDecl;
06210 }
06211 
06212 QualType ASTContext::getVaListTagType() const {
06213   // Force the creation of VaListTagTy by building the __builtin_va_list
06214   // declaration.
06215   if (VaListTagTy.isNull())
06216     (void) getBuiltinVaListDecl();
06217 
06218   return VaListTagTy;
06219 }
06220 
06221 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
06222   assert(ObjCConstantStringType.isNull() &&
06223          "'NSConstantString' type already set!");
06224 
06225   ObjCConstantStringType = getObjCInterfaceType(Decl);
06226 }
06227 
06228 /// \brief Retrieve the template name that corresponds to a non-empty
06229 /// lookup.
06230 TemplateName
06231 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
06232                                       UnresolvedSetIterator End) const {
06233   unsigned size = End - Begin;
06234   assert(size > 1 && "set is not overloaded!");
06235 
06236   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
06237                           size * sizeof(FunctionTemplateDecl*));
06238   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
06239 
06240   NamedDecl **Storage = OT->getStorage();
06241   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
06242     NamedDecl *D = *I;
06243     assert(isa<FunctionTemplateDecl>(D) ||
06244            (isa<UsingShadowDecl>(D) &&
06245             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
06246     *Storage++ = D;
06247   }
06248 
06249   return TemplateName(OT);
06250 }
06251 
06252 /// \brief Retrieve the template name that represents a qualified
06253 /// template name such as \c std::vector.
06254 TemplateName
06255 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
06256                                      bool TemplateKeyword,
06257                                      TemplateDecl *Template) const {
06258   assert(NNS && "Missing nested-name-specifier in qualified template name");
06259   
06260   // FIXME: Canonicalization?
06261   llvm::FoldingSetNodeID ID;
06262   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
06263 
06264   void *InsertPos = nullptr;
06265   QualifiedTemplateName *QTN =
06266     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
06267   if (!QTN) {
06268     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
06269         QualifiedTemplateName(NNS, TemplateKeyword, Template);
06270     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
06271   }
06272 
06273   return TemplateName(QTN);
06274 }
06275 
06276 /// \brief Retrieve the template name that represents a dependent
06277 /// template name such as \c MetaFun::template apply.
06278 TemplateName
06279 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
06280                                      const IdentifierInfo *Name) const {
06281   assert((!NNS || NNS->isDependent()) &&
06282          "Nested name specifier must be dependent");
06283 
06284   llvm::FoldingSetNodeID ID;
06285   DependentTemplateName::Profile(ID, NNS, Name);
06286 
06287   void *InsertPos = nullptr;
06288   DependentTemplateName *QTN =
06289     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
06290 
06291   if (QTN)
06292     return TemplateName(QTN);
06293 
06294   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
06295   if (CanonNNS == NNS) {
06296     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
06297         DependentTemplateName(NNS, Name);
06298   } else {
06299     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
06300     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
06301         DependentTemplateName(NNS, Name, Canon);
06302     DependentTemplateName *CheckQTN =
06303       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
06304     assert(!CheckQTN && "Dependent type name canonicalization broken");
06305     (void)CheckQTN;
06306   }
06307 
06308   DependentTemplateNames.InsertNode(QTN, InsertPos);
06309   return TemplateName(QTN);
06310 }
06311 
06312 /// \brief Retrieve the template name that represents a dependent
06313 /// template name such as \c MetaFun::template operator+.
06314 TemplateName 
06315 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
06316                                      OverloadedOperatorKind Operator) const {
06317   assert((!NNS || NNS->isDependent()) &&
06318          "Nested name specifier must be dependent");
06319   
06320   llvm::FoldingSetNodeID ID;
06321   DependentTemplateName::Profile(ID, NNS, Operator);
06322 
06323   void *InsertPos = nullptr;
06324   DependentTemplateName *QTN
06325     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
06326   
06327   if (QTN)
06328     return TemplateName(QTN);
06329   
06330   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
06331   if (CanonNNS == NNS) {
06332     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
06333         DependentTemplateName(NNS, Operator);
06334   } else {
06335     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
06336     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
06337         DependentTemplateName(NNS, Operator, Canon);
06338     
06339     DependentTemplateName *CheckQTN
06340       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
06341     assert(!CheckQTN && "Dependent template name canonicalization broken");
06342     (void)CheckQTN;
06343   }
06344   
06345   DependentTemplateNames.InsertNode(QTN, InsertPos);
06346   return TemplateName(QTN);
06347 }
06348 
06349 TemplateName 
06350 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
06351                                          TemplateName replacement) const {
06352   llvm::FoldingSetNodeID ID;
06353   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
06354 
06355   void *insertPos = nullptr;
06356   SubstTemplateTemplateParmStorage *subst
06357     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
06358   
06359   if (!subst) {
06360     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
06361     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
06362   }
06363 
06364   return TemplateName(subst);
06365 }
06366 
06367 TemplateName 
06368 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
06369                                        const TemplateArgument &ArgPack) const {
06370   ASTContext &Self = const_cast<ASTContext &>(*this);
06371   llvm::FoldingSetNodeID ID;
06372   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
06373 
06374   void *InsertPos = nullptr;
06375   SubstTemplateTemplateParmPackStorage *Subst
06376     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
06377   
06378   if (!Subst) {
06379     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 
06380                                                            ArgPack.pack_size(),
06381                                                          ArgPack.pack_begin());
06382     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
06383   }
06384 
06385   return TemplateName(Subst);
06386 }
06387 
06388 /// getFromTargetType - Given one of the integer types provided by
06389 /// TargetInfo, produce the corresponding type. The unsigned @p Type
06390 /// is actually a value of type @c TargetInfo::IntType.
06391 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
06392   switch (Type) {
06393   case TargetInfo::NoInt: return CanQualType();
06394   case TargetInfo::SignedChar: return SignedCharTy;
06395   case TargetInfo::UnsignedChar: return UnsignedCharTy;
06396   case TargetInfo::SignedShort: return ShortTy;
06397   case TargetInfo::UnsignedShort: return UnsignedShortTy;
06398   case TargetInfo::SignedInt: return IntTy;
06399   case TargetInfo::UnsignedInt: return UnsignedIntTy;
06400   case TargetInfo::SignedLong: return LongTy;
06401   case TargetInfo::UnsignedLong: return UnsignedLongTy;
06402   case TargetInfo::SignedLongLong: return LongLongTy;
06403   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
06404   }
06405 
06406   llvm_unreachable("Unhandled TargetInfo::IntType value");
06407 }
06408 
06409 //===----------------------------------------------------------------------===//
06410 //                        Type Predicates.
06411 //===----------------------------------------------------------------------===//
06412 
06413 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
06414 /// garbage collection attribute.
06415 ///
06416 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
06417   if (getLangOpts().getGC() == LangOptions::NonGC)
06418     return Qualifiers::GCNone;
06419 
06420   assert(getLangOpts().ObjC1);
06421   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
06422 
06423   // Default behaviour under objective-C's gc is for ObjC pointers
06424   // (or pointers to them) be treated as though they were declared
06425   // as __strong.
06426   if (GCAttrs == Qualifiers::GCNone) {
06427     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
06428       return Qualifiers::Strong;
06429     else if (Ty->isPointerType())
06430       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
06431   } else {
06432     // It's not valid to set GC attributes on anything that isn't a
06433     // pointer.
06434 #ifndef NDEBUG
06435     QualType CT = Ty->getCanonicalTypeInternal();
06436     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
06437       CT = AT->getElementType();
06438     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
06439 #endif
06440   }
06441   return GCAttrs;
06442 }
06443 
06444 //===----------------------------------------------------------------------===//
06445 //                        Type Compatibility Testing
06446 //===----------------------------------------------------------------------===//
06447 
06448 /// areCompatVectorTypes - Return true if the two specified vector types are
06449 /// compatible.
06450 static bool areCompatVectorTypes(const VectorType *LHS,
06451                                  const VectorType *RHS) {
06452   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
06453   return LHS->getElementType() == RHS->getElementType() &&
06454          LHS->getNumElements() == RHS->getNumElements();
06455 }
06456 
06457 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
06458                                           QualType SecondVec) {
06459   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
06460   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
06461 
06462   if (hasSameUnqualifiedType(FirstVec, SecondVec))
06463     return true;
06464 
06465   // Treat Neon vector types and most AltiVec vector types as if they are the
06466   // equivalent GCC vector types.
06467   const VectorType *First = FirstVec->getAs<VectorType>();
06468   const VectorType *Second = SecondVec->getAs<VectorType>();
06469   if (First->getNumElements() == Second->getNumElements() &&
06470       hasSameType(First->getElementType(), Second->getElementType()) &&
06471       First->getVectorKind() != VectorType::AltiVecPixel &&
06472       First->getVectorKind() != VectorType::AltiVecBool &&
06473       Second->getVectorKind() != VectorType::AltiVecPixel &&
06474       Second->getVectorKind() != VectorType::AltiVecBool)
06475     return true;
06476 
06477   return false;
06478 }
06479 
06480 //===----------------------------------------------------------------------===//
06481 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
06482 //===----------------------------------------------------------------------===//
06483 
06484 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
06485 /// inheritance hierarchy of 'rProto'.
06486 bool
06487 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
06488                                            ObjCProtocolDecl *rProto) const {
06489   if (declaresSameEntity(lProto, rProto))
06490     return true;
06491   for (auto *PI : rProto->protocols())
06492     if (ProtocolCompatibleWithProtocol(lProto, PI))
06493       return true;
06494   return false;
06495 }
06496 
06497 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
06498 /// Class<pr1, ...>.
06499 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 
06500                                                       QualType rhs) {
06501   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
06502   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
06503   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
06504   
06505   for (auto *lhsProto : lhsQID->quals()) {
06506     bool match = false;
06507     for (auto *rhsProto : rhsOPT->quals()) {
06508       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
06509         match = true;
06510         break;
06511       }
06512     }
06513     if (!match)
06514       return false;
06515   }
06516   return true;
06517 }
06518 
06519 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
06520 /// ObjCQualifiedIDType.
06521 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
06522                                                    bool compare) {
06523   // Allow id<P..> and an 'id' or void* type in all cases.
06524   if (lhs->isVoidPointerType() ||
06525       lhs->isObjCIdType() || lhs->isObjCClassType())
06526     return true;
06527   else if (rhs->isVoidPointerType() ||
06528            rhs->isObjCIdType() || rhs->isObjCClassType())
06529     return true;
06530 
06531   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
06532     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
06533 
06534     if (!rhsOPT) return false;
06535 
06536     if (rhsOPT->qual_empty()) {
06537       // If the RHS is a unqualified interface pointer "NSString*",
06538       // make sure we check the class hierarchy.
06539       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
06540         for (auto *I : lhsQID->quals()) {
06541           // when comparing an id<P> on lhs with a static type on rhs,
06542           // see if static class implements all of id's protocols, directly or
06543           // through its super class and categories.
06544           if (!rhsID->ClassImplementsProtocol(I, true))
06545             return false;
06546         }
06547       }
06548       // If there are no qualifiers and no interface, we have an 'id'.
06549       return true;
06550     }
06551     // Both the right and left sides have qualifiers.
06552     for (auto *lhsProto : lhsQID->quals()) {
06553       bool match = false;
06554 
06555       // when comparing an id<P> on lhs with a static type on rhs,
06556       // see if static class implements all of id's protocols, directly or
06557       // through its super class and categories.
06558       for (auto *rhsProto : rhsOPT->quals()) {
06559         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
06560             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
06561           match = true;
06562           break;
06563         }
06564       }
06565       // If the RHS is a qualified interface pointer "NSString<P>*",
06566       // make sure we check the class hierarchy.
06567       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
06568         for (auto *I : lhsQID->quals()) {
06569           // when comparing an id<P> on lhs with a static type on rhs,
06570           // see if static class implements all of id's protocols, directly or
06571           // through its super class and categories.
06572           if (rhsID->ClassImplementsProtocol(I, true)) {
06573             match = true;
06574             break;
06575           }
06576         }
06577       }
06578       if (!match)
06579         return false;
06580     }
06581 
06582     return true;
06583   }
06584 
06585   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
06586   assert(rhsQID && "One of the LHS/RHS should be id<x>");
06587 
06588   if (const ObjCObjectPointerType *lhsOPT =
06589         lhs->getAsObjCInterfacePointerType()) {
06590     // If both the right and left sides have qualifiers.
06591     for (auto *lhsProto : lhsOPT->quals()) {
06592       bool match = false;
06593 
06594       // when comparing an id<P> on rhs with a static type on lhs,
06595       // see if static class implements all of id's protocols, directly or
06596       // through its super class and categories.
06597       // First, lhs protocols in the qualifier list must be found, direct
06598       // or indirect in rhs's qualifier list or it is a mismatch.
06599       for (auto *rhsProto : rhsQID->quals()) {
06600         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
06601             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
06602           match = true;
06603           break;
06604         }
06605       }
06606       if (!match)
06607         return false;
06608     }
06609     
06610     // Static class's protocols, or its super class or category protocols
06611     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
06612     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
06613       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
06614       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
06615       // This is rather dubious but matches gcc's behavior. If lhs has
06616       // no type qualifier and its class has no static protocol(s)
06617       // assume that it is mismatch.
06618       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
06619         return false;
06620       for (auto *lhsProto : LHSInheritedProtocols) {
06621         bool match = false;
06622         for (auto *rhsProto : rhsQID->quals()) {
06623           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
06624               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
06625             match = true;
06626             break;
06627           }
06628         }
06629         if (!match)
06630           return false;
06631       }
06632     }
06633     return true;
06634   }
06635   return false;
06636 }
06637 
06638 /// canAssignObjCInterfaces - Return true if the two interface types are
06639 /// compatible for assignment from RHS to LHS.  This handles validation of any
06640 /// protocol qualifiers on the LHS or RHS.
06641 ///
06642 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
06643                                          const ObjCObjectPointerType *RHSOPT) {
06644   const ObjCObjectType* LHS = LHSOPT->getObjectType();
06645   const ObjCObjectType* RHS = RHSOPT->getObjectType();
06646 
06647   // If either type represents the built-in 'id' or 'Class' types, return true.
06648   if (LHS->isObjCUnqualifiedIdOrClass() ||
06649       RHS->isObjCUnqualifiedIdOrClass())
06650     return true;
06651 
06652   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
06653     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
06654                                              QualType(RHSOPT,0),
06655                                              false);
06656   
06657   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
06658     return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
06659                                                 QualType(RHSOPT,0));
06660   
06661   // If we have 2 user-defined types, fall into that path.
06662   if (LHS->getInterface() && RHS->getInterface())
06663     return canAssignObjCInterfaces(LHS, RHS);
06664 
06665   return false;
06666 }
06667 
06668 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
06669 /// for providing type-safety for objective-c pointers used to pass/return 
06670 /// arguments in block literals. When passed as arguments, passing 'A*' where
06671 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
06672 /// not OK. For the return type, the opposite is not OK.
06673 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
06674                                          const ObjCObjectPointerType *LHSOPT,
06675                                          const ObjCObjectPointerType *RHSOPT,
06676                                          bool BlockReturnType) {
06677   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
06678     return true;
06679   
06680   if (LHSOPT->isObjCBuiltinType()) {
06681     return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
06682   }
06683   
06684   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
06685     return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
06686                                              QualType(RHSOPT,0),
06687                                              false);
06688   
06689   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
06690   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
06691   if (LHS && RHS)  { // We have 2 user-defined types.
06692     if (LHS != RHS) {
06693       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
06694         return BlockReturnType;
06695       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
06696         return !BlockReturnType;
06697     }
06698     else
06699       return true;
06700   }
06701   return false;
06702 }
06703 
06704 /// getIntersectionOfProtocols - This routine finds the intersection of set
06705 /// of protocols inherited from two distinct objective-c pointer objects.
06706 /// It is used to build composite qualifier list of the composite type of
06707 /// the conditional expression involving two objective-c pointer objects.
06708 static 
06709 void getIntersectionOfProtocols(ASTContext &Context,
06710                                 const ObjCObjectPointerType *LHSOPT,
06711                                 const ObjCObjectPointerType *RHSOPT,
06712       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
06713   
06714   const ObjCObjectType* LHS = LHSOPT->getObjectType();
06715   const ObjCObjectType* RHS = RHSOPT->getObjectType();
06716   assert(LHS->getInterface() && "LHS must have an interface base");
06717   assert(RHS->getInterface() && "RHS must have an interface base");
06718   
06719   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
06720   unsigned LHSNumProtocols = LHS->getNumProtocols();
06721   if (LHSNumProtocols > 0)
06722     InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
06723   else {
06724     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
06725     Context.CollectInheritedProtocols(LHS->getInterface(),
06726                                       LHSInheritedProtocols);
06727     InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 
06728                                 LHSInheritedProtocols.end());
06729   }
06730   
06731   unsigned RHSNumProtocols = RHS->getNumProtocols();
06732   if (RHSNumProtocols > 0) {
06733     ObjCProtocolDecl **RHSProtocols =
06734       const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
06735     for (unsigned i = 0; i < RHSNumProtocols; ++i)
06736       if (InheritedProtocolSet.count(RHSProtocols[i]))
06737         IntersectionOfProtocols.push_back(RHSProtocols[i]);
06738   } else {
06739     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
06740     Context.CollectInheritedProtocols(RHS->getInterface(),
06741                                       RHSInheritedProtocols);
06742     for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
06743       if (InheritedProtocolSet.count(ProtDecl))
06744         IntersectionOfProtocols.push_back(ProtDecl);
06745   }
06746 }
06747 
06748 /// areCommonBaseCompatible - Returns common base class of the two classes if
06749 /// one found. Note that this is O'2 algorithm. But it will be called as the
06750 /// last type comparison in a ?-exp of ObjC pointer types before a 
06751 /// warning is issued. So, its invokation is extremely rare.
06752 QualType ASTContext::areCommonBaseCompatible(
06753                                           const ObjCObjectPointerType *Lptr,
06754                                           const ObjCObjectPointerType *Rptr) {
06755   const ObjCObjectType *LHS = Lptr->getObjectType();
06756   const ObjCObjectType *RHS = Rptr->getObjectType();
06757   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
06758   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
06759   if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
06760     return QualType();
06761   
06762   do {
06763     LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
06764     if (canAssignObjCInterfaces(LHS, RHS)) {
06765       SmallVector<ObjCProtocolDecl *, 8> Protocols;
06766       getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
06767 
06768       QualType Result = QualType(LHS, 0);
06769       if (!Protocols.empty())
06770         Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
06771       Result = getObjCObjectPointerType(Result);
06772       return Result;
06773     }
06774   } while ((LDecl = LDecl->getSuperClass()));
06775     
06776   return QualType();
06777 }
06778 
06779 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
06780                                          const ObjCObjectType *RHS) {
06781   assert(LHS->getInterface() && "LHS is not an interface type");
06782   assert(RHS->getInterface() && "RHS is not an interface type");
06783 
06784   // Verify that the base decls are compatible: the RHS must be a subclass of
06785   // the LHS.
06786   if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
06787     return false;
06788 
06789   // RHS must have a superset of the protocols in the LHS.  If the LHS is not
06790   // protocol qualified at all, then we are good.
06791   if (LHS->getNumProtocols() == 0)
06792     return true;
06793 
06794   // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
06795   // More detailed analysis is required.
06796   // OK, if LHS is same or a superclass of RHS *and*
06797   // this LHS, or as RHS's super class is assignment compatible with LHS.
06798   bool IsSuperClass =
06799     LHS->getInterface()->isSuperClassOf(RHS->getInterface());
06800   if (IsSuperClass) {
06801     // OK if conversion of LHS to SuperClass results in narrowing of types
06802     // ; i.e., SuperClass may implement at least one of the protocols
06803     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
06804     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
06805     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
06806     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
06807     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
06808     // qualifiers.
06809     for (auto *RHSPI : RHS->quals())
06810       SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
06811     // If there is no protocols associated with RHS, it is not a match.
06812     if (SuperClassInheritedProtocols.empty())
06813       return false;
06814       
06815     for (const auto *LHSProto : LHS->quals()) {
06816       bool SuperImplementsProtocol = false;
06817       for (auto *SuperClassProto : SuperClassInheritedProtocols)
06818         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
06819           SuperImplementsProtocol = true;
06820           break;
06821         }
06822       if (!SuperImplementsProtocol)
06823         return false;
06824     }
06825     return true;
06826   }
06827   return false;
06828 }
06829 
06830 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
06831   // get the "pointed to" types
06832   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
06833   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
06834 
06835   if (!LHSOPT || !RHSOPT)
06836     return false;
06837 
06838   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
06839          canAssignObjCInterfaces(RHSOPT, LHSOPT);
06840 }
06841 
06842 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
06843   return canAssignObjCInterfaces(
06844                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
06845                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
06846 }
06847 
06848 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
06849 /// both shall have the identically qualified version of a compatible type.
06850 /// C99 6.2.7p1: Two types have compatible types if their types are the
06851 /// same. See 6.7.[2,3,5] for additional rules.
06852 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
06853                                     bool CompareUnqualified) {
06854   if (getLangOpts().CPlusPlus)
06855     return hasSameType(LHS, RHS);
06856   
06857   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
06858 }
06859 
06860 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
06861   return typesAreCompatible(LHS, RHS);
06862 }
06863 
06864 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
06865   return !mergeTypes(LHS, RHS, true).isNull();
06866 }
06867 
06868 /// mergeTransparentUnionType - if T is a transparent union type and a member
06869 /// of T is compatible with SubType, return the merged type, else return
06870 /// QualType()
06871 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
06872                                                bool OfBlockPointer,
06873                                                bool Unqualified) {
06874   if (const RecordType *UT = T->getAsUnionType()) {
06875     RecordDecl *UD = UT->getDecl();
06876     if (UD->hasAttr<TransparentUnionAttr>()) {
06877       for (const auto *I : UD->fields()) {
06878         QualType ET = I->getType().getUnqualifiedType();
06879         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
06880         if (!MT.isNull())
06881           return MT;
06882       }
06883     }
06884   }
06885 
06886   return QualType();
06887 }
06888 
06889 /// mergeFunctionParameterTypes - merge two types which appear as function
06890 /// parameter types
06891 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
06892                                                  bool OfBlockPointer,
06893                                                  bool Unqualified) {
06894   // GNU extension: two types are compatible if they appear as a function
06895   // argument, one of the types is a transparent union type and the other
06896   // type is compatible with a union member
06897   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
06898                                               Unqualified);
06899   if (!lmerge.isNull())
06900     return lmerge;
06901 
06902   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
06903                                               Unqualified);
06904   if (!rmerge.isNull())
06905     return rmerge;
06906 
06907   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
06908 }
06909 
06910 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 
06911                                         bool OfBlockPointer,
06912                                         bool Unqualified) {
06913   const FunctionType *lbase = lhs->getAs<FunctionType>();
06914   const FunctionType *rbase = rhs->getAs<FunctionType>();
06915   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
06916   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
06917   bool allLTypes = true;
06918   bool allRTypes = true;
06919 
06920   // Check return type
06921   QualType retType;
06922   if (OfBlockPointer) {
06923     QualType RHS = rbase->getReturnType();
06924     QualType LHS = lbase->getReturnType();
06925     bool UnqualifiedResult = Unqualified;
06926     if (!UnqualifiedResult)
06927       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
06928     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
06929   }
06930   else
06931     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
06932                          Unqualified);
06933   if (retType.isNull()) return QualType();
06934   
06935   if (Unqualified)
06936     retType = retType.getUnqualifiedType();
06937 
06938   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
06939   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
06940   if (Unqualified) {
06941     LRetType = LRetType.getUnqualifiedType();
06942     RRetType = RRetType.getUnqualifiedType();
06943   }
06944   
06945   if (getCanonicalType(retType) != LRetType)
06946     allLTypes = false;
06947   if (getCanonicalType(retType) != RRetType)
06948     allRTypes = false;
06949 
06950   // FIXME: double check this
06951   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
06952   //                           rbase->getRegParmAttr() != 0 &&
06953   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
06954   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
06955   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
06956 
06957   // Compatible functions must have compatible calling conventions
06958   if (lbaseInfo.getCC() != rbaseInfo.getCC())
06959     return QualType();
06960 
06961   // Regparm is part of the calling convention.
06962   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
06963     return QualType();
06964   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
06965     return QualType();
06966 
06967   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
06968     return QualType();
06969 
06970   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
06971   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
06972 
06973   if (lbaseInfo.getNoReturn() != NoReturn)
06974     allLTypes = false;
06975   if (rbaseInfo.getNoReturn() != NoReturn)
06976     allRTypes = false;
06977 
06978   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
06979 
06980   if (lproto && rproto) { // two C99 style function prototypes
06981     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
06982            "C++ shouldn't be here");
06983     // Compatible functions must have the same number of parameters
06984     if (lproto->getNumParams() != rproto->getNumParams())
06985       return QualType();
06986 
06987     // Variadic and non-variadic functions aren't compatible
06988     if (lproto->isVariadic() != rproto->isVariadic())
06989       return QualType();
06990 
06991     if (lproto->getTypeQuals() != rproto->getTypeQuals())
06992       return QualType();
06993 
06994     if (LangOpts.ObjCAutoRefCount &&
06995         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
06996       return QualType();
06997 
06998     // Check parameter type compatibility
06999     SmallVector<QualType, 10> types;
07000     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
07001       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
07002       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
07003       QualType paramType = mergeFunctionParameterTypes(
07004           lParamType, rParamType, OfBlockPointer, Unqualified);
07005       if (paramType.isNull())
07006         return QualType();
07007 
07008       if (Unqualified)
07009         paramType = paramType.getUnqualifiedType();
07010 
07011       types.push_back(paramType);
07012       if (Unqualified) {
07013         lParamType = lParamType.getUnqualifiedType();
07014         rParamType = rParamType.getUnqualifiedType();
07015       }
07016 
07017       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
07018         allLTypes = false;
07019       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
07020         allRTypes = false;
07021     }
07022       
07023     if (allLTypes) return lhs;
07024     if (allRTypes) return rhs;
07025 
07026     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
07027     EPI.ExtInfo = einfo;
07028     return getFunctionType(retType, types, EPI);
07029   }
07030 
07031   if (lproto) allRTypes = false;
07032   if (rproto) allLTypes = false;
07033 
07034   const FunctionProtoType *proto = lproto ? lproto : rproto;
07035   if (proto) {
07036     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
07037     if (proto->isVariadic()) return QualType();
07038     // Check that the types are compatible with the types that
07039     // would result from default argument promotions (C99 6.7.5.3p15).
07040     // The only types actually affected are promotable integer
07041     // types and floats, which would be passed as a different
07042     // type depending on whether the prototype is visible.
07043     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
07044       QualType paramTy = proto->getParamType(i);
07045 
07046       // Look at the converted type of enum types, since that is the type used
07047       // to pass enum values.
07048       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
07049         paramTy = Enum->getDecl()->getIntegerType();
07050         if (paramTy.isNull())
07051           return QualType();
07052       }
07053 
07054       if (paramTy->isPromotableIntegerType() ||
07055           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
07056         return QualType();
07057     }
07058 
07059     if (allLTypes) return lhs;
07060     if (allRTypes) return rhs;
07061 
07062     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
07063     EPI.ExtInfo = einfo;
07064     return getFunctionType(retType, proto->getParamTypes(), EPI);
07065   }
07066 
07067   if (allLTypes) return lhs;
07068   if (allRTypes) return rhs;
07069   return getFunctionNoProtoType(retType, einfo);
07070 }
07071 
07072 /// Given that we have an enum type and a non-enum type, try to merge them.
07073 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
07074                                      QualType other, bool isBlockReturnType) {
07075   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
07076   // a signed integer type, or an unsigned integer type.
07077   // Compatibility is based on the underlying type, not the promotion
07078   // type.
07079   QualType underlyingType = ET->getDecl()->getIntegerType();
07080   if (underlyingType.isNull()) return QualType();
07081   if (Context.hasSameType(underlyingType, other))
07082     return other;
07083 
07084   // In block return types, we're more permissive and accept any
07085   // integral type of the same size.
07086   if (isBlockReturnType && other->isIntegerType() &&
07087       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
07088     return other;
07089 
07090   return QualType();
07091 }
07092 
07093 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 
07094                                 bool OfBlockPointer,
07095                                 bool Unqualified, bool BlockReturnType) {
07096   // C++ [expr]: If an expression initially has the type "reference to T", the
07097   // type is adjusted to "T" prior to any further analysis, the expression
07098   // designates the object or function denoted by the reference, and the
07099   // expression is an lvalue unless the reference is an rvalue reference and
07100   // the expression is a function call (possibly inside parentheses).
07101   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
07102   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
07103 
07104   if (Unqualified) {
07105     LHS = LHS.getUnqualifiedType();
07106     RHS = RHS.getUnqualifiedType();
07107   }
07108   
07109   QualType LHSCan = getCanonicalType(LHS),
07110            RHSCan = getCanonicalType(RHS);
07111 
07112   // If two types are identical, they are compatible.
07113   if (LHSCan == RHSCan)
07114     return LHS;
07115 
07116   // If the qualifiers are different, the types aren't compatible... mostly.
07117   Qualifiers LQuals = LHSCan.getLocalQualifiers();
07118   Qualifiers RQuals = RHSCan.getLocalQualifiers();
07119   if (LQuals != RQuals) {
07120     // If any of these qualifiers are different, we have a type
07121     // mismatch.
07122     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
07123         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
07124         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
07125       return QualType();
07126 
07127     // Exactly one GC qualifier difference is allowed: __strong is
07128     // okay if the other type has no GC qualifier but is an Objective
07129     // C object pointer (i.e. implicitly strong by default).  We fix
07130     // this by pretending that the unqualified type was actually
07131     // qualified __strong.
07132     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
07133     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
07134     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
07135 
07136     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
07137       return QualType();
07138 
07139     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
07140       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
07141     }
07142     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
07143       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
07144     }
07145     return QualType();
07146   }
07147 
07148   // Okay, qualifiers are equal.
07149 
07150   Type::TypeClass LHSClass = LHSCan->getTypeClass();
07151   Type::TypeClass RHSClass = RHSCan->getTypeClass();
07152 
07153   // We want to consider the two function types to be the same for these
07154   // comparisons, just force one to the other.
07155   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
07156   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
07157 
07158   // Same as above for arrays
07159   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
07160     LHSClass = Type::ConstantArray;
07161   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
07162     RHSClass = Type::ConstantArray;
07163 
07164   // ObjCInterfaces are just specialized ObjCObjects.
07165   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
07166   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
07167 
07168   // Canonicalize ExtVector -> Vector.
07169   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
07170   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
07171 
07172   // If the canonical type classes don't match.
07173   if (LHSClass != RHSClass) {
07174     // Note that we only have special rules for turning block enum
07175     // returns into block int returns, not vice-versa.
07176     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
07177       return mergeEnumWithInteger(*this, ETy, RHS, false);
07178     }
07179     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
07180       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
07181     }
07182     // allow block pointer type to match an 'id' type.
07183     if (OfBlockPointer && !BlockReturnType) {
07184        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
07185          return LHS;
07186       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
07187         return RHS;
07188     }
07189     
07190     return QualType();
07191   }
07192 
07193   // The canonical type classes match.
07194   switch (LHSClass) {
07195 #define TYPE(Class, Base)
07196 #define ABSTRACT_TYPE(Class, Base)
07197 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
07198 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
07199 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
07200 #include "clang/AST/TypeNodes.def"
07201     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
07202 
07203   case Type::Auto:
07204   case Type::LValueReference:
07205   case Type::RValueReference:
07206   case Type::MemberPointer:
07207     llvm_unreachable("C++ should never be in mergeTypes");
07208 
07209   case Type::ObjCInterface:
07210   case Type::IncompleteArray:
07211   case Type::VariableArray:
07212   case Type::FunctionProto:
07213   case Type::ExtVector:
07214     llvm_unreachable("Types are eliminated above");
07215 
07216   case Type::Pointer:
07217   {
07218     // Merge two pointer types, while trying to preserve typedef info
07219     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
07220     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
07221     if (Unqualified) {
07222       LHSPointee = LHSPointee.getUnqualifiedType();
07223       RHSPointee = RHSPointee.getUnqualifiedType();
07224     }
07225     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 
07226                                      Unqualified);
07227     if (ResultType.isNull()) return QualType();
07228     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
07229       return LHS;
07230     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
07231       return RHS;
07232     return getPointerType(ResultType);
07233   }
07234   case Type::BlockPointer:
07235   {
07236     // Merge two block pointer types, while trying to preserve typedef info
07237     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
07238     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
07239     if (Unqualified) {
07240       LHSPointee = LHSPointee.getUnqualifiedType();
07241       RHSPointee = RHSPointee.getUnqualifiedType();
07242     }
07243     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
07244                                      Unqualified);
07245     if (ResultType.isNull()) return QualType();
07246     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
07247       return LHS;
07248     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
07249       return RHS;
07250     return getBlockPointerType(ResultType);
07251   }
07252   case Type::Atomic:
07253   {
07254     // Merge two pointer types, while trying to preserve typedef info
07255     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
07256     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
07257     if (Unqualified) {
07258       LHSValue = LHSValue.getUnqualifiedType();
07259       RHSValue = RHSValue.getUnqualifiedType();
07260     }
07261     QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 
07262                                      Unqualified);
07263     if (ResultType.isNull()) return QualType();
07264     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
07265       return LHS;
07266     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
07267       return RHS;
07268     return getAtomicType(ResultType);
07269   }
07270   case Type::ConstantArray:
07271   {
07272     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
07273     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
07274     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
07275       return QualType();
07276 
07277     QualType LHSElem = getAsArrayType(LHS)->getElementType();
07278     QualType RHSElem = getAsArrayType(RHS)->getElementType();
07279     if (Unqualified) {
07280       LHSElem = LHSElem.getUnqualifiedType();
07281       RHSElem = RHSElem.getUnqualifiedType();
07282     }
07283     
07284     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
07285     if (ResultType.isNull()) return QualType();
07286     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
07287       return LHS;
07288     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
07289       return RHS;
07290     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
07291                                           ArrayType::ArraySizeModifier(), 0);
07292     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
07293                                           ArrayType::ArraySizeModifier(), 0);
07294     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
07295     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
07296     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
07297       return LHS;
07298     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
07299       return RHS;
07300     if (LVAT) {
07301       // FIXME: This isn't correct! But tricky to implement because
07302       // the array's size has to be the size of LHS, but the type
07303       // has to be different.
07304       return LHS;
07305     }
07306     if (RVAT) {
07307       // FIXME: This isn't correct! But tricky to implement because
07308       // the array's size has to be the size of RHS, but the type
07309       // has to be different.
07310       return RHS;
07311     }
07312     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
07313     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
07314     return getIncompleteArrayType(ResultType,
07315                                   ArrayType::ArraySizeModifier(), 0);
07316   }
07317   case Type::FunctionNoProto:
07318     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
07319   case Type::Record:
07320   case Type::Enum:
07321     return QualType();
07322   case Type::Builtin:
07323     // Only exactly equal builtin types are compatible, which is tested above.
07324     return QualType();
07325   case Type::Complex:
07326     // Distinct complex types are incompatible.
07327     return QualType();
07328   case Type::Vector:
07329     // FIXME: The merged type should be an ExtVector!
07330     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
07331                              RHSCan->getAs<VectorType>()))
07332       return LHS;
07333     return QualType();
07334   case Type::ObjCObject: {
07335     // Check if the types are assignment compatible.
07336     // FIXME: This should be type compatibility, e.g. whether
07337     // "LHS x; RHS x;" at global scope is legal.
07338     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
07339     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
07340     if (canAssignObjCInterfaces(LHSIface, RHSIface))
07341       return LHS;
07342 
07343     return QualType();
07344   }
07345   case Type::ObjCObjectPointer: {
07346     if (OfBlockPointer) {
07347       if (canAssignObjCInterfacesInBlockPointer(
07348                                           LHS->getAs<ObjCObjectPointerType>(),
07349                                           RHS->getAs<ObjCObjectPointerType>(),
07350                                           BlockReturnType))
07351         return LHS;
07352       return QualType();
07353     }
07354     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
07355                                 RHS->getAs<ObjCObjectPointerType>()))
07356       return LHS;
07357 
07358     return QualType();
07359   }
07360   }
07361 
07362   llvm_unreachable("Invalid Type::Class!");
07363 }
07364 
07365 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
07366                    const FunctionProtoType *FromFunctionType,
07367                    const FunctionProtoType *ToFunctionType) {
07368   if (FromFunctionType->hasAnyConsumedParams() !=
07369       ToFunctionType->hasAnyConsumedParams())
07370     return false;
07371   FunctionProtoType::ExtProtoInfo FromEPI = 
07372     FromFunctionType->getExtProtoInfo();
07373   FunctionProtoType::ExtProtoInfo ToEPI = 
07374     ToFunctionType->getExtProtoInfo();
07375   if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
07376     for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
07377       if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
07378         return false;
07379     }
07380   return true;
07381 }
07382 
07383 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
07384 /// 'RHS' attributes and returns the merged version; including for function
07385 /// return types.
07386 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
07387   QualType LHSCan = getCanonicalType(LHS),
07388   RHSCan = getCanonicalType(RHS);
07389   // If two types are identical, they are compatible.
07390   if (LHSCan == RHSCan)
07391     return LHS;
07392   if (RHSCan->isFunctionType()) {
07393     if (!LHSCan->isFunctionType())
07394       return QualType();
07395     QualType OldReturnType =
07396         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
07397     QualType NewReturnType =
07398         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
07399     QualType ResReturnType = 
07400       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
07401     if (ResReturnType.isNull())
07402       return QualType();
07403     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
07404       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
07405       // In either case, use OldReturnType to build the new function type.
07406       const FunctionType *F = LHS->getAs<FunctionType>();
07407       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
07408         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
07409         EPI.ExtInfo = getFunctionExtInfo(LHS);
07410         QualType ResultType =
07411             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
07412         return ResultType;
07413       }
07414     }
07415     return QualType();
07416   }
07417   
07418   // If the qualifiers are different, the types can still be merged.
07419   Qualifiers LQuals = LHSCan.getLocalQualifiers();
07420   Qualifiers RQuals = RHSCan.getLocalQualifiers();
07421   if (LQuals != RQuals) {
07422     // If any of these qualifiers are different, we have a type mismatch.
07423     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
07424         LQuals.getAddressSpace() != RQuals.getAddressSpace())
07425       return QualType();
07426     
07427     // Exactly one GC qualifier difference is allowed: __strong is
07428     // okay if the other type has no GC qualifier but is an Objective
07429     // C object pointer (i.e. implicitly strong by default).  We fix
07430     // this by pretending that the unqualified type was actually
07431     // qualified __strong.
07432     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
07433     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
07434     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
07435     
07436     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
07437       return QualType();
07438     
07439     if (GC_L == Qualifiers::Strong)
07440       return LHS;
07441     if (GC_R == Qualifiers::Strong)
07442       return RHS;
07443     return QualType();
07444   }
07445   
07446   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
07447     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
07448     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
07449     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
07450     if (ResQT == LHSBaseQT)
07451       return LHS;
07452     if (ResQT == RHSBaseQT)
07453       return RHS;
07454   }
07455   return QualType();
07456 }
07457 
07458 //===----------------------------------------------------------------------===//
07459 //                         Integer Predicates
07460 //===----------------------------------------------------------------------===//
07461 
07462 unsigned ASTContext::getIntWidth(QualType T) const {
07463   if (const EnumType *ET = T->getAs<EnumType>())
07464     T = ET->getDecl()->getIntegerType();
07465   if (T->isBooleanType())
07466     return 1;
07467   // For builtin types, just use the standard type sizing method
07468   return (unsigned)getTypeSize(T);
07469 }
07470 
07471 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
07472   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
07473   
07474   // Turn <4 x signed int> -> <4 x unsigned int>
07475   if (const VectorType *VTy = T->getAs<VectorType>())
07476     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
07477                          VTy->getNumElements(), VTy->getVectorKind());
07478 
07479   // For enums, we return the unsigned version of the base type.
07480   if (const EnumType *ETy = T->getAs<EnumType>())
07481     T = ETy->getDecl()->getIntegerType();
07482   
07483   const BuiltinType *BTy = T->getAs<BuiltinType>();
07484   assert(BTy && "Unexpected signed integer type");
07485   switch (BTy->getKind()) {
07486   case BuiltinType::Char_S:
07487   case BuiltinType::SChar:
07488     return UnsignedCharTy;
07489   case BuiltinType::Short:
07490     return UnsignedShortTy;
07491   case BuiltinType::Int:
07492     return UnsignedIntTy;
07493   case BuiltinType::Long:
07494     return UnsignedLongTy;
07495   case BuiltinType::LongLong:
07496     return UnsignedLongLongTy;
07497   case BuiltinType::Int128:
07498     return UnsignedInt128Ty;
07499   default:
07500     llvm_unreachable("Unexpected signed integer type");
07501   }
07502 }
07503 
07504 ASTMutationListener::~ASTMutationListener() { }
07505 
07506 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
07507                                             QualType ReturnType) {}
07508 
07509 //===----------------------------------------------------------------------===//
07510 //                          Builtin Type Computation
07511 //===----------------------------------------------------------------------===//
07512 
07513 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
07514 /// pointer over the consumed characters.  This returns the resultant type.  If
07515 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
07516 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
07517 /// a vector of "i*".
07518 ///
07519 /// RequiresICE is filled in on return to indicate whether the value is required
07520 /// to be an Integer Constant Expression.
07521 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
07522                                   ASTContext::GetBuiltinTypeError &Error,
07523                                   bool &RequiresICE,
07524                                   bool AllowTypeModifiers) {
07525   // Modifiers.
07526   int HowLong = 0;
07527   bool Signed = false, Unsigned = false;
07528   RequiresICE = false;
07529   
07530   // Read the prefixed modifiers first.
07531   bool Done = false;
07532   while (!Done) {
07533     switch (*Str++) {
07534     default: Done = true; --Str; break;
07535     case 'I':
07536       RequiresICE = true;
07537       break;
07538     case 'S':
07539       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
07540       assert(!Signed && "Can't use 'S' modifier multiple times!");
07541       Signed = true;
07542       break;
07543     case 'U':
07544       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
07545       assert(!Unsigned && "Can't use 'S' modifier multiple times!");
07546       Unsigned = true;
07547       break;
07548     case 'L':
07549       assert(HowLong <= 2 && "Can't have LLLL modifier");
07550       ++HowLong;
07551       break;
07552     case 'W':
07553       // This modifier represents int64 type.
07554       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
07555       switch (Context.getTargetInfo().getInt64Type()) {
07556       default:
07557         llvm_unreachable("Unexpected integer type");
07558       case TargetInfo::SignedLong:
07559         HowLong = 1;
07560         break;
07561       case TargetInfo::SignedLongLong:
07562         HowLong = 2;
07563         break;
07564       }
07565     }
07566   }
07567 
07568   QualType Type;
07569 
07570   // Read the base type.
07571   switch (*Str++) {
07572   default: llvm_unreachable("Unknown builtin type letter!");
07573   case 'v':
07574     assert(HowLong == 0 && !Signed && !Unsigned &&
07575            "Bad modifiers used with 'v'!");
07576     Type = Context.VoidTy;
07577     break;
07578   case 'h':
07579     assert(HowLong == 0 && !Signed && !Unsigned &&
07580            "Bad modifiers used with 'f'!");
07581     Type = Context.HalfTy;
07582     break;
07583   case 'f':
07584     assert(HowLong == 0 && !Signed && !Unsigned &&
07585            "Bad modifiers used with 'f'!");
07586     Type = Context.FloatTy;
07587     break;
07588   case 'd':
07589     assert(HowLong < 2 && !Signed && !Unsigned &&
07590            "Bad modifiers used with 'd'!");
07591     if (HowLong)
07592       Type = Context.LongDoubleTy;
07593     else
07594       Type = Context.DoubleTy;
07595     break;
07596   case 's':
07597     assert(HowLong == 0 && "Bad modifiers used with 's'!");
07598     if (Unsigned)
07599       Type = Context.UnsignedShortTy;
07600     else
07601       Type = Context.ShortTy;
07602     break;
07603   case 'i':
07604     if (HowLong == 3)
07605       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
07606     else if (HowLong == 2)
07607       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
07608     else if (HowLong == 1)
07609       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
07610     else
07611       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
07612     break;
07613   case 'c':
07614     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
07615     if (Signed)
07616       Type = Context.SignedCharTy;
07617     else if (Unsigned)
07618       Type = Context.UnsignedCharTy;
07619     else
07620       Type = Context.CharTy;
07621     break;
07622   case 'b': // boolean
07623     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
07624     Type = Context.BoolTy;
07625     break;
07626   case 'z':  // size_t.
07627     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
07628     Type = Context.getSizeType();
07629     break;
07630   case 'F':
07631     Type = Context.getCFConstantStringType();
07632     break;
07633   case 'G':
07634     Type = Context.getObjCIdType();
07635     break;
07636   case 'H':
07637     Type = Context.getObjCSelType();
07638     break;
07639   case 'M':
07640     Type = Context.getObjCSuperType();
07641     break;
07642   case 'a':
07643     Type = Context.getBuiltinVaListType();
07644     assert(!Type.isNull() && "builtin va list type not initialized!");
07645     break;
07646   case 'A':
07647     // This is a "reference" to a va_list; however, what exactly
07648     // this means depends on how va_list is defined. There are two
07649     // different kinds of va_list: ones passed by value, and ones
07650     // passed by reference.  An example of a by-value va_list is
07651     // x86, where va_list is a char*. An example of by-ref va_list
07652     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
07653     // we want this argument to be a char*&; for x86-64, we want
07654     // it to be a __va_list_tag*.
07655     Type = Context.getBuiltinVaListType();
07656     assert(!Type.isNull() && "builtin va list type not initialized!");
07657     if (Type->isArrayType())
07658       Type = Context.getArrayDecayedType(Type);
07659     else
07660       Type = Context.getLValueReferenceType(Type);
07661     break;
07662   case 'V': {
07663     char *End;
07664     unsigned NumElements = strtoul(Str, &End, 10);
07665     assert(End != Str && "Missing vector size");
07666     Str = End;
07667 
07668     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 
07669                                              RequiresICE, false);
07670     assert(!RequiresICE && "Can't require vector ICE");
07671     
07672     // TODO: No way to make AltiVec vectors in builtins yet.
07673     Type = Context.getVectorType(ElementType, NumElements,
07674                                  VectorType::GenericVector);
07675     break;
07676   }
07677   case 'E': {
07678     char *End;
07679     
07680     unsigned NumElements = strtoul(Str, &End, 10);
07681     assert(End != Str && "Missing vector size");
07682     
07683     Str = End;
07684     
07685     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
07686                                              false);
07687     Type = Context.getExtVectorType(ElementType, NumElements);
07688     break;    
07689   }
07690   case 'X': {
07691     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
07692                                              false);
07693     assert(!RequiresICE && "Can't require complex ICE");
07694     Type = Context.getComplexType(ElementType);
07695     break;
07696   }  
07697   case 'Y' : {
07698     Type = Context.getPointerDiffType();
07699     break;
07700   }
07701   case 'P':
07702     Type = Context.getFILEType();
07703     if (Type.isNull()) {
07704       Error = ASTContext::GE_Missing_stdio;
07705       return QualType();
07706     }
07707     break;
07708   case 'J':
07709     if (Signed)
07710       Type = Context.getsigjmp_bufType();
07711     else
07712       Type = Context.getjmp_bufType();
07713 
07714     if (Type.isNull()) {
07715       Error = ASTContext::GE_Missing_setjmp;
07716       return QualType();
07717     }
07718     break;
07719   case 'K':
07720     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
07721     Type = Context.getucontext_tType();
07722 
07723     if (Type.isNull()) {
07724       Error = ASTContext::GE_Missing_ucontext;
07725       return QualType();
07726     }
07727     break;
07728   case 'p':
07729     Type = Context.getProcessIDType();
07730     break;
07731   }
07732 
07733   // If there are modifiers and if we're allowed to parse them, go for it.
07734   Done = !AllowTypeModifiers;
07735   while (!Done) {
07736     switch (char c = *Str++) {
07737     default: Done = true; --Str; break;
07738     case '*':
07739     case '&': {
07740       // Both pointers and references can have their pointee types
07741       // qualified with an address space.
07742       char *End;
07743       unsigned AddrSpace = strtoul(Str, &End, 10);
07744       if (End != Str && AddrSpace != 0) {
07745         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
07746         Str = End;
07747       }
07748       if (c == '*')
07749         Type = Context.getPointerType(Type);
07750       else
07751         Type = Context.getLValueReferenceType(Type);
07752       break;
07753     }
07754     // FIXME: There's no way to have a built-in with an rvalue ref arg.
07755     case 'C':
07756       Type = Type.withConst();
07757       break;
07758     case 'D':
07759       Type = Context.getVolatileType(Type);
07760       break;
07761     case 'R':
07762       Type = Type.withRestrict();
07763       break;
07764     }
07765   }
07766   
07767   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
07768          "Integer constant 'I' type must be an integer"); 
07769 
07770   return Type;
07771 }
07772 
07773 /// GetBuiltinType - Return the type for the specified builtin.
07774 QualType ASTContext::GetBuiltinType(unsigned Id,
07775                                     GetBuiltinTypeError &Error,
07776                                     unsigned *IntegerConstantArgs) const {
07777   const char *TypeStr = BuiltinInfo.GetTypeString(Id);
07778 
07779   SmallVector<QualType, 8> ArgTypes;
07780 
07781   bool RequiresICE = false;
07782   Error = GE_None;
07783   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
07784                                        RequiresICE, true);
07785   if (Error != GE_None)
07786     return QualType();
07787   
07788   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
07789   
07790   while (TypeStr[0] && TypeStr[0] != '.') {
07791     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
07792     if (Error != GE_None)
07793       return QualType();
07794 
07795     // If this argument is required to be an IntegerConstantExpression and the
07796     // caller cares, fill in the bitmask we return.
07797     if (RequiresICE && IntegerConstantArgs)
07798       *IntegerConstantArgs |= 1 << ArgTypes.size();
07799     
07800     // Do array -> pointer decay.  The builtin should use the decayed type.
07801     if (Ty->isArrayType())
07802       Ty = getArrayDecayedType(Ty);
07803 
07804     ArgTypes.push_back(Ty);
07805   }
07806 
07807   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
07808          "'.' should only occur at end of builtin type list!");
07809 
07810   FunctionType::ExtInfo EI(CC_C);
07811   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
07812 
07813   bool Variadic = (TypeStr[0] == '.');
07814 
07815   // We really shouldn't be making a no-proto type here, especially in C++.
07816   if (ArgTypes.empty() && Variadic)
07817     return getFunctionNoProtoType(ResType, EI);
07818 
07819   FunctionProtoType::ExtProtoInfo EPI;
07820   EPI.ExtInfo = EI;
07821   EPI.Variadic = Variadic;
07822 
07823   return getFunctionType(ResType, ArgTypes, EPI);
07824 }
07825 
07826 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
07827                                              const FunctionDecl *FD) {
07828   if (!FD->isExternallyVisible())
07829     return GVA_Internal;
07830 
07831   GVALinkage External = GVA_StrongExternal;
07832   switch (FD->getTemplateSpecializationKind()) {
07833   case TSK_Undeclared:
07834   case TSK_ExplicitSpecialization:
07835     External = GVA_StrongExternal;
07836     break;
07837 
07838   case TSK_ExplicitInstantiationDefinition:
07839     return GVA_StrongODR;
07840 
07841   // C++11 [temp.explicit]p10:
07842   //   [ Note: The intent is that an inline function that is the subject of
07843   //   an explicit instantiation declaration will still be implicitly
07844   //   instantiated when used so that the body can be considered for
07845   //   inlining, but that no out-of-line copy of the inline function would be
07846   //   generated in the translation unit. -- end note ]
07847   case TSK_ExplicitInstantiationDeclaration:
07848     return GVA_AvailableExternally;
07849 
07850   case TSK_ImplicitInstantiation:
07851     External = GVA_DiscardableODR;
07852     break;
07853   }
07854 
07855   if (!FD->isInlined())
07856     return External;
07857 
07858   if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
07859        !FD->hasAttr<DLLExportAttr>()) ||
07860       FD->hasAttr<GNUInlineAttr>()) {
07861     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
07862 
07863     // GNU or C99 inline semantics. Determine whether this symbol should be
07864     // externally visible.
07865     if (FD->isInlineDefinitionExternallyVisible())
07866       return External;
07867 
07868     // C99 inline semantics, where the symbol is not externally visible.
07869     return GVA_AvailableExternally;
07870   }
07871 
07872   // Functions specified with extern and inline in -fms-compatibility mode
07873   // forcibly get emitted.  While the body of the function cannot be later
07874   // replaced, the function definition cannot be discarded.
07875   if (FD->getMostRecentDecl()->isMSExternInline())
07876     return GVA_StrongODR;
07877 
07878   return GVA_DiscardableODR;
07879 }
07880 
07881 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
07882   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
07883   // dllexport/dllimport on inline functions.
07884   if (D->hasAttr<DLLImportAttr>()) {
07885     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
07886       return GVA_AvailableExternally;
07887   } else if (D->hasAttr<DLLExportAttr>()) {
07888     if (L == GVA_DiscardableODR)
07889       return GVA_StrongODR;
07890   }
07891   return L;
07892 }
07893 
07894 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
07895   return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
07896                                          FD);
07897 }
07898 
07899 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
07900                                              const VarDecl *VD) {
07901   if (!VD->isExternallyVisible())
07902     return GVA_Internal;
07903 
07904   if (VD->isStaticLocal()) {
07905     GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
07906     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
07907     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
07908       LexicalContext = LexicalContext->getLexicalParent();
07909 
07910     // Let the static local variable inherit it's linkage from the nearest
07911     // enclosing function.
07912     if (LexicalContext)
07913       StaticLocalLinkage =
07914           Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
07915 
07916     // GVA_StrongODR function linkage is stronger than what we need,
07917     // downgrade to GVA_DiscardableODR.
07918     // This allows us to discard the variable if we never end up needing it.
07919     return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
07920                                                : StaticLocalLinkage;
07921   }
07922 
07923   // MSVC treats in-class initialized static data members as definitions.
07924   // By giving them non-strong linkage, out-of-line definitions won't
07925   // cause link errors.
07926   if (Context.isMSStaticDataMemberInlineDefinition(VD))
07927     return GVA_DiscardableODR;
07928 
07929   switch (VD->getTemplateSpecializationKind()) {
07930   case TSK_Undeclared:
07931   case TSK_ExplicitSpecialization:
07932     return GVA_StrongExternal;
07933 
07934   case TSK_ExplicitInstantiationDefinition:
07935     return GVA_StrongODR;
07936 
07937   case TSK_ExplicitInstantiationDeclaration:
07938     return GVA_AvailableExternally;
07939 
07940   case TSK_ImplicitInstantiation:
07941     return GVA_DiscardableODR;
07942   }
07943 
07944   llvm_unreachable("Invalid Linkage!");
07945 }
07946 
07947 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
07948   return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
07949                                          VD);
07950 }
07951 
07952 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
07953   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
07954     if (!VD->isFileVarDecl())
07955       return false;
07956     // Global named register variables (GNU extension) are never emitted.
07957     if (VD->getStorageClass() == SC_Register)
07958       return false;
07959   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
07960     // We never need to emit an uninstantiated function template.
07961     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
07962       return false;
07963   } else if (isa<OMPThreadPrivateDecl>(D))
07964     return true;
07965   else
07966     return false;
07967 
07968   // If this is a member of a class template, we do not need to emit it.
07969   if (D->getDeclContext()->isDependentContext())
07970     return false;
07971 
07972   // Weak references don't produce any output by themselves.
07973   if (D->hasAttr<WeakRefAttr>())
07974     return false;
07975 
07976   // Aliases and used decls are required.
07977   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
07978     return true;
07979 
07980   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
07981     // Forward declarations aren't required.
07982     if (!FD->doesThisDeclarationHaveABody())
07983       return FD->doesDeclarationForceExternallyVisibleDefinition();
07984 
07985     // Constructors and destructors are required.
07986     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
07987       return true;
07988     
07989     // The key function for a class is required.  This rule only comes
07990     // into play when inline functions can be key functions, though.
07991     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
07992       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
07993         const CXXRecordDecl *RD = MD->getParent();
07994         if (MD->isOutOfLine() && RD->isDynamicClass()) {
07995           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
07996           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
07997             return true;
07998         }
07999       }
08000     }
08001 
08002     GVALinkage Linkage = GetGVALinkageForFunction(FD);
08003 
08004     // static, static inline, always_inline, and extern inline functions can
08005     // always be deferred.  Normal inline functions can be deferred in C99/C++.
08006     // Implicit template instantiations can also be deferred in C++.
08007     if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
08008         Linkage == GVA_DiscardableODR)
08009       return false;
08010     return true;
08011   }
08012   
08013   const VarDecl *VD = cast<VarDecl>(D);
08014   assert(VD->isFileVarDecl() && "Expected file scoped var");
08015 
08016   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
08017       !isMSStaticDataMemberInlineDefinition(VD))
08018     return false;
08019 
08020   // Variables that can be needed in other TUs are required.
08021   GVALinkage L = GetGVALinkageForVariable(VD);
08022   if (L != GVA_Internal && L != GVA_AvailableExternally &&
08023       L != GVA_DiscardableODR)
08024     return true;
08025 
08026   // Variables that have destruction with side-effects are required.
08027   if (VD->getType().isDestructedType())
08028     return true;
08029 
08030   // Variables that have initialization with side-effects are required.
08031   if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
08032     return true;
08033 
08034   return false;
08035 }
08036 
08037 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
08038                                                     bool IsCXXMethod) const {
08039   // Pass through to the C++ ABI object
08040   if (IsCXXMethod)
08041     return ABI->getDefaultMethodCallConv(IsVariadic);
08042 
08043   return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
08044 }
08045 
08046 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
08047   // Pass through to the C++ ABI object
08048   return ABI->isNearlyEmpty(RD);
08049 }
08050 
08051 VTableContextBase *ASTContext::getVTableContext() {
08052   if (!VTContext.get()) {
08053     if (Target->getCXXABI().isMicrosoft())
08054       VTContext.reset(new MicrosoftVTableContext(*this));
08055     else
08056       VTContext.reset(new ItaniumVTableContext(*this));
08057   }
08058   return VTContext.get();
08059 }
08060 
08061 MangleContext *ASTContext::createMangleContext() {
08062   switch (Target->getCXXABI().getKind()) {
08063   case TargetCXXABI::GenericAArch64:
08064   case TargetCXXABI::GenericItanium:
08065   case TargetCXXABI::GenericARM:
08066   case TargetCXXABI::iOS:
08067   case TargetCXXABI::iOS64:
08068     return ItaniumMangleContext::create(*this, getDiagnostics());
08069   case TargetCXXABI::Microsoft:
08070     return MicrosoftMangleContext::create(*this, getDiagnostics());
08071   }
08072   llvm_unreachable("Unsupported ABI");
08073 }
08074 
08075 CXXABI::~CXXABI() {}
08076 
08077 size_t ASTContext::getSideTableAllocatedMemory() const {
08078   return ASTRecordLayouts.getMemorySize() +
08079          llvm::capacity_in_bytes(ObjCLayouts) +
08080          llvm::capacity_in_bytes(KeyFunctions) +
08081          llvm::capacity_in_bytes(ObjCImpls) +
08082          llvm::capacity_in_bytes(BlockVarCopyInits) +
08083          llvm::capacity_in_bytes(DeclAttrs) +
08084          llvm::capacity_in_bytes(TemplateOrInstantiation) +
08085          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
08086          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
08087          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
08088          llvm::capacity_in_bytes(OverriddenMethods) +
08089          llvm::capacity_in_bytes(Types) +
08090          llvm::capacity_in_bytes(VariableArrayTypes) +
08091          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
08092 }
08093 
08094 /// getIntTypeForBitwidth -
08095 /// sets integer QualTy according to specified details:
08096 /// bitwidth, signed/unsigned.
08097 /// Returns empty type if there is no appropriate target types.
08098 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
08099                                            unsigned Signed) const {
08100   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
08101   CanQualType QualTy = getFromTargetType(Ty);
08102   if (!QualTy && DestWidth == 128)
08103     return Signed ? Int128Ty : UnsignedInt128Ty;
08104   return QualTy;
08105 }
08106 
08107 /// getRealTypeForBitwidth -
08108 /// sets floating point QualTy according to specified bitwidth.
08109 /// Returns empty type if there is no appropriate target types.
08110 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
08111   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
08112   switch (Ty) {
08113   case TargetInfo::Float:
08114     return FloatTy;
08115   case TargetInfo::Double:
08116     return DoubleTy;
08117   case TargetInfo::LongDouble:
08118     return LongDoubleTy;
08119   case TargetInfo::NoFloat:
08120     return QualType();
08121   }
08122 
08123   llvm_unreachable("Unhandled TargetInfo::RealType value");
08124 }
08125 
08126 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
08127   if (Number > 1)
08128     MangleNumbers[ND] = Number;
08129 }
08130 
08131 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
08132   llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
08133     MangleNumbers.find(ND);
08134   return I != MangleNumbers.end() ? I->second : 1;
08135 }
08136 
08137 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
08138   if (Number > 1)
08139     StaticLocalNumbers[VD] = Number;
08140 }
08141 
08142 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
08143   llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
08144       StaticLocalNumbers.find(VD);
08145   return I != StaticLocalNumbers.end() ? I->second : 1;
08146 }
08147 
08148 MangleNumberingContext &
08149 ASTContext::getManglingNumberContext(const DeclContext *DC) {
08150   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
08151   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
08152   if (!MCtx)
08153     MCtx = createMangleNumberingContext();
08154   return *MCtx;
08155 }
08156 
08157 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
08158   return ABI->createMangleNumberingContext();
08159 }
08160 
08161 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
08162   ParamIndices[D] = index;
08163 }
08164 
08165 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
08166   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
08167   assert(I != ParamIndices.end() && 
08168          "ParmIndices lacks entry set by ParmVarDecl");
08169   return I->second;
08170 }
08171 
08172 APValue *
08173 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
08174                                           bool MayCreate) {
08175   assert(E && E->getStorageDuration() == SD_Static &&
08176          "don't need to cache the computed value for this temporary");
08177   if (MayCreate)
08178     return &MaterializedTemporaryValues[E];
08179 
08180   llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
08181       MaterializedTemporaryValues.find(E);
08182   return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
08183 }
08184 
08185 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
08186   const llvm::Triple &T = getTargetInfo().getTriple();
08187   if (!T.isOSDarwin())
08188     return false;
08189 
08190   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
08191       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
08192     return false;
08193 
08194   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
08195   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
08196   uint64_t Size = sizeChars.getQuantity();
08197   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
08198   unsigned Align = alignChars.getQuantity();
08199   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
08200   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
08201 }
08202 
08203 namespace {
08204 
08205   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
08206   /// parents as defined by the \c RecursiveASTVisitor.
08207   ///
08208   /// Note that the relationship described here is purely in terms of AST
08209   /// traversal - there are other relationships (for example declaration context)
08210   /// in the AST that are better modeled by special matchers.
08211   ///
08212   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
08213   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
08214 
08215   public:
08216     /// \brief Builds and returns the translation unit's parent map.
08217     ///
08218     ///  The caller takes ownership of the returned \c ParentMap.
08219     static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
08220       ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
08221       Visitor.TraverseDecl(&TU);
08222       return Visitor.Parents;
08223     }
08224 
08225   private:
08226     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
08227 
08228     ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
08229     }
08230 
08231     bool shouldVisitTemplateInstantiations() const {
08232       return true;
08233     }
08234     bool shouldVisitImplicitCode() const {
08235       return true;
08236     }
08237     // Disables data recursion. We intercept Traverse* methods in the RAV, which
08238     // are not triggered during data recursion.
08239     bool shouldUseDataRecursionFor(clang::Stmt *S) const {
08240       return false;
08241     }
08242 
08243     template <typename T>
08244     bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
08245       if (!Node)
08246         return true;
08247       if (ParentStack.size() > 0) {
08248         // FIXME: Currently we add the same parent multiple times, but only
08249         // when no memoization data is available for the type.
08250         // For example when we visit all subexpressions of template
08251         // instantiations; this is suboptimal, but benign: the only way to
08252         // visit those is with hasAncestor / hasParent, and those do not create
08253         // new matches.
08254         // The plan is to enable DynTypedNode to be storable in a map or hash
08255         // map. The main problem there is to implement hash functions /
08256         // comparison operators for all types that DynTypedNode supports that
08257         // do not have pointer identity.
08258         auto &NodeOrVector = (*Parents)[Node];
08259         if (NodeOrVector.isNull()) {
08260           NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
08261         } else {
08262           if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
08263             auto *Node =
08264                 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
08265             auto *Vector = new ASTContext::ParentVector(1, *Node);
08266             NodeOrVector = Vector;
08267             delete Node;
08268           }
08269           assert(NodeOrVector.template is<ASTContext::ParentVector *>());
08270 
08271           auto *Vector =
08272               NodeOrVector.template get<ASTContext::ParentVector *>();
08273           // Skip duplicates for types that have memoization data.
08274           // We must check that the type has memoization data before calling
08275           // std::find() because DynTypedNode::operator== can't compare all
08276           // types.
08277           bool Found = ParentStack.back().getMemoizationData() &&
08278                        std::find(Vector->begin(), Vector->end(),
08279                                  ParentStack.back()) != Vector->end();
08280           if (!Found)
08281             Vector->push_back(ParentStack.back());
08282         }
08283       }
08284       ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
08285       bool Result = (this ->* traverse) (Node);
08286       ParentStack.pop_back();
08287       return Result;
08288     }
08289 
08290     bool TraverseDecl(Decl *DeclNode) {
08291       return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
08292     }
08293 
08294     bool TraverseStmt(Stmt *StmtNode) {
08295       return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
08296     }
08297 
08298     ASTContext::ParentMap *Parents;
08299     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
08300 
08301     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
08302   };
08303 
08304 } // end namespace
08305 
08306 ArrayRef<ast_type_traits::DynTypedNode>
08307 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
08308   assert(Node.getMemoizationData() &&
08309          "Invariant broken: only nodes that support memoization may be "
08310          "used in the parent map.");
08311   if (!AllParents) {
08312     // We always need to run over the whole translation unit, as
08313     // hasAncestor can escape any subtree.
08314     AllParents.reset(
08315         ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
08316   }
08317   ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
08318   if (I == AllParents->end()) {
08319     return None;
08320   }
08321   if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
08322     return llvm::makeArrayRef(N, 1);
08323   }
08324   return *I->second.get<ParentVector *>();
08325 }
08326 
08327 bool
08328 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
08329                                 const ObjCMethodDecl *MethodImpl) {
08330   // No point trying to match an unavailable/deprecated mothod.
08331   if (MethodDecl->hasAttr<UnavailableAttr>()
08332       || MethodDecl->hasAttr<DeprecatedAttr>())
08333     return false;
08334   if (MethodDecl->getObjCDeclQualifier() !=
08335       MethodImpl->getObjCDeclQualifier())
08336     return false;
08337   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
08338     return false;
08339   
08340   if (MethodDecl->param_size() != MethodImpl->param_size())
08341     return false;
08342   
08343   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
08344        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
08345        EF = MethodDecl->param_end();
08346        IM != EM && IF != EF; ++IM, ++IF) {
08347     const ParmVarDecl *DeclVar = (*IF);
08348     const ParmVarDecl *ImplVar = (*IM);
08349     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
08350       return false;
08351     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
08352       return false;
08353   }
08354   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
08355   
08356 }
08357 
08358 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
08359 // doesn't include ASTContext.h
08360 template
08361 clang::LazyGenerationalUpdatePtr<
08362     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
08363 clang::LazyGenerationalUpdatePtr<
08364     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
08365         const clang::ASTContext &Ctx, Decl *Value);