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