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