ASTContext.cpp revision 5e301007e31e14c8ff647288e1b8bd8dbf8a5fe4
1ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
3ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//                     The LLVM Compiler Infrastructure
4ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com//
5ec3ed6a5ebf6f2c406d7bcf94b6bc34fcaeb976eepoger@google.com// This file is distributed under the University of Illinois Open Source
6ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com// License. See LICENSE.TXT for details.
7ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//
8ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//===----------------------------------------------------------------------===//
9ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//
10ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//  This file implements the ASTContext interface.
11ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//
12ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com//===----------------------------------------------------------------------===//
13ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com
14b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/ASTContext.h"
15b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/DeclCXX.h"
16ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com#include "clang/AST/DeclObjC.h"
17b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/DeclTemplate.h"
18b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/Expr.h"
19b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/RecordLayout.h"
20ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com#include "clang/Basic/TargetInfo.h"
21641f8b19a6799b6d73ac17b9c2d2f8a5e6f5ad4drobertphillips@google.com#include "llvm/ADT/StringExtras.h"
22ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com#include "llvm/Bitcode/Serialize.h"
23a0b40280a49a8a43af7929ead3b3489951c58501commit-bot@chromium.org#include "llvm/Bitcode/Deserialize.h"
24ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com#include "llvm/Support/MathExtras.h"
25471d471dcd7422e5dd9c822c1092b2ba4721dcfebsalomon@google.com
261c13c9668a889e56a0c85b51b9f28139c25b76ffbsalomon@google.comusing namespace clang;
27471d471dcd7422e5dd9c822c1092b2ba4721dcfebsalomon@google.com
281c13c9668a889e56a0c85b51b9f28139c25b76ffbsalomon@google.comenum FloatingRank {
291c13c9668a889e56a0c85b51b9f28139c25b76ffbsalomon@google.com  FloatRank, DoubleRank, LongDoubleRank
3055e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com};
3155e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com
3255e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.comASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
3355e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com                       TargetInfo &t,
3455e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com                       IdentifierTable &idents, SelectorTable &sels,
3555e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com                       bool FreeMem, unsigned size_reserve) :
3655e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com  CFConstantStringTypeDecl(0), ObjCFastEnumerationStateTypeDecl(0),
3755e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com  SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
3807d3a6575b86845ded0d4bd785aec8f4c2cc99dcskia.committer@gmail.com  Idents(idents), Selectors(sels)
39ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com{
40ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com  if (size_reserve > 0) Types.reserve(size_reserve);
41ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com  InitBuiltinTypes();
4286afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  BuiltinInfo.InitializeBuiltins(idents, Target, LangOpts.Freestanding);
4386afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  TUDecl = TranslationUnitDecl::Create(*this);
4486afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com}
456e4e65066a7c0dbc9bfbfe4b8f5d49c3d8a79b59bsalomon@google.com
4686afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.comASTContext::~ASTContext() {
4786afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  // Deallocate all the types.
4886afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  while (!Types.empty()) {
4986afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    Types.back()->Destroy(*this);
5086afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    Types.pop_back();
516e4e65066a7c0dbc9bfbfe4b8f5d49c3d8a79b59bsalomon@google.com  }
52471d471dcd7422e5dd9c822c1092b2ba4721dcfebsalomon@google.com
531c13c9668a889e56a0c85b51b9f28139c25b76ffbsalomon@google.com  {
54ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
55ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
56ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    while (I != E) {
5786afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
5855e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com      delete R;
5955e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com    }
6086afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  }
6186afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com
6286afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  {
6386afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    llvm::DenseMap<const ObjCInterfaceDecl*, const ASTRecordLayout*>::iterator
646e4e65066a7c0dbc9bfbfe4b8f5d49c3d8a79b59bsalomon@google.com      I = ASTObjCInterfaces.begin(), E = ASTObjCInterfaces.end();
6555e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com    while (I != E) {
6655e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
6755e4a2005eae1e4f677ec145c577c615a63cf05dbsalomon@google.com      delete R;
6886afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    }
691267fbd95290f58443652ca8d947bde50b212618robertphillips@google.com  }
7097805382d89b717de3355312a79a957ea4a864c9bsalomon@google.com
71a8916ffd90c04dc6cc1fb9ba94af2ff950284fadcommit-bot@chromium.org  {
72a8916ffd90c04dc6cc1fb9ba94af2ff950284fadcommit-bot@chromium.org    llvm::DenseMap<const ObjCInterfaceDecl*, const RecordDecl*>::iterator
73a8916ffd90c04dc6cc1fb9ba94af2ff950284fadcommit-bot@chromium.org      I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end();
7486afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    while (I != E) {
75b75b0a0b8492e14c7728e0a0881f87dc64ce60f9jvanverth@google.com      RecordDecl *R = const_cast<RecordDecl*>((I++)->second);
7697805382d89b717de3355312a79a957ea4a864c9bsalomon@google.com      R->Destroy(*this);
77fd03d4a829efe2d77a712fd991927c55f59a2ffecommit-bot@chromium.org    }
78c82a8b7aa4ec19fba508c394920a9e88d3e5bd12robertphillips@google.com  }
7956ce48ade325f6f49acb0da31d6252806e4ed7efrobertphillips@google.com
8028361fad1054d59ed4e6a320c7a8b8782a1487c7commit-bot@chromium.org  TUDecl->Destroy(*this);
8128361fad1054d59ed4e6a320c7a8b8782a1487c7commit-bot@chromium.org}
8228361fad1054d59ed4e6a320c7a8b8782a1487c7commit-bot@chromium.org
830b335c1ac100aeacf79a4c98a052286fd46661e7bsalomon@google.comvoid ASTContext::PrintStats() const {
84eb85117c05471e1a55ce387cbc38279f857a4584bsalomon@google.com  fprintf(stderr, "*** AST Context Stats:\n");
85eb85117c05471e1a55ce387cbc38279f857a4584bsalomon@google.com  fprintf(stderr, "  %d types total.\n", (int)Types.size());
8697805382d89b717de3355312a79a957ea4a864c9bsalomon@google.com  unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
8702ddc8b85ace91b15feb329a6a1d5d62b2b846c6bsalomon@google.com  unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0;
8802ddc8b85ace91b15feb329a6a1d5d62b2b846c6bsalomon@google.com  unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0, NumReference = 0;
89ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com  unsigned NumMemberPointer = 0;
90a4f6b10818819a16bc94738e2eda42dfec332c43bsalomon@google.com
91ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com  unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
92ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com  unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
93ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com  unsigned NumObjCQualifiedIds = 0;
94ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com  unsigned NumTypeOfTypes = 0, NumTypeOfExprTypes = 0;
95ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com
96116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
9732184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org    Type *T = Types[i];
989b62aa156bcf1db6f11af9302bf8bb8ef2567142commit-bot@chromium.org    if (isa<BuiltinType>(T))
99a4f6b10818819a16bc94738e2eda42dfec332c43bsalomon@google.com      ++NumBuiltin;
100a4f6b10818819a16bc94738e2eda42dfec332c43bsalomon@google.com    else if (isa<PointerType>(T))
101b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumPointer;
102d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com    else if (isa<BlockPointerType>(T))
103b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumBlockPointer;
104b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<ReferenceType>(T))
10545725db1d82615d43408ec488549aec6218f80e4bsalomon      ++NumReference;
10645725db1d82615d43408ec488549aec6218f80e4bsalomon    else if (isa<MemberPointerType>(T))
107b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumMemberPointer;
108b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<ComplexType>(T))
109b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumComplex;
110b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<ArrayType>(T))
111b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumArray;
11245725db1d82615d43408ec488549aec6218f80e4bsalomon    else if (isa<VectorType>(T))
11345725db1d82615d43408ec488549aec6218f80e4bsalomon      ++NumVector;
114ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    else if (isa<FunctionNoProtoType>(T))
115ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com      ++NumFunctionNP;
116a0b40280a49a8a43af7929ead3b3489951c58501commit-bot@chromium.org    else if (isa<FunctionProtoType>(T))
11745725db1d82615d43408ec488549aec6218f80e4bsalomon      ++NumFunctionP;
118b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<TypedefType>(T))
119b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumTypeName;
1205f74cf8c49701f514b69dc6f1a8b5c0ffd78af0asugoi@google.com    else if (TagType *TT = dyn_cast<TagType>(T)) {
121b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumTagged;
122b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      switch (TT->getDecl()->getTagKind()) {
123b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      default: assert(0 && "Unknown tagged type!");
12445725db1d82615d43408ec488549aec6218f80e4bsalomon      case TagDecl::TK_struct: ++NumTagStruct; break;
125ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com      case TagDecl::TK_union:  ++NumTagUnion; break;
126ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com      case TagDecl::TK_class:  ++NumTagClass; break;
12732184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org      case TagDecl::TK_enum:   ++NumTagEnum; break;
12845725db1d82615d43408ec488549aec6218f80e4bsalomon      }
129b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    } else if (isa<ObjCInterfaceType>(T))
130b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumObjCInterfaces;
131c4dc0ad8e252a7e30d19b47d3d0d9f2c69faf854commit-bot@chromium.org    else if (isa<ObjCQualifiedInterfaceType>(T))
132b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumObjCQualifiedInterfaces;
133b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<ObjCQualifiedIdType>(T))
134b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      ++NumObjCQualifiedIds;
135b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    else if (isa<TypeOfType>(T))
13645725db1d82615d43408ec488549aec6218f80e4bsalomon      ++NumTypeOfTypes;
137c4dc0ad8e252a7e30d19b47d3d0d9f2c69faf854commit-bot@chromium.org    else if (isa<TypeOfExprType>(T))
138c4dc0ad8e252a7e30d19b47d3d0d9f2c69faf854commit-bot@chromium.org      ++NumTypeOfExprTypes;
1399b62aa156bcf1db6f11af9302bf8bb8ef2567142commit-bot@chromium.org    else {
140b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      QualType(T, 0).dump();
14145725db1d82615d43408ec488549aec6218f80e4bsalomon      assert(0 && "Unknown type!");
142b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    }
143b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  }
144b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
145b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d builtin types\n", NumBuiltin);
146b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d pointer types\n", NumPointer);
147b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d block pointer types\n", NumBlockPointer);
148b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d reference types\n", NumReference);
149b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d member pointer types\n", NumMemberPointer);
150b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d complex types\n", NumComplex);
151b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d array types\n", NumArray);
152b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d vector types\n", NumVector);
153b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d function types with proto\n", NumFunctionP);
154b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d function types with no proto\n", NumFunctionNP);
155b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d typename (typedef) types\n", NumTypeName);
156b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d tagged types\n", NumTagged);
157b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "      %d struct types\n", NumTagStruct);
158b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "      %d union types\n", NumTagUnion);
159b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "      %d class types\n", NumTagClass);
160b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "      %d enum types\n", NumTagEnum);
161b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "    %d interface types\n", NumObjCInterfaces);
16245725db1d82615d43408ec488549aec6218f80e4bsalomon  fprintf(stderr, "    %d protocol qualified interface types\n",
1639b62aa156bcf1db6f11af9302bf8bb8ef2567142commit-bot@chromium.org          NumObjCQualifiedInterfaces);
1649b62aa156bcf1db6f11af9302bf8bb8ef2567142commit-bot@chromium.org  fprintf(stderr, "    %d protocol qualified id types\n",
16528361fad1054d59ed4e6a320c7a8b8782a1487c7commit-bot@chromium.org          NumObjCQualifiedIds);
166a0b40280a49a8a43af7929ead3b3489951c58501commit-bot@chromium.org  fprintf(stderr, "    %d typeof types\n", NumTypeOfTypes);
16745725db1d82615d43408ec488549aec6218f80e4bsalomon  fprintf(stderr, "    %d typeof exprs\n", NumTypeOfExprTypes);
168b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
169b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
170b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
171b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
172b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    NumMemberPointer*sizeof(MemberPointerType)+
173b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    NumFunctionP*sizeof(FunctionProtoType)+
174c82a8b7aa4ec19fba508c394920a9e88d3e5bd12robertphillips@google.com    NumFunctionNP*sizeof(FunctionNoProtoType)+
175b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
17645725db1d82615d43408ec488549aec6218f80e4bsalomon    NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprTypes*sizeof(TypeOfExprType)));
1770b335c1ac100aeacf79a4c98a052286fd46661e7bsalomon@google.com}
1780b335c1ac100aeacf79a4c98a052286fd46661e7bsalomon@google.com
179a0b40280a49a8a43af7929ead3b3489951c58501commit-bot@chromium.org
18045725db1d82615d43408ec488549aec6218f80e4bsalomonvoid ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
181b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
182b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon}
183b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
184b3e3a955b6628acc540ef14854b57abb089e62dfbsalomonvoid ASTContext::InitBuiltinTypes() {
185b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  assert(VoidTy.isNull() && "Context reinitialized?");
186b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
187b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  // C99 6.2.5p19.
188b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  InitBuiltinType(VoidTy,              BuiltinType::Void);
18945725db1d82615d43408ec488549aec6218f80e4bsalomon
19045725db1d82615d43408ec488549aec6218f80e4bsalomon  // C99 6.2.5p2.
191116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  InitBuiltinType(BoolTy,              BuiltinType::Bool);
192116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  // C99 6.2.5p3.
193f0480b1e697dcaee8b4004ca5b494917c939cde7bsalomon  if (Target.isCharSigned())
194f0480b1e697dcaee8b4004ca5b494917c939cde7bsalomon    InitBuiltinType(CharTy,            BuiltinType::Char_S);
195f0480b1e697dcaee8b4004ca5b494917c939cde7bsalomon  else
196f0480b1e697dcaee8b4004ca5b494917c939cde7bsalomon    InitBuiltinType(CharTy,            BuiltinType::Char_U);
197f0480b1e697dcaee8b4004ca5b494917c939cde7bsalomon  // C99 6.2.5p4.
19825fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
19974749cd45c29b4f5300e2518f2c2c765ce8ae208bsalomon@google.com  InitBuiltinType(ShortTy,             BuiltinType::Short);
200fd03d4a829efe2d77a712fd991927c55f59a2ffecommit-bot@chromium.org  InitBuiltinType(IntTy,               BuiltinType::Int);
201fd03d4a829efe2d77a712fd991927c55f59a2ffecommit-bot@chromium.org  InitBuiltinType(LongTy,              BuiltinType::Long);
2020406b9e1faee06c6ecb2732a1bcf3b0e53104e07bsalomon@google.com  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
20332184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org
20432184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org  // C99 6.2.5p6.
20532184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
206c4dc0ad8e252a7e30d19b47d3d0d9f2c69faf854commit-bot@chromium.org  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
207b85a0aab6905af8b329539b7573a7555b727d5e5cdalton  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
208b85a0aab6905af8b329539b7573a7555b727d5e5cdalton  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
209b85a0aab6905af8b329539b7573a7555b727d5e5cdalton  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
210b85a0aab6905af8b329539b7573a7555b727d5e5cdalton
21132184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org  // C99 6.2.5p10.
212a63389843dd18003382d61c2e4610af09ed07d38jvanverth@google.com  InitBuiltinType(FloatTy,             BuiltinType::Float);
21325fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com  InitBuiltinType(DoubleTy,            BuiltinType::Double);
21413f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
21513f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com
21613f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
21713f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com    InitBuiltinType(WCharTy,           BuiltinType::WChar);
21813f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  else // C99
219bcdbbe61e1a3f89545b2c1461164f0f8bf5f0797bsalomon@google.com    WCharTy = getFromTargetType(Target.getWCharType());
22013f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com
221bcdbbe61e1a3f89545b2c1461164f0f8bf5f0797bsalomon@google.com  // Placeholder type for functions.
22213f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
22313f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com
22413f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  // Placeholder type for type-dependent expressions whose type is
22513f1b6f1569bb5c639ca762f6b153133173c6295bsalomon@google.com  // completely unknown. No code should ever check a type against
22602ddc8b85ace91b15feb329a6a1d5d62b2b846c6bsalomon@google.com  // DependentTy and users should never see it; however, it is here to
227b75b0a0b8492e14c7728e0a0881f87dc64ce60f9jvanverth@google.com  // help diagnose failures to properly check for type-dependent
22802ddc8b85ace91b15feb329a6a1d5d62b2b846c6bsalomon@google.com  // expressions.
229116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
230116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com
231116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  // C99 6.2.5p11.
232116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  FloatComplexTy      = getComplexType(FloatTy);
233116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  DoubleComplexTy     = getComplexType(DoubleTy);
234116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  LongDoubleComplexTy = getComplexType(LongDoubleTy);
235116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com
236116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  BuiltinVaListType = QualType();
237116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com  ObjCIdType = QualType();
238d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  IdStructType = 0;
23902ddc8b85ace91b15feb329a6a1d5d62b2b846c6bsalomon@google.com  ObjCClassType = QualType();
2402a05de0c049a8648942a55016126a1f92e1c14d6commit-bot@chromium.org  ClassStructType = 0;
2412a05de0c049a8648942a55016126a1f92e1c14d6commit-bot@chromium.org
242a3baf3be0e2a3128fb73bd41d40d130f75a4dc86commit-bot@chromium.org  ObjCConstantStringType = QualType();
243d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com
244d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  // void * type
245d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  VoidPtrTy = getPointerType(VoidTy);
2461c13c9668a889e56a0c85b51b9f28139c25b76ffbsalomon@google.com}
247838f62db0a77487f6732ed13a0972a1e646ae16absalomon
248838f62db0a77487f6732ed13a0972a1e646ae16absalomon//===----------------------------------------------------------------------===//
249838f62db0a77487f6732ed13a0972a1e646ae16absalomon//                         Type Sizing and Analysis
25086afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com//===----------------------------------------------------------------------===//
251ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com
252a4f6b10818819a16bc94738e2eda42dfec332c43bsalomon@google.com/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
253ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com/// scalar floating point type.
254ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.comconst llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
255b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  const BuiltinType *BT = T->getAsBuiltinType();
256b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  assert(BT && "Not a floating point type!");
257b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  switch (BT->getKind()) {
258b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  default: assert(0 && "Not a floating point type!");
259b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  case BuiltinType::Float:      return Target.getFloatFormat();
260b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  case BuiltinType::Double:     return Target.getDoubleFormat();
261b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
262b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  }
263b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon}
264934c570297c1b1f99cb4ca8d012d468a7eddf73fbsalomon@google.com
265116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com/// getDeclAlign - Return a conservative estimate of the alignment of the
2664b90c62dfcda5866808ceedee46358b3d9792c93bsalomon@google.com/// specified decl.  Note that bitfields do not have a valid alignment, so
267a4f6b10818819a16bc94738e2eda42dfec332c43bsalomon@google.com/// this method will assert on them.
268bce3d6dbb91c3e67f1010556c2b8aaf6d7a49267bsalomonunsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
269ded4f4b163f5aa19c22c871178c55ecb34623846bsalomon@google.com  unsigned Align = Target.getCharWidth();
27032184d81629e39809bb9e915286d8fe971a8ed68commit-bot@chromium.org
2719b62aa156bcf1db6f11af9302bf8bb8ef2567142commit-bot@chromium.org  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
2724b90c62dfcda5866808ceedee46358b3d9792c93bsalomon@google.com    Align = std::max(Align, AA->getAlignment());
2734b90c62dfcda5866808ceedee46358b3d9792c93bsalomon@google.com
274bce3d6dbb91c3e67f1010556c2b8aaf6d7a49267bsalomon  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
2754b90c62dfcda5866808ceedee46358b3d9792c93bsalomon@google.com    QualType T = VD->getType();
276116ad84d3126b0db22b2312ca59ed70e5c56f6fcbsalomon@google.com    // Incomplete or function types default to 1.
2774b90c62dfcda5866808ceedee46358b3d9792c93bsalomon@google.com    if (!T->isIncompleteType() && !T->isFunctionType()) {
278ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
279b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon        T = cast<ArrayType>(T)->getElementType();
280b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
281b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
282b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    }
283b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  }
284b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
285b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  return Align / Target.getCharWidth();
286b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon}
287b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon
288b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon/// getTypeSize - Return the size of the specified type, in bits.  This method
289b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon/// does not work on incomplete types.
290b3e3a955b6628acc540ef14854b57abb089e62dfbsalomonstd::pair<uint64_t, unsigned>
291b3e3a955b6628acc540ef14854b57abb089e62dfbsalomonASTContext::getTypeInfo(const Type *T) {
292b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  T = getCanonicalType(T);
293b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  uint64_t Width=0;
294b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  unsigned Align=8;
295b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  switch (T->getTypeClass()) {
296b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#define TYPE(Class, Base)
297b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#define ABSTRACT_TYPE(Class, Base)
298b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
299b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#define DEPENDENT_TYPE(Class, Base) case Type::Class:
300b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon#include "clang/AST/TypeNodes.def"
30186afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com    assert(false && "Should not see non-canonical or dependent types");
302d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com    break;
303d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com
304d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  case Type::FunctionNoProto:
305d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  case Type::FunctionProto:
306d62e88e5af39347a8fc2a5abdf5feb67d7ea256dbsalomon@google.com  case Type::IncompleteArray:
307934c570297c1b1f99cb4ca8d012d468a7eddf73fbsalomon@google.com    assert(0 && "Incomplete types have no size!");
308b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  case Type::VariableArray:
309b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    assert(0 && "VLAs not implemented yet!");
310b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  case Type::ConstantArray: {
311b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
312934c570297c1b1f99cb4ca8d012d468a7eddf73fbsalomon@google.com
31325fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
314b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    Width = EltInfo.first*CAT->getSize().getZExtValue();
315b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    Align = EltInfo.second;
316b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    break;
317b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  }
31825fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com  case Type::ExtVector:
31925fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com  case Type::Vector: {
32025fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com    std::pair<uint64_t, unsigned> EltInfo =
321b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon      getTypeInfo(cast<VectorType>(T)->getElementType());
322b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
32325fb21f5df904c6f111bbf8f07e6a6c339416d09bsalomon@google.com    Align = Width;
324a55847ba22ae4a673af022e7d88404e080195464bsalomon@google.com    // If the alignment is not a power of 2, round up to the next power of 2.
325b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    // This happens for non-power-of-2 length vectors.
3262a05de0c049a8648942a55016126a1f92e1c14d6commit-bot@chromium.org    // FIXME: this should probably be a target property.
327b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    Align = 1 << llvm::Log2_32_Ceil(Align);
328b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon    break;
329b3e3a955b6628acc540ef14854b57abb089e62dfbsalomon  }
330c82a8b7aa4ec19fba508c394920a9e88d3e5bd12robertphillips@google.com
33186afc2ae27fec84c01eb0e81a32766bdaf67dca8bsalomon@google.com  case Type::Builtin:
332ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    switch (cast<BuiltinType>(T)->getKind()) {
333ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    default: assert(0 && "Unknown builtin type!");
334ac10a2d039c5d52eed66e27cbbc503ab523c1cd5reed@google.com    case BuiltinType::Void:
335      assert(0 && "Incomplete types have no size!");
336    case BuiltinType::Bool:
337      Width = Target.getBoolWidth();
338      Align = Target.getBoolAlign();
339      break;
340    case BuiltinType::Char_S:
341    case BuiltinType::Char_U:
342    case BuiltinType::UChar:
343    case BuiltinType::SChar:
344      Width = Target.getCharWidth();
345      Align = Target.getCharAlign();
346      break;
347    case BuiltinType::WChar:
348      Width = Target.getWCharWidth();
349      Align = Target.getWCharAlign();
350      break;
351    case BuiltinType::UShort:
352    case BuiltinType::Short:
353      Width = Target.getShortWidth();
354      Align = Target.getShortAlign();
355      break;
356    case BuiltinType::UInt:
357    case BuiltinType::Int:
358      Width = Target.getIntWidth();
359      Align = Target.getIntAlign();
360      break;
361    case BuiltinType::ULong:
362    case BuiltinType::Long:
363      Width = Target.getLongWidth();
364      Align = Target.getLongAlign();
365      break;
366    case BuiltinType::ULongLong:
367    case BuiltinType::LongLong:
368      Width = Target.getLongLongWidth();
369      Align = Target.getLongLongAlign();
370      break;
371    case BuiltinType::Float:
372      Width = Target.getFloatWidth();
373      Align = Target.getFloatAlign();
374      break;
375    case BuiltinType::Double:
376      Width = Target.getDoubleWidth();
377      Align = Target.getDoubleAlign();
378      break;
379    case BuiltinType::LongDouble:
380      Width = Target.getLongDoubleWidth();
381      Align = Target.getLongDoubleAlign();
382      break;
383    }
384    break;
385  case Type::FixedWidthInt:
386    // FIXME: This isn't precisely correct; the width/alignment should depend
387    // on the available types for the target
388    Width = cast<FixedWidthIntType>(T)->getWidth();
389    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
390    Align = Width;
391    break;
392  case Type::ExtQual:
393    // FIXME: Pointers into different addr spaces could have different sizes and
394    // alignment requirements: getPointerInfo should take an AddrSpace.
395    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
396  case Type::ObjCQualifiedId:
397  case Type::ObjCQualifiedClass:
398  case Type::ObjCQualifiedInterface:
399    Width = Target.getPointerWidth(0);
400    Align = Target.getPointerAlign(0);
401    break;
402  case Type::BlockPointer: {
403    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
404    Width = Target.getPointerWidth(AS);
405    Align = Target.getPointerAlign(AS);
406    break;
407  }
408  case Type::Pointer: {
409    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
410    Width = Target.getPointerWidth(AS);
411    Align = Target.getPointerAlign(AS);
412    break;
413  }
414  case Type::Reference:
415    // "When applied to a reference or a reference type, the result is the size
416    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
417    // FIXME: This is wrong for struct layout: a reference in a struct has
418    // pointer size.
419    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
420  case Type::MemberPointer: {
421    // FIXME: This is not only platform- but also ABI-dependent. We follow
422    // the GCC ABI, where pointers to data are one pointer large, pointers to
423    // functions two pointers. But if we want to support ABI compatibility with
424    // other compilers too, we need to delegate this completely to TargetInfo
425    // or some ABI abstraction layer.
426    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
427    unsigned AS = Pointee.getAddressSpace();
428    Width = Target.getPointerWidth(AS);
429    if (Pointee->isFunctionType())
430      Width *= 2;
431    Align = Target.getPointerAlign(AS);
432    // GCC aligns at single pointer width.
433  }
434  case Type::Complex: {
435    // Complex types have the same alignment as their elements, but twice the
436    // size.
437    std::pair<uint64_t, unsigned> EltInfo =
438      getTypeInfo(cast<ComplexType>(T)->getElementType());
439    Width = EltInfo.first*2;
440    Align = EltInfo.second;
441    break;
442  }
443  case Type::ObjCInterface: {
444    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
445    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
446    Width = Layout.getSize();
447    Align = Layout.getAlignment();
448    break;
449  }
450  case Type::Record:
451  case Type::CXXRecord:
452  case Type::Enum: {
453    const TagType *TT = cast<TagType>(T);
454
455    if (TT->getDecl()->isInvalidDecl()) {
456      Width = 1;
457      Align = 1;
458      break;
459    }
460
461    if (const EnumType *ET = dyn_cast<EnumType>(TT))
462      return getTypeInfo(ET->getDecl()->getIntegerType());
463
464    const RecordType *RT = cast<RecordType>(TT);
465    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
466    Width = Layout.getSize();
467    Align = Layout.getAlignment();
468    break;
469  }
470  }
471
472  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
473  return std::make_pair(Width, Align);
474}
475
476/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
477/// type for the current target in bits.  This can be different than the ABI
478/// alignment in cases where it is beneficial for performance to overalign
479/// a data type.
480unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
481  unsigned ABIAlign = getTypeAlign(T);
482
483  // Doubles should be naturally aligned if possible.
484  if (T->isSpecificBuiltinType(BuiltinType::Double))
485    return std::max(ABIAlign, 64U);
486
487  return ABIAlign;
488}
489
490
491/// LayoutField - Field layout.
492void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
493                                  bool IsUnion, unsigned StructPacking,
494                                  ASTContext &Context) {
495  unsigned FieldPacking = StructPacking;
496  uint64_t FieldOffset = IsUnion ? 0 : Size;
497  uint64_t FieldSize;
498  unsigned FieldAlign;
499
500  // FIXME: Should this override struct packing? Probably we want to
501  // take the minimum?
502  if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
503    FieldPacking = PA->getAlignment();
504
505  if (const Expr *BitWidthExpr = FD->getBitWidth()) {
506    // TODO: Need to check this algorithm on other targets!
507    //       (tested on Linux-X86)
508    FieldSize =
509      BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
510
511    std::pair<uint64_t, unsigned> FieldInfo =
512      Context.getTypeInfo(FD->getType());
513    uint64_t TypeSize = FieldInfo.first;
514
515    // Determine the alignment of this bitfield. The packing
516    // attributes define a maximum and the alignment attribute defines
517    // a minimum.
518    // FIXME: What is the right behavior when the specified alignment
519    // is smaller than the specified packing?
520    FieldAlign = FieldInfo.second;
521    if (FieldPacking)
522      FieldAlign = std::min(FieldAlign, FieldPacking);
523    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
524      FieldAlign = std::max(FieldAlign, AA->getAlignment());
525
526    // Check if we need to add padding to give the field the correct
527    // alignment.
528    if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
529      FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
530
531    // Padding members don't affect overall alignment
532    if (!FD->getIdentifier())
533      FieldAlign = 1;
534  } else {
535    if (FD->getType()->isIncompleteArrayType()) {
536      // This is a flexible array member; we can't directly
537      // query getTypeInfo about these, so we figure it out here.
538      // Flexible array members don't have any size, but they
539      // have to be aligned appropriately for their element type.
540      FieldSize = 0;
541      const ArrayType* ATy = Context.getAsArrayType(FD->getType());
542      FieldAlign = Context.getTypeAlign(ATy->getElementType());
543    } else {
544      std::pair<uint64_t, unsigned> FieldInfo =
545        Context.getTypeInfo(FD->getType());
546      FieldSize = FieldInfo.first;
547      FieldAlign = FieldInfo.second;
548    }
549
550    // Determine the alignment of this bitfield. The packing
551    // attributes define a maximum and the alignment attribute defines
552    // a minimum. Additionally, the packing alignment must be at least
553    // a byte for non-bitfields.
554    //
555    // FIXME: What is the right behavior when the specified alignment
556    // is smaller than the specified packing?
557    if (FieldPacking)
558      FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
559    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
560      FieldAlign = std::max(FieldAlign, AA->getAlignment());
561
562    // Round up the current record size to the field's alignment boundary.
563    FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
564  }
565
566  // Place this field at the current location.
567  FieldOffsets[FieldNo] = FieldOffset;
568
569  // Reserve space for this field.
570  if (IsUnion) {
571    Size = std::max(Size, FieldSize);
572  } else {
573    Size = FieldOffset + FieldSize;
574  }
575
576  // Remember max struct/class alignment.
577  Alignment = std::max(Alignment, FieldAlign);
578}
579
580static void CollectObjCIvars(const ObjCInterfaceDecl *OI,
581                             std::vector<FieldDecl*> &Fields) {
582  const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
583  if (SuperClass)
584    CollectObjCIvars(SuperClass, Fields);
585  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
586       E = OI->ivar_end(); I != E; ++I) {
587    ObjCIvarDecl *IVDecl = (*I);
588    if (!IVDecl->isInvalidDecl())
589      Fields.push_back(cast<FieldDecl>(IVDecl));
590  }
591}
592
593/// addRecordToClass - produces record info. for the class for its
594/// ivars and all those inherited.
595///
596const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D)
597{
598  const RecordDecl *&RD = ASTRecordForInterface[D];
599  if (RD)
600    return RD;
601  std::vector<FieldDecl*> RecFields;
602  CollectObjCIvars(D, RecFields);
603  RecordDecl *NewRD = RecordDecl::Create(*this, TagDecl::TK_struct, 0,
604                                         D->getLocation(),
605                                         D->getIdentifier());
606  /// FIXME! Can do collection of ivars and adding to the record while
607  /// doing it.
608  for (unsigned int i = 0; i != RecFields.size(); i++) {
609    FieldDecl *Field =  FieldDecl::Create(*this, NewRD,
610                                          RecFields[i]->getLocation(),
611                                          RecFields[i]->getIdentifier(),
612                                          RecFields[i]->getType(),
613                                          RecFields[i]->getBitWidth(), false);
614    NewRD->addDecl(Field);
615  }
616  NewRD->completeDefinition(*this);
617  RD = NewRD;
618  return RD;
619}
620
621/// setFieldDecl - maps a field for the given Ivar reference node.
622//
623void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI,
624                              const ObjCIvarDecl *Ivar,
625                              const ObjCIvarRefExpr *MRef) {
626  FieldDecl *FD = (const_cast<ObjCInterfaceDecl *>(OI))->
627                    lookupFieldDeclForIvar(*this, Ivar);
628  ASTFieldForIvarRef[MRef] = FD;
629}
630
631/// getASTObjcInterfaceLayout - Get or compute information about the layout of
632/// the specified Objective C, which indicates its size and ivar
633/// position information.
634const ASTRecordLayout &
635ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
636  // Look up this layout, if already laid out, return what we have.
637  const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
638  if (Entry) return *Entry;
639
640  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
641  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
642  ASTRecordLayout *NewEntry = NULL;
643  unsigned FieldCount = D->ivar_size();
644  if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
645    FieldCount++;
646    const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
647    unsigned Alignment = SL.getAlignment();
648    uint64_t Size = SL.getSize();
649    NewEntry = new ASTRecordLayout(Size, Alignment);
650    NewEntry->InitializeLayout(FieldCount);
651    // Super class is at the beginning of the layout.
652    NewEntry->SetFieldOffset(0, 0);
653  } else {
654    NewEntry = new ASTRecordLayout();
655    NewEntry->InitializeLayout(FieldCount);
656  }
657  Entry = NewEntry;
658
659  unsigned StructPacking = 0;
660  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
661    StructPacking = PA->getAlignment();
662
663  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
664    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
665                                    AA->getAlignment()));
666
667  // Layout each ivar sequentially.
668  unsigned i = 0;
669  for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
670       IVE = D->ivar_end(); IVI != IVE; ++IVI) {
671    const ObjCIvarDecl* Ivar = (*IVI);
672    NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
673  }
674
675  // Finally, round the size of the total struct up to the alignment of the
676  // struct itself.
677  NewEntry->FinalizeLayout();
678  return *NewEntry;
679}
680
681/// getASTRecordLayout - Get or compute information about the layout of the
682/// specified record (struct/union/class), which indicates its size and field
683/// position information.
684const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
685  D = D->getDefinition(*this);
686  assert(D && "Cannot get layout of forward declarations!");
687
688  // Look up this layout, if already laid out, return what we have.
689  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
690  if (Entry) return *Entry;
691
692  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
693  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
694  ASTRecordLayout *NewEntry = new ASTRecordLayout();
695  Entry = NewEntry;
696
697  // FIXME: Avoid linear walk through the fields, if possible.
698  NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
699  bool IsUnion = D->isUnion();
700
701  unsigned StructPacking = 0;
702  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
703    StructPacking = PA->getAlignment();
704
705  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
706    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
707                                    AA->getAlignment()));
708
709  // Layout each field, for now, just sequentially, respecting alignment.  In
710  // the future, this will need to be tweakable by targets.
711  unsigned FieldIdx = 0;
712  for (RecordDecl::field_iterator Field = D->field_begin(),
713                               FieldEnd = D->field_end();
714       Field != FieldEnd; (void)++Field, ++FieldIdx)
715    NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
716
717  // Finally, round the size of the total struct up to the alignment of the
718  // struct itself.
719  NewEntry->FinalizeLayout();
720  return *NewEntry;
721}
722
723//===----------------------------------------------------------------------===//
724//                   Type creation/memoization methods
725//===----------------------------------------------------------------------===//
726
727QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
728  QualType CanT = getCanonicalType(T);
729  if (CanT.getAddressSpace() == AddressSpace)
730    return T;
731
732  // If we are composing extended qualifiers together, merge together into one
733  // ExtQualType node.
734  unsigned CVRQuals = T.getCVRQualifiers();
735  QualType::GCAttrTypes GCAttr = QualType::GCNone;
736  Type *TypeNode = T.getTypePtr();
737
738  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
739    // If this type already has an address space specified, it cannot get
740    // another one.
741    assert(EQT->getAddressSpace() == 0 &&
742           "Type cannot be in multiple addr spaces!");
743    GCAttr = EQT->getObjCGCAttr();
744    TypeNode = EQT->getBaseType();
745  }
746
747  // Check if we've already instantiated this type.
748  llvm::FoldingSetNodeID ID;
749  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
750  void *InsertPos = 0;
751  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
752    return QualType(EXTQy, CVRQuals);
753
754  // If the base type isn't canonical, this won't be a canonical type either,
755  // so fill in the canonical type field.
756  QualType Canonical;
757  if (!TypeNode->isCanonical()) {
758    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
759
760    // Update InsertPos, the previous call could have invalidated it.
761    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
762    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
763  }
764  ExtQualType *New =
765    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
766  ExtQualTypes.InsertNode(New, InsertPos);
767  Types.push_back(New);
768  return QualType(New, CVRQuals);
769}
770
771QualType ASTContext::getObjCGCQualType(QualType T,
772                                       QualType::GCAttrTypes GCAttr) {
773  QualType CanT = getCanonicalType(T);
774  if (CanT.getObjCGCAttr() == GCAttr)
775    return T;
776
777  // If we are composing extended qualifiers together, merge together into one
778  // ExtQualType node.
779  unsigned CVRQuals = T.getCVRQualifiers();
780  Type *TypeNode = T.getTypePtr();
781  unsigned AddressSpace = 0;
782
783  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
784    // If this type already has an address space specified, it cannot get
785    // another one.
786    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
787           "Type cannot be in multiple addr spaces!");
788    AddressSpace = EQT->getAddressSpace();
789    TypeNode = EQT->getBaseType();
790  }
791
792  // Check if we've already instantiated an gc qual'd type of this type.
793  llvm::FoldingSetNodeID ID;
794  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
795  void *InsertPos = 0;
796  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
797    return QualType(EXTQy, CVRQuals);
798
799  // If the base type isn't canonical, this won't be a canonical type either,
800  // so fill in the canonical type field.
801  QualType Canonical;
802  if (!T->isCanonical()) {
803    Canonical = getObjCGCQualType(CanT, GCAttr);
804
805    // Update InsertPos, the previous call could have invalidated it.
806    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
807    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
808  }
809  ExtQualType *New =
810    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
811  ExtQualTypes.InsertNode(New, InsertPos);
812  Types.push_back(New);
813  return QualType(New, CVRQuals);
814}
815
816/// getComplexType - Return the uniqued reference to the type for a complex
817/// number with the specified element type.
818QualType ASTContext::getComplexType(QualType T) {
819  // Unique pointers, to guarantee there is only one pointer of a particular
820  // structure.
821  llvm::FoldingSetNodeID ID;
822  ComplexType::Profile(ID, T);
823
824  void *InsertPos = 0;
825  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
826    return QualType(CT, 0);
827
828  // If the pointee type isn't canonical, this won't be a canonical type either,
829  // so fill in the canonical type field.
830  QualType Canonical;
831  if (!T->isCanonical()) {
832    Canonical = getComplexType(getCanonicalType(T));
833
834    // Get the new insert position for the node we care about.
835    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
836    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
837  }
838  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
839  Types.push_back(New);
840  ComplexTypes.InsertNode(New, InsertPos);
841  return QualType(New, 0);
842}
843
844QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
845  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
846     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
847  FixedWidthIntType *&Entry = Map[Width];
848  if (!Entry)
849    Entry = new FixedWidthIntType(Width, Signed);
850  return QualType(Entry, 0);
851}
852
853/// getPointerType - Return the uniqued reference to the type for a pointer to
854/// the specified type.
855QualType ASTContext::getPointerType(QualType T) {
856  // Unique pointers, to guarantee there is only one pointer of a particular
857  // structure.
858  llvm::FoldingSetNodeID ID;
859  PointerType::Profile(ID, T);
860
861  void *InsertPos = 0;
862  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
863    return QualType(PT, 0);
864
865  // If the pointee type isn't canonical, this won't be a canonical type either,
866  // so fill in the canonical type field.
867  QualType Canonical;
868  if (!T->isCanonical()) {
869    Canonical = getPointerType(getCanonicalType(T));
870
871    // Get the new insert position for the node we care about.
872    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
873    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
874  }
875  PointerType *New = new (*this,8) PointerType(T, Canonical);
876  Types.push_back(New);
877  PointerTypes.InsertNode(New, InsertPos);
878  return QualType(New, 0);
879}
880
881/// getBlockPointerType - Return the uniqued reference to the type for
882/// a pointer to the specified block.
883QualType ASTContext::getBlockPointerType(QualType T) {
884  assert(T->isFunctionType() && "block of function types only");
885  // Unique pointers, to guarantee there is only one block of a particular
886  // structure.
887  llvm::FoldingSetNodeID ID;
888  BlockPointerType::Profile(ID, T);
889
890  void *InsertPos = 0;
891  if (BlockPointerType *PT =
892        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
893    return QualType(PT, 0);
894
895  // If the block pointee type isn't canonical, this won't be a canonical
896  // type either so fill in the canonical type field.
897  QualType Canonical;
898  if (!T->isCanonical()) {
899    Canonical = getBlockPointerType(getCanonicalType(T));
900
901    // Get the new insert position for the node we care about.
902    BlockPointerType *NewIP =
903      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
904    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
905  }
906  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
907  Types.push_back(New);
908  BlockPointerTypes.InsertNode(New, InsertPos);
909  return QualType(New, 0);
910}
911
912/// getReferenceType - Return the uniqued reference to the type for a reference
913/// to the specified type.
914QualType ASTContext::getReferenceType(QualType T) {
915  // Unique pointers, to guarantee there is only one pointer of a particular
916  // structure.
917  llvm::FoldingSetNodeID ID;
918  ReferenceType::Profile(ID, T);
919
920  void *InsertPos = 0;
921  if (ReferenceType *RT = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
922    return QualType(RT, 0);
923
924  // If the referencee type isn't canonical, this won't be a canonical type
925  // either, so fill in the canonical type field.
926  QualType Canonical;
927  if (!T->isCanonical()) {
928    Canonical = getReferenceType(getCanonicalType(T));
929
930    // Get the new insert position for the node we care about.
931    ReferenceType *NewIP = ReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
932    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
933  }
934
935  ReferenceType *New = new (*this,8) ReferenceType(T, Canonical);
936  Types.push_back(New);
937  ReferenceTypes.InsertNode(New, InsertPos);
938  return QualType(New, 0);
939}
940
941/// getMemberPointerType - Return the uniqued reference to the type for a
942/// member pointer to the specified type, in the specified class.
943QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
944{
945  // Unique pointers, to guarantee there is only one pointer of a particular
946  // structure.
947  llvm::FoldingSetNodeID ID;
948  MemberPointerType::Profile(ID, T, Cls);
949
950  void *InsertPos = 0;
951  if (MemberPointerType *PT =
952      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
953    return QualType(PT, 0);
954
955  // If the pointee or class type isn't canonical, this won't be a canonical
956  // type either, so fill in the canonical type field.
957  QualType Canonical;
958  if (!T->isCanonical()) {
959    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
960
961    // Get the new insert position for the node we care about.
962    MemberPointerType *NewIP =
963      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
964    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
965  }
966  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
967  Types.push_back(New);
968  MemberPointerTypes.InsertNode(New, InsertPos);
969  return QualType(New, 0);
970}
971
972/// getConstantArrayType - Return the unique reference to the type for an
973/// array of the specified element type.
974QualType ASTContext::getConstantArrayType(QualType EltTy,
975                                          const llvm::APInt &ArySize,
976                                          ArrayType::ArraySizeModifier ASM,
977                                          unsigned EltTypeQuals) {
978  llvm::FoldingSetNodeID ID;
979  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
980
981  void *InsertPos = 0;
982  if (ConstantArrayType *ATP =
983      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
984    return QualType(ATP, 0);
985
986  // If the element type isn't canonical, this won't be a canonical type either,
987  // so fill in the canonical type field.
988  QualType Canonical;
989  if (!EltTy->isCanonical()) {
990    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
991                                     ASM, EltTypeQuals);
992    // Get the new insert position for the node we care about.
993    ConstantArrayType *NewIP =
994      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
995    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
996  }
997
998  ConstantArrayType *New =
999    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1000  ConstantArrayTypes.InsertNode(New, InsertPos);
1001  Types.push_back(New);
1002  return QualType(New, 0);
1003}
1004
1005/// getVariableArrayType - Returns a non-unique reference to the type for a
1006/// variable array of the specified element type.
1007QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1008                                          ArrayType::ArraySizeModifier ASM,
1009                                          unsigned EltTypeQuals) {
1010  // Since we don't unique expressions, it isn't possible to unique VLA's
1011  // that have an expression provided for their size.
1012
1013  VariableArrayType *New =
1014    new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
1015
1016  VariableArrayTypes.push_back(New);
1017  Types.push_back(New);
1018  return QualType(New, 0);
1019}
1020
1021/// getDependentSizedArrayType - Returns a non-unique reference to
1022/// the type for a dependently-sized array of the specified element
1023/// type. FIXME: We will need these to be uniqued, or at least
1024/// comparable, at some point.
1025QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1026                                                ArrayType::ArraySizeModifier ASM,
1027                                                unsigned EltTypeQuals) {
1028  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1029         "Size must be type- or value-dependent!");
1030
1031  // Since we don't unique expressions, it isn't possible to unique
1032  // dependently-sized array types.
1033
1034  DependentSizedArrayType *New =
1035      new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1036                                            ASM, EltTypeQuals);
1037
1038  DependentSizedArrayTypes.push_back(New);
1039  Types.push_back(New);
1040  return QualType(New, 0);
1041}
1042
1043QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1044                                            ArrayType::ArraySizeModifier ASM,
1045                                            unsigned EltTypeQuals) {
1046  llvm::FoldingSetNodeID ID;
1047  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1048
1049  void *InsertPos = 0;
1050  if (IncompleteArrayType *ATP =
1051       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1052    return QualType(ATP, 0);
1053
1054  // If the element type isn't canonical, this won't be a canonical type
1055  // either, so fill in the canonical type field.
1056  QualType Canonical;
1057
1058  if (!EltTy->isCanonical()) {
1059    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1060                                       ASM, EltTypeQuals);
1061
1062    // Get the new insert position for the node we care about.
1063    IncompleteArrayType *NewIP =
1064      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1065    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1066  }
1067
1068  IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1069                                                           ASM, EltTypeQuals);
1070
1071  IncompleteArrayTypes.InsertNode(New, InsertPos);
1072  Types.push_back(New);
1073  return QualType(New, 0);
1074}
1075
1076/// getVectorType - Return the unique reference to a vector type of
1077/// the specified element type and size. VectorType must be a built-in type.
1078QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1079  BuiltinType *baseType;
1080
1081  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1082  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1083
1084  // Check if we've already instantiated a vector of this type.
1085  llvm::FoldingSetNodeID ID;
1086  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1087  void *InsertPos = 0;
1088  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1089    return QualType(VTP, 0);
1090
1091  // If the element type isn't canonical, this won't be a canonical type either,
1092  // so fill in the canonical type field.
1093  QualType Canonical;
1094  if (!vecType->isCanonical()) {
1095    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1096
1097    // Get the new insert position for the node we care about.
1098    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1099    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1100  }
1101  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1102  VectorTypes.InsertNode(New, InsertPos);
1103  Types.push_back(New);
1104  return QualType(New, 0);
1105}
1106
1107/// getExtVectorType - Return the unique reference to an extended vector type of
1108/// the specified element type and size. VectorType must be a built-in type.
1109QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1110  BuiltinType *baseType;
1111
1112  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1113  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1114
1115  // Check if we've already instantiated a vector of this type.
1116  llvm::FoldingSetNodeID ID;
1117  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1118  void *InsertPos = 0;
1119  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1120    return QualType(VTP, 0);
1121
1122  // If the element type isn't canonical, this won't be a canonical type either,
1123  // so fill in the canonical type field.
1124  QualType Canonical;
1125  if (!vecType->isCanonical()) {
1126    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1127
1128    // Get the new insert position for the node we care about.
1129    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1130    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1131  }
1132  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1133  VectorTypes.InsertNode(New, InsertPos);
1134  Types.push_back(New);
1135  return QualType(New, 0);
1136}
1137
1138/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1139///
1140QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1141  // Unique functions, to guarantee there is only one function of a particular
1142  // structure.
1143  llvm::FoldingSetNodeID ID;
1144  FunctionNoProtoType::Profile(ID, ResultTy);
1145
1146  void *InsertPos = 0;
1147  if (FunctionNoProtoType *FT =
1148        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1149    return QualType(FT, 0);
1150
1151  QualType Canonical;
1152  if (!ResultTy->isCanonical()) {
1153    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1154
1155    // Get the new insert position for the node we care about.
1156    FunctionNoProtoType *NewIP =
1157      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1158    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1159  }
1160
1161  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1162  Types.push_back(New);
1163  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1164  return QualType(New, 0);
1165}
1166
1167/// getFunctionType - Return a normal function type with a typed argument
1168/// list.  isVariadic indicates whether the argument list includes '...'.
1169QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1170                                     unsigned NumArgs, bool isVariadic,
1171                                     unsigned TypeQuals) {
1172  // Unique functions, to guarantee there is only one function of a particular
1173  // structure.
1174  llvm::FoldingSetNodeID ID;
1175  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1176                             TypeQuals);
1177
1178  void *InsertPos = 0;
1179  if (FunctionProtoType *FTP =
1180        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1181    return QualType(FTP, 0);
1182
1183  // Determine whether the type being created is already canonical or not.
1184  bool isCanonical = ResultTy->isCanonical();
1185  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1186    if (!ArgArray[i]->isCanonical())
1187      isCanonical = false;
1188
1189  // If this type isn't canonical, get the canonical version of it.
1190  QualType Canonical;
1191  if (!isCanonical) {
1192    llvm::SmallVector<QualType, 16> CanonicalArgs;
1193    CanonicalArgs.reserve(NumArgs);
1194    for (unsigned i = 0; i != NumArgs; ++i)
1195      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1196
1197    Canonical = getFunctionType(getCanonicalType(ResultTy),
1198                                &CanonicalArgs[0], NumArgs,
1199                                isVariadic, TypeQuals);
1200
1201    // Get the new insert position for the node we care about.
1202    FunctionProtoType *NewIP =
1203      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1204    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1205  }
1206
1207  // FunctionProtoType objects are allocated with extra bytes after them
1208  // for a variable size array (for parameter types) at the end of them.
1209  FunctionProtoType *FTP =
1210    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1211                                 NumArgs*sizeof(QualType), 8);
1212  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1213                              TypeQuals, Canonical);
1214  Types.push_back(FTP);
1215  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1216  return QualType(FTP, 0);
1217}
1218
1219/// getTypeDeclType - Return the unique reference to the type for the
1220/// specified type declaration.
1221QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1222  assert(Decl && "Passed null for Decl param");
1223  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1224
1225  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1226    return getTypedefType(Typedef);
1227  else if (isa<TemplateTypeParmDecl>(Decl)) {
1228    assert(false && "Template type parameter types are always available.");
1229  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1230    return getObjCInterfaceType(ObjCInterface);
1231
1232  if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Decl)) {
1233    if (PrevDecl)
1234      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1235    else
1236      Decl->TypeForDecl = new (*this,8) CXXRecordType(CXXRecord);
1237  }
1238  else if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1239    if (PrevDecl)
1240      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1241    else
1242      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1243  }
1244  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1245    if (PrevDecl)
1246      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1247    else
1248      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1249  }
1250  else
1251    assert(false && "TypeDecl without a type?");
1252
1253  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1254  return QualType(Decl->TypeForDecl, 0);
1255}
1256
1257/// getTypedefType - Return the unique reference to the type for the
1258/// specified typename decl.
1259QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1260  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1261
1262  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1263  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1264  Types.push_back(Decl->TypeForDecl);
1265  return QualType(Decl->TypeForDecl, 0);
1266}
1267
1268/// getObjCInterfaceType - Return the unique reference to the type for the
1269/// specified ObjC interface decl.
1270QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
1271  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1272
1273  Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
1274  Types.push_back(Decl->TypeForDecl);
1275  return QualType(Decl->TypeForDecl, 0);
1276}
1277
1278/// buildObjCInterfaceType - Returns a new type for the interface
1279/// declaration, regardless. It also removes any previously built
1280/// record declaration so caller can rebuild it.
1281QualType ASTContext::buildObjCInterfaceType(ObjCInterfaceDecl *Decl) {
1282  const RecordDecl *&RD = ASTRecordForInterface[Decl];
1283  if (RD)
1284    RD = 0;
1285  Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
1286  Types.push_back(Decl->TypeForDecl);
1287  return QualType(Decl->TypeForDecl, 0);
1288}
1289
1290/// \brief Retrieve the template type parameter type for a template
1291/// parameter with the given depth, index, and (optionally) name.
1292QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1293                                             IdentifierInfo *Name) {
1294  llvm::FoldingSetNodeID ID;
1295  TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1296  void *InsertPos = 0;
1297  TemplateTypeParmType *TypeParm
1298    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1299
1300  if (TypeParm)
1301    return QualType(TypeParm, 0);
1302
1303  if (Name)
1304    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1305                                         getTemplateTypeParmType(Depth, Index));
1306  else
1307    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1308
1309  Types.push_back(TypeParm);
1310  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1311
1312  return QualType(TypeParm, 0);
1313}
1314
1315QualType
1316ASTContext::getClassTemplateSpecializationType(TemplateDecl *Template,
1317                                               unsigned NumArgs,
1318                                               uintptr_t *Args, bool *ArgIsType,
1319                                               QualType Canon) {
1320  Canon = getCanonicalType(Canon);
1321
1322  llvm::FoldingSetNodeID ID;
1323  ClassTemplateSpecializationType::Profile(ID, Template, NumArgs, Args,
1324                                           ArgIsType);
1325  void *InsertPos = 0;
1326  ClassTemplateSpecializationType *Spec
1327    = ClassTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1328
1329  if (Spec)
1330    return QualType(Spec, 0);
1331
1332  void *Mem = Allocate(sizeof(ClassTemplateSpecializationType) +
1333                       (sizeof(uintptr_t) *
1334                        (ClassTemplateSpecializationType::
1335                           getNumPackedWords(NumArgs) +
1336                         NumArgs)), 8);
1337  Spec = new (Mem) ClassTemplateSpecializationType(Template, NumArgs, Args,
1338                                                   ArgIsType, Canon);
1339  Types.push_back(Spec);
1340  ClassTemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1341
1342  return QualType(Spec, 0);
1343}
1344
1345/// CmpProtocolNames - Comparison predicate for sorting protocols
1346/// alphabetically.
1347static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1348                            const ObjCProtocolDecl *RHS) {
1349  return LHS->getDeclName() < RHS->getDeclName();
1350}
1351
1352static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1353                                   unsigned &NumProtocols) {
1354  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1355
1356  // Sort protocols, keyed by name.
1357  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1358
1359  // Remove duplicates.
1360  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1361  NumProtocols = ProtocolsEnd-Protocols;
1362}
1363
1364
1365/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1366/// the given interface decl and the conforming protocol list.
1367QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1368                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1369  // Sort the protocol list alphabetically to canonicalize it.
1370  SortAndUniqueProtocols(Protocols, NumProtocols);
1371
1372  llvm::FoldingSetNodeID ID;
1373  ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1374
1375  void *InsertPos = 0;
1376  if (ObjCQualifiedInterfaceType *QT =
1377      ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1378    return QualType(QT, 0);
1379
1380  // No Match;
1381  ObjCQualifiedInterfaceType *QType =
1382    new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
1383
1384  Types.push_back(QType);
1385  ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
1386  return QualType(QType, 0);
1387}
1388
1389/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1390/// and the conforming protocol list.
1391QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
1392                                            unsigned NumProtocols) {
1393  // Sort the protocol list alphabetically to canonicalize it.
1394  SortAndUniqueProtocols(Protocols, NumProtocols);
1395
1396  llvm::FoldingSetNodeID ID;
1397  ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
1398
1399  void *InsertPos = 0;
1400  if (ObjCQualifiedIdType *QT =
1401        ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
1402    return QualType(QT, 0);
1403
1404  // No Match;
1405  ObjCQualifiedIdType *QType =
1406    new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
1407  Types.push_back(QType);
1408  ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
1409  return QualType(QType, 0);
1410}
1411
1412/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1413/// TypeOfExprType AST's (since expression's are never shared). For example,
1414/// multiple declarations that refer to "typeof(x)" all contain different
1415/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1416/// on canonical type's (which are always unique).
1417QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1418  QualType Canonical = getCanonicalType(tofExpr->getType());
1419  TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1420  Types.push_back(toe);
1421  return QualType(toe, 0);
1422}
1423
1424/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1425/// TypeOfType AST's. The only motivation to unique these nodes would be
1426/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1427/// an issue. This doesn't effect the type checker, since it operates
1428/// on canonical type's (which are always unique).
1429QualType ASTContext::getTypeOfType(QualType tofType) {
1430  QualType Canonical = getCanonicalType(tofType);
1431  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1432  Types.push_back(tot);
1433  return QualType(tot, 0);
1434}
1435
1436/// getTagDeclType - Return the unique reference to the type for the
1437/// specified TagDecl (struct/union/class/enum) decl.
1438QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1439  assert (Decl);
1440  return getTypeDeclType(Decl);
1441}
1442
1443/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1444/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1445/// needs to agree with the definition in <stddef.h>.
1446QualType ASTContext::getSizeType() const {
1447  return getFromTargetType(Target.getSizeType());
1448}
1449
1450/// getSignedWCharType - Return the type of "signed wchar_t".
1451/// Used when in C++, as a GCC extension.
1452QualType ASTContext::getSignedWCharType() const {
1453  // FIXME: derive from "Target" ?
1454  return WCharTy;
1455}
1456
1457/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1458/// Used when in C++, as a GCC extension.
1459QualType ASTContext::getUnsignedWCharType() const {
1460  // FIXME: derive from "Target" ?
1461  return UnsignedIntTy;
1462}
1463
1464/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1465/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1466QualType ASTContext::getPointerDiffType() const {
1467  return getFromTargetType(Target.getPtrDiffType(0));
1468}
1469
1470//===----------------------------------------------------------------------===//
1471//                              Type Operators
1472//===----------------------------------------------------------------------===//
1473
1474/// getCanonicalType - Return the canonical (structural) type corresponding to
1475/// the specified potentially non-canonical type.  The non-canonical version
1476/// of a type may have many "decorated" versions of types.  Decorators can
1477/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1478/// to be free of any of these, allowing two canonical types to be compared
1479/// for exact equality with a simple pointer comparison.
1480QualType ASTContext::getCanonicalType(QualType T) {
1481  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1482
1483  // If the result has type qualifiers, make sure to canonicalize them as well.
1484  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1485  if (TypeQuals == 0) return CanType;
1486
1487  // If the type qualifiers are on an array type, get the canonical type of the
1488  // array with the qualifiers applied to the element type.
1489  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1490  if (!AT)
1491    return CanType.getQualifiedType(TypeQuals);
1492
1493  // Get the canonical version of the element with the extra qualifiers on it.
1494  // This can recursively sink qualifiers through multiple levels of arrays.
1495  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1496  NewEltTy = getCanonicalType(NewEltTy);
1497
1498  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1499    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1500                                CAT->getIndexTypeQualifier());
1501  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1502    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1503                                  IAT->getIndexTypeQualifier());
1504
1505  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1506    return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1507                                      DSAT->getSizeModifier(),
1508                                      DSAT->getIndexTypeQualifier());
1509
1510  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1511  return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1512                              VAT->getSizeModifier(),
1513                              VAT->getIndexTypeQualifier());
1514}
1515
1516
1517const ArrayType *ASTContext::getAsArrayType(QualType T) {
1518  // Handle the non-qualified case efficiently.
1519  if (T.getCVRQualifiers() == 0) {
1520    // Handle the common positive case fast.
1521    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1522      return AT;
1523  }
1524
1525  // Handle the common negative case fast, ignoring CVR qualifiers.
1526  QualType CType = T->getCanonicalTypeInternal();
1527
1528  // Make sure to look through type qualifiers (like ExtQuals) for the negative
1529  // test.
1530  if (!isa<ArrayType>(CType) &&
1531      !isa<ArrayType>(CType.getUnqualifiedType()))
1532    return 0;
1533
1534  // Apply any CVR qualifiers from the array type to the element type.  This
1535  // implements C99 6.7.3p8: "If the specification of an array type includes
1536  // any type qualifiers, the element type is so qualified, not the array type."
1537
1538  // If we get here, we either have type qualifiers on the type, or we have
1539  // sugar such as a typedef in the way.  If we have type qualifiers on the type
1540  // we must propagate them down into the elemeng type.
1541  unsigned CVRQuals = T.getCVRQualifiers();
1542  unsigned AddrSpace = 0;
1543  Type *Ty = T.getTypePtr();
1544
1545  // Rip through ExtQualType's and typedefs to get to a concrete type.
1546  while (1) {
1547    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1548      AddrSpace = EXTQT->getAddressSpace();
1549      Ty = EXTQT->getBaseType();
1550    } else {
1551      T = Ty->getDesugaredType();
1552      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1553        break;
1554      CVRQuals |= T.getCVRQualifiers();
1555      Ty = T.getTypePtr();
1556    }
1557  }
1558
1559  // If we have a simple case, just return now.
1560  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1561  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1562    return ATy;
1563
1564  // Otherwise, we have an array and we have qualifiers on it.  Push the
1565  // qualifiers into the array element type and return a new array type.
1566  // Get the canonical version of the element with the extra qualifiers on it.
1567  // This can recursively sink qualifiers through multiple levels of arrays.
1568  QualType NewEltTy = ATy->getElementType();
1569  if (AddrSpace)
1570    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
1571  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1572
1573  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1574    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1575                                                CAT->getSizeModifier(),
1576                                                CAT->getIndexTypeQualifier()));
1577  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1578    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1579                                                  IAT->getSizeModifier(),
1580                                                 IAT->getIndexTypeQualifier()));
1581
1582  if (const DependentSizedArrayType *DSAT
1583        = dyn_cast<DependentSizedArrayType>(ATy))
1584    return cast<ArrayType>(
1585                     getDependentSizedArrayType(NewEltTy,
1586                                                DSAT->getSizeExpr(),
1587                                                DSAT->getSizeModifier(),
1588                                                DSAT->getIndexTypeQualifier()));
1589
1590  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1591  return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1592                                              VAT->getSizeModifier(),
1593                                              VAT->getIndexTypeQualifier()));
1594}
1595
1596
1597/// getArrayDecayedType - Return the properly qualified result of decaying the
1598/// specified array type to a pointer.  This operation is non-trivial when
1599/// handling typedefs etc.  The canonical type of "T" must be an array type,
1600/// this returns a pointer to a properly qualified element of the array.
1601///
1602/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1603QualType ASTContext::getArrayDecayedType(QualType Ty) {
1604  // Get the element type with 'getAsArrayType' so that we don't lose any
1605  // typedefs in the element type of the array.  This also handles propagation
1606  // of type qualifiers from the array type into the element type if present
1607  // (C99 6.7.3p8).
1608  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1609  assert(PrettyArrayType && "Not an array type!");
1610
1611  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
1612
1613  // int x[restrict 4] ->  int *restrict
1614  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
1615}
1616
1617QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
1618  QualType ElemTy = VAT->getElementType();
1619
1620  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1621    return getBaseElementType(VAT);
1622
1623  return ElemTy;
1624}
1625
1626/// getFloatingRank - Return a relative rank for floating point types.
1627/// This routine will assert if passed a built-in type that isn't a float.
1628static FloatingRank getFloatingRank(QualType T) {
1629  if (const ComplexType *CT = T->getAsComplexType())
1630    return getFloatingRank(CT->getElementType());
1631
1632  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
1633  switch (T->getAsBuiltinType()->getKind()) {
1634  default: assert(0 && "getFloatingRank(): not a floating type");
1635  case BuiltinType::Float:      return FloatRank;
1636  case BuiltinType::Double:     return DoubleRank;
1637  case BuiltinType::LongDouble: return LongDoubleRank;
1638  }
1639}
1640
1641/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1642/// point or a complex type (based on typeDomain/typeSize).
1643/// 'typeDomain' is a real floating point or complex type.
1644/// 'typeSize' is a real floating point or complex type.
1645QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1646                                                       QualType Domain) const {
1647  FloatingRank EltRank = getFloatingRank(Size);
1648  if (Domain->isComplexType()) {
1649    switch (EltRank) {
1650    default: assert(0 && "getFloatingRank(): illegal value for rank");
1651    case FloatRank:      return FloatComplexTy;
1652    case DoubleRank:     return DoubleComplexTy;
1653    case LongDoubleRank: return LongDoubleComplexTy;
1654    }
1655  }
1656
1657  assert(Domain->isRealFloatingType() && "Unknown domain!");
1658  switch (EltRank) {
1659  default: assert(0 && "getFloatingRank(): illegal value for rank");
1660  case FloatRank:      return FloatTy;
1661  case DoubleRank:     return DoubleTy;
1662  case LongDoubleRank: return LongDoubleTy;
1663  }
1664}
1665
1666/// getFloatingTypeOrder - Compare the rank of the two specified floating
1667/// point types, ignoring the domain of the type (i.e. 'double' ==
1668/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1669/// LHS < RHS, return -1.
1670int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1671  FloatingRank LHSR = getFloatingRank(LHS);
1672  FloatingRank RHSR = getFloatingRank(RHS);
1673
1674  if (LHSR == RHSR)
1675    return 0;
1676  if (LHSR > RHSR)
1677    return 1;
1678  return -1;
1679}
1680
1681/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1682/// routine will assert if passed a built-in type that isn't an integer or enum,
1683/// or if it is not canonicalized.
1684unsigned ASTContext::getIntegerRank(Type *T) {
1685  assert(T->isCanonical() && "T should be canonicalized");
1686  if (EnumType* ET = dyn_cast<EnumType>(T))
1687    T = ET->getDecl()->getIntegerType().getTypePtr();
1688
1689  // There are two things which impact the integer rank: the width, and
1690  // the ordering of builtins.  The builtin ordering is encoded in the
1691  // bottom three bits; the width is encoded in the bits above that.
1692  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1693    return FWIT->getWidth() << 3;
1694  }
1695
1696  switch (cast<BuiltinType>(T)->getKind()) {
1697  default: assert(0 && "getIntegerRank(): not a built-in integer");
1698  case BuiltinType::Bool:
1699    return 1 + (getIntWidth(BoolTy) << 3);
1700  case BuiltinType::Char_S:
1701  case BuiltinType::Char_U:
1702  case BuiltinType::SChar:
1703  case BuiltinType::UChar:
1704    return 2 + (getIntWidth(CharTy) << 3);
1705  case BuiltinType::Short:
1706  case BuiltinType::UShort:
1707    return 3 + (getIntWidth(ShortTy) << 3);
1708  case BuiltinType::Int:
1709  case BuiltinType::UInt:
1710    return 4 + (getIntWidth(IntTy) << 3);
1711  case BuiltinType::Long:
1712  case BuiltinType::ULong:
1713    return 5 + (getIntWidth(LongTy) << 3);
1714  case BuiltinType::LongLong:
1715  case BuiltinType::ULongLong:
1716    return 6 + (getIntWidth(LongLongTy) << 3);
1717  }
1718}
1719
1720/// getIntegerTypeOrder - Returns the highest ranked integer type:
1721/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
1722/// LHS < RHS, return -1.
1723int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
1724  Type *LHSC = getCanonicalType(LHS).getTypePtr();
1725  Type *RHSC = getCanonicalType(RHS).getTypePtr();
1726  if (LHSC == RHSC) return 0;
1727
1728  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1729  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
1730
1731  unsigned LHSRank = getIntegerRank(LHSC);
1732  unsigned RHSRank = getIntegerRank(RHSC);
1733
1734  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
1735    if (LHSRank == RHSRank) return 0;
1736    return LHSRank > RHSRank ? 1 : -1;
1737  }
1738
1739  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1740  if (LHSUnsigned) {
1741    // If the unsigned [LHS] type is larger, return it.
1742    if (LHSRank >= RHSRank)
1743      return 1;
1744
1745    // If the signed type can represent all values of the unsigned type, it
1746    // wins.  Because we are dealing with 2's complement and types that are
1747    // powers of two larger than each other, this is always safe.
1748    return -1;
1749  }
1750
1751  // If the unsigned [RHS] type is larger, return it.
1752  if (RHSRank >= LHSRank)
1753    return -1;
1754
1755  // If the signed type can represent all values of the unsigned type, it
1756  // wins.  Because we are dealing with 2's complement and types that are
1757  // powers of two larger than each other, this is always safe.
1758  return 1;
1759}
1760
1761// getCFConstantStringType - Return the type used for constant CFStrings.
1762QualType ASTContext::getCFConstantStringType() {
1763  if (!CFConstantStringTypeDecl) {
1764    CFConstantStringTypeDecl =
1765      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1766                         &Idents.get("NSConstantString"));
1767    QualType FieldTypes[4];
1768
1769    // const int *isa;
1770    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
1771    // int flags;
1772    FieldTypes[1] = IntTy;
1773    // const char *str;
1774    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
1775    // long length;
1776    FieldTypes[3] = LongTy;
1777
1778    // Create fields
1779    for (unsigned i = 0; i < 4; ++i) {
1780      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
1781                                           SourceLocation(), 0,
1782                                           FieldTypes[i], /*BitWidth=*/0,
1783                                           /*Mutable=*/false);
1784      CFConstantStringTypeDecl->addDecl(Field);
1785    }
1786
1787    CFConstantStringTypeDecl->completeDefinition(*this);
1788  }
1789
1790  return getTagDeclType(CFConstantStringTypeDecl);
1791}
1792
1793QualType ASTContext::getObjCFastEnumerationStateType()
1794{
1795  if (!ObjCFastEnumerationStateTypeDecl) {
1796    ObjCFastEnumerationStateTypeDecl =
1797      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1798                         &Idents.get("__objcFastEnumerationState"));
1799
1800    QualType FieldTypes[] = {
1801      UnsignedLongTy,
1802      getPointerType(ObjCIdType),
1803      getPointerType(UnsignedLongTy),
1804      getConstantArrayType(UnsignedLongTy,
1805                           llvm::APInt(32, 5), ArrayType::Normal, 0)
1806    };
1807
1808    for (size_t i = 0; i < 4; ++i) {
1809      FieldDecl *Field = FieldDecl::Create(*this,
1810                                           ObjCFastEnumerationStateTypeDecl,
1811                                           SourceLocation(), 0,
1812                                           FieldTypes[i], /*BitWidth=*/0,
1813                                           /*Mutable=*/false);
1814      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
1815    }
1816
1817    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
1818  }
1819
1820  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1821}
1822
1823// This returns true if a type has been typedefed to BOOL:
1824// typedef <type> BOOL;
1825static bool isTypeTypedefedAsBOOL(QualType T) {
1826  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1827    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
1828      return II->isStr("BOOL");
1829
1830  return false;
1831}
1832
1833/// getObjCEncodingTypeSize returns size of type for objective-c encoding
1834/// purpose.
1835int ASTContext::getObjCEncodingTypeSize(QualType type) {
1836  uint64_t sz = getTypeSize(type);
1837
1838  // Make all integer and enum types at least as large as an int
1839  if (sz > 0 && type->isIntegralType())
1840    sz = std::max(sz, getTypeSize(IntTy));
1841  // Treat arrays as pointers, since that's how they're passed in.
1842  else if (type->isArrayType())
1843    sz = getTypeSize(VoidPtrTy);
1844  return sz / getTypeSize(CharTy);
1845}
1846
1847/// getObjCEncodingForMethodDecl - Return the encoded type for this method
1848/// declaration.
1849void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1850                                              std::string& S) {
1851  // FIXME: This is not very efficient.
1852  // Encode type qualifer, 'in', 'inout', etc. for the return type.
1853  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
1854  // Encode result type.
1855  getObjCEncodingForType(Decl->getResultType(), S);
1856  // Compute size of all parameters.
1857  // Start with computing size of a pointer in number of bytes.
1858  // FIXME: There might(should) be a better way of doing this computation!
1859  SourceLocation Loc;
1860  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
1861  // The first two arguments (self and _cmd) are pointers; account for
1862  // their size.
1863  int ParmOffset = 2 * PtrSize;
1864  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
1865       E = Decl->param_end(); PI != E; ++PI) {
1866    QualType PType = (*PI)->getType();
1867    int sz = getObjCEncodingTypeSize(PType);
1868    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
1869    ParmOffset += sz;
1870  }
1871  S += llvm::utostr(ParmOffset);
1872  S += "@0:";
1873  S += llvm::utostr(PtrSize);
1874
1875  // Argument types.
1876  ParmOffset = 2 * PtrSize;
1877  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
1878       E = Decl->param_end(); PI != E; ++PI) {
1879    ParmVarDecl *PVDecl = *PI;
1880    QualType PType = PVDecl->getOriginalType();
1881    if (const ArrayType *AT =
1882          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal()))
1883        // Use array's original type only if it has known number of
1884        // elements.
1885        if (!dyn_cast<ConstantArrayType>(AT))
1886          PType = PVDecl->getType();
1887    // Process argument qualifiers for user supplied arguments; such as,
1888    // 'in', 'inout', etc.
1889    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
1890    getObjCEncodingForType(PType, S);
1891    S += llvm::utostr(ParmOffset);
1892    ParmOffset += getObjCEncodingTypeSize(PType);
1893  }
1894}
1895
1896/// getObjCEncodingForPropertyDecl - Return the encoded type for this
1897/// property declaration. If non-NULL, Container must be either an
1898/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
1899/// NULL when getting encodings for protocol properties.
1900/// Property attributes are stored as a comma-delimited C string. The simple
1901/// attributes readonly and bycopy are encoded as single characters. The
1902/// parametrized attributes, getter=name, setter=name, and ivar=name, are
1903/// encoded as single characters, followed by an identifier. Property types
1904/// are also encoded as a parametrized attribute. The characters used to encode
1905/// these attributes are defined by the following enumeration:
1906/// @code
1907/// enum PropertyAttributes {
1908/// kPropertyReadOnly = 'R',   // property is read-only.
1909/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
1910/// kPropertyByref = '&',  // property is a reference to the value last assigned
1911/// kPropertyDynamic = 'D',    // property is dynamic
1912/// kPropertyGetter = 'G',     // followed by getter selector name
1913/// kPropertySetter = 'S',     // followed by setter selector name
1914/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
1915/// kPropertyType = 't'              // followed by old-style type encoding.
1916/// kPropertyWeak = 'W'              // 'weak' property
1917/// kPropertyStrong = 'P'            // property GC'able
1918/// kPropertyNonAtomic = 'N'         // property non-atomic
1919/// };
1920/// @endcode
1921void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1922                                                const Decl *Container,
1923                                                std::string& S) {
1924  // Collect information from the property implementation decl(s).
1925  bool Dynamic = false;
1926  ObjCPropertyImplDecl *SynthesizePID = 0;
1927
1928  // FIXME: Duplicated code due to poor abstraction.
1929  if (Container) {
1930    if (const ObjCCategoryImplDecl *CID =
1931        dyn_cast<ObjCCategoryImplDecl>(Container)) {
1932      for (ObjCCategoryImplDecl::propimpl_iterator
1933             i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
1934        ObjCPropertyImplDecl *PID = *i;
1935        if (PID->getPropertyDecl() == PD) {
1936          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1937            Dynamic = true;
1938          } else {
1939            SynthesizePID = PID;
1940          }
1941        }
1942      }
1943    } else {
1944      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
1945      for (ObjCCategoryImplDecl::propimpl_iterator
1946             i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
1947        ObjCPropertyImplDecl *PID = *i;
1948        if (PID->getPropertyDecl() == PD) {
1949          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
1950            Dynamic = true;
1951          } else {
1952            SynthesizePID = PID;
1953          }
1954        }
1955      }
1956    }
1957  }
1958
1959  // FIXME: This is not very efficient.
1960  S = "T";
1961
1962  // Encode result type.
1963  // GCC has some special rules regarding encoding of properties which
1964  // closely resembles encoding of ivars.
1965  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, NULL,
1966                             true /* outermost type */,
1967                             true /* encoding for property */);
1968
1969  if (PD->isReadOnly()) {
1970    S += ",R";
1971  } else {
1972    switch (PD->getSetterKind()) {
1973    case ObjCPropertyDecl::Assign: break;
1974    case ObjCPropertyDecl::Copy:   S += ",C"; break;
1975    case ObjCPropertyDecl::Retain: S += ",&"; break;
1976    }
1977  }
1978
1979  // It really isn't clear at all what this means, since properties
1980  // are "dynamic by default".
1981  if (Dynamic)
1982    S += ",D";
1983
1984  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
1985    S += ",N";
1986
1987  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
1988    S += ",G";
1989    S += PD->getGetterName().getAsString();
1990  }
1991
1992  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
1993    S += ",S";
1994    S += PD->getSetterName().getAsString();
1995  }
1996
1997  if (SynthesizePID) {
1998    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
1999    S += ",V";
2000    S += OID->getNameAsString();
2001  }
2002
2003  // FIXME: OBJCGC: weak & strong
2004}
2005
2006/// getLegacyIntegralTypeEncoding -
2007/// Another legacy compatibility encoding: 32-bit longs are encoded as
2008/// 'l' or 'L' , but not always.  For typedefs, we need to use
2009/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2010///
2011void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2012  if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2013    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2014      if (BT->getKind() == BuiltinType::ULong &&
2015          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2016        PointeeTy = UnsignedIntTy;
2017      else
2018        if (BT->getKind() == BuiltinType::Long &&
2019            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2020          PointeeTy = IntTy;
2021    }
2022  }
2023}
2024
2025void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2026                                        FieldDecl *Field) const {
2027  // We follow the behavior of gcc, expanding structures which are
2028  // directly pointed to, and expanding embedded structures. Note that
2029  // these rules are sufficient to prevent recursive encoding of the
2030  // same type.
2031  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2032                             true /* outermost type */);
2033}
2034
2035static void EncodeBitField(const ASTContext *Context, std::string& S,
2036                           FieldDecl *FD) {
2037  const Expr *E = FD->getBitWidth();
2038  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2039  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2040  unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue();
2041  S += 'b';
2042  S += llvm::utostr(N);
2043}
2044
2045void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2046                                            bool ExpandPointedToStructures,
2047                                            bool ExpandStructures,
2048                                            FieldDecl *FD,
2049                                            bool OutermostType,
2050                                            bool EncodingProperty) const {
2051  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2052    if (FD && FD->isBitField()) {
2053      EncodeBitField(this, S, FD);
2054    }
2055    else {
2056      char encoding;
2057      switch (BT->getKind()) {
2058      default: assert(0 && "Unhandled builtin type kind");
2059      case BuiltinType::Void:       encoding = 'v'; break;
2060      case BuiltinType::Bool:       encoding = 'B'; break;
2061      case BuiltinType::Char_U:
2062      case BuiltinType::UChar:      encoding = 'C'; break;
2063      case BuiltinType::UShort:     encoding = 'S'; break;
2064      case BuiltinType::UInt:       encoding = 'I'; break;
2065      case BuiltinType::ULong:
2066          encoding =
2067            (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2068          break;
2069      case BuiltinType::ULongLong:  encoding = 'Q'; break;
2070      case BuiltinType::Char_S:
2071      case BuiltinType::SChar:      encoding = 'c'; break;
2072      case BuiltinType::Short:      encoding = 's'; break;
2073      case BuiltinType::Int:        encoding = 'i'; break;
2074      case BuiltinType::Long:
2075        encoding =
2076          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2077        break;
2078      case BuiltinType::LongLong:   encoding = 'q'; break;
2079      case BuiltinType::Float:      encoding = 'f'; break;
2080      case BuiltinType::Double:     encoding = 'd'; break;
2081      case BuiltinType::LongDouble: encoding = 'd'; break;
2082      }
2083
2084      S += encoding;
2085    }
2086  }
2087  else if (T->isObjCQualifiedIdType()) {
2088    getObjCEncodingForTypeImpl(getObjCIdType(), S,
2089                               ExpandPointedToStructures,
2090                               ExpandStructures, FD);
2091    if (FD || EncodingProperty) {
2092      // Note that we do extended encoding of protocol qualifer list
2093      // Only when doing ivar or property encoding.
2094      const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2095      S += '"';
2096      for (unsigned i =0; i < QIDT->getNumProtocols(); i++) {
2097        ObjCProtocolDecl *Proto = QIDT->getProtocols(i);
2098        S += '<';
2099        S += Proto->getNameAsString();
2100        S += '>';
2101      }
2102      S += '"';
2103    }
2104    return;
2105  }
2106  else if (const PointerType *PT = T->getAsPointerType()) {
2107    QualType PointeeTy = PT->getPointeeType();
2108    bool isReadOnly = false;
2109    // For historical/compatibility reasons, the read-only qualifier of the
2110    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2111    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2112    // Also, do not emit the 'r' for anything but the outermost type!
2113    if (dyn_cast<TypedefType>(T.getTypePtr())) {
2114      if (OutermostType && T.isConstQualified()) {
2115        isReadOnly = true;
2116        S += 'r';
2117      }
2118    }
2119    else if (OutermostType) {
2120      QualType P = PointeeTy;
2121      while (P->getAsPointerType())
2122        P = P->getAsPointerType()->getPointeeType();
2123      if (P.isConstQualified()) {
2124        isReadOnly = true;
2125        S += 'r';
2126      }
2127    }
2128    if (isReadOnly) {
2129      // Another legacy compatibility encoding. Some ObjC qualifier and type
2130      // combinations need to be rearranged.
2131      // Rewrite "in const" from "nr" to "rn"
2132      const char * s = S.c_str();
2133      int len = S.length();
2134      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2135        std::string replace = "rn";
2136        S.replace(S.end()-2, S.end(), replace);
2137      }
2138    }
2139    if (isObjCIdStructType(PointeeTy)) {
2140      S += '@';
2141      return;
2142    }
2143    else if (PointeeTy->isObjCInterfaceType()) {
2144      if (!EncodingProperty &&
2145          isa<TypedefType>(PointeeTy.getTypePtr())) {
2146        // Another historical/compatibility reason.
2147        // We encode the underlying type which comes out as
2148        // {...};
2149        S += '^';
2150        getObjCEncodingForTypeImpl(PointeeTy, S,
2151                                   false, ExpandPointedToStructures,
2152                                   NULL);
2153        return;
2154      }
2155      S += '@';
2156      if (FD || EncodingProperty) {
2157        const ObjCInterfaceType *OIT =
2158                PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
2159        ObjCInterfaceDecl *OI = OIT->getDecl();
2160        S += '"';
2161        S += OI->getNameAsCString();
2162        for (unsigned i =0; i < OIT->getNumProtocols(); i++) {
2163          ObjCProtocolDecl *Proto = OIT->getProtocol(i);
2164          S += '<';
2165          S += Proto->getNameAsString();
2166          S += '>';
2167        }
2168        S += '"';
2169      }
2170      return;
2171    } else if (isObjCClassStructType(PointeeTy)) {
2172      S += '#';
2173      return;
2174    } else if (isObjCSelType(PointeeTy)) {
2175      S += ':';
2176      return;
2177    }
2178
2179    if (PointeeTy->isCharType()) {
2180      // char pointer types should be encoded as '*' unless it is a
2181      // type that has been typedef'd to 'BOOL'.
2182      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2183        S += '*';
2184        return;
2185      }
2186    }
2187
2188    S += '^';
2189    getLegacyIntegralTypeEncoding(PointeeTy);
2190
2191    getObjCEncodingForTypeImpl(PointeeTy, S,
2192                               false, ExpandPointedToStructures,
2193                               NULL);
2194  } else if (const ArrayType *AT =
2195               // Ignore type qualifiers etc.
2196               dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2197    if (isa<IncompleteArrayType>(AT)) {
2198      // Incomplete arrays are encoded as a pointer to the array element.
2199      S += '^';
2200
2201      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2202                                 false, ExpandStructures, FD);
2203    } else {
2204      S += '[';
2205
2206      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2207        S += llvm::utostr(CAT->getSize().getZExtValue());
2208      else {
2209        //Variable length arrays are encoded as a regular array with 0 elements.
2210        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2211        S += '0';
2212      }
2213
2214      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2215                                 false, ExpandStructures, FD);
2216      S += ']';
2217    }
2218  } else if (T->getAsFunctionType()) {
2219    S += '?';
2220  } else if (const RecordType *RTy = T->getAsRecordType()) {
2221    RecordDecl *RDecl = RTy->getDecl();
2222    S += RDecl->isUnion() ? '(' : '{';
2223    // Anonymous structures print as '?'
2224    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2225      S += II->getName();
2226    } else {
2227      S += '?';
2228    }
2229    if (ExpandStructures) {
2230      S += '=';
2231      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2232                                   FieldEnd = RDecl->field_end();
2233           Field != FieldEnd; ++Field) {
2234        if (FD) {
2235          S += '"';
2236          S += Field->getNameAsString();
2237          S += '"';
2238        }
2239
2240        // Special case bit-fields.
2241        if (Field->isBitField()) {
2242          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2243                                     (*Field));
2244        } else {
2245          QualType qt = Field->getType();
2246          getLegacyIntegralTypeEncoding(qt);
2247          getObjCEncodingForTypeImpl(qt, S, false, true,
2248                                     FD);
2249        }
2250      }
2251    }
2252    S += RDecl->isUnion() ? ')' : '}';
2253  } else if (T->isEnumeralType()) {
2254    if (FD && FD->isBitField())
2255      EncodeBitField(this, S, FD);
2256    else
2257      S += 'i';
2258  } else if (T->isBlockPointerType()) {
2259    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2260  } else if (T->isObjCInterfaceType()) {
2261    // @encode(class_name)
2262    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2263    S += '{';
2264    const IdentifierInfo *II = OI->getIdentifier();
2265    S += II->getName();
2266    S += '=';
2267    std::vector<FieldDecl*> RecFields;
2268    CollectObjCIvars(OI, RecFields);
2269    for (unsigned int i = 0; i != RecFields.size(); i++) {
2270      if (RecFields[i]->isBitField())
2271        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2272                                   RecFields[i]);
2273      else
2274        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2275                                   FD);
2276    }
2277    S += '}';
2278  }
2279  else
2280    assert(0 && "@encode for type not implemented!");
2281}
2282
2283void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2284                                                 std::string& S) const {
2285  if (QT & Decl::OBJC_TQ_In)
2286    S += 'n';
2287  if (QT & Decl::OBJC_TQ_Inout)
2288    S += 'N';
2289  if (QT & Decl::OBJC_TQ_Out)
2290    S += 'o';
2291  if (QT & Decl::OBJC_TQ_Bycopy)
2292    S += 'O';
2293  if (QT & Decl::OBJC_TQ_Byref)
2294    S += 'R';
2295  if (QT & Decl::OBJC_TQ_Oneway)
2296    S += 'V';
2297}
2298
2299void ASTContext::setBuiltinVaListType(QualType T)
2300{
2301  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2302
2303  BuiltinVaListType = T;
2304}
2305
2306void ASTContext::setObjCIdType(TypedefDecl *TD)
2307{
2308  ObjCIdType = getTypedefType(TD);
2309
2310  // typedef struct objc_object *id;
2311  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2312  // User error - caller will issue diagnostics.
2313  if (!ptr)
2314    return;
2315  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2316  // User error - caller will issue diagnostics.
2317  if (!rec)
2318    return;
2319  IdStructType = rec;
2320}
2321
2322void ASTContext::setObjCSelType(TypedefDecl *TD)
2323{
2324  ObjCSelType = getTypedefType(TD);
2325
2326  // typedef struct objc_selector *SEL;
2327  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2328  if (!ptr)
2329    return;
2330  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2331  if (!rec)
2332    return;
2333  SelStructType = rec;
2334}
2335
2336void ASTContext::setObjCProtoType(QualType QT)
2337{
2338  ObjCProtoType = QT;
2339}
2340
2341void ASTContext::setObjCClassType(TypedefDecl *TD)
2342{
2343  ObjCClassType = getTypedefType(TD);
2344
2345  // typedef struct objc_class *Class;
2346  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2347  assert(ptr && "'Class' incorrectly typed");
2348  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2349  assert(rec && "'Class' incorrectly typed");
2350  ClassStructType = rec;
2351}
2352
2353void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2354  assert(ObjCConstantStringType.isNull() &&
2355         "'NSConstantString' type already set!");
2356
2357  ObjCConstantStringType = getObjCInterfaceType(Decl);
2358}
2359
2360/// getFromTargetType - Given one of the integer types provided by
2361/// TargetInfo, produce the corresponding type. The unsigned @p Type
2362/// is actually a value of type @c TargetInfo::IntType.
2363QualType ASTContext::getFromTargetType(unsigned Type) const {
2364  switch (Type) {
2365  case TargetInfo::NoInt: return QualType();
2366  case TargetInfo::SignedShort: return ShortTy;
2367  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2368  case TargetInfo::SignedInt: return IntTy;
2369  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2370  case TargetInfo::SignedLong: return LongTy;
2371  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2372  case TargetInfo::SignedLongLong: return LongLongTy;
2373  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2374  }
2375
2376  assert(false && "Unhandled TargetInfo::IntType value");
2377  return QualType();
2378}
2379
2380//===----------------------------------------------------------------------===//
2381//                        Type Predicates.
2382//===----------------------------------------------------------------------===//
2383
2384/// isObjCNSObjectType - Return true if this is an NSObject object using
2385/// NSObject attribute on a c-style pointer type.
2386/// FIXME - Make it work directly on types.
2387///
2388bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2389  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2390    if (TypedefDecl *TD = TDT->getDecl())
2391      if (TD->getAttr<ObjCNSObjectAttr>())
2392        return true;
2393  }
2394  return false;
2395}
2396
2397/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2398/// to an object type.  This includes "id" and "Class" (two 'special' pointers
2399/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2400/// ID type).
2401bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
2402  if (Ty->isObjCQualifiedIdType())
2403    return true;
2404
2405  // Blocks are objects.
2406  if (Ty->isBlockPointerType())
2407    return true;
2408
2409  // All other object types are pointers.
2410  if (!Ty->isPointerType())
2411    return false;
2412
2413  // Check to see if this is 'id' or 'Class', both of which are typedefs for
2414  // pointer types.  This looks for the typedef specifically, not for the
2415  // underlying type.
2416  if (Ty == getObjCIdType() || Ty == getObjCClassType())
2417    return true;
2418
2419  // If this a pointer to an interface (e.g. NSString*), it is ok.
2420  if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType())
2421    return true;
2422
2423  // If is has NSObject attribute, OK as well.
2424  return isObjCNSObjectType(Ty);
2425}
2426
2427/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2428/// garbage collection attribute.
2429///
2430QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
2431  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
2432  if (getLangOptions().ObjC1 &&
2433      getLangOptions().getGCMode() != LangOptions::NonGC) {
2434    GCAttrs = Ty.getObjCGCAttr();
2435    // Default behavious under objective-c's gc is for objective-c pointers
2436    // (or pointers to them) be treated as though they were declared
2437    // as __strong.
2438    if (GCAttrs == QualType::GCNone) {
2439      if (isObjCObjectPointerType(Ty))
2440        GCAttrs = QualType::Strong;
2441      else if (Ty->isPointerType())
2442        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2443    }
2444  }
2445  return GCAttrs;
2446}
2447
2448//===----------------------------------------------------------------------===//
2449//                        Type Compatibility Testing
2450//===----------------------------------------------------------------------===//
2451
2452/// typesAreBlockCompatible - This routine is called when comparing two
2453/// block types. Types must be strictly compatible here. For example,
2454/// C unfortunately doesn't produce an error for the following:
2455///
2456///   int (*emptyArgFunc)();
2457///   int (*intArgList)(int) = emptyArgFunc;
2458///
2459/// For blocks, we will produce an error for the following (similar to C++):
2460///
2461///   int (^emptyArgBlock)();
2462///   int (^intArgBlock)(int) = emptyArgBlock;
2463///
2464/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2465///
2466bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
2467  const FunctionType *lbase = lhs->getAsFunctionType();
2468  const FunctionType *rbase = rhs->getAsFunctionType();
2469  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2470  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
2471  if (lproto && rproto)
2472    return !mergeTypes(lhs, rhs).isNull();
2473  return false;
2474}
2475
2476/// areCompatVectorTypes - Return true if the two specified vector types are
2477/// compatible.
2478static bool areCompatVectorTypes(const VectorType *LHS,
2479                                 const VectorType *RHS) {
2480  assert(LHS->isCanonical() && RHS->isCanonical());
2481  return LHS->getElementType() == RHS->getElementType() &&
2482         LHS->getNumElements() == RHS->getNumElements();
2483}
2484
2485/// canAssignObjCInterfaces - Return true if the two interface types are
2486/// compatible for assignment from RHS to LHS.  This handles validation of any
2487/// protocol qualifiers on the LHS or RHS.
2488///
2489bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2490                                         const ObjCInterfaceType *RHS) {
2491  // Verify that the base decls are compatible: the RHS must be a subclass of
2492  // the LHS.
2493  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2494    return false;
2495
2496  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
2497  // protocol qualified at all, then we are good.
2498  if (!isa<ObjCQualifiedInterfaceType>(LHS))
2499    return true;
2500
2501  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
2502  // isn't a superset.
2503  if (!isa<ObjCQualifiedInterfaceType>(RHS))
2504    return true;  // FIXME: should return false!
2505
2506  // Finally, we must have two protocol-qualified interfaces.
2507  const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2508  const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
2509  ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin();
2510  ObjCQualifiedInterfaceType::qual_iterator LHSPE = LHSP->qual_end();
2511  ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin();
2512  ObjCQualifiedInterfaceType::qual_iterator RHSPE = RHSP->qual_end();
2513
2514  // All protocols in LHS must have a presence in RHS.  Since the protocol lists
2515  // are both sorted alphabetically and have no duplicates, we can scan RHS and
2516  // LHS in a single parallel scan until we run out of elements in LHS.
2517  assert(LHSPI != LHSPE && "Empty LHS protocol list?");
2518  ObjCProtocolDecl *LHSProto = *LHSPI;
2519
2520  while (RHSPI != RHSPE) {
2521    ObjCProtocolDecl *RHSProto = *RHSPI++;
2522    // If the RHS has a protocol that the LHS doesn't, ignore it.
2523    if (RHSProto != LHSProto)
2524      continue;
2525
2526    // Otherwise, the RHS does have this element.
2527    ++LHSPI;
2528    if (LHSPI == LHSPE)
2529      return true;  // All protocols in LHS exist in RHS.
2530
2531    LHSProto = *LHSPI;
2532  }
2533
2534  // If we got here, we didn't find one of the LHS's protocols in the RHS list.
2535  return false;
2536}
2537
2538bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2539  // get the "pointed to" types
2540  const PointerType *LHSPT = LHS->getAsPointerType();
2541  const PointerType *RHSPT = RHS->getAsPointerType();
2542
2543  if (!LHSPT || !RHSPT)
2544    return false;
2545
2546  QualType lhptee = LHSPT->getPointeeType();
2547  QualType rhptee = RHSPT->getPointeeType();
2548  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2549  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2550  // ID acts sort of like void* for ObjC interfaces
2551  if (LHSIface && isObjCIdStructType(rhptee))
2552    return true;
2553  if (RHSIface && isObjCIdStructType(lhptee))
2554    return true;
2555  if (!LHSIface || !RHSIface)
2556    return false;
2557  return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2558         canAssignObjCInterfaces(RHSIface, LHSIface);
2559}
2560
2561/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2562/// both shall have the identically qualified version of a compatible type.
2563/// C99 6.2.7p1: Two types have compatible types if their types are the
2564/// same. See 6.7.[2,3,5] for additional rules.
2565bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2566  return !mergeTypes(LHS, RHS).isNull();
2567}
2568
2569QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2570  const FunctionType *lbase = lhs->getAsFunctionType();
2571  const FunctionType *rbase = rhs->getAsFunctionType();
2572  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2573  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
2574  bool allLTypes = true;
2575  bool allRTypes = true;
2576
2577  // Check return type
2578  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2579  if (retType.isNull()) return QualType();
2580  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2581    allLTypes = false;
2582  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2583    allRTypes = false;
2584
2585  if (lproto && rproto) { // two C99 style function prototypes
2586    unsigned lproto_nargs = lproto->getNumArgs();
2587    unsigned rproto_nargs = rproto->getNumArgs();
2588
2589    // Compatible functions must have the same number of arguments
2590    if (lproto_nargs != rproto_nargs)
2591      return QualType();
2592
2593    // Variadic and non-variadic functions aren't compatible
2594    if (lproto->isVariadic() != rproto->isVariadic())
2595      return QualType();
2596
2597    if (lproto->getTypeQuals() != rproto->getTypeQuals())
2598      return QualType();
2599
2600    // Check argument compatibility
2601    llvm::SmallVector<QualType, 10> types;
2602    for (unsigned i = 0; i < lproto_nargs; i++) {
2603      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2604      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2605      QualType argtype = mergeTypes(largtype, rargtype);
2606      if (argtype.isNull()) return QualType();
2607      types.push_back(argtype);
2608      if (getCanonicalType(argtype) != getCanonicalType(largtype))
2609        allLTypes = false;
2610      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2611        allRTypes = false;
2612    }
2613    if (allLTypes) return lhs;
2614    if (allRTypes) return rhs;
2615    return getFunctionType(retType, types.begin(), types.size(),
2616                           lproto->isVariadic(), lproto->getTypeQuals());
2617  }
2618
2619  if (lproto) allRTypes = false;
2620  if (rproto) allLTypes = false;
2621
2622  const FunctionProtoType *proto = lproto ? lproto : rproto;
2623  if (proto) {
2624    if (proto->isVariadic()) return QualType();
2625    // Check that the types are compatible with the types that
2626    // would result from default argument promotions (C99 6.7.5.3p15).
2627    // The only types actually affected are promotable integer
2628    // types and floats, which would be passed as a different
2629    // type depending on whether the prototype is visible.
2630    unsigned proto_nargs = proto->getNumArgs();
2631    for (unsigned i = 0; i < proto_nargs; ++i) {
2632      QualType argTy = proto->getArgType(i);
2633      if (argTy->isPromotableIntegerType() ||
2634          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2635        return QualType();
2636    }
2637
2638    if (allLTypes) return lhs;
2639    if (allRTypes) return rhs;
2640    return getFunctionType(retType, proto->arg_type_begin(),
2641                           proto->getNumArgs(), lproto->isVariadic(),
2642                           lproto->getTypeQuals());
2643  }
2644
2645  if (allLTypes) return lhs;
2646  if (allRTypes) return rhs;
2647  return getFunctionNoProtoType(retType);
2648}
2649
2650QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
2651  // C++ [expr]: If an expression initially has the type "reference to T", the
2652  // type is adjusted to "T" prior to any further analysis, the expression
2653  // designates the object or function denoted by the reference, and the
2654  // expression is an lvalue.
2655  // FIXME: C++ shouldn't be going through here!  The rules are different
2656  // enough that they should be handled separately.
2657  if (const ReferenceType *RT = LHS->getAsReferenceType())
2658    LHS = RT->getPointeeType();
2659  if (const ReferenceType *RT = RHS->getAsReferenceType())
2660    RHS = RT->getPointeeType();
2661
2662  QualType LHSCan = getCanonicalType(LHS),
2663           RHSCan = getCanonicalType(RHS);
2664
2665  // If two types are identical, they are compatible.
2666  if (LHSCan == RHSCan)
2667    return LHS;
2668
2669  // If the qualifiers are different, the types aren't compatible
2670  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers() ||
2671      LHSCan.getAddressSpace() != RHSCan.getAddressSpace())
2672    return QualType();
2673
2674  Type::TypeClass LHSClass = LHSCan->getTypeClass();
2675  Type::TypeClass RHSClass = RHSCan->getTypeClass();
2676
2677  // We want to consider the two function types to be the same for these
2678  // comparisons, just force one to the other.
2679  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
2680  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
2681
2682  // Same as above for arrays
2683  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
2684    LHSClass = Type::ConstantArray;
2685  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
2686    RHSClass = Type::ConstantArray;
2687
2688  // Canonicalize ExtVector -> Vector.
2689  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
2690  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
2691
2692  // Consider qualified interfaces and interfaces the same.
2693  if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2694  if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
2695
2696  // If the canonical type classes don't match.
2697  if (LHSClass != RHSClass) {
2698    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2699    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2700
2701    // ID acts sort of like void* for ObjC interfaces
2702    if (LHSIface && isObjCIdStructType(RHS))
2703      return LHS;
2704    if (RHSIface && isObjCIdStructType(LHS))
2705      return RHS;
2706
2707    // ID is compatible with all qualified id types.
2708    if (LHS->isObjCQualifiedIdType()) {
2709      if (const PointerType *PT = RHS->getAsPointerType()) {
2710        QualType pType = PT->getPointeeType();
2711        if (isObjCIdStructType(pType))
2712          return LHS;
2713        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2714        // Unfortunately, this API is part of Sema (which we don't have access
2715        // to. Need to refactor. The following check is insufficient, since we
2716        // need to make sure the class implements the protocol.
2717        if (pType->isObjCInterfaceType())
2718          return LHS;
2719      }
2720    }
2721    if (RHS->isObjCQualifiedIdType()) {
2722      if (const PointerType *PT = LHS->getAsPointerType()) {
2723        QualType pType = PT->getPointeeType();
2724        if (isObjCIdStructType(pType))
2725          return RHS;
2726        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2727        // Unfortunately, this API is part of Sema (which we don't have access
2728        // to. Need to refactor. The following check is insufficient, since we
2729        // need to make sure the class implements the protocol.
2730        if (pType->isObjCInterfaceType())
2731          return RHS;
2732      }
2733    }
2734    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2735    // a signed integer type, or an unsigned integer type.
2736    if (const EnumType* ETy = LHS->getAsEnumType()) {
2737      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2738        return RHS;
2739    }
2740    if (const EnumType* ETy = RHS->getAsEnumType()) {
2741      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2742        return LHS;
2743    }
2744
2745    return QualType();
2746  }
2747
2748  // The canonical type classes match.
2749  switch (LHSClass) {
2750#define TYPE(Class, Base)
2751#define ABSTRACT_TYPE(Class, Base)
2752#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2753#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2754#include "clang/AST/TypeNodes.def"
2755    assert(false && "Non-canonical and dependent types shouldn't get here");
2756    return QualType();
2757
2758  case Type::Reference:
2759  case Type::MemberPointer:
2760    assert(false && "C++ should never be in mergeTypes");
2761    return QualType();
2762
2763  case Type::IncompleteArray:
2764  case Type::VariableArray:
2765  case Type::FunctionProto:
2766  case Type::ExtVector:
2767  case Type::ObjCQualifiedInterface:
2768    assert(false && "Types are eliminated above");
2769    return QualType();
2770
2771  case Type::Pointer:
2772  {
2773    // Merge two pointer types, while trying to preserve typedef info
2774    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2775    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2776    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2777    if (ResultType.isNull()) return QualType();
2778    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2779      return LHS;
2780    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2781      return RHS;
2782    return getPointerType(ResultType);
2783  }
2784  case Type::BlockPointer:
2785  {
2786    // Merge two block pointer types, while trying to preserve typedef info
2787    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
2788    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
2789    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2790    if (ResultType.isNull()) return QualType();
2791    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2792      return LHS;
2793    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2794      return RHS;
2795    return getBlockPointerType(ResultType);
2796  }
2797  case Type::ConstantArray:
2798  {
2799    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
2800    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
2801    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
2802      return QualType();
2803
2804    QualType LHSElem = getAsArrayType(LHS)->getElementType();
2805    QualType RHSElem = getAsArrayType(RHS)->getElementType();
2806    QualType ResultType = mergeTypes(LHSElem, RHSElem);
2807    if (ResultType.isNull()) return QualType();
2808    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2809      return LHS;
2810    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2811      return RHS;
2812    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
2813                                          ArrayType::ArraySizeModifier(), 0);
2814    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
2815                                          ArrayType::ArraySizeModifier(), 0);
2816    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
2817    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
2818    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2819      return LHS;
2820    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2821      return RHS;
2822    if (LVAT) {
2823      // FIXME: This isn't correct! But tricky to implement because
2824      // the array's size has to be the size of LHS, but the type
2825      // has to be different.
2826      return LHS;
2827    }
2828    if (RVAT) {
2829      // FIXME: This isn't correct! But tricky to implement because
2830      // the array's size has to be the size of RHS, but the type
2831      // has to be different.
2832      return RHS;
2833    }
2834    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
2835    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
2836    return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
2837  }
2838  case Type::FunctionNoProto:
2839    return mergeFunctionTypes(LHS, RHS);
2840  case Type::Record:
2841  case Type::CXXRecord:
2842  case Type::Enum:
2843    // FIXME: Why are these compatible?
2844    if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
2845    if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
2846    return QualType();
2847  case Type::Builtin:
2848    // Only exactly equal builtin types are compatible, which is tested above.
2849    return QualType();
2850  case Type::Complex:
2851    // Distinct complex types are incompatible.
2852    return QualType();
2853  case Type::Vector:
2854    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
2855      return LHS;
2856    return QualType();
2857  case Type::ObjCInterface: {
2858    // Check if the interfaces are assignment compatible.
2859    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2860    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2861    if (LHSIface && RHSIface &&
2862        canAssignObjCInterfaces(LHSIface, RHSIface))
2863      return LHS;
2864
2865    return QualType();
2866  }
2867  case Type::ObjCQualifiedId:
2868    // Distinct qualified id's are not compatible.
2869    return QualType();
2870  }
2871
2872  return QualType();
2873}
2874
2875//===----------------------------------------------------------------------===//
2876//                         Integer Predicates
2877//===----------------------------------------------------------------------===//
2878
2879unsigned ASTContext::getIntWidth(QualType T) {
2880  if (T == BoolTy)
2881    return 1;
2882  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
2883    return FWIT->getWidth();
2884  }
2885  // For builtin types, just use the standard type sizing method
2886  return (unsigned)getTypeSize(T);
2887}
2888
2889QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
2890  assert(T->isSignedIntegerType() && "Unexpected type");
2891  if (const EnumType* ETy = T->getAsEnumType())
2892    T = ETy->getDecl()->getIntegerType();
2893  const BuiltinType* BTy = T->getAsBuiltinType();
2894  assert (BTy && "Unexpected signed integer type");
2895  switch (BTy->getKind()) {
2896  case BuiltinType::Char_S:
2897  case BuiltinType::SChar:
2898    return UnsignedCharTy;
2899  case BuiltinType::Short:
2900    return UnsignedShortTy;
2901  case BuiltinType::Int:
2902    return UnsignedIntTy;
2903  case BuiltinType::Long:
2904    return UnsignedLongTy;
2905  case BuiltinType::LongLong:
2906    return UnsignedLongLongTy;
2907  default:
2908    assert(0 && "Unexpected signed integer type");
2909    return QualType();
2910  }
2911}
2912
2913
2914//===----------------------------------------------------------------------===//
2915//                         Serialization Support
2916//===----------------------------------------------------------------------===//
2917
2918/// Emit - Serialize an ASTContext object to Bitcode.
2919void ASTContext::Emit(llvm::Serializer& S) const {
2920  S.Emit(LangOpts);
2921  S.EmitRef(SourceMgr);
2922  S.EmitRef(Target);
2923  S.EmitRef(Idents);
2924  S.EmitRef(Selectors);
2925
2926  // Emit the size of the type vector so that we can reserve that size
2927  // when we reconstitute the ASTContext object.
2928  S.EmitInt(Types.size());
2929
2930  for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
2931                                          I!=E;++I)
2932    (*I)->Emit(S);
2933
2934  S.EmitOwnedPtr(TUDecl);
2935
2936  // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
2937}
2938
2939ASTContext* ASTContext::Create(llvm::Deserializer& D) {
2940
2941  // Read the language options.
2942  LangOptions LOpts;
2943  LOpts.Read(D);
2944
2945  SourceManager &SM = D.ReadRef<SourceManager>();
2946  TargetInfo &t = D.ReadRef<TargetInfo>();
2947  IdentifierTable &idents = D.ReadRef<IdentifierTable>();
2948  SelectorTable &sels = D.ReadRef<SelectorTable>();
2949
2950  unsigned size_reserve = D.ReadInt();
2951
2952  ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels,
2953                                 size_reserve);
2954
2955  for (unsigned i = 0; i < size_reserve; ++i)
2956    Type::Create(*A,i,D);
2957
2958  A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
2959
2960  // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
2961
2962  return A;
2963}
2964