ASTContext.cpp revision 71842cc07aafdebc9b180322ebb46f530beca5d6
1f540c54701e3eeb34cb619a3a4eb18f1ac70ef2dJordan Rose//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//
3740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//                     The LLVM Compiler Infrastructure
4740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//
5740d490593e0de8732a697c9f77b90ddd463863bJordan Rose// This file is distributed under the University of Illinois Open Source
6740d490593e0de8732a697c9f77b90ddd463863bJordan Rose// License. See LICENSE.TXT for details.
7740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//
8740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//===----------------------------------------------------------------------===//
9740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//
10740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//  This file implements the ASTContext interface.
11740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//
12740d490593e0de8732a697c9f77b90ddd463863bJordan Rose//===----------------------------------------------------------------------===//
13740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
14740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/ASTContext.h"
15740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/CharUnits.h"
16740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/DeclCXX.h"
17740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/DeclObjC.h"
18740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/DeclTemplate.h"
19740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/TypeLoc.h"
20740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/Expr.h"
21740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/ExternalASTSource.h"
22740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/AST/RecordLayout.h"
23de507eaf3cb54d3cb234dc14499c10ab3373d15fJordan Rose#include "clang/Basic/Builtins.h"
24740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "clang/Basic/SourceManager.h"
25b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose#include "clang/Basic/TargetInfo.h"
26740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "llvm/ADT/SmallString.h"
27740d490593e0de8732a697c9f77b90ddd463863bJordan Rose#include "llvm/ADT/StringExtras.h"
2828038f33aa2db4833881fea757a1f0daf85ac02bJordan Rose#include "llvm/Support/MathExtras.h"
2928038f33aa2db4833881fea757a1f0daf85ac02bJordan Rose#include "llvm/Support/raw_ostream.h"
3028038f33aa2db4833881fea757a1f0daf85ac02bJordan Rose#include "RecordLayoutBuilder.h"
31740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
32740d490593e0de8732a697c9f77b90ddd463863bJordan Roseusing namespace clang;
33740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
34740d490593e0de8732a697c9f77b90ddd463863bJordan Roseenum FloatingRank {
35740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  FloatRank, DoubleRank, LongDoubleRank
36740d490593e0de8732a697c9f77b90ddd463863bJordan Rose};
37740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
38645baeed6800f952e9ad1d5666e01080385531a2Jordan RoseASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
39645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose                       const TargetInfo &t,
408d276d38c258dfc572586daf6c0e8f8fce249c0eJordan Rose                       IdentifierTable &idents, SelectorTable &sels,
41645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose                       Builtin::Context &builtins,
42645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose                       bool FreeMem, unsigned size_reserve) :
43645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
4470cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
45740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
4670cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  SourceMgr(SM), LangOpts(LOpts),
478919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
48740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  Idents(idents), Selectors(sels),
49740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
50972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  ObjCIdRedefinitionType = QualType();
51d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  ObjCClassRedefinitionType = QualType();
52972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  ObjCSelRedefinitionType = QualType();
53d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  if (size_reserve > 0) Types.reserve(size_reserve);
54d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  TUDecl = TranslationUnitDecl::Create(*this);
55d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  InitBuiltinTypes();
56d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose}
57d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
58d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan RoseASTContext::~ASTContext() {
59d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  if (FreeMemory) {
60d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    // Deallocate all the types.
61d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    while (!Types.empty()) {
6257c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose      Types.back()->Destroy(*this);
6357c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose      Types.pop_back();
6457c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose    }
6557c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose
6657c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose    for (llvm::FoldingSet<ExtQuals>::iterator
6757c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose         I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
6857c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose      // Increment in loop to prevent using deallocated memory.
69d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Deallocate(&*I++);
70b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    }
715960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  }
72fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks
735960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
745960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
75fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks    // Increment in loop to prevent using deallocated memory.
765960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks    ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
775960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks    delete R;
785960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  }
795960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks
80fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks  for (llvm::DenseMap<const ObjCContainerDecl*,
815960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks                      const ASTRecordLayout*>::iterator
82fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
83fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks    // Increment in loop to prevent using deallocated memory.
84fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks    ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85fc05decf08feefd2ffe8cc250219aee6eab3119cAnna Zaks    delete R;
865960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  }
875960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks
885960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  // Destroy nested-name-specifiers.
89e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks         NNS = NestedNameSpecifiers.begin(),
91740d490593e0de8732a697c9f77b90ddd463863bJordan Rose         NNSEnd = NestedNameSpecifiers.end();
92740d490593e0de8732a697c9f77b90ddd463863bJordan Rose       NNS != NNSEnd; ) {
93972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    // Increment in loop to prevent using deallocated memory.
94972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    (*NNS++).Destroy(*this);
95972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
96972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
97972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (GlobalNestedNameSpecifier)
98972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    GlobalNestedNameSpecifier->Destroy(*this);
99972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
100740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  TUDecl->Destroy(*this);
101740d490593e0de8732a697c9f77b90ddd463863bJordan Rose}
102740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
103740d490593e0de8732a697c9f77b90ddd463863bJordan Rosevoid
104b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan RoseASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
1057c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  ExternalSource.reset(Source.take());
1067c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose}
107b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
108b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rosevoid ASTContext::PrintStats() const {
109972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  fprintf(stderr, "*** AST Context Stats:\n");
1107c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  fprintf(stderr, "  %d types total.\n", (int)Types.size());
1117c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
112740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  unsigned counts[] = {
113b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose#define TYPE(Name, Parent) 0,
114b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose#define ABSTRACT_TYPE(Name, Parent)
115972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose#include "clang/AST/TypeNodes.def"
116972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    0 // Extra
117972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  };
118972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
119b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    Type *T = Types[i];
121972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    counts[(unsigned)T->getTypeClass()]++;
122972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
123972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
124972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  unsigned Idx = 0;
125972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  unsigned TotalBytes = 0;
126972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose#define TYPE(Name, Parent)                                              \
127972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (counts[Idx])                                                      \
128972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
129d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
130d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  ++Idx;
1317c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose#define ABSTRACT_TYPE(Name, Parent)
132972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose#include "clang/AST/TypeNodes.def"
133b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
1347c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
135972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
136972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (ExternalSource.get()) {
137972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    fprintf(stderr, "\n");
138972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    ExternalSource->PrintStats();
139972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
140972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose}
141b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
142d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
1437c99aa385178c630e29f671299cdd9c104f1c885Jordan Rosevoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1447c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
145b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
146b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  Types.push_back(Ty);
147b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose}
1487c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
149b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rosevoid ASTContext::InitBuiltinTypes() {
150740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  assert(VoidTy.isNull() && "Context reinitialized?");
151740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
152972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  // C99 6.2.5p19.
153972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  InitBuiltinType(VoidTy,              BuiltinType::Void);
154972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
155740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // C99 6.2.5p2.
156740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(BoolTy,              BuiltinType::Bool);
157b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  // C99 6.2.5p3.
158740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (LangOpts.CharIsSigned)
159740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    InitBuiltinType(CharTy,            BuiltinType::Char_S);
160972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  else
161740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    InitBuiltinType(CharTy,            BuiltinType::Char_U);
162740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // C99 6.2.5p4.
163740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
164740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(ShortTy,             BuiltinType::Short);
1657c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(IntTy,               BuiltinType::Int);
166740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(LongTy,              BuiltinType::Long);
1677c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
168740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
169740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // C99 6.2.5p6.
1707c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1717c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
172b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1737c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
174b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
175740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
176740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // C99 6.2.5p10.
1777c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(FloatTy,             BuiltinType::Float);
1787c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(DoubleTy,            BuiltinType::Double);
1797c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
180740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
181ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose  // GNU extension, 128-bit integers.
1825960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
183e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
184ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose
185740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    InitBuiltinType(WCharTy,           BuiltinType::WChar);
187b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  else // C99
188b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    WCharTy = getFromTargetType(Target.getWCharType());
189b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
190740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
192740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  else // C99
193740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    Char16Ty = getFromTargetType(Target.getChar16Type());
194740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
195740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1967c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
197740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  else // C99
198740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    Char32Ty = getFromTargetType(Target.getChar32Type());
199740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
200740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // Placeholder type for functions.
201740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
202740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
203740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // Placeholder type for type-dependent expressions whose type is
204740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // completely unknown. No code should ever check a type against
205740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // DependentTy and users should never see it; however, it is here to
206740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // help diagnose failures to properly check for type-dependent
207b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  // expressions.
208740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
209740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
210740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // Placeholder type for C++0x auto declarations whose real type has
211740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // not yet been deduced.
212740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
213740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
214740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // C99 6.2.5p11.
215740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  FloatComplexTy      = getComplexType(FloatTy);
216740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  DoubleComplexTy     = getComplexType(DoubleTy);
217740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  LongDoubleComplexTy = getComplexType(LongDoubleTy);
218740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
219de507eaf3cb54d3cb234dc14499c10ab3373d15fJordan Rose  BuiltinVaListType = QualType();
220de507eaf3cb54d3cb234dc14499c10ab3373d15fJordan Rose
2217c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
2227c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  ObjCIdTypedefType = QualType();
2237c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  ObjCClassTypedefType = QualType();
224de507eaf3cb54d3cb234dc14499c10ab3373d15fJordan Rose  ObjCSelTypedefType = QualType();
225740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
2267c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  // Builtin types for 'id', 'Class', and 'SEL'.
227740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
229740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
2307c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
231740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  ObjCConstantStringType = QualType();
232740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
2337c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  // void * type
234740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  VoidPtrTy = getPointerType(VoidTy);
2357c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
236740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // nullptr type (C++0x 2.14.7)
237740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
238740d490593e0de8732a697c9f77b90ddd463863bJordan Rose}
239740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
240740d490593e0de8732a697c9f77b90ddd463863bJordan RoseMemberSpecializationInfo *
241740d490593e0de8732a697c9f77b90ddd463863bJordan RoseASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
242740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  assert(Var->isStaticDataMember() && "Not a static data member");
24385d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
24485d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose    = InstantiatedFromStaticDataMember.find(Var);
24585d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose  if (Pos == InstantiatedFromStaticDataMember.end())
24685d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose    return 0;
24785d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose
2487c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  return Pos->second;
2497c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose}
2507c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
25185d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rosevoid
25228038f33aa2db4833881fea757a1f0daf85ac02bJordan RoseASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
2538d276d38c258dfc572586daf6c0e8f8fce249c0eJordan Rose                                                TemplateSpecializationKind TSK) {
25428038f33aa2db4833881fea757a1f0daf85ac02bJordan Rose  assert(Inst->isStaticDataMember() && "Not a static data member");
25528038f33aa2db4833881fea757a1f0daf85ac02bJordan Rose  assert(Tmpl->isStaticDataMember() && "Not a static data member");
256740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  assert(!InstantiatedFromStaticDataMember[Inst] &&
257740d490593e0de8732a697c9f77b90ddd463863bJordan Rose         "Already noted what static data member was instantiated from");
258740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  InstantiatedFromStaticDataMember[Inst]
259740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
260740d490593e0de8732a697c9f77b90ddd463863bJordan Rose}
261740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
262740d490593e0de8732a697c9f77b90ddd463863bJordan RoseNamedDecl *
263ef15831780b705475e7b237ac16418e9b53cb7a6Jordan RoseASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
264ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
265ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    = InstantiatedFromUsingDecl.find(UUD);
266ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  if (Pos == InstantiatedFromUsingDecl.end())
267ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    return 0;
268ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose
269ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  return Pos->second;
270ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose}
271972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
272972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rosevoid
273d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan RoseASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
274972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  assert((isa<UsingDecl>(Pattern) ||
275972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose          isa<UnresolvedUsingValueDecl>(Pattern) ||
276d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose         "pattern decl is not a using decl");
278972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  InstantiatedFromUsingDecl[Inst] = Pattern;
28085d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose}
28185d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose
2827c99aa385178c630e29f671299cdd9c104f1c885Jordan RoseUsingShadowDecl *
2837c99aa385178c630e29f671299cdd9c104f1c885Jordan RoseASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
2847c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
28585d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose    = InstantiatedFromUsingShadowDecl.find(Inst);
28685d7e01cf639b257d70f8a129709a2d7594d7b22Jordan Rose  if (Pos == InstantiatedFromUsingShadowDecl.end())
287e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    return 0;
288740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
289740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  return Pos->second;
290740d490593e0de8732a697c9f77b90ddd463863bJordan Rose}
291740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
292e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rosevoid
293e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan RoseASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose                                               UsingShadowDecl *Pattern) {
295e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
296e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
297e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose}
298e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose
299e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan RoseFieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    = InstantiatedFromUnnamedFieldDecl.find(Field);
302e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    return 0;
304e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose
305e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  return Pos->second;
306e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose}
307e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose
308ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rosevoid ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose                                                     FieldDecl *Tmpl) {
310ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
311e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313740d490593e0de8732a697c9f77b90ddd463863bJordan Rose         "Already noted what unnamed field was instantiated from");
314740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
315e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose}
317e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose
318e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rosenamespace {
319e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  class BeforeInTranslationUnit
320740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    : std::binary_function<SourceRange, SourceRange, bool> {
321740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    SourceManager *SourceMgr;
322740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
323740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  public:
324e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
325740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
326740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    bool operator()(SourceRange X, SourceRange Y) {
327740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    }
3290ffbfd1a7f80f9a3c07317cb8f44c562f2ba1ba5Jordan Rose  };
330b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose}
3310ffbfd1a7f80f9a3c07317cb8f44c562f2ba1ba5Jordan Rose
3320ffbfd1a7f80f9a3c07317cb8f44c562f2ba1ba5Jordan Rose/// \brief Determine whether the given comment is a Doxygen-style comment.
333740d490593e0de8732a697c9f77b90ddd463863bJordan Rose///
334740d490593e0de8732a697c9f77b90ddd463863bJordan Rose/// \param Start the start of the comment text.
335740d490593e0de8732a697c9f77b90ddd463863bJordan Rose///
336b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose/// \param End the end of the comment text.
337740d490593e0de8732a697c9f77b90ddd463863bJordan Rose///
338740d490593e0de8732a697c9f77b90ddd463863bJordan Rose/// \param Member whether we want to check whether this is a member comment
339740d490593e0de8732a697c9f77b90ddd463863bJordan Rose/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
340740d490593e0de8732a697c9f77b90ddd463863bJordan Rose/// we only return true when we find a non-member comment.
341b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rosestatic bool
3427c99aa385178c630e29f671299cdd9c104f1c885Jordan RoseisDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
3437c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose                 bool Member = false) {
344b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  const char *BufferStart
3457c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
3467c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
347972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
348740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
3497c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  if (End - Start < 4)
350740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    return false;
351740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
352b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  assert(Start[0] == '/' && "Not a comment?");
353b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
3547c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    return false;
3557c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
356b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    return false;
357740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
358e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks  return (Start[3] == '<') == Member;
359ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose}
360ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose
361ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose/// \brief Retrieve the comment associated with the given declaration, if
3625960f4aeac9760198c80e05d70d8dadb1db0ff0eAnna Zaks/// it has one.
363e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaksconst char *ASTContext::getCommentForDecl(const Decl *D) {
364ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose  if (!D)
365ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose    return 0;
3667c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
367b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  // Check whether we have cached a comment string for this declaration
368ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  // already.
369ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  llvm::DenseMap<const Decl *, std::string>::iterator Pos
370ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    = DeclComments.find(D);
371ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  if (Pos != DeclComments.end())
372ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    return Pos->second.c_str();
373b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
374740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // If we have an external AST source and have not yet loaded comments from
375740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // that source, do so now.
376740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (ExternalSource && !LoadedExternalComments) {
377740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    std::vector<SourceRange> LoadedComments;
378740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    ExternalSource->ReadComments(LoadedComments);
379740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
380645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    if (!LoadedComments.empty())
381740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Comments.insert(Comments.begin(), LoadedComments.begin(),
382740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                      LoadedComments.end());
383b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
3847c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    LoadedExternalComments = true;
385972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
386972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
387740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // If there are no comments anywhere, we won't find anything.
388740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (Comments.empty())
3897c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    return 0;
390b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
391b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  // If the declaration doesn't map directly to a location in a file, we
392740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // can't find the comment.
3937c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  SourceLocation DeclStartLoc = D->getLocStart();
394740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
3957c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    return 0;
3967c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
3977c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  // Find the comment that occurs just before this declaration.
398b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  std::vector<SourceRange>::iterator LastComment
399740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    = std::lower_bound(Comments.begin(), Comments.end(),
400740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                       SourceRange(DeclStartLoc),
401740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                       BeforeInTranslationUnit(&SourceMgr));
402740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
403740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // Decompose the location for the start of the declaration and find the
404740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // beginning of the file buffer.
405740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  std::pair<FileID, unsigned> DeclStartDecomp
406740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    = SourceMgr.getDecomposedLoc(DeclStartLoc);
407740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  const char *FileBufferStart
408740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
409740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
410740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  // First check whether we have a comment for a member.
411d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  if (LastComment != Comments.end() &&
412972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
413d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      isDoxygenComment(SourceMgr, *LastComment, true)) {
414740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    std::pair<FileID, unsigned> LastCommentEndDecomp
415740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
4167c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417740d490593e0de8732a697c9f77b90ddd463863bJordan Rose        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
418d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
419d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                                     LastCommentEndDecomp.second)) {
420d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      // The Doxygen member comment comes after the declaration starts and
421d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      // is on the same line and in the same file as the declaration. This
4227c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      // is the comment we want.
423b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      std::string &Result = DeclComments[D];
424740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Result.append(FileBufferStart +
425740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                      SourceMgr.getFileOffset(LastComment->getBegin()),
426740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                    FileBufferStart + LastCommentEndDecomp.second + 1);
427740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      return Result.c_str();
428740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    }
429645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  }
430645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
431645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (LastComment == Comments.begin())
432645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    return 0;
433645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  --LastComment;
434645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
435645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // Decompose the end of the comment.
436645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  std::pair<FileID, unsigned> LastCommentEndDecomp
437645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
438645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
439645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // If the comment and the declaration aren't in the same file, then they
440645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // aren't related.
441645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
442645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    return 0;
443645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
444645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // Check that we actually have a Doxygen comment.
445645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (!isDoxygenComment(SourceMgr, *LastComment))
446645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    return 0;
447645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
448645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // Compute the starting line for the declaration and for the end of the
449645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // comment (this is expensive).
450645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  unsigned DeclStartLine
451645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
452645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  unsigned CommentEndLine
453645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
454645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose                              LastCommentEndDecomp.second);
455645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
456645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // If the comment does not end on the line prior to the declaration, then
457645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // the comment is not associated with the declaration at all.
458645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (CommentEndLine + 1 != DeclStartLine)
459645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    return 0;
460645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
461645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // We have a comment, but there may be more comments on the previous lines.
462645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // Keep looking so long as the comments are still Doxygen comments and are
463645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // still adjacent.
464645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  unsigned ExpectedLine
465645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
466645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  std::vector<SourceRange>::iterator FirstComment = LastComment;
467645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  while (FirstComment != Comments.begin()) {
468645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // Look at the previous comment
469645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    --FirstComment;
470645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    std::pair<FileID, unsigned> Decomp
471645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
472645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
473645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // If this previous comment is in a different file, we're done.
474645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    if (Decomp.first != DeclStartDecomp.first) {
475645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      ++FirstComment;
476645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      break;
477645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    }
478645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
479645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // If this comment is not a Doxygen comment, we're done.
480645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
481c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose      ++FirstComment;
482c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose      break;
483645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    }
484740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
4857c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    // If the line number is not what we expected, we're done.
486740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
487c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose    if (Line != ExpectedLine) {
4887c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      ++FirstComment;
489645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      break;
490645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    }
491645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
492645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // Set the next expected line number.
493645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    ExpectedLine
494c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
495645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  }
496972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
497c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose  // The iterator range [FirstComment, LastComment] contains all of the
4989da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose  // BCPL comments that, together, are associated with this declaration.
499645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  // Form a single comment block string for this declaration that concatenates
5009da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose  // all of these comments.
501ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  std::string &Result = DeclComments[D];
502645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  while (FirstComment != LastComment) {
5039da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose    std::pair<FileID, unsigned> DecompStart
5049da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
5059da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose    std::pair<FileID, unsigned> DecompEnd
5069da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
5079da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose    Result.append(FileBufferStart + DecompStart.second,
5089da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose                  FileBufferStart + DecompEnd.second + 1);
509ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    ++FirstComment;
510645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  }
511645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
512e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks  // Append the last comment line.
513c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose  Result.append(FileBufferStart +
514ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose                  SourceMgr.getFileOffset(LastComment->getBegin()),
515ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose                FileBufferStart + LastCommentEndDecomp.second + 1);
516ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose  return Result.c_str();
517c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose}
518c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose
519c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose//===----------------------------------------------------------------------===//
520c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose//                         Type Sizing and Analysis
521c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose//===----------------------------------------------------------------------===//
522c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose
523c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
524c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose/// scalar floating point type.
525c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Roseconst llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
526c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose  const BuiltinType *BT = T->getAs<BuiltinType>();
527d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  assert(BT && "Not a floating point type!");
528972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  switch (BT->getKind()) {
529d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  default: assert(0 && "Not a floating point type!");
530740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  case BuiltinType::Float:      return Target.getFloatFormat();
531c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose  case BuiltinType::Double:     return Target.getDoubleFormat();
5327c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
533740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  }
534d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose}
535d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
536d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
537d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// specified decl.  Note that bitfields do not have a valid alignment, so
5387c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose/// this method will assert on them.
539645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose/// If @p RefAsPointee, references are treated like their underlying type
540645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose/// (for alignof), else they're treated like pointers (for CodeGen).
541645baeed6800f952e9ad1d5666e01080385531a2Jordan Roseunsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
542645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  unsigned Align = Target.getCharWidth();
543645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
544645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
545645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    Align = std::max(Align, AA->getMaxAlignment());
546645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
547645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
548645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    QualType T = VD->getType();
549645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
550740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      if (RefAsPointee)
551740d490593e0de8732a697c9f77b90ddd463863bJordan Rose        T = RT->getPointeeType();
5529da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose      else
5537c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose        T = getPointerType(RT->getPointeeType());
5547c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    }
555e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    if (!T->isIncompleteType() && !T->isFunctionType()) {
556740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      // Incomplete or function types default to 1.
557740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558740d490593e0de8732a697c9f77b90ddd463863bJordan Rose        T = cast<ArrayType>(T)->getElementType();
559740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
560740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    }
562fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose  }
563fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose
564fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose  return Align / Target.getCharWidth();
565c36b30c92c78b95fd29fb5d9d6214d737b3bcb02Jordan Rose}
566d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
567d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// getTypeSize - Return the size of the specified type, in bits.  This method
568972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose/// does not work on incomplete types.
569d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose///
570d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// FIXME: Pointers into different addr spaces could have different sizes and
571d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// alignment requirements: getPointerInfo should take an AddrSpace, this
572d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// should take a QualType, &c.
573972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rosestd::pair<uint64_t, unsigned>
574972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan RoseASTContext::getTypeInfo(const Type *T) {
575972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  uint64_t Width=0;
576972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  unsigned Align=8;
577972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  switch (T->getTypeClass()) {
578972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose#define TYPE(Class, Base)
579fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose#define ABSTRACT_TYPE(Class, Base)
5807c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose#define NON_CANONICAL_TYPE(Class, Base)
581645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose#define DEPENDENT_TYPE(Class, Base) case Type::Class:
582fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose#include "clang/AST/TypeNodes.def"
583fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    assert(false && "Should not see dependent types");
5847c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    break;
5857c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
5867c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::FunctionNoProto:
5877c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::FunctionProto:
588fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    // GCC extension: alignof(function) = 32 bits
589fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    Width = 0;
590fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    Align = 32;
5919da59a67a27a4d3fc9d59552f07808a32f85e9d3Jordan Rose    break;
5927c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
5937c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::IncompleteArray:
594e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose  case Type::VariableArray:
595fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    Width = 0;
596fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
597fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose    break;
598fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose
599fdaa33818cf9bad8d092136e73bd2e489cb821baJordan Rose  case Type::ConstantArray: {
600645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
601740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
602645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
603645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    Width = EltInfo.first*CAT->getSize().getZExtValue();
604645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    Align = EltInfo.second;
605d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    break;
606d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
607740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  case Type::ExtVector:
608645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  case Type::Vector: {
60969f87c956b3ac2b80124fd9604af012e1061473aJordan Rose    const VectorType *VT = cast<VectorType>(T);
610645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
611645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    Width = EltInfo.first*VT->getNumElements();
612645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    Align = Width;
613645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // If the alignment is not a power of 2, round up to the next power of 2.
614645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    // This happens for non-power-of-2 length vectors.
615645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    if (VT->getNumElements() & (VT->getNumElements()-1)) {
616645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Align = llvm::NextPowerOf2(Align);
617645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Width = llvm::RoundUpToAlignment(Width, Align);
618645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    }
619645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    break;
620645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose  }
621740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
622740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  case Type::Builtin:
623645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    switch (cast<BuiltinType>(T)->getKind()) {
624645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    default: assert(0 && "Unknown builtin type!");
625ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose    case BuiltinType::Void:
626645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      // GCC extension: alignof(void) = 8 bits.
627645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Width = 0;
628645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Align = 8;
629ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose      break;
630645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose
631645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    case BuiltinType::Bool:
632b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Width = Target.getBoolWidth();
633645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Align = Target.getBoolAlign();
634b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      break;
635740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::Char_S:
636645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose    case BuiltinType::Char_U:
637740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::UChar:
638740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::SChar:
639740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Width = Target.getCharWidth();
640740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Align = Target.getCharAlign();
641740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      break;
642740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::WChar:
643740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Width = Target.getWCharWidth();
644d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Align = Target.getWCharAlign();
645b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      break;
646d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    case BuiltinType::Char16:
647d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Width = Target.getChar16Width();
648d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Align = Target.getChar16Align();
649d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      break;
650d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    case BuiltinType::Char32:
651d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Width = Target.getChar32Width();
652d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Align = Target.getChar32Align();
653d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      break;
654b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    case BuiltinType::UShort:
655740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::Short:
6567c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      Width = Target.getShortWidth();
657b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Align = Target.getShortAlign();
658b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      break;
659740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::UInt:
660d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    case BuiltinType::Int:
661d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Width = Target.getIntWidth();
662d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Align = Target.getIntAlign();
663d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      break;
664d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    case BuiltinType::ULong:
665d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    case BuiltinType::Long:
6667c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      Width = Target.getLongWidth();
667b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Align = Target.getLongAlign();
668b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      break;
669b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    case BuiltinType::ULongLong:
6707c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    case BuiltinType::LongLong:
671b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Width = Target.getLongLongWidth();
672740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Align = Target.getLongLongAlign();
673740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      break;
6747c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    case BuiltinType::Int128:
675740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::UInt128:
6767c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      Width = 128;
677b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Align = 128; // int128_t is 128-bit aligned on all targets.
678740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      break;
679740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::Float:
680ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose      Width = Target.getFloatWidth();
681645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose      Align = Target.getFloatAlign();
6827c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      break;
683ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose    case BuiltinType::Double:
684ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose      Width = Target.getDoubleWidth();
685ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose      Align = Target.getDoubleAlign();
6867c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose      break;
687e54cfc7b9990acffd0a8a4ba381717b4bb9f3011Jordan Rose    case BuiltinType::LongDouble:
688740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Width = Target.getLongDoubleWidth();
689740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Align = Target.getLongDoubleAlign();
690740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      break;
691740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    case BuiltinType::NullPtr:
692740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
6930e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose      Align = Target.getPointerAlign(0); //   == sizeof(void*)
6940e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose      break;
6950e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose    }
69670cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    break;
697d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  case Type::ObjCObjectPointer:
698972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    Width = Target.getPointerWidth(0);
699d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    Align = Target.getPointerAlign(0);
700b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    break;
70170cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  case Type::BlockPointer: {
7027c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
70370cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    Width = Target.getPointerWidth(AS);
704d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    Align = Target.getPointerAlign(AS);
705d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    break;
706d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
707d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  case Type::LValueReference:
7087c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::RValueReference: {
709b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    // alignof and sizeof should never enter this code path here, so we go
710b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    // the pointer route.
711b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
7127c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    Width = Target.getPointerWidth(AS);
713b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    Align = Target.getPointerAlign(AS);
71470cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    break;
71570cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  }
7167c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::Pointer: {
717b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
718b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    Width = Target.getPointerWidth(AS);
71970cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    Align = Target.getPointerAlign(AS);
7207c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    break;
72170cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  }
72270cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  case Type::MemberPointer: {
72370cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
724b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    std::pair<uint64_t, unsigned> PtrDiffInfo =
72570cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose      getTypeInfo(getPointerDiffType());
72670cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    Width = PtrDiffInfo.first;
7277c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    if (Pointee->isFunctionType())
728b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Width *= 2;
72970cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    Align = PtrDiffInfo.second;
73070cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    break;
73170cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  }
73270cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose  case Type::Complex: {
73370cbf3cc09eb21db1108396d30a414ea66d842ccJordan Rose    // Complex types have the same alignment as their elements, but twice the
7348919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    // size.
7358919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    std::pair<uint64_t, unsigned> EltInfo =
7368919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose      getTypeInfo(cast<ComplexType>(T)->getElementType());
7378919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    Width = EltInfo.first*2;
7388919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    Align = EltInfo.second;
7398919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    break;
7408919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  }
7418919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  case Type::ObjCInterface: {
7428919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
7438919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
744cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose    Width = Layout.getSize();
7458919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    Align = Layout.getAlignment();
7468919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    break;
747cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose  }
748d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  case Type::Record:
749d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  case Type::Enum: {
7508919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    const TagType *TT = cast<TagType>(T);
751cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose
7528919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    if (TT->getDecl()->isInvalidDecl()) {
753d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Width = 1;
754d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Align = 1;
755d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      break;
756d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    }
757d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
758d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    if (const EnumType *ET = dyn_cast<EnumType>(TT))
759972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      return getTypeInfo(ET->getDecl()->getIntegerType());
760972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
761972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    const RecordType *RT = cast<RecordType>(TT);
7627c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
763740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    Width = Layout.getSize();
7647c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    Align = Layout.getAlignment();
765740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    break;
7663f558af01643787d209a133215b0abec81b5fe30Anna Zaks  }
7673f558af01643787d209a133215b0abec81b5fe30Anna Zaks
7683f558af01643787d209a133215b0abec81b5fe30Anna Zaks  case Type::SubstTemplateTypeParm:
7693f558af01643787d209a133215b0abec81b5fe30Anna Zaks    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
770740d490593e0de8732a697c9f77b90ddd463863bJordan Rose                       getReplacementType().getTypePtr());
7717c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
7728919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  case Type::Elaborated:
773cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose    return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
7747c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose                         .getTypePtr());
775b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose
776b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  case Type::Typedef: {
7777c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
778b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
779b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Align = std::max(Aligned->getMaxAlignment(),
7807c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose                       getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
781b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
782b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    } else
783740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
7848919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    break;
7858919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  }
7868919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose
7878919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  case Type::TypeOfExpr:
7888919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
7898919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose                         .getTypePtr());
7908919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose
7918919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  case Type::TypeOf:
7928919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
7938919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose
7947c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose  case Type::Decltype:
7958919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
7960e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose                        .getTypePtr());
797740d490593e0de8732a697c9f77b90ddd463863bJordan Rose
798740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  case Type::QualifiedName:
7990e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
8000e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose
8010e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose  case Type::TemplateSpecialization:
8020e020adcb69e91826f4ee14a0c1d381f7b624a34Jordan Rose    assert(getCanonicalType(T) != T &&
803cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose           "Cannot request the size of a dependent type");
804b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose    // FIXME: this is likely to be wrong once we support template
805cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose    // aliases, since a template alias could refer to a typedef that
806cde8cdbd6a662c636164465ad309b5f17ff01064Jordan Rose    // has an __aligned__ attribute on it.
8078919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose    return getTypeInfo(getCanonicalType(T));
8088919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  }
8098919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose
8108919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
8118919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  return std::make_pair(Width, Align);
8128919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose}
8138919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose
8148919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose/// getTypeSizeInChars - Return the size of the specified type, in characters.
8158919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose/// This method does not work on incomplete types.
8168919e688dc610d1f632a4d43f7f1489f67255476Jordan RoseCharUnits ASTContext::getTypeSizeInChars(QualType T) {
8178919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
8188919e688dc610d1f632a4d43f7f1489f67255476Jordan Rose}
819740d490593e0de8732a697c9f77b90ddd463863bJordan RoseCharUnits ASTContext::getTypeSizeInChars(const Type *T) {
820740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
821e90d3f847dcce76237078b67db8895eb7a24189eAnna Zaks}
822ee158bc29bc12ce544996f7cdfde14aba63acf4dJordan Rose
823ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
824ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose/// type for the current target in bits.  This can be different than the ABI
825ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose/// alignment in cases where it is beneficial for performance to overalign
826ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Rose/// a data type.
827ef15831780b705475e7b237ac16418e9b53cb7a6Jordan Roseunsigned ASTContext::getPreferredTypeAlign(const Type *T) {
828b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  unsigned ABIAlign = getTypeAlign(T);
8297c99aa385178c630e29f671299cdd9c104f1c885Jordan Rose
830b7a23e05d1d8f07f2a6edce5c88c728fe894c2c7Jordan Rose  // Double and long long should be naturally aligned if possible.
831740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (const ComplexType* CT = T->getAs<ComplexType>())
832740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    T = CT->getElementType().getTypePtr();
833740d490593e0de8732a697c9f77b90ddd463863bJordan Rose  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
834740d490593e0de8732a697c9f77b90ddd463863bJordan Rose      T->isSpecificBuiltinType(BuiltinType::LongLong))
835740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    return std::max(ABIAlign, (unsigned)getTypeSize(T));
836972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
837972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  return ABIAlign;
838972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose}
839972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
840972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rosestatic void CollectLocalObjCIvars(ASTContext *Ctx,
841972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose                                  const ObjCInterfaceDecl *OI,
842972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
843972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
844972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose       E = OI->ivar_end(); I != E; ++I) {
845972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    ObjCIvarDecl *IVDecl = *I;
846972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    if (!IVDecl->isInvalidDecl())
847972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      Fields.push_back(cast<FieldDecl>(IVDecl));
848d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
849972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose}
850972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
851972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rosevoid ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
852972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
853972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
854972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    CollectObjCIvars(SuperClass, Fields);
855972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  CollectLocalObjCIvars(this, OI, Fields);
856972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose}
857972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
858972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose/// ShallowCollectObjCIvars -
859972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose/// Collect all ivars, including those synthesized, in the current class.
860972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose///
861972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rosevoid ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
862d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
863d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                                 bool CollectSynthesized) {
864d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
865d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose         E = OI->ivar_end(); I != E; ++I) {
866d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose     Ivars.push_back(*I);
867d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
868d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  if (CollectSynthesized)
869d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    CollectSynthesizedIvars(OI, Ivars);
870d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose}
871d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
872d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rosevoid ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
873d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
874d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
875d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose       E = PD->prop_end(); I != E; ++I)
876d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
877d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Ivars.push_back(Ivar);
878972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
879972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  // Also look into nested protocols.
880d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
88157c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose       E = PD->protocol_end(); P != E; ++P)
88257c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose    CollectProtocolSynthesizedIvars(*P, Ivars);
88357c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose}
88457c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose
88557c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose/// CollectSynthesizedIvars -
886645baeed6800f952e9ad1d5666e01080385531a2Jordan Rose/// This routine collect synthesized ivars for the designated class.
887d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose///
888d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rosevoid ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
889d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
890d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
891d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose       E = OI->prop_end(); I != E; ++I) {
892d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
893d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Ivars.push_back(Ivar);
894d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
895d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  // Also look into interface's protocol list for properties declared
896d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  // in the protocol and whose ivars are synthesized.
897d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
898d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose       PE = OI->protocol_end(); P != PE; ++P) {
899d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    ObjCProtocolDecl *PD = (*P);
900d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    CollectProtocolSynthesizedIvars(PD, Ivars);
901d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  }
902d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose}
903d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose
904d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// CollectInheritedProtocols - Collect all protocols in current class and
905d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose/// those inherited by it.
906d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rosevoid ASTContext::CollectInheritedProtocols(const Decl *CDecl,
907d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose                          llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
908d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
909d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
910d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose         PE = OI->protocol_end(); P != PE; ++P) {
911d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      ObjCProtocolDecl *Proto = (*P);
912d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      Protocols.push_back(Proto);
913d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
914972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose           PE = Proto->protocol_end(); P != PE; ++P)
915972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose        CollectInheritedProtocols(*P, Protocols);
916972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      }
917972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose
918d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    // Categories of this Interface.
919972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
920972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
921972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      CollectInheritedProtocols(CDeclChain, Protocols);
922d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
923d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose      while (SD) {
924d563d3fb73879df7147b8a5302c3bf0e1402ba18Jordan Rose        CollectInheritedProtocols(SD, Protocols);
925972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose        SD = SD->getSuperClass();
926972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      }
927972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    return;
928972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
929972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
930972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
931972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose         PE = OC->protocol_end(); P != PE; ++P) {
932972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      ObjCProtocolDecl *Proto = (*P);
933972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      Protocols.push_back(Proto);
934972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
935972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose           PE = Proto->protocol_end(); P != PE; ++P)
936972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose        CollectInheritedProtocols(*P, Protocols);
937972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    }
938972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    return;
939972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  }
940972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose  if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
941972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
942972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose         PE = OP->protocol_end(); P != PE; ++P) {
943972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      ObjCProtocolDecl *Proto = (*P);
944972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      Protocols.push_back(Proto);
945972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
946972a3680bdd95f2e9d6316b391f1c47513dc78ccJordan Rose           PE = Proto->protocol_end(); P != PE; ++P)
947740d490593e0de8732a697c9f77b90ddd463863bJordan Rose        CollectInheritedProtocols(*P, Protocols);
948740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    }
949740d490593e0de8732a697c9f77b90ddd463863bJordan Rose    return;
95057c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose  }
95157c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose}
95257c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose
95357c033621dacd8720ac9ff65a09025f14f70e22fJordan Roseunsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
95457c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose  unsigned count = 0;
95557c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
95657c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose       E = PD->prop_end(); I != E; ++I)
95757c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose    if ((*I)->getPropertyIvarDecl())
95857c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose      ++count;
95957c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose
96057c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose  // Also look into nested protocols.
96157c033621dacd8720ac9ff65a09025f14f70e22fJordan Rose  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
962740d490593e0de8732a697c9f77b90ddd463863bJordan Rose       E = PD->protocol_end(); P != E; ++P)
963    count += CountProtocolSynthesizedIvars(*P);
964  return count;
965}
966
967unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
968  unsigned count = 0;
969  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
970       E = OI->prop_end(); I != E; ++I) {
971    if ((*I)->getPropertyIvarDecl())
972      ++count;
973  }
974  // Also look into interface's protocol list for properties declared
975  // in the protocol and whose ivars are synthesized.
976  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
977       PE = OI->protocol_end(); P != PE; ++P) {
978    ObjCProtocolDecl *PD = (*P);
979    count += CountProtocolSynthesizedIvars(PD);
980  }
981  return count;
982}
983
984/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
985ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
986  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
987    I = ObjCImpls.find(D);
988  if (I != ObjCImpls.end())
989    return cast<ObjCImplementationDecl>(I->second);
990  return 0;
991}
992/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
993ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
994  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
995    I = ObjCImpls.find(D);
996  if (I != ObjCImpls.end())
997    return cast<ObjCCategoryImplDecl>(I->second);
998  return 0;
999}
1000
1001/// \brief Set the implementation of ObjCInterfaceDecl.
1002void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1003                           ObjCImplementationDecl *ImplD) {
1004  assert(IFaceD && ImplD && "Passed null params");
1005  ObjCImpls[IFaceD] = ImplD;
1006}
1007/// \brief Set the implementation of ObjCCategoryDecl.
1008void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1009                           ObjCCategoryImplDecl *ImplD) {
1010  assert(CatD && ImplD && "Passed null params");
1011  ObjCImpls[CatD] = ImplD;
1012}
1013
1014/// \brief Allocate an uninitialized TypeSourceInfo.
1015///
1016/// The caller should initialize the memory held by TypeSourceInfo using
1017/// the TypeLoc wrappers.
1018///
1019/// \param T the type that will be the basis for type source info. This type
1020/// should refer to how the declarator was written in source code, not to
1021/// what type semantic analysis resolved the declarator to.
1022TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1023                                                 unsigned DataSize) {
1024  if (!DataSize)
1025    DataSize = TypeLoc::getFullDataSizeForType(T);
1026  else
1027    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1028           "incorrect data size provided to CreateTypeSourceInfo!");
1029
1030  TypeSourceInfo *TInfo =
1031    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1032  new (TInfo) TypeSourceInfo(T);
1033  return TInfo;
1034}
1035
1036TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1037                                                     SourceLocation L) {
1038  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1039  DI->getTypeLoc().initialize(L);
1040  return DI;
1041}
1042
1043/// getInterfaceLayoutImpl - Get or compute information about the
1044/// layout of the given interface.
1045///
1046/// \param Impl - If given, also include the layout of the interface's
1047/// implementation. This may differ by including synthesized ivars.
1048const ASTRecordLayout &
1049ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1050                          const ObjCImplementationDecl *Impl) {
1051  assert(!D->isForwardDecl() && "Invalid interface decl!");
1052
1053  // Look up this layout, if already laid out, return what we have.
1054  ObjCContainerDecl *Key =
1055    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1056  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1057    return *Entry;
1058
1059  // Add in synthesized ivar count if laying out an implementation.
1060  if (Impl) {
1061    unsigned SynthCount = CountSynthesizedIvars(D);
1062    // If there aren't any sythesized ivars then reuse the interface
1063    // entry. Note we can't cache this because we simply free all
1064    // entries later; however we shouldn't look up implementations
1065    // frequently.
1066    if (SynthCount == 0)
1067      return getObjCLayout(D, 0);
1068  }
1069
1070  const ASTRecordLayout *NewEntry =
1071    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1072  ObjCLayouts[Key] = NewEntry;
1073
1074  return *NewEntry;
1075}
1076
1077const ASTRecordLayout &
1078ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1079  return getObjCLayout(D, 0);
1080}
1081
1082const ASTRecordLayout &
1083ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1084  return getObjCLayout(D->getClassInterface(), D);
1085}
1086
1087/// getASTRecordLayout - Get or compute information about the layout of the
1088/// specified record (struct/union/class), which indicates its size and field
1089/// position information.
1090const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
1091  D = D->getDefinition(*this);
1092  assert(D && "Cannot get layout of forward declarations!");
1093
1094  // Look up this layout, if already laid out, return what we have.
1095  // Note that we can't save a reference to the entry because this function
1096  // is recursive.
1097  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
1098  if (Entry) return *Entry;
1099
1100  const ASTRecordLayout *NewEntry =
1101    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
1102  ASTRecordLayouts[D] = NewEntry;
1103
1104  return *NewEntry;
1105}
1106
1107const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1108  RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1109  assert(RD && "Cannot get key function for forward declarations!");
1110
1111  const CXXMethodDecl *&Entry = KeyFunctions[RD];
1112  if (!Entry)
1113    Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1114  else
1115    assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1116           "Key function changed!");
1117
1118  return Entry;
1119}
1120
1121//===----------------------------------------------------------------------===//
1122//                   Type creation/memoization methods
1123//===----------------------------------------------------------------------===//
1124
1125QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1126  unsigned Fast = Quals.getFastQualifiers();
1127  Quals.removeFastQualifiers();
1128
1129  // Check if we've already instantiated this type.
1130  llvm::FoldingSetNodeID ID;
1131  ExtQuals::Profile(ID, TypeNode, Quals);
1132  void *InsertPos = 0;
1133  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1134    assert(EQ->getQualifiers() == Quals);
1135    QualType T = QualType(EQ, Fast);
1136    return T;
1137  }
1138
1139  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1140  ExtQualNodes.InsertNode(New, InsertPos);
1141  QualType T = QualType(New, Fast);
1142  return T;
1143}
1144
1145QualType ASTContext::getVolatileType(QualType T) {
1146  QualType CanT = getCanonicalType(T);
1147  if (CanT.isVolatileQualified()) return T;
1148
1149  QualifierCollector Quals;
1150  const Type *TypeNode = Quals.strip(T);
1151  Quals.addVolatile();
1152
1153  return getExtQualType(TypeNode, Quals);
1154}
1155
1156QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1157  QualType CanT = getCanonicalType(T);
1158  if (CanT.getAddressSpace() == AddressSpace)
1159    return T;
1160
1161  // If we are composing extended qualifiers together, merge together
1162  // into one ExtQuals node.
1163  QualifierCollector Quals;
1164  const Type *TypeNode = Quals.strip(T);
1165
1166  // If this type already has an address space specified, it cannot get
1167  // another one.
1168  assert(!Quals.hasAddressSpace() &&
1169         "Type cannot be in multiple addr spaces!");
1170  Quals.addAddressSpace(AddressSpace);
1171
1172  return getExtQualType(TypeNode, Quals);
1173}
1174
1175QualType ASTContext::getObjCGCQualType(QualType T,
1176                                       Qualifiers::GC GCAttr) {
1177  QualType CanT = getCanonicalType(T);
1178  if (CanT.getObjCGCAttr() == GCAttr)
1179    return T;
1180
1181  if (T->isPointerType()) {
1182    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1183    if (Pointee->isAnyPointerType()) {
1184      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1185      return getPointerType(ResultType);
1186    }
1187  }
1188
1189  // If we are composing extended qualifiers together, merge together
1190  // into one ExtQuals node.
1191  QualifierCollector Quals;
1192  const Type *TypeNode = Quals.strip(T);
1193
1194  // If this type already has an ObjCGC specified, it cannot get
1195  // another one.
1196  assert(!Quals.hasObjCGCAttr() &&
1197         "Type cannot have multiple ObjCGCs!");
1198  Quals.addObjCGCAttr(GCAttr);
1199
1200  return getExtQualType(TypeNode, Quals);
1201}
1202
1203static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1204                                        bool AddNoReturn,
1205                                        CallingConv CallConv) {
1206  QualType ResultType;
1207  if (const PointerType *Pointer = T->getAs<PointerType>()) {
1208    QualType Pointee = Pointer->getPointeeType();
1209    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1210                                         CallConv);
1211    if (ResultType == Pointee)
1212      return T;
1213
1214    ResultType = Context.getPointerType(ResultType);
1215  } else if (const BlockPointerType *BlockPointer
1216                                              = T->getAs<BlockPointerType>()) {
1217    QualType Pointee = BlockPointer->getPointeeType();
1218    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1219                                         CallConv);
1220    if (ResultType == Pointee)
1221      return T;
1222
1223    ResultType = Context.getBlockPointerType(ResultType);
1224   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1225    if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
1226      return T;
1227
1228    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1229      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1230                                                  AddNoReturn, CallConv);
1231    } else {
1232      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
1233      ResultType
1234        = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1235                                  FPT->getNumArgs(), FPT->isVariadic(),
1236                                  FPT->getTypeQuals(),
1237                                  FPT->hasExceptionSpec(),
1238                                  FPT->hasAnyExceptionSpec(),
1239                                  FPT->getNumExceptions(),
1240                                  FPT->exception_begin(),
1241                                  AddNoReturn, CallConv);
1242    }
1243  } else
1244    return T;
1245
1246  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1247}
1248
1249QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1250  return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1251}
1252
1253QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1254  return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
1255}
1256
1257/// getComplexType - Return the uniqued reference to the type for a complex
1258/// number with the specified element type.
1259QualType ASTContext::getComplexType(QualType T) {
1260  // Unique pointers, to guarantee there is only one pointer of a particular
1261  // structure.
1262  llvm::FoldingSetNodeID ID;
1263  ComplexType::Profile(ID, T);
1264
1265  void *InsertPos = 0;
1266  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1267    return QualType(CT, 0);
1268
1269  // If the pointee type isn't canonical, this won't be a canonical type either,
1270  // so fill in the canonical type field.
1271  QualType Canonical;
1272  if (!T.isCanonical()) {
1273    Canonical = getComplexType(getCanonicalType(T));
1274
1275    // Get the new insert position for the node we care about.
1276    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1277    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1278  }
1279  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1280  Types.push_back(New);
1281  ComplexTypes.InsertNode(New, InsertPos);
1282  return QualType(New, 0);
1283}
1284
1285/// getPointerType - Return the uniqued reference to the type for a pointer to
1286/// the specified type.
1287QualType ASTContext::getPointerType(QualType T) {
1288  // Unique pointers, to guarantee there is only one pointer of a particular
1289  // structure.
1290  llvm::FoldingSetNodeID ID;
1291  PointerType::Profile(ID, T);
1292
1293  void *InsertPos = 0;
1294  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1295    return QualType(PT, 0);
1296
1297  // If the pointee type isn't canonical, this won't be a canonical type either,
1298  // so fill in the canonical type field.
1299  QualType Canonical;
1300  if (!T.isCanonical()) {
1301    Canonical = getPointerType(getCanonicalType(T));
1302
1303    // Get the new insert position for the node we care about.
1304    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1305    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1306  }
1307  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1308  Types.push_back(New);
1309  PointerTypes.InsertNode(New, InsertPos);
1310  return QualType(New, 0);
1311}
1312
1313/// getBlockPointerType - Return the uniqued reference to the type for
1314/// a pointer to the specified block.
1315QualType ASTContext::getBlockPointerType(QualType T) {
1316  assert(T->isFunctionType() && "block of function types only");
1317  // Unique pointers, to guarantee there is only one block of a particular
1318  // structure.
1319  llvm::FoldingSetNodeID ID;
1320  BlockPointerType::Profile(ID, T);
1321
1322  void *InsertPos = 0;
1323  if (BlockPointerType *PT =
1324        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1325    return QualType(PT, 0);
1326
1327  // If the block pointee type isn't canonical, this won't be a canonical
1328  // type either so fill in the canonical type field.
1329  QualType Canonical;
1330  if (!T.isCanonical()) {
1331    Canonical = getBlockPointerType(getCanonicalType(T));
1332
1333    // Get the new insert position for the node we care about.
1334    BlockPointerType *NewIP =
1335      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1336    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1337  }
1338  BlockPointerType *New
1339    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1340  Types.push_back(New);
1341  BlockPointerTypes.InsertNode(New, InsertPos);
1342  return QualType(New, 0);
1343}
1344
1345/// getLValueReferenceType - Return the uniqued reference to the type for an
1346/// lvalue reference to the specified type.
1347QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1348  // Unique pointers, to guarantee there is only one pointer of a particular
1349  // structure.
1350  llvm::FoldingSetNodeID ID;
1351  ReferenceType::Profile(ID, T, SpelledAsLValue);
1352
1353  void *InsertPos = 0;
1354  if (LValueReferenceType *RT =
1355        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1356    return QualType(RT, 0);
1357
1358  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1359
1360  // If the referencee type isn't canonical, this won't be a canonical type
1361  // either, so fill in the canonical type field.
1362  QualType Canonical;
1363  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1364    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1365    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1366
1367    // Get the new insert position for the node we care about.
1368    LValueReferenceType *NewIP =
1369      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1370    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1371  }
1372
1373  LValueReferenceType *New
1374    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1375                                                     SpelledAsLValue);
1376  Types.push_back(New);
1377  LValueReferenceTypes.InsertNode(New, InsertPos);
1378
1379  return QualType(New, 0);
1380}
1381
1382/// getRValueReferenceType - Return the uniqued reference to the type for an
1383/// rvalue reference to the specified type.
1384QualType ASTContext::getRValueReferenceType(QualType T) {
1385  // Unique pointers, to guarantee there is only one pointer of a particular
1386  // structure.
1387  llvm::FoldingSetNodeID ID;
1388  ReferenceType::Profile(ID, T, false);
1389
1390  void *InsertPos = 0;
1391  if (RValueReferenceType *RT =
1392        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1393    return QualType(RT, 0);
1394
1395  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1396
1397  // If the referencee type isn't canonical, this won't be a canonical type
1398  // either, so fill in the canonical type field.
1399  QualType Canonical;
1400  if (InnerRef || !T.isCanonical()) {
1401    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1402    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1403
1404    // Get the new insert position for the node we care about.
1405    RValueReferenceType *NewIP =
1406      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1407    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1408  }
1409
1410  RValueReferenceType *New
1411    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1412  Types.push_back(New);
1413  RValueReferenceTypes.InsertNode(New, InsertPos);
1414  return QualType(New, 0);
1415}
1416
1417/// getMemberPointerType - Return the uniqued reference to the type for a
1418/// member pointer to the specified type, in the specified class.
1419QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1420  // Unique pointers, to guarantee there is only one pointer of a particular
1421  // structure.
1422  llvm::FoldingSetNodeID ID;
1423  MemberPointerType::Profile(ID, T, Cls);
1424
1425  void *InsertPos = 0;
1426  if (MemberPointerType *PT =
1427      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1428    return QualType(PT, 0);
1429
1430  // If the pointee or class type isn't canonical, this won't be a canonical
1431  // type either, so fill in the canonical type field.
1432  QualType Canonical;
1433  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1434    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1435
1436    // Get the new insert position for the node we care about.
1437    MemberPointerType *NewIP =
1438      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1439    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1440  }
1441  MemberPointerType *New
1442    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1443  Types.push_back(New);
1444  MemberPointerTypes.InsertNode(New, InsertPos);
1445  return QualType(New, 0);
1446}
1447
1448/// getConstantArrayType - Return the unique reference to the type for an
1449/// array of the specified element type.
1450QualType ASTContext::getConstantArrayType(QualType EltTy,
1451                                          const llvm::APInt &ArySizeIn,
1452                                          ArrayType::ArraySizeModifier ASM,
1453                                          unsigned EltTypeQuals) {
1454  assert((EltTy->isDependentType() ||
1455          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1456         "Constant array of VLAs is illegal!");
1457
1458  // Convert the array size into a canonical width matching the pointer size for
1459  // the target.
1460  llvm::APInt ArySize(ArySizeIn);
1461  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1462
1463  llvm::FoldingSetNodeID ID;
1464  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1465
1466  void *InsertPos = 0;
1467  if (ConstantArrayType *ATP =
1468      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1469    return QualType(ATP, 0);
1470
1471  // If the element type isn't canonical, this won't be a canonical type either,
1472  // so fill in the canonical type field.
1473  QualType Canonical;
1474  if (!EltTy.isCanonical()) {
1475    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1476                                     ASM, EltTypeQuals);
1477    // Get the new insert position for the node we care about.
1478    ConstantArrayType *NewIP =
1479      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1480    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1481  }
1482
1483  ConstantArrayType *New = new(*this,TypeAlignment)
1484    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1485  ConstantArrayTypes.InsertNode(New, InsertPos);
1486  Types.push_back(New);
1487  return QualType(New, 0);
1488}
1489
1490/// getVariableArrayType - Returns a non-unique reference to the type for a
1491/// variable array of the specified element type.
1492QualType ASTContext::getVariableArrayType(QualType EltTy,
1493                                          Expr *NumElts,
1494                                          ArrayType::ArraySizeModifier ASM,
1495                                          unsigned EltTypeQuals,
1496                                          SourceRange Brackets) {
1497  // Since we don't unique expressions, it isn't possible to unique VLA's
1498  // that have an expression provided for their size.
1499
1500  VariableArrayType *New = new(*this, TypeAlignment)
1501    VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
1502
1503  VariableArrayTypes.push_back(New);
1504  Types.push_back(New);
1505  return QualType(New, 0);
1506}
1507
1508/// getDependentSizedArrayType - Returns a non-unique reference to
1509/// the type for a dependently-sized array of the specified element
1510/// type.
1511QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1512                                                Expr *NumElts,
1513                                                ArrayType::ArraySizeModifier ASM,
1514                                                unsigned EltTypeQuals,
1515                                                SourceRange Brackets) {
1516  assert((!NumElts || NumElts->isTypeDependent() ||
1517          NumElts->isValueDependent()) &&
1518         "Size must be type- or value-dependent!");
1519
1520  void *InsertPos = 0;
1521  DependentSizedArrayType *Canon = 0;
1522
1523  if (NumElts) {
1524    // Dependently-sized array types that do not have a specified
1525    // number of elements will have their sizes deduced from an
1526    // initializer.
1527    llvm::FoldingSetNodeID ID;
1528    DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1529                                     EltTypeQuals, NumElts);
1530
1531    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1532  }
1533
1534  DependentSizedArrayType *New;
1535  if (Canon) {
1536    // We already have a canonical version of this array type; use it as
1537    // the canonical type for a newly-built type.
1538    New = new (*this, TypeAlignment)
1539      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1540                              NumElts, ASM, EltTypeQuals, Brackets);
1541  } else {
1542    QualType CanonEltTy = getCanonicalType(EltTy);
1543    if (CanonEltTy == EltTy) {
1544      New = new (*this, TypeAlignment)
1545        DependentSizedArrayType(*this, EltTy, QualType(),
1546                                NumElts, ASM, EltTypeQuals, Brackets);
1547
1548      if (NumElts)
1549        DependentSizedArrayTypes.InsertNode(New, InsertPos);
1550    } else {
1551      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1552                                                  ASM, EltTypeQuals,
1553                                                  SourceRange());
1554      New = new (*this, TypeAlignment)
1555        DependentSizedArrayType(*this, EltTy, Canon,
1556                                NumElts, ASM, EltTypeQuals, Brackets);
1557    }
1558  }
1559
1560  Types.push_back(New);
1561  return QualType(New, 0);
1562}
1563
1564QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1565                                            ArrayType::ArraySizeModifier ASM,
1566                                            unsigned EltTypeQuals) {
1567  llvm::FoldingSetNodeID ID;
1568  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1569
1570  void *InsertPos = 0;
1571  if (IncompleteArrayType *ATP =
1572       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1573    return QualType(ATP, 0);
1574
1575  // If the element type isn't canonical, this won't be a canonical type
1576  // either, so fill in the canonical type field.
1577  QualType Canonical;
1578
1579  if (!EltTy.isCanonical()) {
1580    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1581                                       ASM, EltTypeQuals);
1582
1583    // Get the new insert position for the node we care about.
1584    IncompleteArrayType *NewIP =
1585      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1586    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1587  }
1588
1589  IncompleteArrayType *New = new (*this, TypeAlignment)
1590    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1591
1592  IncompleteArrayTypes.InsertNode(New, InsertPos);
1593  Types.push_back(New);
1594  return QualType(New, 0);
1595}
1596
1597/// getVectorType - Return the unique reference to a vector type of
1598/// the specified element type and size. VectorType must be a built-in type.
1599QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1600  BuiltinType *baseType;
1601
1602  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1603  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1604
1605  // Check if we've already instantiated a vector of this type.
1606  llvm::FoldingSetNodeID ID;
1607  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1608  void *InsertPos = 0;
1609  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1610    return QualType(VTP, 0);
1611
1612  // If the element type isn't canonical, this won't be a canonical type either,
1613  // so fill in the canonical type field.
1614  QualType Canonical;
1615  if (!vecType.isCanonical()) {
1616    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1617
1618    // Get the new insert position for the node we care about.
1619    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1620    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1621  }
1622  VectorType *New = new (*this, TypeAlignment)
1623    VectorType(vecType, NumElts, Canonical);
1624  VectorTypes.InsertNode(New, InsertPos);
1625  Types.push_back(New);
1626  return QualType(New, 0);
1627}
1628
1629/// getExtVectorType - Return the unique reference to an extended vector type of
1630/// the specified element type and size. VectorType must be a built-in type.
1631QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1632  BuiltinType *baseType;
1633
1634  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1635  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1636
1637  // Check if we've already instantiated a vector of this type.
1638  llvm::FoldingSetNodeID ID;
1639  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1640  void *InsertPos = 0;
1641  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1642    return QualType(VTP, 0);
1643
1644  // If the element type isn't canonical, this won't be a canonical type either,
1645  // so fill in the canonical type field.
1646  QualType Canonical;
1647  if (!vecType.isCanonical()) {
1648    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1649
1650    // Get the new insert position for the node we care about.
1651    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1652    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1653  }
1654  ExtVectorType *New = new (*this, TypeAlignment)
1655    ExtVectorType(vecType, NumElts, Canonical);
1656  VectorTypes.InsertNode(New, InsertPos);
1657  Types.push_back(New);
1658  return QualType(New, 0);
1659}
1660
1661QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1662                                                    Expr *SizeExpr,
1663                                                    SourceLocation AttrLoc) {
1664  llvm::FoldingSetNodeID ID;
1665  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1666                                       SizeExpr);
1667
1668  void *InsertPos = 0;
1669  DependentSizedExtVectorType *Canon
1670    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1671  DependentSizedExtVectorType *New;
1672  if (Canon) {
1673    // We already have a canonical version of this array type; use it as
1674    // the canonical type for a newly-built type.
1675    New = new (*this, TypeAlignment)
1676      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1677                                  SizeExpr, AttrLoc);
1678  } else {
1679    QualType CanonVecTy = getCanonicalType(vecType);
1680    if (CanonVecTy == vecType) {
1681      New = new (*this, TypeAlignment)
1682        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1683                                    AttrLoc);
1684      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1685    } else {
1686      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1687                                                      SourceLocation());
1688      New = new (*this, TypeAlignment)
1689        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1690    }
1691  }
1692
1693  Types.push_back(New);
1694  return QualType(New, 0);
1695}
1696
1697static CallingConv getCanonicalCallingConv(CallingConv CC) {
1698  if (CC == CC_C)
1699    return CC_Default;
1700  return CC;
1701}
1702
1703/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1704///
1705QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1706                                            CallingConv CallConv) {
1707  // Unique functions, to guarantee there is only one function of a particular
1708  // structure.
1709  llvm::FoldingSetNodeID ID;
1710  FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
1711
1712  void *InsertPos = 0;
1713  if (FunctionNoProtoType *FT =
1714        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1715    return QualType(FT, 0);
1716
1717  QualType Canonical;
1718  if (!ResultTy.isCanonical() ||
1719      getCanonicalCallingConv(CallConv) != CallConv) {
1720    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
1721                                       getCanonicalCallingConv(CallConv));
1722
1723    // Get the new insert position for the node we care about.
1724    FunctionNoProtoType *NewIP =
1725      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1726    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1727  }
1728
1729  FunctionNoProtoType *New = new (*this, TypeAlignment)
1730    FunctionNoProtoType(ResultTy, Canonical, NoReturn);
1731  Types.push_back(New);
1732  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1733  return QualType(New, 0);
1734}
1735
1736/// getFunctionType - Return a normal function type with a typed argument
1737/// list.  isVariadic indicates whether the argument list includes '...'.
1738QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1739                                     unsigned NumArgs, bool isVariadic,
1740                                     unsigned TypeQuals, bool hasExceptionSpec,
1741                                     bool hasAnyExceptionSpec, unsigned NumExs,
1742                                     const QualType *ExArray, bool NoReturn,
1743                                     CallingConv CallConv) {
1744  // Unique functions, to guarantee there is only one function of a particular
1745  // structure.
1746  llvm::FoldingSetNodeID ID;
1747  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1748                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1749                             NumExs, ExArray, NoReturn);
1750
1751  void *InsertPos = 0;
1752  if (FunctionProtoType *FTP =
1753        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1754    return QualType(FTP, 0);
1755
1756  // Determine whether the type being created is already canonical or not.
1757  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1758  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1759    if (!ArgArray[i].isCanonicalAsParam())
1760      isCanonical = false;
1761
1762  // If this type isn't canonical, get the canonical version of it.
1763  // The exception spec is not part of the canonical type.
1764  QualType Canonical;
1765  if (!isCanonical || getCanonicalCallingConv(CallConv) != CallConv) {
1766    llvm::SmallVector<QualType, 16> CanonicalArgs;
1767    CanonicalArgs.reserve(NumArgs);
1768    for (unsigned i = 0; i != NumArgs; ++i)
1769      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1770
1771    Canonical = getFunctionType(getCanonicalType(ResultTy),
1772                                CanonicalArgs.data(), NumArgs,
1773                                isVariadic, TypeQuals, false,
1774                                false, 0, 0, NoReturn,
1775                                getCanonicalCallingConv(CallConv));
1776
1777    // Get the new insert position for the node we care about.
1778    FunctionProtoType *NewIP =
1779      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1780    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1781  }
1782
1783  // FunctionProtoType objects are allocated with extra bytes after them
1784  // for two variable size arrays (for parameter and exception types) at the
1785  // end of them.
1786  FunctionProtoType *FTP =
1787    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1788                                 NumArgs*sizeof(QualType) +
1789                                 NumExs*sizeof(QualType), TypeAlignment);
1790  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1791                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1792                              ExArray, NumExs, Canonical, NoReturn, CallConv);
1793  Types.push_back(FTP);
1794  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1795  return QualType(FTP, 0);
1796}
1797
1798/// getTypeDeclType - Return the unique reference to the type for the
1799/// specified type declaration.
1800QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1801  assert(Decl && "Passed null for Decl param");
1802  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1803
1804  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1805    return getTypedefType(Typedef);
1806  else if (isa<TemplateTypeParmDecl>(Decl)) {
1807    assert(false && "Template type parameter types are always available.");
1808  } else if (ObjCInterfaceDecl *ObjCInterface
1809               = dyn_cast<ObjCInterfaceDecl>(Decl))
1810    return getObjCInterfaceType(ObjCInterface);
1811
1812  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1813    if (PrevDecl)
1814      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1815    else
1816      Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1817  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1818    if (PrevDecl)
1819      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1820    else
1821      Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1822  } else if (UnresolvedUsingTypenameDecl *Using =
1823               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1824    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1825  } else
1826    assert(false && "TypeDecl without a type?");
1827
1828  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1829  return QualType(Decl->TypeForDecl, 0);
1830}
1831
1832/// getTypedefType - Return the unique reference to the type for the
1833/// specified typename decl.
1834QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1835  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1836
1837  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1838  Decl->TypeForDecl = new(*this, TypeAlignment)
1839    TypedefType(Type::Typedef, Decl, Canonical);
1840  Types.push_back(Decl->TypeForDecl);
1841  return QualType(Decl->TypeForDecl, 0);
1842}
1843
1844/// \brief Retrieve a substitution-result type.
1845QualType
1846ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1847                                         QualType Replacement) {
1848  assert(Replacement.isCanonical()
1849         && "replacement types must always be canonical");
1850
1851  llvm::FoldingSetNodeID ID;
1852  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1853  void *InsertPos = 0;
1854  SubstTemplateTypeParmType *SubstParm
1855    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1856
1857  if (!SubstParm) {
1858    SubstParm = new (*this, TypeAlignment)
1859      SubstTemplateTypeParmType(Parm, Replacement);
1860    Types.push_back(SubstParm);
1861    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1862  }
1863
1864  return QualType(SubstParm, 0);
1865}
1866
1867/// \brief Retrieve the template type parameter type for a template
1868/// parameter or parameter pack with the given depth, index, and (optionally)
1869/// name.
1870QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1871                                             bool ParameterPack,
1872                                             IdentifierInfo *Name) {
1873  llvm::FoldingSetNodeID ID;
1874  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1875  void *InsertPos = 0;
1876  TemplateTypeParmType *TypeParm
1877    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1878
1879  if (TypeParm)
1880    return QualType(TypeParm, 0);
1881
1882  if (Name) {
1883    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1884    TypeParm = new (*this, TypeAlignment)
1885      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1886  } else
1887    TypeParm = new (*this, TypeAlignment)
1888      TemplateTypeParmType(Depth, Index, ParameterPack);
1889
1890  Types.push_back(TypeParm);
1891  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1892
1893  return QualType(TypeParm, 0);
1894}
1895
1896QualType
1897ASTContext::getTemplateSpecializationType(TemplateName Template,
1898                                          const TemplateArgumentListInfo &Args,
1899                                          QualType Canon) {
1900  unsigned NumArgs = Args.size();
1901
1902  llvm::SmallVector<TemplateArgument, 4> ArgVec;
1903  ArgVec.reserve(NumArgs);
1904  for (unsigned i = 0; i != NumArgs; ++i)
1905    ArgVec.push_back(Args[i].getArgument());
1906
1907  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1908}
1909
1910QualType
1911ASTContext::getTemplateSpecializationType(TemplateName Template,
1912                                          const TemplateArgument *Args,
1913                                          unsigned NumArgs,
1914                                          QualType Canon) {
1915  if (!Canon.isNull())
1916    Canon = getCanonicalType(Canon);
1917  else {
1918    // Build the canonical template specialization type.
1919    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1920    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1921    CanonArgs.reserve(NumArgs);
1922    for (unsigned I = 0; I != NumArgs; ++I)
1923      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1924
1925    // Determine whether this canonical template specialization type already
1926    // exists.
1927    llvm::FoldingSetNodeID ID;
1928    TemplateSpecializationType::Profile(ID, CanonTemplate,
1929                                        CanonArgs.data(), NumArgs, *this);
1930
1931    void *InsertPos = 0;
1932    TemplateSpecializationType *Spec
1933      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1934
1935    if (!Spec) {
1936      // Allocate a new canonical template specialization type.
1937      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1938                            sizeof(TemplateArgument) * NumArgs),
1939                           TypeAlignment);
1940      Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
1941                                                  CanonArgs.data(), NumArgs,
1942                                                  Canon);
1943      Types.push_back(Spec);
1944      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1945    }
1946
1947    if (Canon.isNull())
1948      Canon = QualType(Spec, 0);
1949    assert(Canon->isDependentType() &&
1950           "Non-dependent template-id type must have a canonical type");
1951  }
1952
1953  // Allocate the (non-canonical) template specialization type, but don't
1954  // try to unique it: these types typically have location information that
1955  // we don't unique and don't want to lose.
1956  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1957                        sizeof(TemplateArgument) * NumArgs),
1958                       TypeAlignment);
1959  TemplateSpecializationType *Spec
1960    = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1961                                           Canon);
1962
1963  Types.push_back(Spec);
1964  return QualType(Spec, 0);
1965}
1966
1967QualType
1968ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1969                                 QualType NamedType) {
1970  llvm::FoldingSetNodeID ID;
1971  QualifiedNameType::Profile(ID, NNS, NamedType);
1972
1973  void *InsertPos = 0;
1974  QualifiedNameType *T
1975    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1976  if (T)
1977    return QualType(T, 0);
1978
1979  T = new (*this) QualifiedNameType(NNS, NamedType,
1980                                    getCanonicalType(NamedType));
1981  Types.push_back(T);
1982  QualifiedNameTypes.InsertNode(T, InsertPos);
1983  return QualType(T, 0);
1984}
1985
1986QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1987                                     const IdentifierInfo *Name,
1988                                     QualType Canon) {
1989  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1990
1991  if (Canon.isNull()) {
1992    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1993    if (CanonNNS != NNS)
1994      Canon = getTypenameType(CanonNNS, Name);
1995  }
1996
1997  llvm::FoldingSetNodeID ID;
1998  TypenameType::Profile(ID, NNS, Name);
1999
2000  void *InsertPos = 0;
2001  TypenameType *T
2002    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2003  if (T)
2004    return QualType(T, 0);
2005
2006  T = new (*this) TypenameType(NNS, Name, Canon);
2007  Types.push_back(T);
2008  TypenameTypes.InsertNode(T, InsertPos);
2009  return QualType(T, 0);
2010}
2011
2012QualType
2013ASTContext::getTypenameType(NestedNameSpecifier *NNS,
2014                            const TemplateSpecializationType *TemplateId,
2015                            QualType Canon) {
2016  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2017
2018  if (Canon.isNull()) {
2019    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2020    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2021    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2022      const TemplateSpecializationType *CanonTemplateId
2023        = CanonType->getAs<TemplateSpecializationType>();
2024      assert(CanonTemplateId &&
2025             "Canonical type must also be a template specialization type");
2026      Canon = getTypenameType(CanonNNS, CanonTemplateId);
2027    }
2028  }
2029
2030  llvm::FoldingSetNodeID ID;
2031  TypenameType::Profile(ID, NNS, TemplateId);
2032
2033  void *InsertPos = 0;
2034  TypenameType *T
2035    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2036  if (T)
2037    return QualType(T, 0);
2038
2039  T = new (*this) TypenameType(NNS, TemplateId, Canon);
2040  Types.push_back(T);
2041  TypenameTypes.InsertNode(T, InsertPos);
2042  return QualType(T, 0);
2043}
2044
2045QualType
2046ASTContext::getElaboratedType(QualType UnderlyingType,
2047                              ElaboratedType::TagKind Tag) {
2048  llvm::FoldingSetNodeID ID;
2049  ElaboratedType::Profile(ID, UnderlyingType, Tag);
2050
2051  void *InsertPos = 0;
2052  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2053  if (T)
2054    return QualType(T, 0);
2055
2056  QualType Canon = getCanonicalType(UnderlyingType);
2057
2058  T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2059  Types.push_back(T);
2060  ElaboratedTypes.InsertNode(T, InsertPos);
2061  return QualType(T, 0);
2062}
2063
2064/// CmpProtocolNames - Comparison predicate for sorting protocols
2065/// alphabetically.
2066static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2067                            const ObjCProtocolDecl *RHS) {
2068  return LHS->getDeclName() < RHS->getDeclName();
2069}
2070
2071static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2072                                unsigned NumProtocols) {
2073  if (NumProtocols == 0) return true;
2074
2075  for (unsigned i = 1; i != NumProtocols; ++i)
2076    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2077      return false;
2078  return true;
2079}
2080
2081static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2082                                   unsigned &NumProtocols) {
2083  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2084
2085  // Sort protocols, keyed by name.
2086  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2087
2088  // Remove duplicates.
2089  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2090  NumProtocols = ProtocolsEnd-Protocols;
2091}
2092
2093/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2094/// the given interface decl and the conforming protocol list.
2095QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
2096                                              ObjCProtocolDecl **Protocols,
2097                                              unsigned NumProtocols) {
2098  llvm::FoldingSetNodeID ID;
2099  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
2100
2101  void *InsertPos = 0;
2102  if (ObjCObjectPointerType *QT =
2103              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2104    return QualType(QT, 0);
2105
2106  // Sort the protocol list alphabetically to canonicalize it.
2107  QualType Canonical;
2108  if (!InterfaceT.isCanonical() ||
2109      !areSortedAndUniqued(Protocols, NumProtocols)) {
2110    if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2111      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2112      unsigned UniqueCount = NumProtocols;
2113
2114      std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2115      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2116
2117      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2118                                           &Sorted[0], UniqueCount);
2119    } else {
2120      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2121                                           Protocols, NumProtocols);
2122    }
2123
2124    // Regenerate InsertPos.
2125    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2126  }
2127
2128  // No Match;
2129  ObjCObjectPointerType *QType = new (*this, TypeAlignment)
2130    ObjCObjectPointerType(*this, Canonical, InterfaceT, Protocols,
2131                          NumProtocols);
2132
2133  Types.push_back(QType);
2134  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2135  return QualType(QType, 0);
2136}
2137
2138/// getObjCInterfaceType - Return the unique reference to the type for the
2139/// specified ObjC interface decl. The list of protocols is optional.
2140QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2141                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
2142  llvm::FoldingSetNodeID ID;
2143  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
2144
2145  void *InsertPos = 0;
2146  if (ObjCInterfaceType *QT =
2147      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
2148    return QualType(QT, 0);
2149
2150  // Sort the protocol list alphabetically to canonicalize it.
2151  QualType Canonical;
2152  if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2153    llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2154    std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2155
2156    unsigned UniqueCount = NumProtocols;
2157    SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2158
2159    Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2160
2161    ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2162  }
2163
2164  ObjCInterfaceType *QType = new (*this, TypeAlignment)
2165    ObjCInterfaceType(*this, Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
2166                      Protocols, NumProtocols);
2167
2168  Types.push_back(QType);
2169  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
2170  return QualType(QType, 0);
2171}
2172
2173/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2174/// TypeOfExprType AST's (since expression's are never shared). For example,
2175/// multiple declarations that refer to "typeof(x)" all contain different
2176/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2177/// on canonical type's (which are always unique).
2178QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2179  TypeOfExprType *toe;
2180  if (tofExpr->isTypeDependent()) {
2181    llvm::FoldingSetNodeID ID;
2182    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2183
2184    void *InsertPos = 0;
2185    DependentTypeOfExprType *Canon
2186      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2187    if (Canon) {
2188      // We already have a "canonical" version of an identical, dependent
2189      // typeof(expr) type. Use that as our canonical type.
2190      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2191                                          QualType((TypeOfExprType*)Canon, 0));
2192    }
2193    else {
2194      // Build a new, canonical typeof(expr) type.
2195      Canon
2196        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2197      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2198      toe = Canon;
2199    }
2200  } else {
2201    QualType Canonical = getCanonicalType(tofExpr->getType());
2202    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2203  }
2204  Types.push_back(toe);
2205  return QualType(toe, 0);
2206}
2207
2208/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2209/// TypeOfType AST's. The only motivation to unique these nodes would be
2210/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2211/// an issue. This doesn't effect the type checker, since it operates
2212/// on canonical type's (which are always unique).
2213QualType ASTContext::getTypeOfType(QualType tofType) {
2214  QualType Canonical = getCanonicalType(tofType);
2215  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2216  Types.push_back(tot);
2217  return QualType(tot, 0);
2218}
2219
2220/// getDecltypeForExpr - Given an expr, will return the decltype for that
2221/// expression, according to the rules in C++0x [dcl.type.simple]p4
2222static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2223  if (e->isTypeDependent())
2224    return Context.DependentTy;
2225
2226  // If e is an id expression or a class member access, decltype(e) is defined
2227  // as the type of the entity named by e.
2228  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2229    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2230      return VD->getType();
2231  }
2232  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2233    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2234      return FD->getType();
2235  }
2236  // If e is a function call or an invocation of an overloaded operator,
2237  // (parentheses around e are ignored), decltype(e) is defined as the
2238  // return type of that function.
2239  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2240    return CE->getCallReturnType();
2241
2242  QualType T = e->getType();
2243
2244  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2245  // defined as T&, otherwise decltype(e) is defined as T.
2246  if (e->isLvalue(Context) == Expr::LV_Valid)
2247    T = Context.getLValueReferenceType(T);
2248
2249  return T;
2250}
2251
2252/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2253/// DecltypeType AST's. The only motivation to unique these nodes would be
2254/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2255/// an issue. This doesn't effect the type checker, since it operates
2256/// on canonical type's (which are always unique).
2257QualType ASTContext::getDecltypeType(Expr *e) {
2258  DecltypeType *dt;
2259  if (e->isTypeDependent()) {
2260    llvm::FoldingSetNodeID ID;
2261    DependentDecltypeType::Profile(ID, *this, e);
2262
2263    void *InsertPos = 0;
2264    DependentDecltypeType *Canon
2265      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2266    if (Canon) {
2267      // We already have a "canonical" version of an equivalent, dependent
2268      // decltype type. Use that as our canonical type.
2269      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2270                                       QualType((DecltypeType*)Canon, 0));
2271    }
2272    else {
2273      // Build a new, canonical typeof(expr) type.
2274      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2275      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2276      dt = Canon;
2277    }
2278  } else {
2279    QualType T = getDecltypeForExpr(e, *this);
2280    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2281  }
2282  Types.push_back(dt);
2283  return QualType(dt, 0);
2284}
2285
2286/// getTagDeclType - Return the unique reference to the type for the
2287/// specified TagDecl (struct/union/class/enum) decl.
2288QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2289  assert (Decl);
2290  // FIXME: What is the design on getTagDeclType when it requires casting
2291  // away const?  mutable?
2292  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2293}
2294
2295/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2296/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2297/// needs to agree with the definition in <stddef.h>.
2298CanQualType ASTContext::getSizeType() const {
2299  return getFromTargetType(Target.getSizeType());
2300}
2301
2302/// getSignedWCharType - Return the type of "signed wchar_t".
2303/// Used when in C++, as a GCC extension.
2304QualType ASTContext::getSignedWCharType() const {
2305  // FIXME: derive from "Target" ?
2306  return WCharTy;
2307}
2308
2309/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2310/// Used when in C++, as a GCC extension.
2311QualType ASTContext::getUnsignedWCharType() const {
2312  // FIXME: derive from "Target" ?
2313  return UnsignedIntTy;
2314}
2315
2316/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2317/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2318QualType ASTContext::getPointerDiffType() const {
2319  return getFromTargetType(Target.getPtrDiffType(0));
2320}
2321
2322//===----------------------------------------------------------------------===//
2323//                              Type Operators
2324//===----------------------------------------------------------------------===//
2325
2326CanQualType ASTContext::getCanonicalParamType(QualType T) {
2327  // Push qualifiers into arrays, and then discard any remaining
2328  // qualifiers.
2329  T = getCanonicalType(T);
2330  const Type *Ty = T.getTypePtr();
2331
2332  QualType Result;
2333  if (isa<ArrayType>(Ty)) {
2334    Result = getArrayDecayedType(QualType(Ty,0));
2335  } else if (isa<FunctionType>(Ty)) {
2336    Result = getPointerType(QualType(Ty, 0));
2337  } else {
2338    Result = QualType(Ty, 0);
2339  }
2340
2341  return CanQualType::CreateUnsafe(Result);
2342}
2343
2344/// getCanonicalType - Return the canonical (structural) type corresponding to
2345/// the specified potentially non-canonical type.  The non-canonical version
2346/// of a type may have many "decorated" versions of types.  Decorators can
2347/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2348/// to be free of any of these, allowing two canonical types to be compared
2349/// for exact equality with a simple pointer comparison.
2350CanQualType ASTContext::getCanonicalType(QualType T) {
2351  QualifierCollector Quals;
2352  const Type *Ptr = Quals.strip(T);
2353  QualType CanType = Ptr->getCanonicalTypeInternal();
2354
2355  // The canonical internal type will be the canonical type *except*
2356  // that we push type qualifiers down through array types.
2357
2358  // If there are no new qualifiers to push down, stop here.
2359  if (!Quals.hasQualifiers())
2360    return CanQualType::CreateUnsafe(CanType);
2361
2362  // If the type qualifiers are on an array type, get the canonical
2363  // type of the array with the qualifiers applied to the element
2364  // type.
2365  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2366  if (!AT)
2367    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2368
2369  // Get the canonical version of the element with the extra qualifiers on it.
2370  // This can recursively sink qualifiers through multiple levels of arrays.
2371  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2372  NewEltTy = getCanonicalType(NewEltTy);
2373
2374  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2375    return CanQualType::CreateUnsafe(
2376             getConstantArrayType(NewEltTy, CAT->getSize(),
2377                                  CAT->getSizeModifier(),
2378                                  CAT->getIndexTypeCVRQualifiers()));
2379  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2380    return CanQualType::CreateUnsafe(
2381             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2382                                    IAT->getIndexTypeCVRQualifiers()));
2383
2384  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2385    return CanQualType::CreateUnsafe(
2386             getDependentSizedArrayType(NewEltTy,
2387                                        DSAT->getSizeExpr() ?
2388                                          DSAT->getSizeExpr()->Retain() : 0,
2389                                        DSAT->getSizeModifier(),
2390                                        DSAT->getIndexTypeCVRQualifiers(),
2391                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2392
2393  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2394  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2395                                                        VAT->getSizeExpr() ?
2396                                              VAT->getSizeExpr()->Retain() : 0,
2397                                                        VAT->getSizeModifier(),
2398                                              VAT->getIndexTypeCVRQualifiers(),
2399                                                     VAT->getBracketsRange()));
2400}
2401
2402QualType ASTContext::getUnqualifiedArrayType(QualType T,
2403                                             Qualifiers &Quals) {
2404  Quals = T.getQualifiers();
2405  if (!isa<ArrayType>(T)) {
2406    return T.getUnqualifiedType();
2407  }
2408
2409  const ArrayType *AT = cast<ArrayType>(T);
2410  QualType Elt = AT->getElementType();
2411  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2412  if (Elt == UnqualElt)
2413    return T;
2414
2415  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2416    return getConstantArrayType(UnqualElt, CAT->getSize(),
2417                                CAT->getSizeModifier(), 0);
2418  }
2419
2420  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2421    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2422  }
2423
2424  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2425  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2426                                    DSAT->getSizeModifier(), 0,
2427                                    SourceRange());
2428}
2429
2430DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2431  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2432    return TD->getDeclName();
2433
2434  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2435    if (DTN->isIdentifier()) {
2436      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2437    } else {
2438      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2439    }
2440  }
2441
2442  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2443  assert(Storage);
2444  return (*Storage->begin())->getDeclName();
2445}
2446
2447TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2448  // If this template name refers to a template, the canonical
2449  // template name merely stores the template itself.
2450  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2451    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2452
2453  assert(!Name.getAsOverloadedTemplate());
2454
2455  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2456  assert(DTN && "Non-dependent template names must refer to template decls.");
2457  return DTN->CanonicalTemplateName;
2458}
2459
2460bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2461  X = getCanonicalTemplateName(X);
2462  Y = getCanonicalTemplateName(Y);
2463  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2464}
2465
2466TemplateArgument
2467ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2468  switch (Arg.getKind()) {
2469    case TemplateArgument::Null:
2470      return Arg;
2471
2472    case TemplateArgument::Expression:
2473      return Arg;
2474
2475    case TemplateArgument::Declaration:
2476      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2477
2478    case TemplateArgument::Template:
2479      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2480
2481    case TemplateArgument::Integral:
2482      return TemplateArgument(*Arg.getAsIntegral(),
2483                              getCanonicalType(Arg.getIntegralType()));
2484
2485    case TemplateArgument::Type:
2486      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2487
2488    case TemplateArgument::Pack: {
2489      // FIXME: Allocate in ASTContext
2490      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2491      unsigned Idx = 0;
2492      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2493                                        AEnd = Arg.pack_end();
2494           A != AEnd; (void)++A, ++Idx)
2495        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2496
2497      TemplateArgument Result;
2498      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2499      return Result;
2500    }
2501  }
2502
2503  // Silence GCC warning
2504  assert(false && "Unhandled template argument kind");
2505  return TemplateArgument();
2506}
2507
2508NestedNameSpecifier *
2509ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2510  if (!NNS)
2511    return 0;
2512
2513  switch (NNS->getKind()) {
2514  case NestedNameSpecifier::Identifier:
2515    // Canonicalize the prefix but keep the identifier the same.
2516    return NestedNameSpecifier::Create(*this,
2517                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2518                                       NNS->getAsIdentifier());
2519
2520  case NestedNameSpecifier::Namespace:
2521    // A namespace is canonical; build a nested-name-specifier with
2522    // this namespace and no prefix.
2523    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2524
2525  case NestedNameSpecifier::TypeSpec:
2526  case NestedNameSpecifier::TypeSpecWithTemplate: {
2527    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2528    return NestedNameSpecifier::Create(*this, 0,
2529                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2530                                       T.getTypePtr());
2531  }
2532
2533  case NestedNameSpecifier::Global:
2534    // The global specifier is canonical and unique.
2535    return NNS;
2536  }
2537
2538  // Required to silence a GCC warning
2539  return 0;
2540}
2541
2542
2543const ArrayType *ASTContext::getAsArrayType(QualType T) {
2544  // Handle the non-qualified case efficiently.
2545  if (!T.hasLocalQualifiers()) {
2546    // Handle the common positive case fast.
2547    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2548      return AT;
2549  }
2550
2551  // Handle the common negative case fast.
2552  QualType CType = T->getCanonicalTypeInternal();
2553  if (!isa<ArrayType>(CType))
2554    return 0;
2555
2556  // Apply any qualifiers from the array type to the element type.  This
2557  // implements C99 6.7.3p8: "If the specification of an array type includes
2558  // any type qualifiers, the element type is so qualified, not the array type."
2559
2560  // If we get here, we either have type qualifiers on the type, or we have
2561  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2562  // we must propagate them down into the element type.
2563
2564  QualifierCollector Qs;
2565  const Type *Ty = Qs.strip(T.getDesugaredType());
2566
2567  // If we have a simple case, just return now.
2568  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2569  if (ATy == 0 || Qs.empty())
2570    return ATy;
2571
2572  // Otherwise, we have an array and we have qualifiers on it.  Push the
2573  // qualifiers into the array element type and return a new array type.
2574  // Get the canonical version of the element with the extra qualifiers on it.
2575  // This can recursively sink qualifiers through multiple levels of arrays.
2576  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2577
2578  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2579    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2580                                                CAT->getSizeModifier(),
2581                                           CAT->getIndexTypeCVRQualifiers()));
2582  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2583    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2584                                                  IAT->getSizeModifier(),
2585                                           IAT->getIndexTypeCVRQualifiers()));
2586
2587  if (const DependentSizedArrayType *DSAT
2588        = dyn_cast<DependentSizedArrayType>(ATy))
2589    return cast<ArrayType>(
2590                     getDependentSizedArrayType(NewEltTy,
2591                                                DSAT->getSizeExpr() ?
2592                                              DSAT->getSizeExpr()->Retain() : 0,
2593                                                DSAT->getSizeModifier(),
2594                                              DSAT->getIndexTypeCVRQualifiers(),
2595                                                DSAT->getBracketsRange()));
2596
2597  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2598  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2599                                              VAT->getSizeExpr() ?
2600                                              VAT->getSizeExpr()->Retain() : 0,
2601                                              VAT->getSizeModifier(),
2602                                              VAT->getIndexTypeCVRQualifiers(),
2603                                              VAT->getBracketsRange()));
2604}
2605
2606
2607/// getArrayDecayedType - Return the properly qualified result of decaying the
2608/// specified array type to a pointer.  This operation is non-trivial when
2609/// handling typedefs etc.  The canonical type of "T" must be an array type,
2610/// this returns a pointer to a properly qualified element of the array.
2611///
2612/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2613QualType ASTContext::getArrayDecayedType(QualType Ty) {
2614  // Get the element type with 'getAsArrayType' so that we don't lose any
2615  // typedefs in the element type of the array.  This also handles propagation
2616  // of type qualifiers from the array type into the element type if present
2617  // (C99 6.7.3p8).
2618  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2619  assert(PrettyArrayType && "Not an array type!");
2620
2621  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2622
2623  // int x[restrict 4] ->  int *restrict
2624  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2625}
2626
2627QualType ASTContext::getBaseElementType(QualType QT) {
2628  QualifierCollector Qs;
2629  while (true) {
2630    const Type *UT = Qs.strip(QT);
2631    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2632      QT = AT->getElementType();
2633    } else {
2634      return Qs.apply(QT);
2635    }
2636  }
2637}
2638
2639QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2640  QualType ElemTy = AT->getElementType();
2641
2642  if (const ArrayType *AT = getAsArrayType(ElemTy))
2643    return getBaseElementType(AT);
2644
2645  return ElemTy;
2646}
2647
2648/// getConstantArrayElementCount - Returns number of constant array elements.
2649uint64_t
2650ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2651  uint64_t ElementCount = 1;
2652  do {
2653    ElementCount *= CA->getSize().getZExtValue();
2654    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2655  } while (CA);
2656  return ElementCount;
2657}
2658
2659/// getFloatingRank - Return a relative rank for floating point types.
2660/// This routine will assert if passed a built-in type that isn't a float.
2661static FloatingRank getFloatingRank(QualType T) {
2662  if (const ComplexType *CT = T->getAs<ComplexType>())
2663    return getFloatingRank(CT->getElementType());
2664
2665  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2666  switch (T->getAs<BuiltinType>()->getKind()) {
2667  default: assert(0 && "getFloatingRank(): not a floating type");
2668  case BuiltinType::Float:      return FloatRank;
2669  case BuiltinType::Double:     return DoubleRank;
2670  case BuiltinType::LongDouble: return LongDoubleRank;
2671  }
2672}
2673
2674/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2675/// point or a complex type (based on typeDomain/typeSize).
2676/// 'typeDomain' is a real floating point or complex type.
2677/// 'typeSize' is a real floating point or complex type.
2678QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2679                                                       QualType Domain) const {
2680  FloatingRank EltRank = getFloatingRank(Size);
2681  if (Domain->isComplexType()) {
2682    switch (EltRank) {
2683    default: assert(0 && "getFloatingRank(): illegal value for rank");
2684    case FloatRank:      return FloatComplexTy;
2685    case DoubleRank:     return DoubleComplexTy;
2686    case LongDoubleRank: return LongDoubleComplexTy;
2687    }
2688  }
2689
2690  assert(Domain->isRealFloatingType() && "Unknown domain!");
2691  switch (EltRank) {
2692  default: assert(0 && "getFloatingRank(): illegal value for rank");
2693  case FloatRank:      return FloatTy;
2694  case DoubleRank:     return DoubleTy;
2695  case LongDoubleRank: return LongDoubleTy;
2696  }
2697}
2698
2699/// getFloatingTypeOrder - Compare the rank of the two specified floating
2700/// point types, ignoring the domain of the type (i.e. 'double' ==
2701/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2702/// LHS < RHS, return -1.
2703int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2704  FloatingRank LHSR = getFloatingRank(LHS);
2705  FloatingRank RHSR = getFloatingRank(RHS);
2706
2707  if (LHSR == RHSR)
2708    return 0;
2709  if (LHSR > RHSR)
2710    return 1;
2711  return -1;
2712}
2713
2714/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2715/// routine will assert if passed a built-in type that isn't an integer or enum,
2716/// or if it is not canonicalized.
2717unsigned ASTContext::getIntegerRank(Type *T) {
2718  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2719  if (EnumType* ET = dyn_cast<EnumType>(T))
2720    T = ET->getDecl()->getPromotionType().getTypePtr();
2721
2722  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2723    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2724
2725  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2726    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2727
2728  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2729    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2730
2731  switch (cast<BuiltinType>(T)->getKind()) {
2732  default: assert(0 && "getIntegerRank(): not a built-in integer");
2733  case BuiltinType::Bool:
2734    return 1 + (getIntWidth(BoolTy) << 3);
2735  case BuiltinType::Char_S:
2736  case BuiltinType::Char_U:
2737  case BuiltinType::SChar:
2738  case BuiltinType::UChar:
2739    return 2 + (getIntWidth(CharTy) << 3);
2740  case BuiltinType::Short:
2741  case BuiltinType::UShort:
2742    return 3 + (getIntWidth(ShortTy) << 3);
2743  case BuiltinType::Int:
2744  case BuiltinType::UInt:
2745    return 4 + (getIntWidth(IntTy) << 3);
2746  case BuiltinType::Long:
2747  case BuiltinType::ULong:
2748    return 5 + (getIntWidth(LongTy) << 3);
2749  case BuiltinType::LongLong:
2750  case BuiltinType::ULongLong:
2751    return 6 + (getIntWidth(LongLongTy) << 3);
2752  case BuiltinType::Int128:
2753  case BuiltinType::UInt128:
2754    return 7 + (getIntWidth(Int128Ty) << 3);
2755  }
2756}
2757
2758/// \brief Whether this is a promotable bitfield reference according
2759/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2760///
2761/// \returns the type this bit-field will promote to, or NULL if no
2762/// promotion occurs.
2763QualType ASTContext::isPromotableBitField(Expr *E) {
2764  FieldDecl *Field = E->getBitField();
2765  if (!Field)
2766    return QualType();
2767
2768  QualType FT = Field->getType();
2769
2770  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2771  uint64_t BitWidth = BitWidthAP.getZExtValue();
2772  uint64_t IntSize = getTypeSize(IntTy);
2773  // GCC extension compatibility: if the bit-field size is less than or equal
2774  // to the size of int, it gets promoted no matter what its type is.
2775  // For instance, unsigned long bf : 4 gets promoted to signed int.
2776  if (BitWidth < IntSize)
2777    return IntTy;
2778
2779  if (BitWidth == IntSize)
2780    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2781
2782  // Types bigger than int are not subject to promotions, and therefore act
2783  // like the base type.
2784  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2785  // is ridiculous.
2786  return QualType();
2787}
2788
2789/// getPromotedIntegerType - Returns the type that Promotable will
2790/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2791/// integer type.
2792QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2793  assert(!Promotable.isNull());
2794  assert(Promotable->isPromotableIntegerType());
2795  if (const EnumType *ET = Promotable->getAs<EnumType>())
2796    return ET->getDecl()->getPromotionType();
2797  if (Promotable->isSignedIntegerType())
2798    return IntTy;
2799  uint64_t PromotableSize = getTypeSize(Promotable);
2800  uint64_t IntSize = getTypeSize(IntTy);
2801  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2802  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2803}
2804
2805/// getIntegerTypeOrder - Returns the highest ranked integer type:
2806/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2807/// LHS < RHS, return -1.
2808int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2809  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2810  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2811  if (LHSC == RHSC) return 0;
2812
2813  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2814  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2815
2816  unsigned LHSRank = getIntegerRank(LHSC);
2817  unsigned RHSRank = getIntegerRank(RHSC);
2818
2819  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2820    if (LHSRank == RHSRank) return 0;
2821    return LHSRank > RHSRank ? 1 : -1;
2822  }
2823
2824  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2825  if (LHSUnsigned) {
2826    // If the unsigned [LHS] type is larger, return it.
2827    if (LHSRank >= RHSRank)
2828      return 1;
2829
2830    // If the signed type can represent all values of the unsigned type, it
2831    // wins.  Because we are dealing with 2's complement and types that are
2832    // powers of two larger than each other, this is always safe.
2833    return -1;
2834  }
2835
2836  // If the unsigned [RHS] type is larger, return it.
2837  if (RHSRank >= LHSRank)
2838    return -1;
2839
2840  // If the signed type can represent all values of the unsigned type, it
2841  // wins.  Because we are dealing with 2's complement and types that are
2842  // powers of two larger than each other, this is always safe.
2843  return 1;
2844}
2845
2846static RecordDecl *
2847CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2848                 SourceLocation L, IdentifierInfo *Id) {
2849  if (Ctx.getLangOptions().CPlusPlus)
2850    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2851  else
2852    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2853}
2854
2855// getCFConstantStringType - Return the type used for constant CFStrings.
2856QualType ASTContext::getCFConstantStringType() {
2857  if (!CFConstantStringTypeDecl) {
2858    CFConstantStringTypeDecl =
2859      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2860                       &Idents.get("NSConstantString"));
2861
2862    QualType FieldTypes[4];
2863
2864    // const int *isa;
2865    FieldTypes[0] = getPointerType(IntTy.withConst());
2866    // int flags;
2867    FieldTypes[1] = IntTy;
2868    // const char *str;
2869    FieldTypes[2] = getPointerType(CharTy.withConst());
2870    // long length;
2871    FieldTypes[3] = LongTy;
2872
2873    // Create fields
2874    for (unsigned i = 0; i < 4; ++i) {
2875      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2876                                           SourceLocation(), 0,
2877                                           FieldTypes[i], /*TInfo=*/0,
2878                                           /*BitWidth=*/0,
2879                                           /*Mutable=*/false);
2880      CFConstantStringTypeDecl->addDecl(Field);
2881    }
2882
2883    CFConstantStringTypeDecl->completeDefinition(*this);
2884  }
2885
2886  return getTagDeclType(CFConstantStringTypeDecl);
2887}
2888
2889void ASTContext::setCFConstantStringType(QualType T) {
2890  const RecordType *Rec = T->getAs<RecordType>();
2891  assert(Rec && "Invalid CFConstantStringType");
2892  CFConstantStringTypeDecl = Rec->getDecl();
2893}
2894
2895QualType ASTContext::getObjCFastEnumerationStateType() {
2896  if (!ObjCFastEnumerationStateTypeDecl) {
2897    ObjCFastEnumerationStateTypeDecl =
2898      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2899                       &Idents.get("__objcFastEnumerationState"));
2900
2901    QualType FieldTypes[] = {
2902      UnsignedLongTy,
2903      getPointerType(ObjCIdTypedefType),
2904      getPointerType(UnsignedLongTy),
2905      getConstantArrayType(UnsignedLongTy,
2906                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2907    };
2908
2909    for (size_t i = 0; i < 4; ++i) {
2910      FieldDecl *Field = FieldDecl::Create(*this,
2911                                           ObjCFastEnumerationStateTypeDecl,
2912                                           SourceLocation(), 0,
2913                                           FieldTypes[i], /*TInfo=*/0,
2914                                           /*BitWidth=*/0,
2915                                           /*Mutable=*/false);
2916      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2917    }
2918
2919    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2920  }
2921
2922  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2923}
2924
2925QualType ASTContext::getBlockDescriptorType() {
2926  if (BlockDescriptorType)
2927    return getTagDeclType(BlockDescriptorType);
2928
2929  RecordDecl *T;
2930  // FIXME: Needs the FlagAppleBlock bit.
2931  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2932                       &Idents.get("__block_descriptor"));
2933
2934  QualType FieldTypes[] = {
2935    UnsignedLongTy,
2936    UnsignedLongTy,
2937  };
2938
2939  const char *FieldNames[] = {
2940    "reserved",
2941    "Size"
2942  };
2943
2944  for (size_t i = 0; i < 2; ++i) {
2945    FieldDecl *Field = FieldDecl::Create(*this,
2946                                         T,
2947                                         SourceLocation(),
2948                                         &Idents.get(FieldNames[i]),
2949                                         FieldTypes[i], /*TInfo=*/0,
2950                                         /*BitWidth=*/0,
2951                                         /*Mutable=*/false);
2952    T->addDecl(Field);
2953  }
2954
2955  T->completeDefinition(*this);
2956
2957  BlockDescriptorType = T;
2958
2959  return getTagDeclType(BlockDescriptorType);
2960}
2961
2962void ASTContext::setBlockDescriptorType(QualType T) {
2963  const RecordType *Rec = T->getAs<RecordType>();
2964  assert(Rec && "Invalid BlockDescriptorType");
2965  BlockDescriptorType = Rec->getDecl();
2966}
2967
2968QualType ASTContext::getBlockDescriptorExtendedType() {
2969  if (BlockDescriptorExtendedType)
2970    return getTagDeclType(BlockDescriptorExtendedType);
2971
2972  RecordDecl *T;
2973  // FIXME: Needs the FlagAppleBlock bit.
2974  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2975                       &Idents.get("__block_descriptor_withcopydispose"));
2976
2977  QualType FieldTypes[] = {
2978    UnsignedLongTy,
2979    UnsignedLongTy,
2980    getPointerType(VoidPtrTy),
2981    getPointerType(VoidPtrTy)
2982  };
2983
2984  const char *FieldNames[] = {
2985    "reserved",
2986    "Size",
2987    "CopyFuncPtr",
2988    "DestroyFuncPtr"
2989  };
2990
2991  for (size_t i = 0; i < 4; ++i) {
2992    FieldDecl *Field = FieldDecl::Create(*this,
2993                                         T,
2994                                         SourceLocation(),
2995                                         &Idents.get(FieldNames[i]),
2996                                         FieldTypes[i], /*TInfo=*/0,
2997                                         /*BitWidth=*/0,
2998                                         /*Mutable=*/false);
2999    T->addDecl(Field);
3000  }
3001
3002  T->completeDefinition(*this);
3003
3004  BlockDescriptorExtendedType = T;
3005
3006  return getTagDeclType(BlockDescriptorExtendedType);
3007}
3008
3009void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3010  const RecordType *Rec = T->getAs<RecordType>();
3011  assert(Rec && "Invalid BlockDescriptorType");
3012  BlockDescriptorExtendedType = Rec->getDecl();
3013}
3014
3015bool ASTContext::BlockRequiresCopying(QualType Ty) {
3016  if (Ty->isBlockPointerType())
3017    return true;
3018  if (isObjCNSObjectType(Ty))
3019    return true;
3020  if (Ty->isObjCObjectPointerType())
3021    return true;
3022  return false;
3023}
3024
3025QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3026  //  type = struct __Block_byref_1_X {
3027  //    void *__isa;
3028  //    struct __Block_byref_1_X *__forwarding;
3029  //    unsigned int __flags;
3030  //    unsigned int __size;
3031  //    void *__copy_helper;		// as needed
3032  //    void *__destroy_help		// as needed
3033  //    int X;
3034  //  } *
3035
3036  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3037
3038  // FIXME: Move up
3039  static unsigned int UniqueBlockByRefTypeID = 0;
3040  llvm::SmallString<36> Name;
3041  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3042                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3043  RecordDecl *T;
3044  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3045                       &Idents.get(Name.str()));
3046  T->startDefinition();
3047  QualType Int32Ty = IntTy;
3048  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3049  QualType FieldTypes[] = {
3050    getPointerType(VoidPtrTy),
3051    getPointerType(getTagDeclType(T)),
3052    Int32Ty,
3053    Int32Ty,
3054    getPointerType(VoidPtrTy),
3055    getPointerType(VoidPtrTy),
3056    Ty
3057  };
3058
3059  const char *FieldNames[] = {
3060    "__isa",
3061    "__forwarding",
3062    "__flags",
3063    "__size",
3064    "__copy_helper",
3065    "__destroy_helper",
3066    DeclName,
3067  };
3068
3069  for (size_t i = 0; i < 7; ++i) {
3070    if (!HasCopyAndDispose && i >=4 && i <= 5)
3071      continue;
3072    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3073                                         &Idents.get(FieldNames[i]),
3074                                         FieldTypes[i], /*TInfo=*/0,
3075                                         /*BitWidth=*/0, /*Mutable=*/false);
3076    T->addDecl(Field);
3077  }
3078
3079  T->completeDefinition(*this);
3080
3081  return getPointerType(getTagDeclType(T));
3082}
3083
3084
3085QualType ASTContext::getBlockParmType(
3086  bool BlockHasCopyDispose,
3087  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
3088  // FIXME: Move up
3089  static unsigned int UniqueBlockParmTypeID = 0;
3090  llvm::SmallString<36> Name;
3091  llvm::raw_svector_ostream(Name) << "__block_literal_"
3092                                  << ++UniqueBlockParmTypeID;
3093  RecordDecl *T;
3094  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3095                       &Idents.get(Name.str()));
3096  QualType FieldTypes[] = {
3097    getPointerType(VoidPtrTy),
3098    IntTy,
3099    IntTy,
3100    getPointerType(VoidPtrTy),
3101    (BlockHasCopyDispose ?
3102     getPointerType(getBlockDescriptorExtendedType()) :
3103     getPointerType(getBlockDescriptorType()))
3104  };
3105
3106  const char *FieldNames[] = {
3107    "__isa",
3108    "__flags",
3109    "__reserved",
3110    "__FuncPtr",
3111    "__descriptor"
3112  };
3113
3114  for (size_t i = 0; i < 5; ++i) {
3115    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3116                                         &Idents.get(FieldNames[i]),
3117                                         FieldTypes[i], /*TInfo=*/0,
3118                                         /*BitWidth=*/0, /*Mutable=*/false);
3119    T->addDecl(Field);
3120  }
3121
3122  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3123    const Expr *E = BlockDeclRefDecls[i];
3124    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3125    clang::IdentifierInfo *Name = 0;
3126    if (BDRE) {
3127      const ValueDecl *D = BDRE->getDecl();
3128      Name = &Idents.get(D->getName());
3129    }
3130    QualType FieldType = E->getType();
3131
3132    if (BDRE && BDRE->isByRef())
3133      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3134                                 FieldType);
3135
3136    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3137                                         Name, FieldType, /*TInfo=*/0,
3138                                         /*BitWidth=*/0, /*Mutable=*/false);
3139    T->addDecl(Field);
3140  }
3141
3142  T->completeDefinition(*this);
3143
3144  return getPointerType(getTagDeclType(T));
3145}
3146
3147void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3148  const RecordType *Rec = T->getAs<RecordType>();
3149  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3150  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3151}
3152
3153// This returns true if a type has been typedefed to BOOL:
3154// typedef <type> BOOL;
3155static bool isTypeTypedefedAsBOOL(QualType T) {
3156  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3157    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3158      return II->isStr("BOOL");
3159
3160  return false;
3161}
3162
3163/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3164/// purpose.
3165CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3166  CharUnits sz = getTypeSizeInChars(type);
3167
3168  // Make all integer and enum types at least as large as an int
3169  if (sz.isPositive() && type->isIntegralType())
3170    sz = std::max(sz, getTypeSizeInChars(IntTy));
3171  // Treat arrays as pointers, since that's how they're passed in.
3172  else if (type->isArrayType())
3173    sz = getTypeSizeInChars(VoidPtrTy);
3174  return sz;
3175}
3176
3177static inline
3178std::string charUnitsToString(const CharUnits &CU) {
3179  return llvm::itostr(CU.getQuantity());
3180}
3181
3182/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3183/// declaration.
3184void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3185                                             std::string& S) {
3186  const BlockDecl *Decl = Expr->getBlockDecl();
3187  QualType BlockTy =
3188      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3189  // Encode result type.
3190  getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3191  // Compute size of all parameters.
3192  // Start with computing size of a pointer in number of bytes.
3193  // FIXME: There might(should) be a better way of doing this computation!
3194  SourceLocation Loc;
3195  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3196  CharUnits ParmOffset = PtrSize;
3197  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3198       E = Decl->param_end(); PI != E; ++PI) {
3199    QualType PType = (*PI)->getType();
3200    CharUnits sz = getObjCEncodingTypeSize(PType);
3201    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3202    ParmOffset += sz;
3203  }
3204  // Size of the argument frame
3205  S += charUnitsToString(ParmOffset);
3206  // Block pointer and offset.
3207  S += "@?0";
3208  ParmOffset = PtrSize;
3209
3210  // Argument types.
3211  ParmOffset = PtrSize;
3212  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3213       Decl->param_end(); PI != E; ++PI) {
3214    ParmVarDecl *PVDecl = *PI;
3215    QualType PType = PVDecl->getOriginalType();
3216    if (const ArrayType *AT =
3217          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3218      // Use array's original type only if it has known number of
3219      // elements.
3220      if (!isa<ConstantArrayType>(AT))
3221        PType = PVDecl->getType();
3222    } else if (PType->isFunctionType())
3223      PType = PVDecl->getType();
3224    getObjCEncodingForType(PType, S);
3225    S += charUnitsToString(ParmOffset);
3226    ParmOffset += getObjCEncodingTypeSize(PType);
3227  }
3228}
3229
3230/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3231/// declaration.
3232void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3233                                              std::string& S) {
3234  // FIXME: This is not very efficient.
3235  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3236  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3237  // Encode result type.
3238  getObjCEncodingForType(Decl->getResultType(), S);
3239  // Compute size of all parameters.
3240  // Start with computing size of a pointer in number of bytes.
3241  // FIXME: There might(should) be a better way of doing this computation!
3242  SourceLocation Loc;
3243  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3244  // The first two arguments (self and _cmd) are pointers; account for
3245  // their size.
3246  CharUnits ParmOffset = 2 * PtrSize;
3247  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3248       E = Decl->param_end(); PI != E; ++PI) {
3249    QualType PType = (*PI)->getType();
3250    CharUnits sz = getObjCEncodingTypeSize(PType);
3251    assert (sz.isPositive() &&
3252        "getObjCEncodingForMethodDecl - Incomplete param type");
3253    ParmOffset += sz;
3254  }
3255  S += charUnitsToString(ParmOffset);
3256  S += "@0:";
3257  S += charUnitsToString(PtrSize);
3258
3259  // Argument types.
3260  ParmOffset = 2 * PtrSize;
3261  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3262       E = Decl->param_end(); PI != E; ++PI) {
3263    ParmVarDecl *PVDecl = *PI;
3264    QualType PType = PVDecl->getOriginalType();
3265    if (const ArrayType *AT =
3266          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3267      // Use array's original type only if it has known number of
3268      // elements.
3269      if (!isa<ConstantArrayType>(AT))
3270        PType = PVDecl->getType();
3271    } else if (PType->isFunctionType())
3272      PType = PVDecl->getType();
3273    // Process argument qualifiers for user supplied arguments; such as,
3274    // 'in', 'inout', etc.
3275    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3276    getObjCEncodingForType(PType, S);
3277    S += charUnitsToString(ParmOffset);
3278    ParmOffset += getObjCEncodingTypeSize(PType);
3279  }
3280}
3281
3282/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3283/// property declaration. If non-NULL, Container must be either an
3284/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3285/// NULL when getting encodings for protocol properties.
3286/// Property attributes are stored as a comma-delimited C string. The simple
3287/// attributes readonly and bycopy are encoded as single characters. The
3288/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3289/// encoded as single characters, followed by an identifier. Property types
3290/// are also encoded as a parametrized attribute. The characters used to encode
3291/// these attributes are defined by the following enumeration:
3292/// @code
3293/// enum PropertyAttributes {
3294/// kPropertyReadOnly = 'R',   // property is read-only.
3295/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3296/// kPropertyByref = '&',  // property is a reference to the value last assigned
3297/// kPropertyDynamic = 'D',    // property is dynamic
3298/// kPropertyGetter = 'G',     // followed by getter selector name
3299/// kPropertySetter = 'S',     // followed by setter selector name
3300/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3301/// kPropertyType = 't'              // followed by old-style type encoding.
3302/// kPropertyWeak = 'W'              // 'weak' property
3303/// kPropertyStrong = 'P'            // property GC'able
3304/// kPropertyNonAtomic = 'N'         // property non-atomic
3305/// };
3306/// @endcode
3307void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3308                                                const Decl *Container,
3309                                                std::string& S) {
3310  // Collect information from the property implementation decl(s).
3311  bool Dynamic = false;
3312  ObjCPropertyImplDecl *SynthesizePID = 0;
3313
3314  // FIXME: Duplicated code due to poor abstraction.
3315  if (Container) {
3316    if (const ObjCCategoryImplDecl *CID =
3317        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3318      for (ObjCCategoryImplDecl::propimpl_iterator
3319             i = CID->propimpl_begin(), e = CID->propimpl_end();
3320           i != e; ++i) {
3321        ObjCPropertyImplDecl *PID = *i;
3322        if (PID->getPropertyDecl() == PD) {
3323          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3324            Dynamic = true;
3325          } else {
3326            SynthesizePID = PID;
3327          }
3328        }
3329      }
3330    } else {
3331      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3332      for (ObjCCategoryImplDecl::propimpl_iterator
3333             i = OID->propimpl_begin(), e = OID->propimpl_end();
3334           i != e; ++i) {
3335        ObjCPropertyImplDecl *PID = *i;
3336        if (PID->getPropertyDecl() == PD) {
3337          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3338            Dynamic = true;
3339          } else {
3340            SynthesizePID = PID;
3341          }
3342        }
3343      }
3344    }
3345  }
3346
3347  // FIXME: This is not very efficient.
3348  S = "T";
3349
3350  // Encode result type.
3351  // GCC has some special rules regarding encoding of properties which
3352  // closely resembles encoding of ivars.
3353  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3354                             true /* outermost type */,
3355                             true /* encoding for property */);
3356
3357  if (PD->isReadOnly()) {
3358    S += ",R";
3359  } else {
3360    switch (PD->getSetterKind()) {
3361    case ObjCPropertyDecl::Assign: break;
3362    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3363    case ObjCPropertyDecl::Retain: S += ",&"; break;
3364    }
3365  }
3366
3367  // It really isn't clear at all what this means, since properties
3368  // are "dynamic by default".
3369  if (Dynamic)
3370    S += ",D";
3371
3372  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3373    S += ",N";
3374
3375  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3376    S += ",G";
3377    S += PD->getGetterName().getAsString();
3378  }
3379
3380  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3381    S += ",S";
3382    S += PD->getSetterName().getAsString();
3383  }
3384
3385  if (SynthesizePID) {
3386    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3387    S += ",V";
3388    S += OID->getNameAsString();
3389  }
3390
3391  // FIXME: OBJCGC: weak & strong
3392}
3393
3394/// getLegacyIntegralTypeEncoding -
3395/// Another legacy compatibility encoding: 32-bit longs are encoded as
3396/// 'l' or 'L' , but not always.  For typedefs, we need to use
3397/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3398///
3399void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3400  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3401    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3402      if (BT->getKind() == BuiltinType::ULong &&
3403          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3404        PointeeTy = UnsignedIntTy;
3405      else
3406        if (BT->getKind() == BuiltinType::Long &&
3407            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3408          PointeeTy = IntTy;
3409    }
3410  }
3411}
3412
3413void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3414                                        const FieldDecl *Field) {
3415  // We follow the behavior of gcc, expanding structures which are
3416  // directly pointed to, and expanding embedded structures. Note that
3417  // these rules are sufficient to prevent recursive encoding of the
3418  // same type.
3419  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3420                             true /* outermost type */);
3421}
3422
3423static void EncodeBitField(const ASTContext *Context, std::string& S,
3424                           const FieldDecl *FD) {
3425  const Expr *E = FD->getBitWidth();
3426  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3427  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3428  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3429  S += 'b';
3430  S += llvm::utostr(N);
3431}
3432
3433// FIXME: Use SmallString for accumulating string.
3434void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3435                                            bool ExpandPointedToStructures,
3436                                            bool ExpandStructures,
3437                                            const FieldDecl *FD,
3438                                            bool OutermostType,
3439                                            bool EncodingProperty) {
3440  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3441    if (FD && FD->isBitField())
3442      return EncodeBitField(this, S, FD);
3443    char encoding;
3444    switch (BT->getKind()) {
3445    default: assert(0 && "Unhandled builtin type kind");
3446    case BuiltinType::Void:       encoding = 'v'; break;
3447    case BuiltinType::Bool:       encoding = 'B'; break;
3448    case BuiltinType::Char_U:
3449    case BuiltinType::UChar:      encoding = 'C'; break;
3450    case BuiltinType::UShort:     encoding = 'S'; break;
3451    case BuiltinType::UInt:       encoding = 'I'; break;
3452    case BuiltinType::ULong:
3453        encoding =
3454          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3455        break;
3456    case BuiltinType::UInt128:    encoding = 'T'; break;
3457    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3458    case BuiltinType::Char_S:
3459    case BuiltinType::SChar:      encoding = 'c'; break;
3460    case BuiltinType::Short:      encoding = 's'; break;
3461    case BuiltinType::Int:        encoding = 'i'; break;
3462    case BuiltinType::Long:
3463      encoding =
3464        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3465      break;
3466    case BuiltinType::LongLong:   encoding = 'q'; break;
3467    case BuiltinType::Int128:     encoding = 't'; break;
3468    case BuiltinType::Float:      encoding = 'f'; break;
3469    case BuiltinType::Double:     encoding = 'd'; break;
3470    case BuiltinType::LongDouble: encoding = 'd'; break;
3471    }
3472
3473    S += encoding;
3474    return;
3475  }
3476
3477  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3478    S += 'j';
3479    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3480                               false);
3481    return;
3482  }
3483
3484  if (const PointerType *PT = T->getAs<PointerType>()) {
3485    if (PT->isObjCSelType()) {
3486      S += ':';
3487      return;
3488    }
3489    QualType PointeeTy = PT->getPointeeType();
3490
3491    bool isReadOnly = false;
3492    // For historical/compatibility reasons, the read-only qualifier of the
3493    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3494    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3495    // Also, do not emit the 'r' for anything but the outermost type!
3496    if (isa<TypedefType>(T.getTypePtr())) {
3497      if (OutermostType && T.isConstQualified()) {
3498        isReadOnly = true;
3499        S += 'r';
3500      }
3501    } else if (OutermostType) {
3502      QualType P = PointeeTy;
3503      while (P->getAs<PointerType>())
3504        P = P->getAs<PointerType>()->getPointeeType();
3505      if (P.isConstQualified()) {
3506        isReadOnly = true;
3507        S += 'r';
3508      }
3509    }
3510    if (isReadOnly) {
3511      // Another legacy compatibility encoding. Some ObjC qualifier and type
3512      // combinations need to be rearranged.
3513      // Rewrite "in const" from "nr" to "rn"
3514      const char * s = S.c_str();
3515      int len = S.length();
3516      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3517        std::string replace = "rn";
3518        S.replace(S.end()-2, S.end(), replace);
3519      }
3520    }
3521
3522    if (PointeeTy->isCharType()) {
3523      // char pointer types should be encoded as '*' unless it is a
3524      // type that has been typedef'd to 'BOOL'.
3525      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3526        S += '*';
3527        return;
3528      }
3529    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3530      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3531      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3532        S += '#';
3533        return;
3534      }
3535      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3536      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3537        S += '@';
3538        return;
3539      }
3540      // fall through...
3541    }
3542    S += '^';
3543    getLegacyIntegralTypeEncoding(PointeeTy);
3544
3545    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3546                               NULL);
3547    return;
3548  }
3549
3550  if (const ArrayType *AT =
3551      // Ignore type qualifiers etc.
3552        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3553    if (isa<IncompleteArrayType>(AT)) {
3554      // Incomplete arrays are encoded as a pointer to the array element.
3555      S += '^';
3556
3557      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3558                                 false, ExpandStructures, FD);
3559    } else {
3560      S += '[';
3561
3562      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3563        S += llvm::utostr(CAT->getSize().getZExtValue());
3564      else {
3565        //Variable length arrays are encoded as a regular array with 0 elements.
3566        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3567        S += '0';
3568      }
3569
3570      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3571                                 false, ExpandStructures, FD);
3572      S += ']';
3573    }
3574    return;
3575  }
3576
3577  if (T->getAs<FunctionType>()) {
3578    S += '?';
3579    return;
3580  }
3581
3582  if (const RecordType *RTy = T->getAs<RecordType>()) {
3583    RecordDecl *RDecl = RTy->getDecl();
3584    S += RDecl->isUnion() ? '(' : '{';
3585    // Anonymous structures print as '?'
3586    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3587      S += II->getName();
3588    } else {
3589      S += '?';
3590    }
3591    if (ExpandStructures) {
3592      S += '=';
3593      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3594                                   FieldEnd = RDecl->field_end();
3595           Field != FieldEnd; ++Field) {
3596        if (FD) {
3597          S += '"';
3598          S += Field->getNameAsString();
3599          S += '"';
3600        }
3601
3602        // Special case bit-fields.
3603        if (Field->isBitField()) {
3604          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3605                                     (*Field));
3606        } else {
3607          QualType qt = Field->getType();
3608          getLegacyIntegralTypeEncoding(qt);
3609          getObjCEncodingForTypeImpl(qt, S, false, true,
3610                                     FD);
3611        }
3612      }
3613    }
3614    S += RDecl->isUnion() ? ')' : '}';
3615    return;
3616  }
3617
3618  if (T->isEnumeralType()) {
3619    if (FD && FD->isBitField())
3620      EncodeBitField(this, S, FD);
3621    else
3622      S += 'i';
3623    return;
3624  }
3625
3626  if (T->isBlockPointerType()) {
3627    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3628    return;
3629  }
3630
3631  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3632    // @encode(class_name)
3633    ObjCInterfaceDecl *OI = OIT->getDecl();
3634    S += '{';
3635    const IdentifierInfo *II = OI->getIdentifier();
3636    S += II->getName();
3637    S += '=';
3638    llvm::SmallVector<FieldDecl*, 32> RecFields;
3639    CollectObjCIvars(OI, RecFields);
3640    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3641      if (RecFields[i]->isBitField())
3642        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3643                                   RecFields[i]);
3644      else
3645        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3646                                   FD);
3647    }
3648    S += '}';
3649    return;
3650  }
3651
3652  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3653    if (OPT->isObjCIdType()) {
3654      S += '@';
3655      return;
3656    }
3657
3658    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3659      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3660      // Since this is a binary compatibility issue, need to consult with runtime
3661      // folks. Fortunately, this is a *very* obsure construct.
3662      S += '#';
3663      return;
3664    }
3665
3666    if (OPT->isObjCQualifiedIdType()) {
3667      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3668                                 ExpandPointedToStructures,
3669                                 ExpandStructures, FD);
3670      if (FD || EncodingProperty) {
3671        // Note that we do extended encoding of protocol qualifer list
3672        // Only when doing ivar or property encoding.
3673        S += '"';
3674        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3675             E = OPT->qual_end(); I != E; ++I) {
3676          S += '<';
3677          S += (*I)->getNameAsString();
3678          S += '>';
3679        }
3680        S += '"';
3681      }
3682      return;
3683    }
3684
3685    QualType PointeeTy = OPT->getPointeeType();
3686    if (!EncodingProperty &&
3687        isa<TypedefType>(PointeeTy.getTypePtr())) {
3688      // Another historical/compatibility reason.
3689      // We encode the underlying type which comes out as
3690      // {...};
3691      S += '^';
3692      getObjCEncodingForTypeImpl(PointeeTy, S,
3693                                 false, ExpandPointedToStructures,
3694                                 NULL);
3695      return;
3696    }
3697
3698    S += '@';
3699    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3700      S += '"';
3701      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3702      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3703           E = OPT->qual_end(); I != E; ++I) {
3704        S += '<';
3705        S += (*I)->getNameAsString();
3706        S += '>';
3707      }
3708      S += '"';
3709    }
3710    return;
3711  }
3712
3713  assert(0 && "@encode for type not implemented!");
3714}
3715
3716void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3717                                                 std::string& S) const {
3718  if (QT & Decl::OBJC_TQ_In)
3719    S += 'n';
3720  if (QT & Decl::OBJC_TQ_Inout)
3721    S += 'N';
3722  if (QT & Decl::OBJC_TQ_Out)
3723    S += 'o';
3724  if (QT & Decl::OBJC_TQ_Bycopy)
3725    S += 'O';
3726  if (QT & Decl::OBJC_TQ_Byref)
3727    S += 'R';
3728  if (QT & Decl::OBJC_TQ_Oneway)
3729    S += 'V';
3730}
3731
3732void ASTContext::setBuiltinVaListType(QualType T) {
3733  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3734
3735  BuiltinVaListType = T;
3736}
3737
3738void ASTContext::setObjCIdType(QualType T) {
3739  ObjCIdTypedefType = T;
3740}
3741
3742void ASTContext::setObjCSelType(QualType T) {
3743  ObjCSelTypedefType = T;
3744}
3745
3746void ASTContext::setObjCProtoType(QualType QT) {
3747  ObjCProtoType = QT;
3748}
3749
3750void ASTContext::setObjCClassType(QualType T) {
3751  ObjCClassTypedefType = T;
3752}
3753
3754void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3755  assert(ObjCConstantStringType.isNull() &&
3756         "'NSConstantString' type already set!");
3757
3758  ObjCConstantStringType = getObjCInterfaceType(Decl);
3759}
3760
3761/// \brief Retrieve the template name that corresponds to a non-empty
3762/// lookup.
3763TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3764                                                   UnresolvedSetIterator End) {
3765  unsigned size = End - Begin;
3766  assert(size > 1 && "set is not overloaded!");
3767
3768  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3769                          size * sizeof(FunctionTemplateDecl*));
3770  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3771
3772  NamedDecl **Storage = OT->getStorage();
3773  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3774    NamedDecl *D = *I;
3775    assert(isa<FunctionTemplateDecl>(D) ||
3776           (isa<UsingShadowDecl>(D) &&
3777            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3778    *Storage++ = D;
3779  }
3780
3781  return TemplateName(OT);
3782}
3783
3784/// \brief Retrieve the template name that represents a qualified
3785/// template name such as \c std::vector.
3786TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3787                                                  bool TemplateKeyword,
3788                                                  TemplateDecl *Template) {
3789  llvm::FoldingSetNodeID ID;
3790  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3791
3792  void *InsertPos = 0;
3793  QualifiedTemplateName *QTN =
3794    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3795  if (!QTN) {
3796    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3797    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3798  }
3799
3800  return TemplateName(QTN);
3801}
3802
3803/// \brief Retrieve the template name that represents a dependent
3804/// template name such as \c MetaFun::template apply.
3805TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3806                                                  const IdentifierInfo *Name) {
3807  assert((!NNS || NNS->isDependent()) &&
3808         "Nested name specifier must be dependent");
3809
3810  llvm::FoldingSetNodeID ID;
3811  DependentTemplateName::Profile(ID, NNS, Name);
3812
3813  void *InsertPos = 0;
3814  DependentTemplateName *QTN =
3815    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3816
3817  if (QTN)
3818    return TemplateName(QTN);
3819
3820  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3821  if (CanonNNS == NNS) {
3822    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3823  } else {
3824    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3825    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3826  }
3827
3828  DependentTemplateNames.InsertNode(QTN, InsertPos);
3829  return TemplateName(QTN);
3830}
3831
3832/// \brief Retrieve the template name that represents a dependent
3833/// template name such as \c MetaFun::template operator+.
3834TemplateName
3835ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3836                                     OverloadedOperatorKind Operator) {
3837  assert((!NNS || NNS->isDependent()) &&
3838         "Nested name specifier must be dependent");
3839
3840  llvm::FoldingSetNodeID ID;
3841  DependentTemplateName::Profile(ID, NNS, Operator);
3842
3843  void *InsertPos = 0;
3844  DependentTemplateName *QTN =
3845  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3846
3847  if (QTN)
3848    return TemplateName(QTN);
3849
3850  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3851  if (CanonNNS == NNS) {
3852    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3853  } else {
3854    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3855    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3856  }
3857
3858  DependentTemplateNames.InsertNode(QTN, InsertPos);
3859  return TemplateName(QTN);
3860}
3861
3862/// getFromTargetType - Given one of the integer types provided by
3863/// TargetInfo, produce the corresponding type. The unsigned @p Type
3864/// is actually a value of type @c TargetInfo::IntType.
3865CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3866  switch (Type) {
3867  case TargetInfo::NoInt: return CanQualType();
3868  case TargetInfo::SignedShort: return ShortTy;
3869  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3870  case TargetInfo::SignedInt: return IntTy;
3871  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3872  case TargetInfo::SignedLong: return LongTy;
3873  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3874  case TargetInfo::SignedLongLong: return LongLongTy;
3875  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3876  }
3877
3878  assert(false && "Unhandled TargetInfo::IntType value");
3879  return CanQualType();
3880}
3881
3882//===----------------------------------------------------------------------===//
3883//                        Type Predicates.
3884//===----------------------------------------------------------------------===//
3885
3886/// isObjCNSObjectType - Return true if this is an NSObject object using
3887/// NSObject attribute on a c-style pointer type.
3888/// FIXME - Make it work directly on types.
3889/// FIXME: Move to Type.
3890///
3891bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3892  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3893    if (TypedefDecl *TD = TDT->getDecl())
3894      if (TD->getAttr<ObjCNSObjectAttr>())
3895        return true;
3896  }
3897  return false;
3898}
3899
3900/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3901/// garbage collection attribute.
3902///
3903Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3904  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3905  if (getLangOptions().ObjC1 &&
3906      getLangOptions().getGCMode() != LangOptions::NonGC) {
3907    GCAttrs = Ty.getObjCGCAttr();
3908    // Default behavious under objective-c's gc is for objective-c pointers
3909    // (or pointers to them) be treated as though they were declared
3910    // as __strong.
3911    if (GCAttrs == Qualifiers::GCNone) {
3912      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3913        GCAttrs = Qualifiers::Strong;
3914      else if (Ty->isPointerType())
3915        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3916    }
3917    // Non-pointers have none gc'able attribute regardless of the attribute
3918    // set on them.
3919    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3920      return Qualifiers::GCNone;
3921  }
3922  return GCAttrs;
3923}
3924
3925//===----------------------------------------------------------------------===//
3926//                        Type Compatibility Testing
3927//===----------------------------------------------------------------------===//
3928
3929/// areCompatVectorTypes - Return true if the two specified vector types are
3930/// compatible.
3931static bool areCompatVectorTypes(const VectorType *LHS,
3932                                 const VectorType *RHS) {
3933  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3934  return LHS->getElementType() == RHS->getElementType() &&
3935         LHS->getNumElements() == RHS->getNumElements();
3936}
3937
3938//===----------------------------------------------------------------------===//
3939// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3940//===----------------------------------------------------------------------===//
3941
3942/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3943/// inheritance hierarchy of 'rProto'.
3944bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3945                                                ObjCProtocolDecl *rProto) {
3946  if (lProto == rProto)
3947    return true;
3948  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3949       E = rProto->protocol_end(); PI != E; ++PI)
3950    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3951      return true;
3952  return false;
3953}
3954
3955/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3956/// return true if lhs's protocols conform to rhs's protocol; false
3957/// otherwise.
3958bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3959  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3960    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3961  return false;
3962}
3963
3964/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3965/// ObjCQualifiedIDType.
3966bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3967                                                   bool compare) {
3968  // Allow id<P..> and an 'id' or void* type in all cases.
3969  if (lhs->isVoidPointerType() ||
3970      lhs->isObjCIdType() || lhs->isObjCClassType())
3971    return true;
3972  else if (rhs->isVoidPointerType() ||
3973           rhs->isObjCIdType() || rhs->isObjCClassType())
3974    return true;
3975
3976  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3977    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
3978
3979    if (!rhsOPT) return false;
3980
3981    if (rhsOPT->qual_empty()) {
3982      // If the RHS is a unqualified interface pointer "NSString*",
3983      // make sure we check the class hierarchy.
3984      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3985        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3986             E = lhsQID->qual_end(); I != E; ++I) {
3987          // when comparing an id<P> on lhs with a static type on rhs,
3988          // see if static class implements all of id's protocols, directly or
3989          // through its super class and categories.
3990          if (!rhsID->ClassImplementsProtocol(*I, true))
3991            return false;
3992        }
3993      }
3994      // If there are no qualifiers and no interface, we have an 'id'.
3995      return true;
3996    }
3997    // Both the right and left sides have qualifiers.
3998    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3999         E = lhsQID->qual_end(); I != E; ++I) {
4000      ObjCProtocolDecl *lhsProto = *I;
4001      bool match = false;
4002
4003      // when comparing an id<P> on lhs with a static type on rhs,
4004      // see if static class implements all of id's protocols, directly or
4005      // through its super class and categories.
4006      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4007           E = rhsOPT->qual_end(); J != E; ++J) {
4008        ObjCProtocolDecl *rhsProto = *J;
4009        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4010            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4011          match = true;
4012          break;
4013        }
4014      }
4015      // If the RHS is a qualified interface pointer "NSString<P>*",
4016      // make sure we check the class hierarchy.
4017      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4018        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4019             E = lhsQID->qual_end(); I != E; ++I) {
4020          // when comparing an id<P> on lhs with a static type on rhs,
4021          // see if static class implements all of id's protocols, directly or
4022          // through its super class and categories.
4023          if (rhsID->ClassImplementsProtocol(*I, true)) {
4024            match = true;
4025            break;
4026          }
4027        }
4028      }
4029      if (!match)
4030        return false;
4031    }
4032
4033    return true;
4034  }
4035
4036  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4037  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4038
4039  if (const ObjCObjectPointerType *lhsOPT =
4040        lhs->getAsObjCInterfacePointerType()) {
4041    if (lhsOPT->qual_empty()) {
4042      bool match = false;
4043      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4044        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4045             E = rhsQID->qual_end(); I != E; ++I) {
4046          // when comparing an id<P> on lhs with a static type on rhs,
4047          // see if static class implements all of id's protocols, directly or
4048          // through its super class and categories.
4049          if (lhsID->ClassImplementsProtocol(*I, true)) {
4050            match = true;
4051            break;
4052          }
4053        }
4054        if (!match)
4055          return false;
4056      }
4057      return true;
4058    }
4059    // Both the right and left sides have qualifiers.
4060    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4061         E = lhsOPT->qual_end(); I != E; ++I) {
4062      ObjCProtocolDecl *lhsProto = *I;
4063      bool match = false;
4064
4065      // when comparing an id<P> on lhs with a static type on rhs,
4066      // see if static class implements all of id's protocols, directly or
4067      // through its super class and categories.
4068      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4069           E = rhsQID->qual_end(); J != E; ++J) {
4070        ObjCProtocolDecl *rhsProto = *J;
4071        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4072            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4073          match = true;
4074          break;
4075        }
4076      }
4077      if (!match)
4078        return false;
4079    }
4080    return true;
4081  }
4082  return false;
4083}
4084
4085/// canAssignObjCInterfaces - Return true if the two interface types are
4086/// compatible for assignment from RHS to LHS.  This handles validation of any
4087/// protocol qualifiers on the LHS or RHS.
4088///
4089bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4090                                         const ObjCObjectPointerType *RHSOPT) {
4091  // If either type represents the built-in 'id' or 'Class' types, return true.
4092  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4093    return true;
4094
4095  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4096    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4097                                             QualType(RHSOPT,0),
4098                                             false);
4099
4100  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4101  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4102  if (LHS && RHS) // We have 2 user-defined types.
4103    return canAssignObjCInterfaces(LHS, RHS);
4104
4105  return false;
4106}
4107
4108/// getIntersectionOfProtocols - This routine finds the intersection of set
4109/// of protocols inherited from two distinct objective-c pointer objects.
4110/// It is used to build composite qualifier list of the composite type of
4111/// the conditional expression involving two objective-c pointer objects.
4112static
4113void getIntersectionOfProtocols(ASTContext &Context,
4114                                const ObjCObjectPointerType *LHSOPT,
4115                                const ObjCObjectPointerType *RHSOPT,
4116      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4117
4118  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4119  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4120
4121  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4122  unsigned LHSNumProtocols = LHS->getNumProtocols();
4123  if (LHSNumProtocols > 0)
4124    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4125  else {
4126    llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4127     Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4128    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4129                                LHSInheritedProtocols.end());
4130  }
4131
4132  unsigned RHSNumProtocols = RHS->getNumProtocols();
4133  if (RHSNumProtocols > 0) {
4134    ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4135    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4136      if (InheritedProtocolSet.count(RHSProtocols[i]))
4137        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4138  }
4139  else {
4140    llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4141    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4142    // FIXME. This may cause duplication of protocols in the list, but should
4143    // be harmless.
4144    for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4145      if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4146        IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4147  }
4148}
4149
4150/// areCommonBaseCompatible - Returns common base class of the two classes if
4151/// one found. Note that this is O'2 algorithm. But it will be called as the
4152/// last type comparison in a ?-exp of ObjC pointer types before a
4153/// warning is issued. So, its invokation is extremely rare.
4154QualType ASTContext::areCommonBaseCompatible(
4155                                          const ObjCObjectPointerType *LHSOPT,
4156                                          const ObjCObjectPointerType *RHSOPT) {
4157  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4158  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4159  if (!LHS || !RHS)
4160    return QualType();
4161
4162  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4163    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4164    LHS = LHSTy->getAs<ObjCInterfaceType>();
4165    if (canAssignObjCInterfaces(LHS, RHS)) {
4166      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4167      getIntersectionOfProtocols(*this,
4168                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4169      if (IntersectionOfProtocols.empty())
4170        LHSTy = getObjCObjectPointerType(LHSTy);
4171      else
4172        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4173                                                IntersectionOfProtocols.size());
4174      return LHSTy;
4175    }
4176  }
4177
4178  return QualType();
4179}
4180
4181bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4182                                         const ObjCInterfaceType *RHS) {
4183  // Verify that the base decls are compatible: the RHS must be a subclass of
4184  // the LHS.
4185  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4186    return false;
4187
4188  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4189  // protocol qualified at all, then we are good.
4190  if (LHS->getNumProtocols() == 0)
4191    return true;
4192
4193  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4194  // isn't a superset.
4195  if (RHS->getNumProtocols() == 0)
4196    return true;  // FIXME: should return false!
4197
4198  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4199                                        LHSPE = LHS->qual_end();
4200       LHSPI != LHSPE; LHSPI++) {
4201    bool RHSImplementsProtocol = false;
4202
4203    // If the RHS doesn't implement the protocol on the left, the types
4204    // are incompatible.
4205    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4206                                          RHSPE = RHS->qual_end();
4207         RHSPI != RHSPE; RHSPI++) {
4208      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4209        RHSImplementsProtocol = true;
4210        break;
4211      }
4212    }
4213    // FIXME: For better diagnostics, consider passing back the protocol name.
4214    if (!RHSImplementsProtocol)
4215      return false;
4216  }
4217  // The RHS implements all protocols listed on the LHS.
4218  return true;
4219}
4220
4221bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4222  // get the "pointed to" types
4223  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4224  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4225
4226  if (!LHSOPT || !RHSOPT)
4227    return false;
4228
4229  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4230         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4231}
4232
4233/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4234/// both shall have the identically qualified version of a compatible type.
4235/// C99 6.2.7p1: Two types have compatible types if their types are the
4236/// same. See 6.7.[2,3,5] for additional rules.
4237bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4238  return !mergeTypes(LHS, RHS).isNull();
4239}
4240
4241static bool isSameCallingConvention(CallingConv lcc, CallingConv rcc) {
4242  return (getCanonicalCallingConv(lcc) == getCanonicalCallingConv(rcc));
4243}
4244
4245QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
4246  const FunctionType *lbase = lhs->getAs<FunctionType>();
4247  const FunctionType *rbase = rhs->getAs<FunctionType>();
4248  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4249  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4250  bool allLTypes = true;
4251  bool allRTypes = true;
4252
4253  // Check return type
4254  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4255  if (retType.isNull()) return QualType();
4256  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4257    allLTypes = false;
4258  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4259    allRTypes = false;
4260  // FIXME: double check this
4261  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4262  if (NoReturn != lbase->getNoReturnAttr())
4263    allLTypes = false;
4264  if (NoReturn != rbase->getNoReturnAttr())
4265    allRTypes = false;
4266  CallingConv lcc = lbase->getCallConv();
4267  CallingConv rcc = rbase->getCallConv();
4268  // Compatible functions must have compatible calling conventions
4269  if (!isSameCallingConvention(lcc, rcc))
4270    return QualType();
4271
4272  if (lproto && rproto) { // two C99 style function prototypes
4273    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4274           "C++ shouldn't be here");
4275    unsigned lproto_nargs = lproto->getNumArgs();
4276    unsigned rproto_nargs = rproto->getNumArgs();
4277
4278    // Compatible functions must have the same number of arguments
4279    if (lproto_nargs != rproto_nargs)
4280      return QualType();
4281
4282    // Variadic and non-variadic functions aren't compatible
4283    if (lproto->isVariadic() != rproto->isVariadic())
4284      return QualType();
4285
4286    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4287      return QualType();
4288
4289    // Check argument compatibility
4290    llvm::SmallVector<QualType, 10> types;
4291    for (unsigned i = 0; i < lproto_nargs; i++) {
4292      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4293      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4294      QualType argtype = mergeTypes(largtype, rargtype);
4295      if (argtype.isNull()) return QualType();
4296      types.push_back(argtype);
4297      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4298        allLTypes = false;
4299      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4300        allRTypes = false;
4301    }
4302    if (allLTypes) return lhs;
4303    if (allRTypes) return rhs;
4304    return getFunctionType(retType, types.begin(), types.size(),
4305                           lproto->isVariadic(), lproto->getTypeQuals(),
4306                           NoReturn, lcc);
4307  }
4308
4309  if (lproto) allRTypes = false;
4310  if (rproto) allLTypes = false;
4311
4312  const FunctionProtoType *proto = lproto ? lproto : rproto;
4313  if (proto) {
4314    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4315    if (proto->isVariadic()) return QualType();
4316    // Check that the types are compatible with the types that
4317    // would result from default argument promotions (C99 6.7.5.3p15).
4318    // The only types actually affected are promotable integer
4319    // types and floats, which would be passed as a different
4320    // type depending on whether the prototype is visible.
4321    unsigned proto_nargs = proto->getNumArgs();
4322    for (unsigned i = 0; i < proto_nargs; ++i) {
4323      QualType argTy = proto->getArgType(i);
4324      if (argTy->isPromotableIntegerType() ||
4325          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4326        return QualType();
4327    }
4328
4329    if (allLTypes) return lhs;
4330    if (allRTypes) return rhs;
4331    return getFunctionType(retType, proto->arg_type_begin(),
4332                           proto->getNumArgs(), proto->isVariadic(),
4333                           proto->getTypeQuals(), NoReturn, lcc);
4334  }
4335
4336  if (allLTypes) return lhs;
4337  if (allRTypes) return rhs;
4338  return getFunctionNoProtoType(retType, NoReturn, lcc);
4339}
4340
4341QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
4342  // C++ [expr]: If an expression initially has the type "reference to T", the
4343  // type is adjusted to "T" prior to any further analysis, the expression
4344  // designates the object or function denoted by the reference, and the
4345  // expression is an lvalue unless the reference is an rvalue reference and
4346  // the expression is a function call (possibly inside parentheses).
4347  // FIXME: C++ shouldn't be going through here!  The rules are different
4348  // enough that they should be handled separately.
4349  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4350  // shouldn't be going through here!
4351  if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
4352    LHS = RT->getPointeeType();
4353  if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
4354    RHS = RT->getPointeeType();
4355
4356  QualType LHSCan = getCanonicalType(LHS),
4357           RHSCan = getCanonicalType(RHS);
4358
4359  // If two types are identical, they are compatible.
4360  if (LHSCan == RHSCan)
4361    return LHS;
4362
4363  // If the qualifiers are different, the types aren't compatible... mostly.
4364  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4365  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4366  if (LQuals != RQuals) {
4367    // If any of these qualifiers are different, we have a type
4368    // mismatch.
4369    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4370        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4371      return QualType();
4372
4373    // Exactly one GC qualifier difference is allowed: __strong is
4374    // okay if the other type has no GC qualifier but is an Objective
4375    // C object pointer (i.e. implicitly strong by default).  We fix
4376    // this by pretending that the unqualified type was actually
4377    // qualified __strong.
4378    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4379    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4380    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4381
4382    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4383      return QualType();
4384
4385    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4386      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4387    }
4388    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4389      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4390    }
4391    return QualType();
4392  }
4393
4394  // Okay, qualifiers are equal.
4395
4396  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4397  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4398
4399  // We want to consider the two function types to be the same for these
4400  // comparisons, just force one to the other.
4401  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4402  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4403
4404  // Same as above for arrays
4405  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4406    LHSClass = Type::ConstantArray;
4407  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4408    RHSClass = Type::ConstantArray;
4409
4410  // Canonicalize ExtVector -> Vector.
4411  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4412  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4413
4414  // If the canonical type classes don't match.
4415  if (LHSClass != RHSClass) {
4416    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4417    // a signed integer type, or an unsigned integer type.
4418    // Compatibility is based on the underlying type, not the promotion
4419    // type.
4420    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4421      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4422        return RHS;
4423    }
4424    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4425      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4426        return LHS;
4427    }
4428
4429    return QualType();
4430  }
4431
4432  // The canonical type classes match.
4433  switch (LHSClass) {
4434#define TYPE(Class, Base)
4435#define ABSTRACT_TYPE(Class, Base)
4436#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4437#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4438#include "clang/AST/TypeNodes.def"
4439    assert(false && "Non-canonical and dependent types shouldn't get here");
4440    return QualType();
4441
4442  case Type::LValueReference:
4443  case Type::RValueReference:
4444  case Type::MemberPointer:
4445    assert(false && "C++ should never be in mergeTypes");
4446    return QualType();
4447
4448  case Type::IncompleteArray:
4449  case Type::VariableArray:
4450  case Type::FunctionProto:
4451  case Type::ExtVector:
4452    assert(false && "Types are eliminated above");
4453    return QualType();
4454
4455  case Type::Pointer:
4456  {
4457    // Merge two pointer types, while trying to preserve typedef info
4458    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4459    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4460    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4461    if (ResultType.isNull()) return QualType();
4462    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4463      return LHS;
4464    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4465      return RHS;
4466    return getPointerType(ResultType);
4467  }
4468  case Type::BlockPointer:
4469  {
4470    // Merge two block pointer types, while trying to preserve typedef info
4471    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4472    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4473    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4474    if (ResultType.isNull()) return QualType();
4475    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4476      return LHS;
4477    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4478      return RHS;
4479    return getBlockPointerType(ResultType);
4480  }
4481  case Type::ConstantArray:
4482  {
4483    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4484    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4485    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4486      return QualType();
4487
4488    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4489    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4490    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4491    if (ResultType.isNull()) return QualType();
4492    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4493      return LHS;
4494    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4495      return RHS;
4496    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4497                                          ArrayType::ArraySizeModifier(), 0);
4498    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4499                                          ArrayType::ArraySizeModifier(), 0);
4500    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4501    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4502    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4503      return LHS;
4504    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4505      return RHS;
4506    if (LVAT) {
4507      // FIXME: This isn't correct! But tricky to implement because
4508      // the array's size has to be the size of LHS, but the type
4509      // has to be different.
4510      return LHS;
4511    }
4512    if (RVAT) {
4513      // FIXME: This isn't correct! But tricky to implement because
4514      // the array's size has to be the size of RHS, but the type
4515      // has to be different.
4516      return RHS;
4517    }
4518    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4519    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4520    return getIncompleteArrayType(ResultType,
4521                                  ArrayType::ArraySizeModifier(), 0);
4522  }
4523  case Type::FunctionNoProto:
4524    return mergeFunctionTypes(LHS, RHS);
4525  case Type::Record:
4526  case Type::Enum:
4527    return QualType();
4528  case Type::Builtin:
4529    // Only exactly equal builtin types are compatible, which is tested above.
4530    return QualType();
4531  case Type::Complex:
4532    // Distinct complex types are incompatible.
4533    return QualType();
4534  case Type::Vector:
4535    // FIXME: The merged type should be an ExtVector!
4536    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4537      return LHS;
4538    return QualType();
4539  case Type::ObjCInterface: {
4540    // Check if the interfaces are assignment compatible.
4541    // FIXME: This should be type compatibility, e.g. whether
4542    // "LHS x; RHS x;" at global scope is legal.
4543    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4544    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4545    if (LHSIface && RHSIface &&
4546        canAssignObjCInterfaces(LHSIface, RHSIface))
4547      return LHS;
4548
4549    return QualType();
4550  }
4551  case Type::ObjCObjectPointer: {
4552    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4553                                RHS->getAs<ObjCObjectPointerType>()))
4554      return LHS;
4555
4556    return QualType();
4557  }
4558  case Type::TemplateSpecialization:
4559    assert(false && "Dependent types have no size");
4560    break;
4561  }
4562
4563  return QualType();
4564}
4565
4566//===----------------------------------------------------------------------===//
4567//                         Integer Predicates
4568//===----------------------------------------------------------------------===//
4569
4570unsigned ASTContext::getIntWidth(QualType T) {
4571  if (T->isBooleanType())
4572    return 1;
4573  if (EnumType *ET = dyn_cast<EnumType>(T))
4574    T = ET->getDecl()->getIntegerType();
4575  // For builtin types, just use the standard type sizing method
4576  return (unsigned)getTypeSize(T);
4577}
4578
4579QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4580  assert(T->isSignedIntegerType() && "Unexpected type");
4581
4582  // Turn <4 x signed int> -> <4 x unsigned int>
4583  if (const VectorType *VTy = T->getAs<VectorType>())
4584    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4585                         VTy->getNumElements());
4586
4587  // For enums, we return the unsigned version of the base type.
4588  if (const EnumType *ETy = T->getAs<EnumType>())
4589    T = ETy->getDecl()->getIntegerType();
4590
4591  const BuiltinType *BTy = T->getAs<BuiltinType>();
4592  assert(BTy && "Unexpected signed integer type");
4593  switch (BTy->getKind()) {
4594  case BuiltinType::Char_S:
4595  case BuiltinType::SChar:
4596    return UnsignedCharTy;
4597  case BuiltinType::Short:
4598    return UnsignedShortTy;
4599  case BuiltinType::Int:
4600    return UnsignedIntTy;
4601  case BuiltinType::Long:
4602    return UnsignedLongTy;
4603  case BuiltinType::LongLong:
4604    return UnsignedLongLongTy;
4605  case BuiltinType::Int128:
4606    return UnsignedInt128Ty;
4607  default:
4608    assert(0 && "Unexpected signed integer type");
4609    return QualType();
4610  }
4611}
4612
4613ExternalASTSource::~ExternalASTSource() { }
4614
4615void ExternalASTSource::PrintStats() { }
4616
4617
4618//===----------------------------------------------------------------------===//
4619//                          Builtin Type Computation
4620//===----------------------------------------------------------------------===//
4621
4622/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4623/// pointer over the consumed characters.  This returns the resultant type.
4624static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4625                                  ASTContext::GetBuiltinTypeError &Error,
4626                                  bool AllowTypeModifiers = true) {
4627  // Modifiers.
4628  int HowLong = 0;
4629  bool Signed = false, Unsigned = false;
4630
4631  // Read the modifiers first.
4632  bool Done = false;
4633  while (!Done) {
4634    switch (*Str++) {
4635    default: Done = true; --Str; break;
4636    case 'S':
4637      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4638      assert(!Signed && "Can't use 'S' modifier multiple times!");
4639      Signed = true;
4640      break;
4641    case 'U':
4642      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4643      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4644      Unsigned = true;
4645      break;
4646    case 'L':
4647      assert(HowLong <= 2 && "Can't have LLLL modifier");
4648      ++HowLong;
4649      break;
4650    }
4651  }
4652
4653  QualType Type;
4654
4655  // Read the base type.
4656  switch (*Str++) {
4657  default: assert(0 && "Unknown builtin type letter!");
4658  case 'v':
4659    assert(HowLong == 0 && !Signed && !Unsigned &&
4660           "Bad modifiers used with 'v'!");
4661    Type = Context.VoidTy;
4662    break;
4663  case 'f':
4664    assert(HowLong == 0 && !Signed && !Unsigned &&
4665           "Bad modifiers used with 'f'!");
4666    Type = Context.FloatTy;
4667    break;
4668  case 'd':
4669    assert(HowLong < 2 && !Signed && !Unsigned &&
4670           "Bad modifiers used with 'd'!");
4671    if (HowLong)
4672      Type = Context.LongDoubleTy;
4673    else
4674      Type = Context.DoubleTy;
4675    break;
4676  case 's':
4677    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4678    if (Unsigned)
4679      Type = Context.UnsignedShortTy;
4680    else
4681      Type = Context.ShortTy;
4682    break;
4683  case 'i':
4684    if (HowLong == 3)
4685      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4686    else if (HowLong == 2)
4687      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4688    else if (HowLong == 1)
4689      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4690    else
4691      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4692    break;
4693  case 'c':
4694    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4695    if (Signed)
4696      Type = Context.SignedCharTy;
4697    else if (Unsigned)
4698      Type = Context.UnsignedCharTy;
4699    else
4700      Type = Context.CharTy;
4701    break;
4702  case 'b': // boolean
4703    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4704    Type = Context.BoolTy;
4705    break;
4706  case 'z':  // size_t.
4707    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4708    Type = Context.getSizeType();
4709    break;
4710  case 'F':
4711    Type = Context.getCFConstantStringType();
4712    break;
4713  case 'a':
4714    Type = Context.getBuiltinVaListType();
4715    assert(!Type.isNull() && "builtin va list type not initialized!");
4716    break;
4717  case 'A':
4718    // This is a "reference" to a va_list; however, what exactly
4719    // this means depends on how va_list is defined. There are two
4720    // different kinds of va_list: ones passed by value, and ones
4721    // passed by reference.  An example of a by-value va_list is
4722    // x86, where va_list is a char*. An example of by-ref va_list
4723    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4724    // we want this argument to be a char*&; for x86-64, we want
4725    // it to be a __va_list_tag*.
4726    Type = Context.getBuiltinVaListType();
4727    assert(!Type.isNull() && "builtin va list type not initialized!");
4728    if (Type->isArrayType()) {
4729      Type = Context.getArrayDecayedType(Type);
4730    } else {
4731      Type = Context.getLValueReferenceType(Type);
4732    }
4733    break;
4734  case 'V': {
4735    char *End;
4736    unsigned NumElements = strtoul(Str, &End, 10);
4737    assert(End != Str && "Missing vector size");
4738
4739    Str = End;
4740
4741    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4742    Type = Context.getVectorType(ElementType, NumElements);
4743    break;
4744  }
4745  case 'X': {
4746    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4747    Type = Context.getComplexType(ElementType);
4748    break;
4749  }
4750  case 'P':
4751    Type = Context.getFILEType();
4752    if (Type.isNull()) {
4753      Error = ASTContext::GE_Missing_stdio;
4754      return QualType();
4755    }
4756    break;
4757  case 'J':
4758    if (Signed)
4759      Type = Context.getsigjmp_bufType();
4760    else
4761      Type = Context.getjmp_bufType();
4762
4763    if (Type.isNull()) {
4764      Error = ASTContext::GE_Missing_setjmp;
4765      return QualType();
4766    }
4767    break;
4768  }
4769
4770  if (!AllowTypeModifiers)
4771    return Type;
4772
4773  Done = false;
4774  while (!Done) {
4775    switch (*Str++) {
4776      default: Done = true; --Str; break;
4777      case '*':
4778        Type = Context.getPointerType(Type);
4779        break;
4780      case '&':
4781        Type = Context.getLValueReferenceType(Type);
4782        break;
4783      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4784      case 'C':
4785        Type = Type.withConst();
4786        break;
4787    }
4788  }
4789
4790  return Type;
4791}
4792
4793/// GetBuiltinType - Return the type for the specified builtin.
4794QualType ASTContext::GetBuiltinType(unsigned id,
4795                                    GetBuiltinTypeError &Error) {
4796  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4797
4798  llvm::SmallVector<QualType, 8> ArgTypes;
4799
4800  Error = GE_None;
4801  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4802  if (Error != GE_None)
4803    return QualType();
4804  while (TypeStr[0] && TypeStr[0] != '.') {
4805    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4806    if (Error != GE_None)
4807      return QualType();
4808
4809    // Do array -> pointer decay.  The builtin should use the decayed type.
4810    if (Ty->isArrayType())
4811      Ty = getArrayDecayedType(Ty);
4812
4813    ArgTypes.push_back(Ty);
4814  }
4815
4816  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4817         "'.' should only occur at end of builtin type list!");
4818
4819  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4820  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4821    return getFunctionNoProtoType(ResType);
4822  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4823                         TypeStr[0] == '.', 0);
4824}
4825
4826QualType
4827ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4828  // Perform the usual unary conversions. We do this early so that
4829  // integral promotions to "int" can allow us to exit early, in the
4830  // lhs == rhs check. Also, for conversion purposes, we ignore any
4831  // qualifiers.  For example, "const float" and "float" are
4832  // equivalent.
4833  if (lhs->isPromotableIntegerType())
4834    lhs = getPromotedIntegerType(lhs);
4835  else
4836    lhs = lhs.getUnqualifiedType();
4837  if (rhs->isPromotableIntegerType())
4838    rhs = getPromotedIntegerType(rhs);
4839  else
4840    rhs = rhs.getUnqualifiedType();
4841
4842  // If both types are identical, no conversion is needed.
4843  if (lhs == rhs)
4844    return lhs;
4845
4846  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4847  // The caller can deal with this (e.g. pointer + int).
4848  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4849    return lhs;
4850
4851  // At this point, we have two different arithmetic types.
4852
4853  // Handle complex types first (C99 6.3.1.8p1).
4854  if (lhs->isComplexType() || rhs->isComplexType()) {
4855    // if we have an integer operand, the result is the complex type.
4856    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4857      // convert the rhs to the lhs complex type.
4858      return lhs;
4859    }
4860    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4861      // convert the lhs to the rhs complex type.
4862      return rhs;
4863    }
4864    // This handles complex/complex, complex/float, or float/complex.
4865    // When both operands are complex, the shorter operand is converted to the
4866    // type of the longer, and that is the type of the result. This corresponds
4867    // to what is done when combining two real floating-point operands.
4868    // The fun begins when size promotion occur across type domains.
4869    // From H&S 6.3.4: When one operand is complex and the other is a real
4870    // floating-point type, the less precise type is converted, within it's
4871    // real or complex domain, to the precision of the other type. For example,
4872    // when combining a "long double" with a "double _Complex", the
4873    // "double _Complex" is promoted to "long double _Complex".
4874    int result = getFloatingTypeOrder(lhs, rhs);
4875
4876    if (result > 0) { // The left side is bigger, convert rhs.
4877      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4878    } else if (result < 0) { // The right side is bigger, convert lhs.
4879      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4880    }
4881    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4882    // domains match. This is a requirement for our implementation, C99
4883    // does not require this promotion.
4884    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4885      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4886        return rhs;
4887      } else { // handle "_Complex double, double".
4888        return lhs;
4889      }
4890    }
4891    return lhs; // The domain/size match exactly.
4892  }
4893  // Now handle "real" floating types (i.e. float, double, long double).
4894  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4895    // if we have an integer operand, the result is the real floating type.
4896    if (rhs->isIntegerType()) {
4897      // convert rhs to the lhs floating point type.
4898      return lhs;
4899    }
4900    if (rhs->isComplexIntegerType()) {
4901      // convert rhs to the complex floating point type.
4902      return getComplexType(lhs);
4903    }
4904    if (lhs->isIntegerType()) {
4905      // convert lhs to the rhs floating point type.
4906      return rhs;
4907    }
4908    if (lhs->isComplexIntegerType()) {
4909      // convert lhs to the complex floating point type.
4910      return getComplexType(rhs);
4911    }
4912    // We have two real floating types, float/complex combos were handled above.
4913    // Convert the smaller operand to the bigger result.
4914    int result = getFloatingTypeOrder(lhs, rhs);
4915    if (result > 0) // convert the rhs
4916      return lhs;
4917    assert(result < 0 && "illegal float comparison");
4918    return rhs;   // convert the lhs
4919  }
4920  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4921    // Handle GCC complex int extension.
4922    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4923    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4924
4925    if (lhsComplexInt && rhsComplexInt) {
4926      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4927                              rhsComplexInt->getElementType()) >= 0)
4928        return lhs; // convert the rhs
4929      return rhs;
4930    } else if (lhsComplexInt && rhs->isIntegerType()) {
4931      // convert the rhs to the lhs complex type.
4932      return lhs;
4933    } else if (rhsComplexInt && lhs->isIntegerType()) {
4934      // convert the lhs to the rhs complex type.
4935      return rhs;
4936    }
4937  }
4938  // Finally, we have two differing integer types.
4939  // The rules for this case are in C99 6.3.1.8
4940  int compare = getIntegerTypeOrder(lhs, rhs);
4941  bool lhsSigned = lhs->isSignedIntegerType(),
4942       rhsSigned = rhs->isSignedIntegerType();
4943  QualType destType;
4944  if (lhsSigned == rhsSigned) {
4945    // Same signedness; use the higher-ranked type
4946    destType = compare >= 0 ? lhs : rhs;
4947  } else if (compare != (lhsSigned ? 1 : -1)) {
4948    // The unsigned type has greater than or equal rank to the
4949    // signed type, so use the unsigned type
4950    destType = lhsSigned ? rhs : lhs;
4951  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4952    // The two types are different widths; if we are here, that
4953    // means the signed type is larger than the unsigned type, so
4954    // use the signed type.
4955    destType = lhsSigned ? lhs : rhs;
4956  } else {
4957    // The signed type is higher-ranked than the unsigned type,
4958    // but isn't actually any bigger (like unsigned int and long
4959    // on most 32-bit systems).  Use the unsigned type corresponding
4960    // to the signed type.
4961    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4962  }
4963  return destType;
4964}
4965