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