ASTContext.cpp revision 8e1fab243ab8023b7ee3899745386b3b3a4258f8
136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//
336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//                     The LLVM Compiler Infrastructure
436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//
536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// This file is distributed under the University of Illinois Open Source
636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines// License. See LICENSE.TXT for details.
736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//
836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//===----------------------------------------------------------------------===//
936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//
1036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//  This file implements the ASTContext interface.
1136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//
1236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines//===----------------------------------------------------------------------===//
1336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
1436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/ASTContext.h"
1536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/DeclCXX.h"
1636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/DeclObjC.h"
1736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/DeclTemplate.h"
1836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/Expr.h"
1936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/ExternalASTSource.h"
2036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/RecordLayout.h"
2136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/Basic/Builtins.h"
2236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/Basic/SourceManager.h"
2336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/Basic/TargetInfo.h"
2436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/ADT/StringExtras.h"
2536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/Support/MathExtras.h"
2636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "llvm/Support/MemoryBuffer.h"
2736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "RecordLayoutBuilder.h"
2836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
2936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesusing namespace clang;
3036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
3136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesenum FloatingRank {
3236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  FloatRank, DoubleRank, LongDoubleRank
3336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines};
3436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
3536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen HinesASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
3636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                       TargetInfo &t,
3736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                       IdentifierTable &idents, SelectorTable &sels,
3836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                       Builtin::Context &builtins,
3936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines                       bool FreeMem, unsigned size_reserve) :
4036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
4136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
4236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  SourceMgr(SM), LangOpts(LOpts),
4336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
4436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Idents(idents), Selectors(sels),
4536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
4636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (size_reserve > 0) Types.reserve(size_reserve);
4736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  TUDecl = TranslationUnitDecl::Create(*this);
4836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinTypes();
4936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
5036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
5136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen HinesASTContext::~ASTContext() {
5236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Deallocate all the types.
5336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  while (!Types.empty()) {
5436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Types.back()->Destroy(*this);
5536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Types.pop_back();
5636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
5736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
5836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  {
5936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
6036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
6136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    while (I != E) {
6236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
6336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      delete R;
6436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
6536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
6636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
6736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  {
6836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
6936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
7036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    while (I != E) {
7136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
7236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      delete R;
7336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    }
7436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
7536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
7636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Destroy nested-name-specifiers.
7736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
7836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         NNS = NestedNameSpecifiers.begin(),
7936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines         NNSEnd = NestedNameSpecifiers.end();
8036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines       NNS != NNSEnd;
8136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines       /* Increment in loop */)
8236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    (*NNS++).Destroy(*this);
8336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
8436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (GlobalNestedNameSpecifier)
8536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    GlobalNestedNameSpecifier->Destroy(*this);
8636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
8736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  TUDecl->Destroy(*this);
8836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
8936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
9036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesvoid
9136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen HinesASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
9236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  ExternalSource.reset(Source.take());
9336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
9436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
9536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesvoid ASTContext::PrintStats() const {
9636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  fprintf(stderr, "*** AST Context Stats:\n");
9736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  fprintf(stderr, "  %d types total.\n", (int)Types.size());
9836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
9936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  unsigned counts[] = {
10036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#define TYPE(Name, Parent) 0,
10136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#define ABSTRACT_TYPE(Name, Parent)
10236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/TypeNodes.def"
10336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    0 // Extra
10436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  };
10536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
10636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
10736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Type *T = Types[i];
10836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    counts[(unsigned)T->getTypeClass()]++;
10936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
11036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
11136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  unsigned Idx = 0;
11236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  unsigned TotalBytes = 0;
11336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#define TYPE(Name, Parent)                                              \
11436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (counts[Idx])                                                      \
11536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
11636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
11736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  ++Idx;
11836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#define ABSTRACT_TYPE(Name, Parent)
11936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines#include "clang/AST/TypeNodes.def"
12036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
12136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
12236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
12336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (ExternalSource.get()) {
12436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    fprintf(stderr, "\n");
12536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    ExternalSource->PrintStats();
12636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  }
12736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
12836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
12936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
13036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesvoid ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
13136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
13236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines}
13336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
13436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hinesvoid ASTContext::InitBuiltinTypes() {
135cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  assert(VoidTy.isNull() && "Context reinitialized?");
136cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines
137cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  // C99 6.2.5p19.
138cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  InitBuiltinType(VoidTy,              BuiltinType::Void);
139cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines
140cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  // C99 6.2.5p2.
141cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  InitBuiltinType(BoolTy,              BuiltinType::Bool);
142cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  // C99 6.2.5p3.
143cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  if (LangOpts.CharIsSigned)
144cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines    InitBuiltinType(CharTy,            BuiltinType::Char_S);
145cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  else
146cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines    InitBuiltinType(CharTy,            BuiltinType::Char_U);
147cd81d94322a39503e4a3e87b6ee03d4fcb3465fbStephen Hines  // C99 6.2.5p4.
14836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
14936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(ShortTy,             BuiltinType::Short);
15036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(IntTy,               BuiltinType::Int);
15136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(LongTy,              BuiltinType::Long);
15236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
15336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
15436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // C99 6.2.5p6.
15536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
15636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
15736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
15836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
15936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
16036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
16136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // C99 6.2.5p10.
16236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(FloatTy,             BuiltinType::Float);
16336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(DoubleTy,            BuiltinType::Double);
16436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
16536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
16636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // GNU extension, 128-bit integers.
16736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
16836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
16936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
17036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
17136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InitBuiltinType(WCharTy,           BuiltinType::WChar);
17236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  else // C99
17336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    WCharTy = getFromTargetType(Target.getWCharType());
17436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
17536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
17636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
17736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  else // C99
17836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Char16Ty = getFromTargetType(Target.getChar16Type());
17936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
18036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
18136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
18236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  else // C99
18336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Char32Ty = getFromTargetType(Target.getChar32Type());
18436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
18536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Placeholder type for functions.
18636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
18736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
18836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Placeholder type for type-dependent expressions whose type is
18936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // completely unknown. No code should ever check a type against
19036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // DependentTy and users should never see it; however, it is here to
19136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // help diagnose failures to properly check for type-dependent
19236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // expressions.
19336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
19436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
19536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // Placeholder type for C++0x auto declarations whose real type has
19636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // not yet been deduced.
19736b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
19836b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
19936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  // C99 6.2.5p11.
20036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  FloatComplexTy      = getComplexType(FloatTy);
20136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  DoubleComplexTy     = getComplexType(DoubleTy);
20236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  LongDoubleComplexTy = getComplexType(LongDoubleTy);
20336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
20436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  BuiltinVaListType = QualType();
20536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines
206  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
207  ObjCIdTypedefType = QualType();
208  ObjCClassTypedefType = QualType();
209
210  // Builtin types for 'id' and 'Class'.
211  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
212  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
213
214  ObjCConstantStringType = QualType();
215
216  // void * type
217  VoidPtrTy = getPointerType(VoidTy);
218
219  // nullptr type (C++0x 2.14.7)
220  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
221}
222
223namespace {
224  class BeforeInTranslationUnit
225    : std::binary_function<SourceRange, SourceRange, bool> {
226    SourceManager *SourceMgr;
227
228  public:
229    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
230
231    bool operator()(SourceRange X, SourceRange Y) {
232      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
233    }
234  };
235}
236
237/// \brief Determine whether the given comment is a Doxygen-style comment.
238///
239/// \param Start the start of the comment text.
240///
241/// \param End the end of the comment text.
242///
243/// \param Member whether we want to check whether this is a member comment
244/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
245/// we only return true when we find a non-member comment.
246static bool
247isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
248                 bool Member = false) {
249  const char *BufferStart
250    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
251  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
252  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
253
254  if (End - Start < 4)
255    return false;
256
257  assert(Start[0] == '/' && "Not a comment?");
258  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
259    return false;
260  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
261    return false;
262
263  return (Start[3] == '<') == Member;
264}
265
266/// \brief Retrieve the comment associated with the given declaration, if
267/// it has one.
268const char *ASTContext::getCommentForDecl(const Decl *D) {
269  if (!D)
270    return 0;
271
272  // Check whether we have cached a comment string for this declaration
273  // already.
274  llvm::DenseMap<const Decl *, std::string>::iterator Pos
275    = DeclComments.find(D);
276  if (Pos != DeclComments.end())
277    return Pos->second.c_str();
278
279  // If we have an external AST source and have not yet loaded comments from
280  // that source, do so now.
281  if (ExternalSource && !LoadedExternalComments) {
282    std::vector<SourceRange> LoadedComments;
283    ExternalSource->ReadComments(LoadedComments);
284
285    if (!LoadedComments.empty())
286      Comments.insert(Comments.begin(), LoadedComments.begin(),
287                      LoadedComments.end());
288
289    LoadedExternalComments = true;
290  }
291
292  // If there are no comments anywhere, we won't find anything.
293  if (Comments.empty())
294    return 0;
295
296  // If the declaration doesn't map directly to a location in a file, we
297  // can't find the comment.
298  SourceLocation DeclStartLoc = D->getLocStart();
299  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
300    return 0;
301
302  // Find the comment that occurs just before this declaration.
303  std::vector<SourceRange>::iterator LastComment
304    = std::lower_bound(Comments.begin(), Comments.end(),
305                       SourceRange(DeclStartLoc),
306                       BeforeInTranslationUnit(&SourceMgr));
307
308  // Decompose the location for the start of the declaration and find the
309  // beginning of the file buffer.
310  std::pair<FileID, unsigned> DeclStartDecomp
311    = SourceMgr.getDecomposedLoc(DeclStartLoc);
312  const char *FileBufferStart
313    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
314
315  // First check whether we have a comment for a member.
316  if (LastComment != Comments.end() &&
317      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
318      isDoxygenComment(SourceMgr, *LastComment, true)) {
319    std::pair<FileID, unsigned> LastCommentEndDecomp
320      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
321    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
322        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
323          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
324                                     LastCommentEndDecomp.second)) {
325      // The Doxygen member comment comes after the declaration starts and
326      // is on the same line and in the same file as the declaration. This
327      // is the comment we want.
328      std::string &Result = DeclComments[D];
329      Result.append(FileBufferStart +
330                      SourceMgr.getFileOffset(LastComment->getBegin()),
331                    FileBufferStart + LastCommentEndDecomp.second + 1);
332      return Result.c_str();
333    }
334  }
335
336  if (LastComment == Comments.begin())
337    return 0;
338  --LastComment;
339
340  // Decompose the end of the comment.
341  std::pair<FileID, unsigned> LastCommentEndDecomp
342    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
343
344  // If the comment and the declaration aren't in the same file, then they
345  // aren't related.
346  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
347    return 0;
348
349  // Check that we actually have a Doxygen comment.
350  if (!isDoxygenComment(SourceMgr, *LastComment))
351    return 0;
352
353  // Compute the starting line for the declaration and for the end of the
354  // comment (this is expensive).
355  unsigned DeclStartLine
356    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
357  unsigned CommentEndLine
358    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
359                              LastCommentEndDecomp.second);
360
361  // If the comment does not end on the line prior to the declaration, then
362  // the comment is not associated with the declaration at all.
363  if (CommentEndLine + 1 != DeclStartLine)
364    return 0;
365
366  // We have a comment, but there may be more comments on the previous lines.
367  // Keep looking so long as the comments are still Doxygen comments and are
368  // still adjacent.
369  unsigned ExpectedLine
370    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
371  std::vector<SourceRange>::iterator FirstComment = LastComment;
372  while (FirstComment != Comments.begin()) {
373    // Look at the previous comment
374    --FirstComment;
375    std::pair<FileID, unsigned> Decomp
376      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
377
378    // If this previous comment is in a different file, we're done.
379    if (Decomp.first != DeclStartDecomp.first) {
380      ++FirstComment;
381      break;
382    }
383
384    // If this comment is not a Doxygen comment, we're done.
385    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
386      ++FirstComment;
387      break;
388    }
389
390    // If the line number is not what we expected, we're done.
391    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
392    if (Line != ExpectedLine) {
393      ++FirstComment;
394      break;
395    }
396
397    // Set the next expected line number.
398    ExpectedLine
399      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
400  }
401
402  // The iterator range [FirstComment, LastComment] contains all of the
403  // BCPL comments that, together, are associated with this declaration.
404  // Form a single comment block string for this declaration that concatenates
405  // all of these comments.
406  std::string &Result = DeclComments[D];
407  while (FirstComment != LastComment) {
408    std::pair<FileID, unsigned> DecompStart
409      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
410    std::pair<FileID, unsigned> DecompEnd
411      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
412    Result.append(FileBufferStart + DecompStart.second,
413                  FileBufferStart + DecompEnd.second + 1);
414    ++FirstComment;
415  }
416
417  // Append the last comment line.
418  Result.append(FileBufferStart +
419                  SourceMgr.getFileOffset(LastComment->getBegin()),
420                FileBufferStart + LastCommentEndDecomp.second + 1);
421  return Result.c_str();
422}
423
424//===----------------------------------------------------------------------===//
425//                         Type Sizing and Analysis
426//===----------------------------------------------------------------------===//
427
428/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
429/// scalar floating point type.
430const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
431  const BuiltinType *BT = T->getAsBuiltinType();
432  assert(BT && "Not a floating point type!");
433  switch (BT->getKind()) {
434  default: assert(0 && "Not a floating point type!");
435  case BuiltinType::Float:      return Target.getFloatFormat();
436  case BuiltinType::Double:     return Target.getDoubleFormat();
437  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
438  }
439}
440
441/// getDeclAlign - Return a conservative estimate of the alignment of the
442/// specified decl.  Note that bitfields do not have a valid alignment, so
443/// this method will assert on them.
444unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
445  unsigned Align = Target.getCharWidth();
446
447  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
448    Align = std::max(Align, AA->getAlignment());
449
450  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
451    QualType T = VD->getType();
452    if (const ReferenceType* RT = T->getAsReferenceType()) {
453      unsigned AS = RT->getPointeeType().getAddressSpace();
454      Align = Target.getPointerAlign(AS);
455    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
456      // Incomplete or function types default to 1.
457      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
458        T = cast<ArrayType>(T)->getElementType();
459
460      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
461    }
462  }
463
464  return Align / Target.getCharWidth();
465}
466
467/// getTypeSize - Return the size of the specified type, in bits.  This method
468/// does not work on incomplete types.
469std::pair<uint64_t, unsigned>
470ASTContext::getTypeInfo(const Type *T) {
471  uint64_t Width=0;
472  unsigned Align=8;
473  switch (T->getTypeClass()) {
474#define TYPE(Class, Base)
475#define ABSTRACT_TYPE(Class, Base)
476#define NON_CANONICAL_TYPE(Class, Base)
477#define DEPENDENT_TYPE(Class, Base) case Type::Class:
478#include "clang/AST/TypeNodes.def"
479    assert(false && "Should not see dependent types");
480    break;
481
482  case Type::FunctionNoProto:
483  case Type::FunctionProto:
484    // GCC extension: alignof(function) = 32 bits
485    Width = 0;
486    Align = 32;
487    break;
488
489  case Type::IncompleteArray:
490  case Type::VariableArray:
491    Width = 0;
492    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
493    break;
494
495  case Type::ConstantArrayWithExpr:
496  case Type::ConstantArrayWithoutExpr:
497  case Type::ConstantArray: {
498    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
499
500    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
501    Width = EltInfo.first*CAT->getSize().getZExtValue();
502    Align = EltInfo.second;
503    break;
504  }
505  case Type::ExtVector:
506  case Type::Vector: {
507    std::pair<uint64_t, unsigned> EltInfo =
508      getTypeInfo(cast<VectorType>(T)->getElementType());
509    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
510    Align = Width;
511    // If the alignment is not a power of 2, round up to the next power of 2.
512    // This happens for non-power-of-2 length vectors.
513    // FIXME: this should probably be a target property.
514    Align = 1 << llvm::Log2_32_Ceil(Align);
515    break;
516  }
517
518  case Type::Builtin:
519    switch (cast<BuiltinType>(T)->getKind()) {
520    default: assert(0 && "Unknown builtin type!");
521    case BuiltinType::Void:
522      // GCC extension: alignof(void) = 8 bits.
523      Width = 0;
524      Align = 8;
525      break;
526
527    case BuiltinType::Bool:
528      Width = Target.getBoolWidth();
529      Align = Target.getBoolAlign();
530      break;
531    case BuiltinType::Char_S:
532    case BuiltinType::Char_U:
533    case BuiltinType::UChar:
534    case BuiltinType::SChar:
535      Width = Target.getCharWidth();
536      Align = Target.getCharAlign();
537      break;
538    case BuiltinType::WChar:
539      Width = Target.getWCharWidth();
540      Align = Target.getWCharAlign();
541      break;
542    case BuiltinType::Char16:
543      Width = Target.getChar16Width();
544      Align = Target.getChar16Align();
545      break;
546    case BuiltinType::Char32:
547      Width = Target.getChar32Width();
548      Align = Target.getChar32Align();
549      break;
550    case BuiltinType::UShort:
551    case BuiltinType::Short:
552      Width = Target.getShortWidth();
553      Align = Target.getShortAlign();
554      break;
555    case BuiltinType::UInt:
556    case BuiltinType::Int:
557      Width = Target.getIntWidth();
558      Align = Target.getIntAlign();
559      break;
560    case BuiltinType::ULong:
561    case BuiltinType::Long:
562      Width = Target.getLongWidth();
563      Align = Target.getLongAlign();
564      break;
565    case BuiltinType::ULongLong:
566    case BuiltinType::LongLong:
567      Width = Target.getLongLongWidth();
568      Align = Target.getLongLongAlign();
569      break;
570    case BuiltinType::Int128:
571    case BuiltinType::UInt128:
572      Width = 128;
573      Align = 128; // int128_t is 128-bit aligned on all targets.
574      break;
575    case BuiltinType::Float:
576      Width = Target.getFloatWidth();
577      Align = Target.getFloatAlign();
578      break;
579    case BuiltinType::Double:
580      Width = Target.getDoubleWidth();
581      Align = Target.getDoubleAlign();
582      break;
583    case BuiltinType::LongDouble:
584      Width = Target.getLongDoubleWidth();
585      Align = Target.getLongDoubleAlign();
586      break;
587    case BuiltinType::NullPtr:
588      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
589      Align = Target.getPointerAlign(0); //   == sizeof(void*)
590      break;
591    }
592    break;
593  case Type::FixedWidthInt:
594    // FIXME: This isn't precisely correct; the width/alignment should depend
595    // on the available types for the target
596    Width = cast<FixedWidthIntType>(T)->getWidth();
597    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
598    Align = Width;
599    break;
600  case Type::ExtQual:
601    // FIXME: Pointers into different addr spaces could have different sizes and
602    // alignment requirements: getPointerInfo should take an AddrSpace.
603    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
604  case Type::ObjCObjectPointer:
605    Width = Target.getPointerWidth(0);
606    Align = Target.getPointerAlign(0);
607    break;
608  case Type::BlockPointer: {
609    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
610    Width = Target.getPointerWidth(AS);
611    Align = Target.getPointerAlign(AS);
612    break;
613  }
614  case Type::Pointer: {
615    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
616    Width = Target.getPointerWidth(AS);
617    Align = Target.getPointerAlign(AS);
618    break;
619  }
620  case Type::LValueReference:
621  case Type::RValueReference:
622    // "When applied to a reference or a reference type, the result is the size
623    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
624    // FIXME: This is wrong for struct layout: a reference in a struct has
625    // pointer size.
626    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
627  case Type::MemberPointer: {
628    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
629    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
630    // If we ever want to support other ABIs this needs to be abstracted.
631
632    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
633    std::pair<uint64_t, unsigned> PtrDiffInfo =
634      getTypeInfo(getPointerDiffType());
635    Width = PtrDiffInfo.first;
636    if (Pointee->isFunctionType())
637      Width *= 2;
638    Align = PtrDiffInfo.second;
639    break;
640  }
641  case Type::Complex: {
642    // Complex types have the same alignment as their elements, but twice the
643    // size.
644    std::pair<uint64_t, unsigned> EltInfo =
645      getTypeInfo(cast<ComplexType>(T)->getElementType());
646    Width = EltInfo.first*2;
647    Align = EltInfo.second;
648    break;
649  }
650  case Type::ObjCInterface: {
651    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
652    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
653    Width = Layout.getSize();
654    Align = Layout.getAlignment();
655    break;
656  }
657  case Type::Record:
658  case Type::Enum: {
659    const TagType *TT = cast<TagType>(T);
660
661    if (TT->getDecl()->isInvalidDecl()) {
662      Width = 1;
663      Align = 1;
664      break;
665    }
666
667    if (const EnumType *ET = dyn_cast<EnumType>(TT))
668      return getTypeInfo(ET->getDecl()->getIntegerType());
669
670    const RecordType *RT = cast<RecordType>(TT);
671    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
672    Width = Layout.getSize();
673    Align = Layout.getAlignment();
674    break;
675  }
676
677  case Type::Typedef: {
678    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
679    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
680      Align = Aligned->getAlignment();
681      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
682    } else
683      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
684    break;
685  }
686
687  case Type::TypeOfExpr:
688    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
689                         .getTypePtr());
690
691  case Type::TypeOf:
692    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
693
694  case Type::Decltype:
695    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
696                        .getTypePtr());
697
698  case Type::QualifiedName:
699    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
700
701  case Type::TemplateSpecialization:
702    assert(getCanonicalType(T) != T &&
703           "Cannot request the size of a dependent type");
704    // FIXME: this is likely to be wrong once we support template
705    // aliases, since a template alias could refer to a typedef that
706    // has an __aligned__ attribute on it.
707    return getTypeInfo(getCanonicalType(T));
708  }
709
710  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
711  return std::make_pair(Width, Align);
712}
713
714/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
715/// type for the current target in bits.  This can be different than the ABI
716/// alignment in cases where it is beneficial for performance to overalign
717/// a data type.
718unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
719  unsigned ABIAlign = getTypeAlign(T);
720
721  // Double and long long should be naturally aligned if possible.
722  if (const ComplexType* CT = T->getAsComplexType())
723    T = CT->getElementType().getTypePtr();
724  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
725      T->isSpecificBuiltinType(BuiltinType::LongLong))
726    return std::max(ABIAlign, (unsigned)getTypeSize(T));
727
728  return ABIAlign;
729}
730
731static void CollectLocalObjCIvars(ASTContext *Ctx,
732                                  const ObjCInterfaceDecl *OI,
733                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
734  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
735       E = OI->ivar_end(); I != E; ++I) {
736    ObjCIvarDecl *IVDecl = *I;
737    if (!IVDecl->isInvalidDecl())
738      Fields.push_back(cast<FieldDecl>(IVDecl));
739  }
740}
741
742void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
743                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
744  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
745    CollectObjCIvars(SuperClass, Fields);
746  CollectLocalObjCIvars(this, OI, Fields);
747}
748
749/// ShallowCollectObjCIvars -
750/// Collect all ivars, including those synthesized, in the current class.
751///
752void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
753                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
754                                 bool CollectSynthesized) {
755  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
756         E = OI->ivar_end(); I != E; ++I) {
757     Ivars.push_back(*I);
758  }
759  if (CollectSynthesized)
760    CollectSynthesizedIvars(OI, Ivars);
761}
762
763void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
764                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
765  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
766       E = PD->prop_end(); I != E; ++I)
767    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
768      Ivars.push_back(Ivar);
769
770  // Also look into nested protocols.
771  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
772       E = PD->protocol_end(); P != E; ++P)
773    CollectProtocolSynthesizedIvars(*P, Ivars);
774}
775
776/// CollectSynthesizedIvars -
777/// This routine collect synthesized ivars for the designated class.
778///
779void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
780                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
781  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
782       E = OI->prop_end(); I != E; ++I) {
783    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
784      Ivars.push_back(Ivar);
785  }
786  // Also look into interface's protocol list for properties declared
787  // in the protocol and whose ivars are synthesized.
788  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
789       PE = OI->protocol_end(); P != PE; ++P) {
790    ObjCProtocolDecl *PD = (*P);
791    CollectProtocolSynthesizedIvars(PD, Ivars);
792  }
793}
794
795unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
796  unsigned count = 0;
797  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
798       E = PD->prop_end(); I != E; ++I)
799    if ((*I)->getPropertyIvarDecl())
800      ++count;
801
802  // Also look into nested protocols.
803  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
804       E = PD->protocol_end(); P != E; ++P)
805    count += CountProtocolSynthesizedIvars(*P);
806  return count;
807}
808
809unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
810{
811  unsigned count = 0;
812  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
813       E = OI->prop_end(); I != E; ++I) {
814    if ((*I)->getPropertyIvarDecl())
815      ++count;
816  }
817  // Also look into interface's protocol list for properties declared
818  // in the protocol and whose ivars are synthesized.
819  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
820       PE = OI->protocol_end(); P != PE; ++P) {
821    ObjCProtocolDecl *PD = (*P);
822    count += CountProtocolSynthesizedIvars(PD);
823  }
824  return count;
825}
826
827/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
828ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
829  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
830    I = ObjCImpls.find(D);
831  if (I != ObjCImpls.end())
832    return cast<ObjCImplementationDecl>(I->second);
833  return 0;
834}
835/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
836ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
837  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
838    I = ObjCImpls.find(D);
839  if (I != ObjCImpls.end())
840    return cast<ObjCCategoryImplDecl>(I->second);
841  return 0;
842}
843
844/// \brief Set the implementation of ObjCInterfaceDecl.
845void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
846                           ObjCImplementationDecl *ImplD) {
847  assert(IFaceD && ImplD && "Passed null params");
848  ObjCImpls[IFaceD] = ImplD;
849}
850/// \brief Set the implementation of ObjCCategoryDecl.
851void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
852                           ObjCCategoryImplDecl *ImplD) {
853  assert(CatD && ImplD && "Passed null params");
854  ObjCImpls[CatD] = ImplD;
855}
856
857/// getInterfaceLayoutImpl - Get or compute information about the
858/// layout of the given interface.
859///
860/// \param Impl - If given, also include the layout of the interface's
861/// implementation. This may differ by including synthesized ivars.
862const ASTRecordLayout &
863ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
864                          const ObjCImplementationDecl *Impl) {
865  assert(!D->isForwardDecl() && "Invalid interface decl!");
866
867  // Look up this layout, if already laid out, return what we have.
868  ObjCContainerDecl *Key =
869    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
870  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
871    return *Entry;
872
873  // Add in synthesized ivar count if laying out an implementation.
874  if (Impl) {
875    unsigned FieldCount = D->ivar_size();
876    unsigned SynthCount = CountSynthesizedIvars(D);
877    FieldCount += SynthCount;
878    // If there aren't any sythesized ivars then reuse the interface
879    // entry. Note we can't cache this because we simply free all
880    // entries later; however we shouldn't look up implementations
881    // frequently.
882    if (SynthCount == 0)
883      return getObjCLayout(D, 0);
884  }
885
886  const ASTRecordLayout *NewEntry =
887    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
888  ObjCLayouts[Key] = NewEntry;
889
890  return *NewEntry;
891}
892
893const ASTRecordLayout &
894ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
895  return getObjCLayout(D, 0);
896}
897
898const ASTRecordLayout &
899ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
900  return getObjCLayout(D->getClassInterface(), D);
901}
902
903/// getASTRecordLayout - Get or compute information about the layout of the
904/// specified record (struct/union/class), which indicates its size and field
905/// position information.
906const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
907  D = D->getDefinition(*this);
908  assert(D && "Cannot get layout of forward declarations!");
909
910  // Look up this layout, if already laid out, return what we have.
911  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
912  if (Entry) return *Entry;
913
914  const ASTRecordLayout *NewEntry =
915    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
916  Entry = NewEntry;
917
918  return *NewEntry;
919}
920
921//===----------------------------------------------------------------------===//
922//                   Type creation/memoization methods
923//===----------------------------------------------------------------------===//
924
925QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
926  QualType CanT = getCanonicalType(T);
927  if (CanT.getAddressSpace() == AddressSpace)
928    return T;
929
930  // If we are composing extended qualifiers together, merge together into one
931  // ExtQualType node.
932  unsigned CVRQuals = T.getCVRQualifiers();
933  QualType::GCAttrTypes GCAttr = QualType::GCNone;
934  Type *TypeNode = T.getTypePtr();
935
936  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
937    // If this type already has an address space specified, it cannot get
938    // another one.
939    assert(EQT->getAddressSpace() == 0 &&
940           "Type cannot be in multiple addr spaces!");
941    GCAttr = EQT->getObjCGCAttr();
942    TypeNode = EQT->getBaseType();
943  }
944
945  // Check if we've already instantiated this type.
946  llvm::FoldingSetNodeID ID;
947  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
948  void *InsertPos = 0;
949  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
950    return QualType(EXTQy, CVRQuals);
951
952  // If the base type isn't canonical, this won't be a canonical type either,
953  // so fill in the canonical type field.
954  QualType Canonical;
955  if (!TypeNode->isCanonical()) {
956    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
957
958    // Update InsertPos, the previous call could have invalidated it.
959    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
960    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
961  }
962  ExtQualType *New =
963    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
964  ExtQualTypes.InsertNode(New, InsertPos);
965  Types.push_back(New);
966  return QualType(New, CVRQuals);
967}
968
969QualType ASTContext::getObjCGCQualType(QualType T,
970                                       QualType::GCAttrTypes GCAttr) {
971  QualType CanT = getCanonicalType(T);
972  if (CanT.getObjCGCAttr() == GCAttr)
973    return T;
974
975  if (T->isPointerType()) {
976    QualType Pointee = T->getAsPointerType()->getPointeeType();
977    if (Pointee->isAnyPointerType()) {
978      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
979      return getPointerType(ResultType);
980    }
981  }
982  // If we are composing extended qualifiers together, merge together into one
983  // ExtQualType node.
984  unsigned CVRQuals = T.getCVRQualifiers();
985  Type *TypeNode = T.getTypePtr();
986  unsigned AddressSpace = 0;
987
988  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
989    // If this type already has an address space specified, it cannot get
990    // another one.
991    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
992           "Type cannot be in multiple addr spaces!");
993    AddressSpace = EQT->getAddressSpace();
994    TypeNode = EQT->getBaseType();
995  }
996
997  // Check if we've already instantiated an gc qual'd type of this type.
998  llvm::FoldingSetNodeID ID;
999  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
1000  void *InsertPos = 0;
1001  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
1002    return QualType(EXTQy, CVRQuals);
1003
1004  // If the base type isn't canonical, this won't be a canonical type either,
1005  // so fill in the canonical type field.
1006  // FIXME: Isn't this also not canonical if the base type is a array
1007  // or pointer type?  I can't find any documentation for objc_gc, though...
1008  QualType Canonical;
1009  if (!T->isCanonical()) {
1010    Canonical = getObjCGCQualType(CanT, GCAttr);
1011
1012    // Update InsertPos, the previous call could have invalidated it.
1013    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1014    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1015  }
1016  ExtQualType *New =
1017    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
1018  ExtQualTypes.InsertNode(New, InsertPos);
1019  Types.push_back(New);
1020  return QualType(New, CVRQuals);
1021}
1022
1023/// getComplexType - Return the uniqued reference to the type for a complex
1024/// number with the specified element type.
1025QualType ASTContext::getComplexType(QualType T) {
1026  // Unique pointers, to guarantee there is only one pointer of a particular
1027  // structure.
1028  llvm::FoldingSetNodeID ID;
1029  ComplexType::Profile(ID, T);
1030
1031  void *InsertPos = 0;
1032  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1033    return QualType(CT, 0);
1034
1035  // If the pointee type isn't canonical, this won't be a canonical type either,
1036  // so fill in the canonical type field.
1037  QualType Canonical;
1038  if (!T->isCanonical()) {
1039    Canonical = getComplexType(getCanonicalType(T));
1040
1041    // Get the new insert position for the node we care about.
1042    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1043    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1044  }
1045  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
1046  Types.push_back(New);
1047  ComplexTypes.InsertNode(New, InsertPos);
1048  return QualType(New, 0);
1049}
1050
1051QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1052  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1053     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1054  FixedWidthIntType *&Entry = Map[Width];
1055  if (!Entry)
1056    Entry = new FixedWidthIntType(Width, Signed);
1057  return QualType(Entry, 0);
1058}
1059
1060/// getPointerType - Return the uniqued reference to the type for a pointer to
1061/// the specified type.
1062QualType ASTContext::getPointerType(QualType T) {
1063  // Unique pointers, to guarantee there is only one pointer of a particular
1064  // structure.
1065  llvm::FoldingSetNodeID ID;
1066  PointerType::Profile(ID, T);
1067
1068  void *InsertPos = 0;
1069  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1070    return QualType(PT, 0);
1071
1072  // If the pointee type isn't canonical, this won't be a canonical type either,
1073  // so fill in the canonical type field.
1074  QualType Canonical;
1075  if (!T->isCanonical()) {
1076    Canonical = getPointerType(getCanonicalType(T));
1077
1078    // Get the new insert position for the node we care about.
1079    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1080    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1081  }
1082  PointerType *New = new (*this,8) PointerType(T, Canonical);
1083  Types.push_back(New);
1084  PointerTypes.InsertNode(New, InsertPos);
1085  return QualType(New, 0);
1086}
1087
1088/// getBlockPointerType - Return the uniqued reference to the type for
1089/// a pointer to the specified block.
1090QualType ASTContext::getBlockPointerType(QualType T) {
1091  assert(T->isFunctionType() && "block of function types only");
1092  // Unique pointers, to guarantee there is only one block of a particular
1093  // structure.
1094  llvm::FoldingSetNodeID ID;
1095  BlockPointerType::Profile(ID, T);
1096
1097  void *InsertPos = 0;
1098  if (BlockPointerType *PT =
1099        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1100    return QualType(PT, 0);
1101
1102  // If the block pointee type isn't canonical, this won't be a canonical
1103  // type either so fill in the canonical type field.
1104  QualType Canonical;
1105  if (!T->isCanonical()) {
1106    Canonical = getBlockPointerType(getCanonicalType(T));
1107
1108    // Get the new insert position for the node we care about.
1109    BlockPointerType *NewIP =
1110      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1111    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1112  }
1113  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
1114  Types.push_back(New);
1115  BlockPointerTypes.InsertNode(New, InsertPos);
1116  return QualType(New, 0);
1117}
1118
1119/// getLValueReferenceType - Return the uniqued reference to the type for an
1120/// lvalue reference to the specified type.
1121QualType ASTContext::getLValueReferenceType(QualType T) {
1122  // Unique pointers, to guarantee there is only one pointer of a particular
1123  // structure.
1124  llvm::FoldingSetNodeID ID;
1125  ReferenceType::Profile(ID, T);
1126
1127  void *InsertPos = 0;
1128  if (LValueReferenceType *RT =
1129        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1130    return QualType(RT, 0);
1131
1132  // If the referencee type isn't canonical, this won't be a canonical type
1133  // either, so fill in the canonical type field.
1134  QualType Canonical;
1135  if (!T->isCanonical()) {
1136    Canonical = getLValueReferenceType(getCanonicalType(T));
1137
1138    // Get the new insert position for the node we care about.
1139    LValueReferenceType *NewIP =
1140      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1141    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1142  }
1143
1144  LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
1145  Types.push_back(New);
1146  LValueReferenceTypes.InsertNode(New, InsertPos);
1147  return QualType(New, 0);
1148}
1149
1150/// getRValueReferenceType - Return the uniqued reference to the type for an
1151/// rvalue reference to the specified type.
1152QualType ASTContext::getRValueReferenceType(QualType T) {
1153  // Unique pointers, to guarantee there is only one pointer of a particular
1154  // structure.
1155  llvm::FoldingSetNodeID ID;
1156  ReferenceType::Profile(ID, T);
1157
1158  void *InsertPos = 0;
1159  if (RValueReferenceType *RT =
1160        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1161    return QualType(RT, 0);
1162
1163  // If the referencee type isn't canonical, this won't be a canonical type
1164  // either, so fill in the canonical type field.
1165  QualType Canonical;
1166  if (!T->isCanonical()) {
1167    Canonical = getRValueReferenceType(getCanonicalType(T));
1168
1169    // Get the new insert position for the node we care about.
1170    RValueReferenceType *NewIP =
1171      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1172    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1173  }
1174
1175  RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1176  Types.push_back(New);
1177  RValueReferenceTypes.InsertNode(New, InsertPos);
1178  return QualType(New, 0);
1179}
1180
1181/// getMemberPointerType - Return the uniqued reference to the type for a
1182/// member pointer to the specified type, in the specified class.
1183QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1184{
1185  // Unique pointers, to guarantee there is only one pointer of a particular
1186  // structure.
1187  llvm::FoldingSetNodeID ID;
1188  MemberPointerType::Profile(ID, T, Cls);
1189
1190  void *InsertPos = 0;
1191  if (MemberPointerType *PT =
1192      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1193    return QualType(PT, 0);
1194
1195  // If the pointee or class type isn't canonical, this won't be a canonical
1196  // type either, so fill in the canonical type field.
1197  QualType Canonical;
1198  if (!T->isCanonical()) {
1199    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1200
1201    // Get the new insert position for the node we care about.
1202    MemberPointerType *NewIP =
1203      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1204    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1205  }
1206  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
1207  Types.push_back(New);
1208  MemberPointerTypes.InsertNode(New, InsertPos);
1209  return QualType(New, 0);
1210}
1211
1212/// getConstantArrayType - Return the unique reference to the type for an
1213/// array of the specified element type.
1214QualType ASTContext::getConstantArrayType(QualType EltTy,
1215                                          const llvm::APInt &ArySizeIn,
1216                                          ArrayType::ArraySizeModifier ASM,
1217                                          unsigned EltTypeQuals) {
1218  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1219         "Constant array of VLAs is illegal!");
1220
1221  // Convert the array size into a canonical width matching the pointer size for
1222  // the target.
1223  llvm::APInt ArySize(ArySizeIn);
1224  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1225
1226  llvm::FoldingSetNodeID ID;
1227  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1228
1229  void *InsertPos = 0;
1230  if (ConstantArrayType *ATP =
1231      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1232    return QualType(ATP, 0);
1233
1234  // If the element type isn't canonical, this won't be a canonical type either,
1235  // so fill in the canonical type field.
1236  QualType Canonical;
1237  if (!EltTy->isCanonical()) {
1238    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1239                                     ASM, EltTypeQuals);
1240    // Get the new insert position for the node we care about.
1241    ConstantArrayType *NewIP =
1242      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1243    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1244  }
1245
1246  ConstantArrayType *New =
1247    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1248  ConstantArrayTypes.InsertNode(New, InsertPos);
1249  Types.push_back(New);
1250  return QualType(New, 0);
1251}
1252
1253/// getConstantArrayWithExprType - Return a reference to the type for
1254/// an array of the specified element type.
1255QualType
1256ASTContext::getConstantArrayWithExprType(QualType EltTy,
1257                                         const llvm::APInt &ArySizeIn,
1258                                         Expr *ArySizeExpr,
1259                                         ArrayType::ArraySizeModifier ASM,
1260                                         unsigned EltTypeQuals,
1261                                         SourceRange Brackets) {
1262  // Convert the array size into a canonical width matching the pointer
1263  // size for the target.
1264  llvm::APInt ArySize(ArySizeIn);
1265  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1266
1267  // Compute the canonical ConstantArrayType.
1268  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1269                                            ArySize, ASM, EltTypeQuals);
1270  // Since we don't unique expressions, it isn't possible to unique VLA's
1271  // that have an expression provided for their size.
1272  ConstantArrayWithExprType *New =
1273    new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1274                                          ArySize, ArySizeExpr,
1275                                          ASM, EltTypeQuals, Brackets);
1276  Types.push_back(New);
1277  return QualType(New, 0);
1278}
1279
1280/// getConstantArrayWithoutExprType - Return a reference to the type for
1281/// an array of the specified element type.
1282QualType
1283ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1284                                            const llvm::APInt &ArySizeIn,
1285                                            ArrayType::ArraySizeModifier ASM,
1286                                            unsigned EltTypeQuals) {
1287  // Convert the array size into a canonical width matching the pointer
1288  // size for the target.
1289  llvm::APInt ArySize(ArySizeIn);
1290  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1291
1292  // Compute the canonical ConstantArrayType.
1293  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1294                                            ArySize, ASM, EltTypeQuals);
1295  ConstantArrayWithoutExprType *New =
1296    new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1297                                             ArySize, ASM, EltTypeQuals);
1298  Types.push_back(New);
1299  return QualType(New, 0);
1300}
1301
1302/// getVariableArrayType - Returns a non-unique reference to the type for a
1303/// variable array of the specified element type.
1304QualType ASTContext::getVariableArrayType(QualType EltTy,
1305                                          Expr *NumElts,
1306                                          ArrayType::ArraySizeModifier ASM,
1307                                          unsigned EltTypeQuals,
1308                                          SourceRange Brackets) {
1309  // Since we don't unique expressions, it isn't possible to unique VLA's
1310  // that have an expression provided for their size.
1311
1312  VariableArrayType *New =
1313    new(*this,8)VariableArrayType(EltTy, QualType(),
1314                                  NumElts, ASM, EltTypeQuals, Brackets);
1315
1316  VariableArrayTypes.push_back(New);
1317  Types.push_back(New);
1318  return QualType(New, 0);
1319}
1320
1321/// getDependentSizedArrayType - Returns a non-unique reference to
1322/// the type for a dependently-sized array of the specified element
1323/// type. FIXME: We will need these to be uniqued, or at least
1324/// comparable, at some point.
1325QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1326                                                Expr *NumElts,
1327                                                ArrayType::ArraySizeModifier ASM,
1328                                                unsigned EltTypeQuals,
1329                                                SourceRange Brackets) {
1330  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1331         "Size must be type- or value-dependent!");
1332
1333  // Since we don't unique expressions, it isn't possible to unique
1334  // dependently-sized array types.
1335
1336  DependentSizedArrayType *New =
1337    new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1338                                          NumElts, ASM, EltTypeQuals,
1339                                          Brackets);
1340
1341  DependentSizedArrayTypes.push_back(New);
1342  Types.push_back(New);
1343  return QualType(New, 0);
1344}
1345
1346QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1347                                            ArrayType::ArraySizeModifier ASM,
1348                                            unsigned EltTypeQuals) {
1349  llvm::FoldingSetNodeID ID;
1350  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1351
1352  void *InsertPos = 0;
1353  if (IncompleteArrayType *ATP =
1354       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1355    return QualType(ATP, 0);
1356
1357  // If the element type isn't canonical, this won't be a canonical type
1358  // either, so fill in the canonical type field.
1359  QualType Canonical;
1360
1361  if (!EltTy->isCanonical()) {
1362    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1363                                       ASM, EltTypeQuals);
1364
1365    // Get the new insert position for the node we care about.
1366    IncompleteArrayType *NewIP =
1367      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1368    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1369  }
1370
1371  IncompleteArrayType *New
1372    = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1373                                        ASM, EltTypeQuals);
1374
1375  IncompleteArrayTypes.InsertNode(New, InsertPos);
1376  Types.push_back(New);
1377  return QualType(New, 0);
1378}
1379
1380/// getVectorType - Return the unique reference to a vector type of
1381/// the specified element type and size. VectorType must be a built-in type.
1382QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1383  BuiltinType *baseType;
1384
1385  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1386  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1387
1388  // Check if we've already instantiated a vector of this type.
1389  llvm::FoldingSetNodeID ID;
1390  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1391  void *InsertPos = 0;
1392  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1393    return QualType(VTP, 0);
1394
1395  // If the element type isn't canonical, this won't be a canonical type either,
1396  // so fill in the canonical type field.
1397  QualType Canonical;
1398  if (!vecType->isCanonical()) {
1399    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1400
1401    // Get the new insert position for the node we care about.
1402    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1403    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1404  }
1405  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1406  VectorTypes.InsertNode(New, InsertPos);
1407  Types.push_back(New);
1408  return QualType(New, 0);
1409}
1410
1411/// getExtVectorType - Return the unique reference to an extended vector type of
1412/// the specified element type and size. VectorType must be a built-in type.
1413QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1414  BuiltinType *baseType;
1415
1416  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1417  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1418
1419  // Check if we've already instantiated a vector of this type.
1420  llvm::FoldingSetNodeID ID;
1421  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1422  void *InsertPos = 0;
1423  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1424    return QualType(VTP, 0);
1425
1426  // If the element type isn't canonical, this won't be a canonical type either,
1427  // so fill in the canonical type field.
1428  QualType Canonical;
1429  if (!vecType->isCanonical()) {
1430    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1431
1432    // Get the new insert position for the node we care about.
1433    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1434    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1435  }
1436  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1437  VectorTypes.InsertNode(New, InsertPos);
1438  Types.push_back(New);
1439  return QualType(New, 0);
1440}
1441
1442QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1443                                                    Expr *SizeExpr,
1444                                                    SourceLocation AttrLoc) {
1445  DependentSizedExtVectorType *New =
1446      new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1447                                                SizeExpr, AttrLoc);
1448
1449  DependentSizedExtVectorTypes.push_back(New);
1450  Types.push_back(New);
1451  return QualType(New, 0);
1452}
1453
1454/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1455///
1456QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1457  // Unique functions, to guarantee there is only one function of a particular
1458  // structure.
1459  llvm::FoldingSetNodeID ID;
1460  FunctionNoProtoType::Profile(ID, ResultTy);
1461
1462  void *InsertPos = 0;
1463  if (FunctionNoProtoType *FT =
1464        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1465    return QualType(FT, 0);
1466
1467  QualType Canonical;
1468  if (!ResultTy->isCanonical()) {
1469    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1470
1471    // Get the new insert position for the node we care about.
1472    FunctionNoProtoType *NewIP =
1473      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1474    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1475  }
1476
1477  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1478  Types.push_back(New);
1479  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1480  return QualType(New, 0);
1481}
1482
1483/// getFunctionType - Return a normal function type with a typed argument
1484/// list.  isVariadic indicates whether the argument list includes '...'.
1485QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1486                                     unsigned NumArgs, bool isVariadic,
1487                                     unsigned TypeQuals, bool hasExceptionSpec,
1488                                     bool hasAnyExceptionSpec, unsigned NumExs,
1489                                     const QualType *ExArray) {
1490  // Unique functions, to guarantee there is only one function of a particular
1491  // structure.
1492  llvm::FoldingSetNodeID ID;
1493  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1494                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1495                             NumExs, ExArray);
1496
1497  void *InsertPos = 0;
1498  if (FunctionProtoType *FTP =
1499        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1500    return QualType(FTP, 0);
1501
1502  // Determine whether the type being created is already canonical or not.
1503  bool isCanonical = ResultTy->isCanonical();
1504  if (hasExceptionSpec)
1505    isCanonical = false;
1506  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1507    if (!ArgArray[i]->isCanonical())
1508      isCanonical = false;
1509
1510  // If this type isn't canonical, get the canonical version of it.
1511  // The exception spec is not part of the canonical type.
1512  QualType Canonical;
1513  if (!isCanonical) {
1514    llvm::SmallVector<QualType, 16> CanonicalArgs;
1515    CanonicalArgs.reserve(NumArgs);
1516    for (unsigned i = 0; i != NumArgs; ++i)
1517      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1518
1519    Canonical = getFunctionType(getCanonicalType(ResultTy),
1520                                CanonicalArgs.data(), NumArgs,
1521                                isVariadic, TypeQuals);
1522
1523    // Get the new insert position for the node we care about.
1524    FunctionProtoType *NewIP =
1525      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1526    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1527  }
1528
1529  // FunctionProtoType objects are allocated with extra bytes after them
1530  // for two variable size arrays (for parameter and exception types) at the
1531  // end of them.
1532  FunctionProtoType *FTP =
1533    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1534                                 NumArgs*sizeof(QualType) +
1535                                 NumExs*sizeof(QualType), 8);
1536  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1537                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1538                              ExArray, NumExs, Canonical);
1539  Types.push_back(FTP);
1540  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1541  return QualType(FTP, 0);
1542}
1543
1544/// getTypeDeclType - Return the unique reference to the type for the
1545/// specified type declaration.
1546QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1547  assert(Decl && "Passed null for Decl param");
1548  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1549
1550  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1551    return getTypedefType(Typedef);
1552  else if (isa<TemplateTypeParmDecl>(Decl)) {
1553    assert(false && "Template type parameter types are always available.");
1554  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1555    return getObjCInterfaceType(ObjCInterface);
1556
1557  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1558    if (PrevDecl)
1559      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1560    else
1561      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1562  }
1563  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1564    if (PrevDecl)
1565      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1566    else
1567      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1568  }
1569  else
1570    assert(false && "TypeDecl without a type?");
1571
1572  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1573  return QualType(Decl->TypeForDecl, 0);
1574}
1575
1576/// getTypedefType - Return the unique reference to the type for the
1577/// specified typename decl.
1578QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1579  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1580
1581  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1582  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1583  Types.push_back(Decl->TypeForDecl);
1584  return QualType(Decl->TypeForDecl, 0);
1585}
1586
1587/// \brief Retrieve the template type parameter type for a template
1588/// parameter or parameter pack with the given depth, index, and (optionally)
1589/// name.
1590QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1591                                             bool ParameterPack,
1592                                             IdentifierInfo *Name) {
1593  llvm::FoldingSetNodeID ID;
1594  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1595  void *InsertPos = 0;
1596  TemplateTypeParmType *TypeParm
1597    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1598
1599  if (TypeParm)
1600    return QualType(TypeParm, 0);
1601
1602  if (Name) {
1603    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1604    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1605                                                   Name, Canon);
1606  } else
1607    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
1608
1609  Types.push_back(TypeParm);
1610  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1611
1612  return QualType(TypeParm, 0);
1613}
1614
1615QualType
1616ASTContext::getTemplateSpecializationType(TemplateName Template,
1617                                          const TemplateArgument *Args,
1618                                          unsigned NumArgs,
1619                                          QualType Canon) {
1620  if (!Canon.isNull())
1621    Canon = getCanonicalType(Canon);
1622
1623  llvm::FoldingSetNodeID ID;
1624  TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1625
1626  void *InsertPos = 0;
1627  TemplateSpecializationType *Spec
1628    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1629
1630  if (Spec)
1631    return QualType(Spec, 0);
1632
1633  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1634                        sizeof(TemplateArgument) * NumArgs),
1635                       8);
1636  Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
1637  Types.push_back(Spec);
1638  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1639
1640  return QualType(Spec, 0);
1641}
1642
1643QualType
1644ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1645                                 QualType NamedType) {
1646  llvm::FoldingSetNodeID ID;
1647  QualifiedNameType::Profile(ID, NNS, NamedType);
1648
1649  void *InsertPos = 0;
1650  QualifiedNameType *T
1651    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1652  if (T)
1653    return QualType(T, 0);
1654
1655  T = new (*this) QualifiedNameType(NNS, NamedType,
1656                                    getCanonicalType(NamedType));
1657  Types.push_back(T);
1658  QualifiedNameTypes.InsertNode(T, InsertPos);
1659  return QualType(T, 0);
1660}
1661
1662QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1663                                     const IdentifierInfo *Name,
1664                                     QualType Canon) {
1665  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1666
1667  if (Canon.isNull()) {
1668    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1669    if (CanonNNS != NNS)
1670      Canon = getTypenameType(CanonNNS, Name);
1671  }
1672
1673  llvm::FoldingSetNodeID ID;
1674  TypenameType::Profile(ID, NNS, Name);
1675
1676  void *InsertPos = 0;
1677  TypenameType *T
1678    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1679  if (T)
1680    return QualType(T, 0);
1681
1682  T = new (*this) TypenameType(NNS, Name, Canon);
1683  Types.push_back(T);
1684  TypenameTypes.InsertNode(T, InsertPos);
1685  return QualType(T, 0);
1686}
1687
1688QualType
1689ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1690                            const TemplateSpecializationType *TemplateId,
1691                            QualType Canon) {
1692  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1693
1694  if (Canon.isNull()) {
1695    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1696    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1697    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1698      const TemplateSpecializationType *CanonTemplateId
1699        = CanonType->getAsTemplateSpecializationType();
1700      assert(CanonTemplateId &&
1701             "Canonical type must also be a template specialization type");
1702      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1703    }
1704  }
1705
1706  llvm::FoldingSetNodeID ID;
1707  TypenameType::Profile(ID, NNS, TemplateId);
1708
1709  void *InsertPos = 0;
1710  TypenameType *T
1711    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1712  if (T)
1713    return QualType(T, 0);
1714
1715  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1716  Types.push_back(T);
1717  TypenameTypes.InsertNode(T, InsertPos);
1718  return QualType(T, 0);
1719}
1720
1721/// CmpProtocolNames - Comparison predicate for sorting protocols
1722/// alphabetically.
1723static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1724                            const ObjCProtocolDecl *RHS) {
1725  return LHS->getDeclName() < RHS->getDeclName();
1726}
1727
1728static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1729                                   unsigned &NumProtocols) {
1730  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1731
1732  // Sort protocols, keyed by name.
1733  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1734
1735  // Remove duplicates.
1736  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1737  NumProtocols = ProtocolsEnd-Protocols;
1738}
1739
1740/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1741/// the given interface decl and the conforming protocol list.
1742QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
1743                                              ObjCProtocolDecl **Protocols,
1744                                              unsigned NumProtocols) {
1745  // Sort the protocol list alphabetically to canonicalize it.
1746  if (NumProtocols)
1747    SortAndUniqueProtocols(Protocols, NumProtocols);
1748
1749  llvm::FoldingSetNodeID ID;
1750  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
1751
1752  void *InsertPos = 0;
1753  if (ObjCObjectPointerType *QT =
1754              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1755    return QualType(QT, 0);
1756
1757  // No Match;
1758  ObjCObjectPointerType *QType =
1759    new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
1760
1761  Types.push_back(QType);
1762  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1763  return QualType(QType, 0);
1764}
1765
1766/// getObjCInterfaceType - Return the unique reference to the type for the
1767/// specified ObjC interface decl. The list of protocols is optional.
1768QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1769                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1770  if (NumProtocols)
1771    // Sort the protocol list alphabetically to canonicalize it.
1772    SortAndUniqueProtocols(Protocols, NumProtocols);
1773
1774  llvm::FoldingSetNodeID ID;
1775  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1776
1777  void *InsertPos = 0;
1778  if (ObjCInterfaceType *QT =
1779      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1780    return QualType(QT, 0);
1781
1782  // No Match;
1783  ObjCInterfaceType *QType =
1784    new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1785                                    Protocols, NumProtocols);
1786  Types.push_back(QType);
1787  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
1788  return QualType(QType, 0);
1789}
1790
1791/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1792/// TypeOfExprType AST's (since expression's are never shared). For example,
1793/// multiple declarations that refer to "typeof(x)" all contain different
1794/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1795/// on canonical type's (which are always unique).
1796QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1797  TypeOfExprType *toe;
1798  if (tofExpr->isTypeDependent())
1799    toe = new (*this, 8) TypeOfExprType(tofExpr);
1800  else {
1801    QualType Canonical = getCanonicalType(tofExpr->getType());
1802    toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1803  }
1804  Types.push_back(toe);
1805  return QualType(toe, 0);
1806}
1807
1808/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1809/// TypeOfType AST's. The only motivation to unique these nodes would be
1810/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1811/// an issue. This doesn't effect the type checker, since it operates
1812/// on canonical type's (which are always unique).
1813QualType ASTContext::getTypeOfType(QualType tofType) {
1814  QualType Canonical = getCanonicalType(tofType);
1815  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1816  Types.push_back(tot);
1817  return QualType(tot, 0);
1818}
1819
1820/// getDecltypeForExpr - Given an expr, will return the decltype for that
1821/// expression, according to the rules in C++0x [dcl.type.simple]p4
1822static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
1823  if (e->isTypeDependent())
1824    return Context.DependentTy;
1825
1826  // If e is an id expression or a class member access, decltype(e) is defined
1827  // as the type of the entity named by e.
1828  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1829    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1830      return VD->getType();
1831  }
1832  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1833    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1834      return FD->getType();
1835  }
1836  // If e is a function call or an invocation of an overloaded operator,
1837  // (parentheses around e are ignored), decltype(e) is defined as the
1838  // return type of that function.
1839  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1840    return CE->getCallReturnType();
1841
1842  QualType T = e->getType();
1843
1844  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1845  // defined as T&, otherwise decltype(e) is defined as T.
1846  if (e->isLvalue(Context) == Expr::LV_Valid)
1847    T = Context.getLValueReferenceType(T);
1848
1849  return T;
1850}
1851
1852/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
1853/// DecltypeType AST's. The only motivation to unique these nodes would be
1854/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1855/// an issue. This doesn't effect the type checker, since it operates
1856/// on canonical type's (which are always unique).
1857QualType ASTContext::getDecltypeType(Expr *e) {
1858  DecltypeType *dt;
1859  if (e->isTypeDependent()) // FIXME: canonicalize the expression
1860    dt = new (*this, 8) DecltypeType(e, DependentTy);
1861  else {
1862    QualType T = getDecltypeForExpr(e, *this);
1863    dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
1864  }
1865  Types.push_back(dt);
1866  return QualType(dt, 0);
1867}
1868
1869/// getTagDeclType - Return the unique reference to the type for the
1870/// specified TagDecl (struct/union/class/enum) decl.
1871QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1872  assert (Decl);
1873  return getTypeDeclType(Decl);
1874}
1875
1876/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1877/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1878/// needs to agree with the definition in <stddef.h>.
1879QualType ASTContext::getSizeType() const {
1880  return getFromTargetType(Target.getSizeType());
1881}
1882
1883/// getSignedWCharType - Return the type of "signed wchar_t".
1884/// Used when in C++, as a GCC extension.
1885QualType ASTContext::getSignedWCharType() const {
1886  // FIXME: derive from "Target" ?
1887  return WCharTy;
1888}
1889
1890/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1891/// Used when in C++, as a GCC extension.
1892QualType ASTContext::getUnsignedWCharType() const {
1893  // FIXME: derive from "Target" ?
1894  return UnsignedIntTy;
1895}
1896
1897/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1898/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1899QualType ASTContext::getPointerDiffType() const {
1900  return getFromTargetType(Target.getPtrDiffType(0));
1901}
1902
1903//===----------------------------------------------------------------------===//
1904//                              Type Operators
1905//===----------------------------------------------------------------------===//
1906
1907/// getCanonicalType - Return the canonical (structural) type corresponding to
1908/// the specified potentially non-canonical type.  The non-canonical version
1909/// of a type may have many "decorated" versions of types.  Decorators can
1910/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1911/// to be free of any of these, allowing two canonical types to be compared
1912/// for exact equality with a simple pointer comparison.
1913QualType ASTContext::getCanonicalType(QualType T) {
1914  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1915
1916  // If the result has type qualifiers, make sure to canonicalize them as well.
1917  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1918  if (TypeQuals == 0) return CanType;
1919
1920  // If the type qualifiers are on an array type, get the canonical type of the
1921  // array with the qualifiers applied to the element type.
1922  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1923  if (!AT)
1924    return CanType.getQualifiedType(TypeQuals);
1925
1926  // Get the canonical version of the element with the extra qualifiers on it.
1927  // This can recursively sink qualifiers through multiple levels of arrays.
1928  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1929  NewEltTy = getCanonicalType(NewEltTy);
1930
1931  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1932    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1933                                CAT->getIndexTypeQualifier());
1934  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1935    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1936                                  IAT->getIndexTypeQualifier());
1937
1938  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1939    return getDependentSizedArrayType(NewEltTy,
1940                                      DSAT->getSizeExpr(),
1941                                      DSAT->getSizeModifier(),
1942                                      DSAT->getIndexTypeQualifier(),
1943                                      DSAT->getBracketsRange());
1944
1945  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1946  return getVariableArrayType(NewEltTy,
1947                              VAT->getSizeExpr(),
1948                              VAT->getSizeModifier(),
1949                              VAT->getIndexTypeQualifier(),
1950                              VAT->getBracketsRange());
1951}
1952
1953TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1954  // If this template name refers to a template, the canonical
1955  // template name merely stores the template itself.
1956  if (TemplateDecl *Template = Name.getAsTemplateDecl())
1957    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
1958
1959  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1960  assert(DTN && "Non-dependent template names must refer to template decls.");
1961  return DTN->CanonicalTemplateName;
1962}
1963
1964NestedNameSpecifier *
1965ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1966  if (!NNS)
1967    return 0;
1968
1969  switch (NNS->getKind()) {
1970  case NestedNameSpecifier::Identifier:
1971    // Canonicalize the prefix but keep the identifier the same.
1972    return NestedNameSpecifier::Create(*this,
1973                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1974                                       NNS->getAsIdentifier());
1975
1976  case NestedNameSpecifier::Namespace:
1977    // A namespace is canonical; build a nested-name-specifier with
1978    // this namespace and no prefix.
1979    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1980
1981  case NestedNameSpecifier::TypeSpec:
1982  case NestedNameSpecifier::TypeSpecWithTemplate: {
1983    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1984    NestedNameSpecifier *Prefix = 0;
1985
1986    // FIXME: This isn't the right check!
1987    if (T->isDependentType())
1988      Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1989
1990    return NestedNameSpecifier::Create(*this, Prefix,
1991                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1992                                       T.getTypePtr());
1993  }
1994
1995  case NestedNameSpecifier::Global:
1996    // The global specifier is canonical and unique.
1997    return NNS;
1998  }
1999
2000  // Required to silence a GCC warning
2001  return 0;
2002}
2003
2004
2005const ArrayType *ASTContext::getAsArrayType(QualType T) {
2006  // Handle the non-qualified case efficiently.
2007  if (T.getCVRQualifiers() == 0) {
2008    // Handle the common positive case fast.
2009    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2010      return AT;
2011  }
2012
2013  // Handle the common negative case fast, ignoring CVR qualifiers.
2014  QualType CType = T->getCanonicalTypeInternal();
2015
2016  // Make sure to look through type qualifiers (like ExtQuals) for the negative
2017  // test.
2018  if (!isa<ArrayType>(CType) &&
2019      !isa<ArrayType>(CType.getUnqualifiedType()))
2020    return 0;
2021
2022  // Apply any CVR qualifiers from the array type to the element type.  This
2023  // implements C99 6.7.3p8: "If the specification of an array type includes
2024  // any type qualifiers, the element type is so qualified, not the array type."
2025
2026  // If we get here, we either have type qualifiers on the type, or we have
2027  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2028  // we must propagate them down into the elemeng type.
2029  unsigned CVRQuals = T.getCVRQualifiers();
2030  unsigned AddrSpace = 0;
2031  Type *Ty = T.getTypePtr();
2032
2033  // Rip through ExtQualType's and typedefs to get to a concrete type.
2034  while (1) {
2035    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2036      AddrSpace = EXTQT->getAddressSpace();
2037      Ty = EXTQT->getBaseType();
2038    } else {
2039      T = Ty->getDesugaredType();
2040      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2041        break;
2042      CVRQuals |= T.getCVRQualifiers();
2043      Ty = T.getTypePtr();
2044    }
2045  }
2046
2047  // If we have a simple case, just return now.
2048  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2049  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2050    return ATy;
2051
2052  // Otherwise, we have an array and we have qualifiers on it.  Push the
2053  // qualifiers into the array element type and return a new array type.
2054  // Get the canonical version of the element with the extra qualifiers on it.
2055  // This can recursively sink qualifiers through multiple levels of arrays.
2056  QualType NewEltTy = ATy->getElementType();
2057  if (AddrSpace)
2058    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
2059  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2060
2061  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2062    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2063                                                CAT->getSizeModifier(),
2064                                                CAT->getIndexTypeQualifier()));
2065  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2066    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2067                                                  IAT->getSizeModifier(),
2068                                                  IAT->getIndexTypeQualifier()));
2069
2070  if (const DependentSizedArrayType *DSAT
2071        = dyn_cast<DependentSizedArrayType>(ATy))
2072    return cast<ArrayType>(
2073                     getDependentSizedArrayType(NewEltTy,
2074                                                DSAT->getSizeExpr(),
2075                                                DSAT->getSizeModifier(),
2076                                                DSAT->getIndexTypeQualifier(),
2077                                                DSAT->getBracketsRange()));
2078
2079  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2080  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2081                                              VAT->getSizeExpr(),
2082                                              VAT->getSizeModifier(),
2083                                              VAT->getIndexTypeQualifier(),
2084                                              VAT->getBracketsRange()));
2085}
2086
2087
2088/// getArrayDecayedType - Return the properly qualified result of decaying the
2089/// specified array type to a pointer.  This operation is non-trivial when
2090/// handling typedefs etc.  The canonical type of "T" must be an array type,
2091/// this returns a pointer to a properly qualified element of the array.
2092///
2093/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2094QualType ASTContext::getArrayDecayedType(QualType Ty) {
2095  // Get the element type with 'getAsArrayType' so that we don't lose any
2096  // typedefs in the element type of the array.  This also handles propagation
2097  // of type qualifiers from the array type into the element type if present
2098  // (C99 6.7.3p8).
2099  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2100  assert(PrettyArrayType && "Not an array type!");
2101
2102  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2103
2104  // int x[restrict 4] ->  int *restrict
2105  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
2106}
2107
2108QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
2109  QualType ElemTy = VAT->getElementType();
2110
2111  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2112    return getBaseElementType(VAT);
2113
2114  return ElemTy;
2115}
2116
2117/// getFloatingRank - Return a relative rank for floating point types.
2118/// This routine will assert if passed a built-in type that isn't a float.
2119static FloatingRank getFloatingRank(QualType T) {
2120  if (const ComplexType *CT = T->getAsComplexType())
2121    return getFloatingRank(CT->getElementType());
2122
2123  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
2124  switch (T->getAsBuiltinType()->getKind()) {
2125  default: assert(0 && "getFloatingRank(): not a floating type");
2126  case BuiltinType::Float:      return FloatRank;
2127  case BuiltinType::Double:     return DoubleRank;
2128  case BuiltinType::LongDouble: return LongDoubleRank;
2129  }
2130}
2131
2132/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2133/// point or a complex type (based on typeDomain/typeSize).
2134/// 'typeDomain' is a real floating point or complex type.
2135/// 'typeSize' is a real floating point or complex type.
2136QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2137                                                       QualType Domain) const {
2138  FloatingRank EltRank = getFloatingRank(Size);
2139  if (Domain->isComplexType()) {
2140    switch (EltRank) {
2141    default: assert(0 && "getFloatingRank(): illegal value for rank");
2142    case FloatRank:      return FloatComplexTy;
2143    case DoubleRank:     return DoubleComplexTy;
2144    case LongDoubleRank: return LongDoubleComplexTy;
2145    }
2146  }
2147
2148  assert(Domain->isRealFloatingType() && "Unknown domain!");
2149  switch (EltRank) {
2150  default: assert(0 && "getFloatingRank(): illegal value for rank");
2151  case FloatRank:      return FloatTy;
2152  case DoubleRank:     return DoubleTy;
2153  case LongDoubleRank: return LongDoubleTy;
2154  }
2155}
2156
2157/// getFloatingTypeOrder - Compare the rank of the two specified floating
2158/// point types, ignoring the domain of the type (i.e. 'double' ==
2159/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2160/// LHS < RHS, return -1.
2161int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2162  FloatingRank LHSR = getFloatingRank(LHS);
2163  FloatingRank RHSR = getFloatingRank(RHS);
2164
2165  if (LHSR == RHSR)
2166    return 0;
2167  if (LHSR > RHSR)
2168    return 1;
2169  return -1;
2170}
2171
2172/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2173/// routine will assert if passed a built-in type that isn't an integer or enum,
2174/// or if it is not canonicalized.
2175unsigned ASTContext::getIntegerRank(Type *T) {
2176  assert(T->isCanonical() && "T should be canonicalized");
2177  if (EnumType* ET = dyn_cast<EnumType>(T))
2178    T = ET->getDecl()->getIntegerType().getTypePtr();
2179
2180  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2181    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2182
2183  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2184    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2185
2186  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2187    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2188
2189  // There are two things which impact the integer rank: the width, and
2190  // the ordering of builtins.  The builtin ordering is encoded in the
2191  // bottom three bits; the width is encoded in the bits above that.
2192  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2193    return FWIT->getWidth() << 3;
2194
2195  switch (cast<BuiltinType>(T)->getKind()) {
2196  default: assert(0 && "getIntegerRank(): not a built-in integer");
2197  case BuiltinType::Bool:
2198    return 1 + (getIntWidth(BoolTy) << 3);
2199  case BuiltinType::Char_S:
2200  case BuiltinType::Char_U:
2201  case BuiltinType::SChar:
2202  case BuiltinType::UChar:
2203    return 2 + (getIntWidth(CharTy) << 3);
2204  case BuiltinType::Short:
2205  case BuiltinType::UShort:
2206    return 3 + (getIntWidth(ShortTy) << 3);
2207  case BuiltinType::Int:
2208  case BuiltinType::UInt:
2209    return 4 + (getIntWidth(IntTy) << 3);
2210  case BuiltinType::Long:
2211  case BuiltinType::ULong:
2212    return 5 + (getIntWidth(LongTy) << 3);
2213  case BuiltinType::LongLong:
2214  case BuiltinType::ULongLong:
2215    return 6 + (getIntWidth(LongLongTy) << 3);
2216  case BuiltinType::Int128:
2217  case BuiltinType::UInt128:
2218    return 7 + (getIntWidth(Int128Ty) << 3);
2219  }
2220}
2221
2222/// getIntegerTypeOrder - Returns the highest ranked integer type:
2223/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2224/// LHS < RHS, return -1.
2225int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2226  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2227  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2228  if (LHSC == RHSC) return 0;
2229
2230  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2231  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2232
2233  unsigned LHSRank = getIntegerRank(LHSC);
2234  unsigned RHSRank = getIntegerRank(RHSC);
2235
2236  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2237    if (LHSRank == RHSRank) return 0;
2238    return LHSRank > RHSRank ? 1 : -1;
2239  }
2240
2241  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2242  if (LHSUnsigned) {
2243    // If the unsigned [LHS] type is larger, return it.
2244    if (LHSRank >= RHSRank)
2245      return 1;
2246
2247    // If the signed type can represent all values of the unsigned type, it
2248    // wins.  Because we are dealing with 2's complement and types that are
2249    // powers of two larger than each other, this is always safe.
2250    return -1;
2251  }
2252
2253  // If the unsigned [RHS] type is larger, return it.
2254  if (RHSRank >= LHSRank)
2255    return -1;
2256
2257  // If the signed type can represent all values of the unsigned type, it
2258  // wins.  Because we are dealing with 2's complement and types that are
2259  // powers of two larger than each other, this is always safe.
2260  return 1;
2261}
2262
2263// getCFConstantStringType - Return the type used for constant CFStrings.
2264QualType ASTContext::getCFConstantStringType() {
2265  if (!CFConstantStringTypeDecl) {
2266    CFConstantStringTypeDecl =
2267      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2268                         &Idents.get("NSConstantString"));
2269    QualType FieldTypes[4];
2270
2271    // const int *isa;
2272    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
2273    // int flags;
2274    FieldTypes[1] = IntTy;
2275    // const char *str;
2276    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
2277    // long length;
2278    FieldTypes[3] = LongTy;
2279
2280    // Create fields
2281    for (unsigned i = 0; i < 4; ++i) {
2282      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2283                                           SourceLocation(), 0,
2284                                           FieldTypes[i], /*BitWidth=*/0,
2285                                           /*Mutable=*/false);
2286      CFConstantStringTypeDecl->addDecl(Field);
2287    }
2288
2289    CFConstantStringTypeDecl->completeDefinition(*this);
2290  }
2291
2292  return getTagDeclType(CFConstantStringTypeDecl);
2293}
2294
2295void ASTContext::setCFConstantStringType(QualType T) {
2296  const RecordType *Rec = T->getAsRecordType();
2297  assert(Rec && "Invalid CFConstantStringType");
2298  CFConstantStringTypeDecl = Rec->getDecl();
2299}
2300
2301QualType ASTContext::getObjCFastEnumerationStateType()
2302{
2303  if (!ObjCFastEnumerationStateTypeDecl) {
2304    ObjCFastEnumerationStateTypeDecl =
2305      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2306                         &Idents.get("__objcFastEnumerationState"));
2307
2308    QualType FieldTypes[] = {
2309      UnsignedLongTy,
2310      getPointerType(ObjCIdTypedefType),
2311      getPointerType(UnsignedLongTy),
2312      getConstantArrayType(UnsignedLongTy,
2313                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2314    };
2315
2316    for (size_t i = 0; i < 4; ++i) {
2317      FieldDecl *Field = FieldDecl::Create(*this,
2318                                           ObjCFastEnumerationStateTypeDecl,
2319                                           SourceLocation(), 0,
2320                                           FieldTypes[i], /*BitWidth=*/0,
2321                                           /*Mutable=*/false);
2322      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2323    }
2324
2325    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2326  }
2327
2328  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2329}
2330
2331void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2332  const RecordType *Rec = T->getAsRecordType();
2333  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2334  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2335}
2336
2337// This returns true if a type has been typedefed to BOOL:
2338// typedef <type> BOOL;
2339static bool isTypeTypedefedAsBOOL(QualType T) {
2340  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2341    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2342      return II->isStr("BOOL");
2343
2344  return false;
2345}
2346
2347/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2348/// purpose.
2349int ASTContext::getObjCEncodingTypeSize(QualType type) {
2350  uint64_t sz = getTypeSize(type);
2351
2352  // Make all integer and enum types at least as large as an int
2353  if (sz > 0 && type->isIntegralType())
2354    sz = std::max(sz, getTypeSize(IntTy));
2355  // Treat arrays as pointers, since that's how they're passed in.
2356  else if (type->isArrayType())
2357    sz = getTypeSize(VoidPtrTy);
2358  return sz / getTypeSize(CharTy);
2359}
2360
2361/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2362/// declaration.
2363void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2364                                              std::string& S) {
2365  // FIXME: This is not very efficient.
2366  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2367  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2368  // Encode result type.
2369  getObjCEncodingForType(Decl->getResultType(), S);
2370  // Compute size of all parameters.
2371  // Start with computing size of a pointer in number of bytes.
2372  // FIXME: There might(should) be a better way of doing this computation!
2373  SourceLocation Loc;
2374  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
2375  // The first two arguments (self and _cmd) are pointers; account for
2376  // their size.
2377  int ParmOffset = 2 * PtrSize;
2378  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2379       E = Decl->param_end(); PI != E; ++PI) {
2380    QualType PType = (*PI)->getType();
2381    int sz = getObjCEncodingTypeSize(PType);
2382    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
2383    ParmOffset += sz;
2384  }
2385  S += llvm::utostr(ParmOffset);
2386  S += "@0:";
2387  S += llvm::utostr(PtrSize);
2388
2389  // Argument types.
2390  ParmOffset = 2 * PtrSize;
2391  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2392       E = Decl->param_end(); PI != E; ++PI) {
2393    ParmVarDecl *PVDecl = *PI;
2394    QualType PType = PVDecl->getOriginalType();
2395    if (const ArrayType *AT =
2396          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2397      // Use array's original type only if it has known number of
2398      // elements.
2399      if (!isa<ConstantArrayType>(AT))
2400        PType = PVDecl->getType();
2401    } else if (PType->isFunctionType())
2402      PType = PVDecl->getType();
2403    // Process argument qualifiers for user supplied arguments; such as,
2404    // 'in', 'inout', etc.
2405    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
2406    getObjCEncodingForType(PType, S);
2407    S += llvm::utostr(ParmOffset);
2408    ParmOffset += getObjCEncodingTypeSize(PType);
2409  }
2410}
2411
2412/// getObjCEncodingForPropertyDecl - Return the encoded type for this
2413/// property declaration. If non-NULL, Container must be either an
2414/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2415/// NULL when getting encodings for protocol properties.
2416/// Property attributes are stored as a comma-delimited C string. The simple
2417/// attributes readonly and bycopy are encoded as single characters. The
2418/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2419/// encoded as single characters, followed by an identifier. Property types
2420/// are also encoded as a parametrized attribute. The characters used to encode
2421/// these attributes are defined by the following enumeration:
2422/// @code
2423/// enum PropertyAttributes {
2424/// kPropertyReadOnly = 'R',   // property is read-only.
2425/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
2426/// kPropertyByref = '&',  // property is a reference to the value last assigned
2427/// kPropertyDynamic = 'D',    // property is dynamic
2428/// kPropertyGetter = 'G',     // followed by getter selector name
2429/// kPropertySetter = 'S',     // followed by setter selector name
2430/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
2431/// kPropertyType = 't'              // followed by old-style type encoding.
2432/// kPropertyWeak = 'W'              // 'weak' property
2433/// kPropertyStrong = 'P'            // property GC'able
2434/// kPropertyNonAtomic = 'N'         // property non-atomic
2435/// };
2436/// @endcode
2437void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2438                                                const Decl *Container,
2439                                                std::string& S) {
2440  // Collect information from the property implementation decl(s).
2441  bool Dynamic = false;
2442  ObjCPropertyImplDecl *SynthesizePID = 0;
2443
2444  // FIXME: Duplicated code due to poor abstraction.
2445  if (Container) {
2446    if (const ObjCCategoryImplDecl *CID =
2447        dyn_cast<ObjCCategoryImplDecl>(Container)) {
2448      for (ObjCCategoryImplDecl::propimpl_iterator
2449             i = CID->propimpl_begin(), e = CID->propimpl_end();
2450           i != e; ++i) {
2451        ObjCPropertyImplDecl *PID = *i;
2452        if (PID->getPropertyDecl() == PD) {
2453          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2454            Dynamic = true;
2455          } else {
2456            SynthesizePID = PID;
2457          }
2458        }
2459      }
2460    } else {
2461      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
2462      for (ObjCCategoryImplDecl::propimpl_iterator
2463             i = OID->propimpl_begin(), e = OID->propimpl_end();
2464           i != e; ++i) {
2465        ObjCPropertyImplDecl *PID = *i;
2466        if (PID->getPropertyDecl() == PD) {
2467          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2468            Dynamic = true;
2469          } else {
2470            SynthesizePID = PID;
2471          }
2472        }
2473      }
2474    }
2475  }
2476
2477  // FIXME: This is not very efficient.
2478  S = "T";
2479
2480  // Encode result type.
2481  // GCC has some special rules regarding encoding of properties which
2482  // closely resembles encoding of ivars.
2483  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
2484                             true /* outermost type */,
2485                             true /* encoding for property */);
2486
2487  if (PD->isReadOnly()) {
2488    S += ",R";
2489  } else {
2490    switch (PD->getSetterKind()) {
2491    case ObjCPropertyDecl::Assign: break;
2492    case ObjCPropertyDecl::Copy:   S += ",C"; break;
2493    case ObjCPropertyDecl::Retain: S += ",&"; break;
2494    }
2495  }
2496
2497  // It really isn't clear at all what this means, since properties
2498  // are "dynamic by default".
2499  if (Dynamic)
2500    S += ",D";
2501
2502  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2503    S += ",N";
2504
2505  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2506    S += ",G";
2507    S += PD->getGetterName().getAsString();
2508  }
2509
2510  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2511    S += ",S";
2512    S += PD->getSetterName().getAsString();
2513  }
2514
2515  if (SynthesizePID) {
2516    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2517    S += ",V";
2518    S += OID->getNameAsString();
2519  }
2520
2521  // FIXME: OBJCGC: weak & strong
2522}
2523
2524/// getLegacyIntegralTypeEncoding -
2525/// Another legacy compatibility encoding: 32-bit longs are encoded as
2526/// 'l' or 'L' , but not always.  For typedefs, we need to use
2527/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2528///
2529void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2530  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
2531    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2532      if (BT->getKind() == BuiltinType::ULong &&
2533          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2534        PointeeTy = UnsignedIntTy;
2535      else
2536        if (BT->getKind() == BuiltinType::Long &&
2537            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2538          PointeeTy = IntTy;
2539    }
2540  }
2541}
2542
2543void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2544                                        const FieldDecl *Field) {
2545  // We follow the behavior of gcc, expanding structures which are
2546  // directly pointed to, and expanding embedded structures. Note that
2547  // these rules are sufficient to prevent recursive encoding of the
2548  // same type.
2549  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2550                             true /* outermost type */);
2551}
2552
2553static void EncodeBitField(const ASTContext *Context, std::string& S,
2554                           const FieldDecl *FD) {
2555  const Expr *E = FD->getBitWidth();
2556  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2557  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2558  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
2559  S += 'b';
2560  S += llvm::utostr(N);
2561}
2562
2563void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2564                                            bool ExpandPointedToStructures,
2565                                            bool ExpandStructures,
2566                                            const FieldDecl *FD,
2567                                            bool OutermostType,
2568                                            bool EncodingProperty) {
2569  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2570    if (FD && FD->isBitField())
2571      return EncodeBitField(this, S, FD);
2572    char encoding;
2573    switch (BT->getKind()) {
2574    default: assert(0 && "Unhandled builtin type kind");
2575    case BuiltinType::Void:       encoding = 'v'; break;
2576    case BuiltinType::Bool:       encoding = 'B'; break;
2577    case BuiltinType::Char_U:
2578    case BuiltinType::UChar:      encoding = 'C'; break;
2579    case BuiltinType::UShort:     encoding = 'S'; break;
2580    case BuiltinType::UInt:       encoding = 'I'; break;
2581    case BuiltinType::ULong:
2582        encoding =
2583          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2584        break;
2585    case BuiltinType::UInt128:    encoding = 'T'; break;
2586    case BuiltinType::ULongLong:  encoding = 'Q'; break;
2587    case BuiltinType::Char_S:
2588    case BuiltinType::SChar:      encoding = 'c'; break;
2589    case BuiltinType::Short:      encoding = 's'; break;
2590    case BuiltinType::Int:        encoding = 'i'; break;
2591    case BuiltinType::Long:
2592      encoding =
2593        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2594      break;
2595    case BuiltinType::LongLong:   encoding = 'q'; break;
2596    case BuiltinType::Int128:     encoding = 't'; break;
2597    case BuiltinType::Float:      encoding = 'f'; break;
2598    case BuiltinType::Double:     encoding = 'd'; break;
2599    case BuiltinType::LongDouble: encoding = 'd'; break;
2600    }
2601
2602    S += encoding;
2603    return;
2604  }
2605
2606  if (const ComplexType *CT = T->getAsComplexType()) {
2607    S += 'j';
2608    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2609                               false);
2610    return;
2611  }
2612
2613  if (const PointerType *PT = T->getAsPointerType()) {
2614    QualType PointeeTy = PT->getPointeeType();
2615    bool isReadOnly = false;
2616    // For historical/compatibility reasons, the read-only qualifier of the
2617    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2618    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2619    // Also, do not emit the 'r' for anything but the outermost type!
2620    if (isa<TypedefType>(T.getTypePtr())) {
2621      if (OutermostType && T.isConstQualified()) {
2622        isReadOnly = true;
2623        S += 'r';
2624      }
2625    }
2626    else if (OutermostType) {
2627      QualType P = PointeeTy;
2628      while (P->getAsPointerType())
2629        P = P->getAsPointerType()->getPointeeType();
2630      if (P.isConstQualified()) {
2631        isReadOnly = true;
2632        S += 'r';
2633      }
2634    }
2635    if (isReadOnly) {
2636      // Another legacy compatibility encoding. Some ObjC qualifier and type
2637      // combinations need to be rearranged.
2638      // Rewrite "in const" from "nr" to "rn"
2639      const char * s = S.c_str();
2640      int len = S.length();
2641      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2642        std::string replace = "rn";
2643        S.replace(S.end()-2, S.end(), replace);
2644      }
2645    }
2646    if (isObjCSelType(PointeeTy)) {
2647      S += ':';
2648      return;
2649    }
2650
2651    if (PointeeTy->isCharType()) {
2652      // char pointer types should be encoded as '*' unless it is a
2653      // type that has been typedef'd to 'BOOL'.
2654      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2655        S += '*';
2656        return;
2657      }
2658    } else if (const RecordType *RTy = PointeeTy->getAsRecordType()) {
2659      // GCC binary compat: Need to convert "struct objc_class *" to "#".
2660      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2661        S += '#';
2662        return;
2663      }
2664      // GCC binary compat: Need to convert "struct objc_object *" to "@".
2665      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2666        S += '@';
2667        return;
2668      }
2669      // fall through...
2670    }
2671    S += '^';
2672    getLegacyIntegralTypeEncoding(PointeeTy);
2673
2674    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
2675                               NULL);
2676    return;
2677  }
2678
2679  if (const ArrayType *AT =
2680      // Ignore type qualifiers etc.
2681        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2682    if (isa<IncompleteArrayType>(AT)) {
2683      // Incomplete arrays are encoded as a pointer to the array element.
2684      S += '^';
2685
2686      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2687                                 false, ExpandStructures, FD);
2688    } else {
2689      S += '[';
2690
2691      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2692        S += llvm::utostr(CAT->getSize().getZExtValue());
2693      else {
2694        //Variable length arrays are encoded as a regular array with 0 elements.
2695        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2696        S += '0';
2697      }
2698
2699      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2700                                 false, ExpandStructures, FD);
2701      S += ']';
2702    }
2703    return;
2704  }
2705
2706  if (T->getAsFunctionType()) {
2707    S += '?';
2708    return;
2709  }
2710
2711  if (const RecordType *RTy = T->getAsRecordType()) {
2712    RecordDecl *RDecl = RTy->getDecl();
2713    S += RDecl->isUnion() ? '(' : '{';
2714    // Anonymous structures print as '?'
2715    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2716      S += II->getName();
2717    } else {
2718      S += '?';
2719    }
2720    if (ExpandStructures) {
2721      S += '=';
2722      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2723                                   FieldEnd = RDecl->field_end();
2724           Field != FieldEnd; ++Field) {
2725        if (FD) {
2726          S += '"';
2727          S += Field->getNameAsString();
2728          S += '"';
2729        }
2730
2731        // Special case bit-fields.
2732        if (Field->isBitField()) {
2733          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2734                                     (*Field));
2735        } else {
2736          QualType qt = Field->getType();
2737          getLegacyIntegralTypeEncoding(qt);
2738          getObjCEncodingForTypeImpl(qt, S, false, true,
2739                                     FD);
2740        }
2741      }
2742    }
2743    S += RDecl->isUnion() ? ')' : '}';
2744    return;
2745  }
2746
2747  if (T->isEnumeralType()) {
2748    if (FD && FD->isBitField())
2749      EncodeBitField(this, S, FD);
2750    else
2751      S += 'i';
2752    return;
2753  }
2754
2755  if (T->isBlockPointerType()) {
2756    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2757    return;
2758  }
2759
2760  if (T->isObjCInterfaceType()) {
2761    // @encode(class_name)
2762    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2763    S += '{';
2764    const IdentifierInfo *II = OI->getIdentifier();
2765    S += II->getName();
2766    S += '=';
2767    llvm::SmallVector<FieldDecl*, 32> RecFields;
2768    CollectObjCIvars(OI, RecFields);
2769    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2770      if (RecFields[i]->isBitField())
2771        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2772                                   RecFields[i]);
2773      else
2774        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2775                                   FD);
2776    }
2777    S += '}';
2778    return;
2779  }
2780
2781  if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
2782    if (OPT->isObjCIdType()) {
2783      S += '@';
2784      return;
2785    }
2786
2787    if (OPT->isObjCClassType()) {
2788      S += '#';
2789      return;
2790    }
2791
2792    if (OPT->isObjCQualifiedIdType()) {
2793      getObjCEncodingForTypeImpl(getObjCIdType(), S,
2794                                 ExpandPointedToStructures,
2795                                 ExpandStructures, FD);
2796      if (FD || EncodingProperty) {
2797        // Note that we do extended encoding of protocol qualifer list
2798        // Only when doing ivar or property encoding.
2799        S += '"';
2800        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2801             E = OPT->qual_end(); I != E; ++I) {
2802          S += '<';
2803          S += (*I)->getNameAsString();
2804          S += '>';
2805        }
2806        S += '"';
2807      }
2808      return;
2809    }
2810
2811    QualType PointeeTy = OPT->getPointeeType();
2812    if (!EncodingProperty &&
2813        isa<TypedefType>(PointeeTy.getTypePtr())) {
2814      // Another historical/compatibility reason.
2815      // We encode the underlying type which comes out as
2816      // {...};
2817      S += '^';
2818      getObjCEncodingForTypeImpl(PointeeTy, S,
2819                                 false, ExpandPointedToStructures,
2820                                 NULL);
2821      return;
2822    }
2823
2824    S += '@';
2825    if (FD || EncodingProperty) {
2826      S += '"';
2827      S += OPT->getInterfaceDecl()->getNameAsCString();
2828      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2829           E = OPT->qual_end(); I != E; ++I) {
2830        S += '<';
2831        S += (*I)->getNameAsString();
2832        S += '>';
2833      }
2834      S += '"';
2835    }
2836    return;
2837  }
2838
2839  assert(0 && "@encode for type not implemented!");
2840}
2841
2842void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2843                                                 std::string& S) const {
2844  if (QT & Decl::OBJC_TQ_In)
2845    S += 'n';
2846  if (QT & Decl::OBJC_TQ_Inout)
2847    S += 'N';
2848  if (QT & Decl::OBJC_TQ_Out)
2849    S += 'o';
2850  if (QT & Decl::OBJC_TQ_Bycopy)
2851    S += 'O';
2852  if (QT & Decl::OBJC_TQ_Byref)
2853    S += 'R';
2854  if (QT & Decl::OBJC_TQ_Oneway)
2855    S += 'V';
2856}
2857
2858void ASTContext::setBuiltinVaListType(QualType T) {
2859  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2860
2861  BuiltinVaListType = T;
2862}
2863
2864void ASTContext::setObjCIdType(QualType T) {
2865  ObjCIdTypedefType = T;
2866}
2867
2868void ASTContext::setObjCSelType(QualType T) {
2869  ObjCSelType = T;
2870
2871  const TypedefType *TT = T->getAsTypedefType();
2872  if (!TT)
2873    return;
2874  TypedefDecl *TD = TT->getDecl();
2875
2876  // typedef struct objc_selector *SEL;
2877  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2878  if (!ptr)
2879    return;
2880  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2881  if (!rec)
2882    return;
2883  SelStructType = rec;
2884}
2885
2886void ASTContext::setObjCProtoType(QualType QT) {
2887  ObjCProtoType = QT;
2888}
2889
2890void ASTContext::setObjCClassType(QualType T) {
2891  ObjCClassTypedefType = T;
2892}
2893
2894void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2895  assert(ObjCConstantStringType.isNull() &&
2896         "'NSConstantString' type already set!");
2897
2898  ObjCConstantStringType = getObjCInterfaceType(Decl);
2899}
2900
2901/// \brief Retrieve the template name that represents a qualified
2902/// template name such as \c std::vector.
2903TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2904                                                  bool TemplateKeyword,
2905                                                  TemplateDecl *Template) {
2906  llvm::FoldingSetNodeID ID;
2907  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2908
2909  void *InsertPos = 0;
2910  QualifiedTemplateName *QTN =
2911    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2912  if (!QTN) {
2913    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2914    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2915  }
2916
2917  return TemplateName(QTN);
2918}
2919
2920/// \brief Retrieve the template name that represents a dependent
2921/// template name such as \c MetaFun::template apply.
2922TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2923                                                  const IdentifierInfo *Name) {
2924  assert(NNS->isDependent() && "Nested name specifier must be dependent");
2925
2926  llvm::FoldingSetNodeID ID;
2927  DependentTemplateName::Profile(ID, NNS, Name);
2928
2929  void *InsertPos = 0;
2930  DependentTemplateName *QTN =
2931    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2932
2933  if (QTN)
2934    return TemplateName(QTN);
2935
2936  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2937  if (CanonNNS == NNS) {
2938    QTN = new (*this,4) DependentTemplateName(NNS, Name);
2939  } else {
2940    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2941    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2942  }
2943
2944  DependentTemplateNames.InsertNode(QTN, InsertPos);
2945  return TemplateName(QTN);
2946}
2947
2948/// getFromTargetType - Given one of the integer types provided by
2949/// TargetInfo, produce the corresponding type. The unsigned @p Type
2950/// is actually a value of type @c TargetInfo::IntType.
2951QualType ASTContext::getFromTargetType(unsigned Type) const {
2952  switch (Type) {
2953  case TargetInfo::NoInt: return QualType();
2954  case TargetInfo::SignedShort: return ShortTy;
2955  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2956  case TargetInfo::SignedInt: return IntTy;
2957  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2958  case TargetInfo::SignedLong: return LongTy;
2959  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2960  case TargetInfo::SignedLongLong: return LongLongTy;
2961  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2962  }
2963
2964  assert(false && "Unhandled TargetInfo::IntType value");
2965  return QualType();
2966}
2967
2968//===----------------------------------------------------------------------===//
2969//                        Type Predicates.
2970//===----------------------------------------------------------------------===//
2971
2972/// isObjCNSObjectType - Return true if this is an NSObject object using
2973/// NSObject attribute on a c-style pointer type.
2974/// FIXME - Make it work directly on types.
2975/// FIXME: Move to Type.
2976///
2977bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2978  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2979    if (TypedefDecl *TD = TDT->getDecl())
2980      if (TD->getAttr<ObjCNSObjectAttr>())
2981        return true;
2982  }
2983  return false;
2984}
2985
2986/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2987/// garbage collection attribute.
2988///
2989QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
2990  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
2991  if (getLangOptions().ObjC1 &&
2992      getLangOptions().getGCMode() != LangOptions::NonGC) {
2993    GCAttrs = Ty.getObjCGCAttr();
2994    // Default behavious under objective-c's gc is for objective-c pointers
2995    // (or pointers to them) be treated as though they were declared
2996    // as __strong.
2997    if (GCAttrs == QualType::GCNone) {
2998      if (Ty->isObjCObjectPointerType())
2999        GCAttrs = QualType::Strong;
3000      else if (Ty->isPointerType())
3001        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3002    }
3003    // Non-pointers have none gc'able attribute regardless of the attribute
3004    // set on them.
3005    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3006      return QualType::GCNone;
3007  }
3008  return GCAttrs;
3009}
3010
3011//===----------------------------------------------------------------------===//
3012//                        Type Compatibility Testing
3013//===----------------------------------------------------------------------===//
3014
3015/// areCompatVectorTypes - Return true if the two specified vector types are
3016/// compatible.
3017static bool areCompatVectorTypes(const VectorType *LHS,
3018                                 const VectorType *RHS) {
3019  assert(LHS->isCanonical() && RHS->isCanonical());
3020  return LHS->getElementType() == RHS->getElementType() &&
3021         LHS->getNumElements() == RHS->getNumElements();
3022}
3023
3024/// canAssignObjCInterfaces - Return true if the two interface types are
3025/// compatible for assignment from RHS to LHS.  This handles validation of any
3026/// protocol qualifiers on the LHS or RHS.
3027///
3028/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3029bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3030                                         const ObjCObjectPointerType *RHSOPT) {
3031  // If either type represents the built-in 'id' or 'Class' types, return true.
3032  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
3033    return true;
3034
3035  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3036  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3037  if (!LHS || !RHS) {
3038    // We have qualified builtin types.
3039    // Both the right and left sides have qualifiers.
3040    for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3041         E = LHSOPT->qual_end(); I != E; ++I) {
3042      bool RHSImplementsProtocol = false;
3043
3044      // when comparing an id<P> on lhs with a static type on rhs,
3045      // see if static class implements all of id's protocols, directly or
3046      // through its super class and categories.
3047      for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3048           E = RHSOPT->qual_end(); J != E; ++J) {
3049        if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
3050          RHSImplementsProtocol = true;
3051          break;
3052        }
3053      }
3054      if (!RHSImplementsProtocol)
3055        return false;
3056    }
3057    // The RHS implements all protocols listed on the LHS.
3058    return true;
3059  }
3060  return canAssignObjCInterfaces(LHS, RHS);
3061}
3062
3063bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3064                                         const ObjCInterfaceType *RHS) {
3065  // Verify that the base decls are compatible: the RHS must be a subclass of
3066  // the LHS.
3067  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3068    return false;
3069
3070  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
3071  // protocol qualified at all, then we are good.
3072  if (LHS->getNumProtocols() == 0)
3073    return true;
3074
3075  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
3076  // isn't a superset.
3077  if (RHS->getNumProtocols() == 0)
3078    return true;  // FIXME: should return false!
3079
3080  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3081                                        LHSPE = LHS->qual_end();
3082       LHSPI != LHSPE; LHSPI++) {
3083    bool RHSImplementsProtocol = false;
3084
3085    // If the RHS doesn't implement the protocol on the left, the types
3086    // are incompatible.
3087    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3088                                                  RHSPE = RHS->qual_end();
3089         RHSPI != RHSPE; RHSPI++) {
3090      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
3091        RHSImplementsProtocol = true;
3092        break;
3093      }
3094    }
3095    // FIXME: For better diagnostics, consider passing back the protocol name.
3096    if (!RHSImplementsProtocol)
3097      return false;
3098  }
3099  // The RHS implements all protocols listed on the LHS.
3100  return true;
3101}
3102
3103bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3104  // get the "pointed to" types
3105  const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3106  const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
3107
3108  if (!LHSOPT || !RHSOPT)
3109    return false;
3110
3111  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3112         canAssignObjCInterfaces(RHSOPT, LHSOPT);
3113}
3114
3115/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3116/// both shall have the identically qualified version of a compatible type.
3117/// C99 6.2.7p1: Two types have compatible types if their types are the
3118/// same. See 6.7.[2,3,5] for additional rules.
3119bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3120  return !mergeTypes(LHS, RHS).isNull();
3121}
3122
3123QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3124  const FunctionType *lbase = lhs->getAsFunctionType();
3125  const FunctionType *rbase = rhs->getAsFunctionType();
3126  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3127  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3128  bool allLTypes = true;
3129  bool allRTypes = true;
3130
3131  // Check return type
3132  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3133  if (retType.isNull()) return QualType();
3134  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3135    allLTypes = false;
3136  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3137    allRTypes = false;
3138
3139  if (lproto && rproto) { // two C99 style function prototypes
3140    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3141           "C++ shouldn't be here");
3142    unsigned lproto_nargs = lproto->getNumArgs();
3143    unsigned rproto_nargs = rproto->getNumArgs();
3144
3145    // Compatible functions must have the same number of arguments
3146    if (lproto_nargs != rproto_nargs)
3147      return QualType();
3148
3149    // Variadic and non-variadic functions aren't compatible
3150    if (lproto->isVariadic() != rproto->isVariadic())
3151      return QualType();
3152
3153    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3154      return QualType();
3155
3156    // Check argument compatibility
3157    llvm::SmallVector<QualType, 10> types;
3158    for (unsigned i = 0; i < lproto_nargs; i++) {
3159      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3160      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3161      QualType argtype = mergeTypes(largtype, rargtype);
3162      if (argtype.isNull()) return QualType();
3163      types.push_back(argtype);
3164      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3165        allLTypes = false;
3166      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3167        allRTypes = false;
3168    }
3169    if (allLTypes) return lhs;
3170    if (allRTypes) return rhs;
3171    return getFunctionType(retType, types.begin(), types.size(),
3172                           lproto->isVariadic(), lproto->getTypeQuals());
3173  }
3174
3175  if (lproto) allRTypes = false;
3176  if (rproto) allLTypes = false;
3177
3178  const FunctionProtoType *proto = lproto ? lproto : rproto;
3179  if (proto) {
3180    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3181    if (proto->isVariadic()) return QualType();
3182    // Check that the types are compatible with the types that
3183    // would result from default argument promotions (C99 6.7.5.3p15).
3184    // The only types actually affected are promotable integer
3185    // types and floats, which would be passed as a different
3186    // type depending on whether the prototype is visible.
3187    unsigned proto_nargs = proto->getNumArgs();
3188    for (unsigned i = 0; i < proto_nargs; ++i) {
3189      QualType argTy = proto->getArgType(i);
3190      if (argTy->isPromotableIntegerType() ||
3191          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3192        return QualType();
3193    }
3194
3195    if (allLTypes) return lhs;
3196    if (allRTypes) return rhs;
3197    return getFunctionType(retType, proto->arg_type_begin(),
3198                           proto->getNumArgs(), lproto->isVariadic(),
3199                           lproto->getTypeQuals());
3200  }
3201
3202  if (allLTypes) return lhs;
3203  if (allRTypes) return rhs;
3204  return getFunctionNoProtoType(retType);
3205}
3206
3207QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3208  // C++ [expr]: If an expression initially has the type "reference to T", the
3209  // type is adjusted to "T" prior to any further analysis, the expression
3210  // designates the object or function denoted by the reference, and the
3211  // expression is an lvalue unless the reference is an rvalue reference and
3212  // the expression is a function call (possibly inside parentheses).
3213  // FIXME: C++ shouldn't be going through here!  The rules are different
3214  // enough that they should be handled separately.
3215  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3216  // shouldn't be going through here!
3217  if (const ReferenceType *RT = LHS->getAsReferenceType())
3218    LHS = RT->getPointeeType();
3219  if (const ReferenceType *RT = RHS->getAsReferenceType())
3220    RHS = RT->getPointeeType();
3221
3222  QualType LHSCan = getCanonicalType(LHS),
3223           RHSCan = getCanonicalType(RHS);
3224
3225  // If two types are identical, they are compatible.
3226  if (LHSCan == RHSCan)
3227    return LHS;
3228
3229  // If the qualifiers are different, the types aren't compatible
3230  // Note that we handle extended qualifiers later, in the
3231  // case for ExtQualType.
3232  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
3233    return QualType();
3234
3235  Type::TypeClass LHSClass = LHSCan->getTypeClass();
3236  Type::TypeClass RHSClass = RHSCan->getTypeClass();
3237
3238  // We want to consider the two function types to be the same for these
3239  // comparisons, just force one to the other.
3240  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3241  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
3242
3243  // Strip off objc_gc attributes off the top level so they can be merged.
3244  // This is a complete mess, but the attribute itself doesn't make much sense.
3245  if (RHSClass == Type::ExtQual) {
3246    QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3247    if (GCAttr != QualType::GCNone) {
3248      QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
3249      // __weak attribute must appear on both declarations.
3250      // __strong attribue is redundant if other decl is an objective-c
3251      // object pointer (or decorated with __strong attribute); otherwise
3252      // issue error.
3253      if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3254          (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3255           !LHSCan->isObjCObjectPointerType()))
3256        return QualType();
3257
3258      RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3259                     RHS.getCVRQualifiers());
3260      QualType Result = mergeTypes(LHS, RHS);
3261      if (!Result.isNull()) {
3262        if (Result.getObjCGCAttr() == QualType::GCNone)
3263          Result = getObjCGCQualType(Result, GCAttr);
3264        else if (Result.getObjCGCAttr() != GCAttr)
3265          Result = QualType();
3266      }
3267      return Result;
3268    }
3269  }
3270  if (LHSClass == Type::ExtQual) {
3271    QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3272    if (GCAttr != QualType::GCNone) {
3273      QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3274      // __weak attribute must appear on both declarations. __strong
3275      // __strong attribue is redundant if other decl is an objective-c
3276      // object pointer (or decorated with __strong attribute); otherwise
3277      // issue error.
3278      if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3279          (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3280           !RHSCan->isObjCObjectPointerType()))
3281        return QualType();
3282
3283      LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3284                     LHS.getCVRQualifiers());
3285      QualType Result = mergeTypes(LHS, RHS);
3286      if (!Result.isNull()) {
3287        if (Result.getObjCGCAttr() == QualType::GCNone)
3288          Result = getObjCGCQualType(Result, GCAttr);
3289        else if (Result.getObjCGCAttr() != GCAttr)
3290          Result = QualType();
3291      }
3292      return Result;
3293    }
3294  }
3295
3296  // Same as above for arrays
3297  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3298    LHSClass = Type::ConstantArray;
3299  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3300    RHSClass = Type::ConstantArray;
3301
3302  // Canonicalize ExtVector -> Vector.
3303  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3304  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
3305
3306  // If the canonical type classes don't match.
3307  if (LHSClass != RHSClass) {
3308    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3309    // a signed integer type, or an unsigned integer type.
3310    if (const EnumType* ETy = LHS->getAsEnumType()) {
3311      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3312        return RHS;
3313    }
3314    if (const EnumType* ETy = RHS->getAsEnumType()) {
3315      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3316        return LHS;
3317    }
3318
3319    return QualType();
3320  }
3321
3322  // The canonical type classes match.
3323  switch (LHSClass) {
3324#define TYPE(Class, Base)
3325#define ABSTRACT_TYPE(Class, Base)
3326#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3327#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3328#include "clang/AST/TypeNodes.def"
3329    assert(false && "Non-canonical and dependent types shouldn't get here");
3330    return QualType();
3331
3332  case Type::LValueReference:
3333  case Type::RValueReference:
3334  case Type::MemberPointer:
3335    assert(false && "C++ should never be in mergeTypes");
3336    return QualType();
3337
3338  case Type::IncompleteArray:
3339  case Type::VariableArray:
3340  case Type::FunctionProto:
3341  case Type::ExtVector:
3342    assert(false && "Types are eliminated above");
3343    return QualType();
3344
3345  case Type::Pointer:
3346  {
3347    // Merge two pointer types, while trying to preserve typedef info
3348    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3349    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3350    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3351    if (ResultType.isNull()) return QualType();
3352    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3353      return LHS;
3354    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3355      return RHS;
3356    return getPointerType(ResultType);
3357  }
3358  case Type::BlockPointer:
3359  {
3360    // Merge two block pointer types, while trying to preserve typedef info
3361    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3362    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3363    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3364    if (ResultType.isNull()) return QualType();
3365    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3366      return LHS;
3367    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3368      return RHS;
3369    return getBlockPointerType(ResultType);
3370  }
3371  case Type::ConstantArray:
3372  {
3373    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3374    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3375    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3376      return QualType();
3377
3378    QualType LHSElem = getAsArrayType(LHS)->getElementType();
3379    QualType RHSElem = getAsArrayType(RHS)->getElementType();
3380    QualType ResultType = mergeTypes(LHSElem, RHSElem);
3381    if (ResultType.isNull()) return QualType();
3382    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3383      return LHS;
3384    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3385      return RHS;
3386    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3387                                          ArrayType::ArraySizeModifier(), 0);
3388    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3389                                          ArrayType::ArraySizeModifier(), 0);
3390    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3391    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
3392    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3393      return LHS;
3394    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3395      return RHS;
3396    if (LVAT) {
3397      // FIXME: This isn't correct! But tricky to implement because
3398      // the array's size has to be the size of LHS, but the type
3399      // has to be different.
3400      return LHS;
3401    }
3402    if (RVAT) {
3403      // FIXME: This isn't correct! But tricky to implement because
3404      // the array's size has to be the size of RHS, but the type
3405      // has to be different.
3406      return RHS;
3407    }
3408    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3409    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
3410    return getIncompleteArrayType(ResultType,
3411                                  ArrayType::ArraySizeModifier(), 0);
3412  }
3413  case Type::FunctionNoProto:
3414    return mergeFunctionTypes(LHS, RHS);
3415  case Type::Record:
3416  case Type::Enum:
3417    return QualType();
3418  case Type::Builtin:
3419    // Only exactly equal builtin types are compatible, which is tested above.
3420    return QualType();
3421  case Type::Complex:
3422    // Distinct complex types are incompatible.
3423    return QualType();
3424  case Type::Vector:
3425    // FIXME: The merged type should be an ExtVector!
3426    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3427      return LHS;
3428    return QualType();
3429  case Type::ObjCInterface: {
3430    // Check if the interfaces are assignment compatible.
3431    // FIXME: This should be type compatibility, e.g. whether
3432    // "LHS x; RHS x;" at global scope is legal.
3433    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3434    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3435    if (LHSIface && RHSIface &&
3436        canAssignObjCInterfaces(LHSIface, RHSIface))
3437      return LHS;
3438
3439    return QualType();
3440  }
3441  case Type::ObjCObjectPointer: {
3442    // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3443    if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3444      return QualType();
3445
3446    if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3447                                RHS->getAsObjCObjectPointerType()))
3448      return LHS;
3449
3450    return QualType();
3451  }
3452  case Type::FixedWidthInt:
3453    // Distinct fixed-width integers are not compatible.
3454    return QualType();
3455  case Type::ExtQual:
3456    // FIXME: ExtQual types can be compatible even if they're not
3457    // identical!
3458    return QualType();
3459    // First attempt at an implementation, but I'm not really sure it's
3460    // right...
3461#if 0
3462    ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3463    ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3464    if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3465        LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3466      return QualType();
3467    QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3468    LHSBase = QualType(LQual->getBaseType(), 0);
3469    RHSBase = QualType(RQual->getBaseType(), 0);
3470    ResultType = mergeTypes(LHSBase, RHSBase);
3471    if (ResultType.isNull()) return QualType();
3472    ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3473    if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3474      return LHS;
3475    if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3476      return RHS;
3477    ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3478    ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3479    ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3480    return ResultType;
3481#endif
3482
3483  case Type::TemplateSpecialization:
3484    assert(false && "Dependent types have no size");
3485    break;
3486  }
3487
3488  return QualType();
3489}
3490
3491//===----------------------------------------------------------------------===//
3492//                         Integer Predicates
3493//===----------------------------------------------------------------------===//
3494
3495unsigned ASTContext::getIntWidth(QualType T) {
3496  if (T == BoolTy)
3497    return 1;
3498  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3499    return FWIT->getWidth();
3500  }
3501  // For builtin types, just use the standard type sizing method
3502  return (unsigned)getTypeSize(T);
3503}
3504
3505QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3506  assert(T->isSignedIntegerType() && "Unexpected type");
3507  if (const EnumType* ETy = T->getAsEnumType())
3508    T = ETy->getDecl()->getIntegerType();
3509  const BuiltinType* BTy = T->getAsBuiltinType();
3510  assert (BTy && "Unexpected signed integer type");
3511  switch (BTy->getKind()) {
3512  case BuiltinType::Char_S:
3513  case BuiltinType::SChar:
3514    return UnsignedCharTy;
3515  case BuiltinType::Short:
3516    return UnsignedShortTy;
3517  case BuiltinType::Int:
3518    return UnsignedIntTy;
3519  case BuiltinType::Long:
3520    return UnsignedLongTy;
3521  case BuiltinType::LongLong:
3522    return UnsignedLongLongTy;
3523  case BuiltinType::Int128:
3524    return UnsignedInt128Ty;
3525  default:
3526    assert(0 && "Unexpected signed integer type");
3527    return QualType();
3528  }
3529}
3530
3531ExternalASTSource::~ExternalASTSource() { }
3532
3533void ExternalASTSource::PrintStats() { }
3534
3535
3536//===----------------------------------------------------------------------===//
3537//                          Builtin Type Computation
3538//===----------------------------------------------------------------------===//
3539
3540/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3541/// pointer over the consumed characters.  This returns the resultant type.
3542static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3543                                  ASTContext::GetBuiltinTypeError &Error,
3544                                  bool AllowTypeModifiers = true) {
3545  // Modifiers.
3546  int HowLong = 0;
3547  bool Signed = false, Unsigned = false;
3548
3549  // Read the modifiers first.
3550  bool Done = false;
3551  while (!Done) {
3552    switch (*Str++) {
3553    default: Done = true; --Str; break;
3554    case 'S':
3555      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3556      assert(!Signed && "Can't use 'S' modifier multiple times!");
3557      Signed = true;
3558      break;
3559    case 'U':
3560      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3561      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3562      Unsigned = true;
3563      break;
3564    case 'L':
3565      assert(HowLong <= 2 && "Can't have LLLL modifier");
3566      ++HowLong;
3567      break;
3568    }
3569  }
3570
3571  QualType Type;
3572
3573  // Read the base type.
3574  switch (*Str++) {
3575  default: assert(0 && "Unknown builtin type letter!");
3576  case 'v':
3577    assert(HowLong == 0 && !Signed && !Unsigned &&
3578           "Bad modifiers used with 'v'!");
3579    Type = Context.VoidTy;
3580    break;
3581  case 'f':
3582    assert(HowLong == 0 && !Signed && !Unsigned &&
3583           "Bad modifiers used with 'f'!");
3584    Type = Context.FloatTy;
3585    break;
3586  case 'd':
3587    assert(HowLong < 2 && !Signed && !Unsigned &&
3588           "Bad modifiers used with 'd'!");
3589    if (HowLong)
3590      Type = Context.LongDoubleTy;
3591    else
3592      Type = Context.DoubleTy;
3593    break;
3594  case 's':
3595    assert(HowLong == 0 && "Bad modifiers used with 's'!");
3596    if (Unsigned)
3597      Type = Context.UnsignedShortTy;
3598    else
3599      Type = Context.ShortTy;
3600    break;
3601  case 'i':
3602    if (HowLong == 3)
3603      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3604    else if (HowLong == 2)
3605      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3606    else if (HowLong == 1)
3607      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3608    else
3609      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3610    break;
3611  case 'c':
3612    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3613    if (Signed)
3614      Type = Context.SignedCharTy;
3615    else if (Unsigned)
3616      Type = Context.UnsignedCharTy;
3617    else
3618      Type = Context.CharTy;
3619    break;
3620  case 'b': // boolean
3621    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3622    Type = Context.BoolTy;
3623    break;
3624  case 'z':  // size_t.
3625    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3626    Type = Context.getSizeType();
3627    break;
3628  case 'F':
3629    Type = Context.getCFConstantStringType();
3630    break;
3631  case 'a':
3632    Type = Context.getBuiltinVaListType();
3633    assert(!Type.isNull() && "builtin va list type not initialized!");
3634    break;
3635  case 'A':
3636    // This is a "reference" to a va_list; however, what exactly
3637    // this means depends on how va_list is defined. There are two
3638    // different kinds of va_list: ones passed by value, and ones
3639    // passed by reference.  An example of a by-value va_list is
3640    // x86, where va_list is a char*. An example of by-ref va_list
3641    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3642    // we want this argument to be a char*&; for x86-64, we want
3643    // it to be a __va_list_tag*.
3644    Type = Context.getBuiltinVaListType();
3645    assert(!Type.isNull() && "builtin va list type not initialized!");
3646    if (Type->isArrayType()) {
3647      Type = Context.getArrayDecayedType(Type);
3648    } else {
3649      Type = Context.getLValueReferenceType(Type);
3650    }
3651    break;
3652  case 'V': {
3653    char *End;
3654
3655    unsigned NumElements = strtoul(Str, &End, 10);
3656    assert(End != Str && "Missing vector size");
3657
3658    Str = End;
3659
3660    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3661    Type = Context.getVectorType(ElementType, NumElements);
3662    break;
3663  }
3664  case 'P': {
3665    Type = Context.getFILEType();
3666    if (Type.isNull()) {
3667      Error = ASTContext::GE_Missing_FILE;
3668      return QualType();
3669    } else {
3670      break;
3671    }
3672  }
3673  }
3674
3675  if (!AllowTypeModifiers)
3676    return Type;
3677
3678  Done = false;
3679  while (!Done) {
3680    switch (*Str++) {
3681      default: Done = true; --Str; break;
3682      case '*':
3683        Type = Context.getPointerType(Type);
3684        break;
3685      case '&':
3686        Type = Context.getLValueReferenceType(Type);
3687        break;
3688      // FIXME: There's no way to have a built-in with an rvalue ref arg.
3689      case 'C':
3690        Type = Type.getQualifiedType(QualType::Const);
3691        break;
3692    }
3693  }
3694
3695  return Type;
3696}
3697
3698/// GetBuiltinType - Return the type for the specified builtin.
3699QualType ASTContext::GetBuiltinType(unsigned id,
3700                                    GetBuiltinTypeError &Error) {
3701  const char *TypeStr = BuiltinInfo.GetTypeString(id);
3702
3703  llvm::SmallVector<QualType, 8> ArgTypes;
3704
3705  Error = GE_None;
3706  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3707  if (Error != GE_None)
3708    return QualType();
3709  while (TypeStr[0] && TypeStr[0] != '.') {
3710    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3711    if (Error != GE_None)
3712      return QualType();
3713
3714    // Do array -> pointer decay.  The builtin should use the decayed type.
3715    if (Ty->isArrayType())
3716      Ty = getArrayDecayedType(Ty);
3717
3718    ArgTypes.push_back(Ty);
3719  }
3720
3721  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3722         "'.' should only occur at end of builtin type list!");
3723
3724  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3725  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3726    return getFunctionNoProtoType(ResType);
3727  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3728                         TypeStr[0] == '.', 0);
3729}
3730