ASTContext.cpp revision fd6a0887a099256c35a5b23e9afd517ffe95fa0a
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
52a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
82a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//  This file implements the ASTContext interface.
112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/ASTContext.h"
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/CharUnits.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclCXX.h"
175e3f23d412006dc4db4e659864679f29341e113fTorne (Richard Coles)#include "clang/AST/DeclObjC.h"
182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/DeclTemplate.h"
195e3f23d412006dc4db4e659864679f29341e113fTorne (Richard Coles)#include "clang/AST/TypeLoc.h"
20868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)#include "clang/AST/Expr.h"
21eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "clang/AST/ExternalASTSource.h"
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/RecordLayout.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Builtins.h"
2446d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)#include "clang/Basic/SourceManager.h"
25f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/Basic/TargetInfo.h"
262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/SmallString.h"
272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/StringExtras.h"
28eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch#include "llvm/Support/MathExtras.h"
297dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch#include "llvm/Support/raw_ostream.h"
307dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch#include "RecordLayoutBuilder.h"
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang;
337dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)enum FloatingRank {
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FloatRank, DoubleRank, LongDoubleRank
36eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch};
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3803b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
39cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)                       const TargetInfo &t,
40cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)                       IdentifierTable &idents, SelectorTable &sels,
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       Builtin::Context &builtins,
42a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                       bool FreeMem, unsigned size_reserve) :
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
447dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
45f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SourceMgr(SM), LangOpts(LOpts),
475f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Idents(idents), Selectors(sels),
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
505d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ObjCIdRedefinitionType = QualType();
515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ObjCClassRedefinitionType = QualType();
527dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  ObjCSelRedefinitionType = QualType();
537dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  if (size_reserve > 0) Types.reserve(size_reserve);
542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TUDecl = TranslationUnitDecl::Create(*this);
552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinTypes();
562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::~ASTContext() {
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (FreeMemory) {
600529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    // Deallocate all the types.
61a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    while (!Types.empty()) {
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Types.back()->Destroy(*this);
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Types.pop_back();
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    for (llvm::FoldingSet<ExtQuals>::iterator
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // Increment in loop to prevent using deallocated memory.
692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Deallocate(&*I++);
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Increment in loop to prevent using deallocated memory.
765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    delete R;
782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (llvm::DenseMap<const ObjCContainerDecl*,
815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                      const ASTRecordLayout*>::iterator
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
836e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)    // Increment in loop to prevent using deallocated memory.
845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    delete R;
865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Destroy nested-name-specifiers.
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         NNS = NestedNameSpecifiers.begin(),
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         NNSEnd = NestedNameSpecifiers.end();
92010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)       NNS != NNSEnd; ) {
931e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    // Increment in loop to prevent using deallocated memory.
94b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)    (*NNS++).Destroy(*this);
955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (GlobalNestedNameSpecifier)
985c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu    GlobalNestedNameSpecifier->Destroy(*this);
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  TUDecl->Destroy(*this);
1015c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu}
1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void
1045f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
1055f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)  ExternalSource.reset(Source.take());
1065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
1075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void ASTContext::PrintStats() const {
1095c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  fprintf(stderr, "*** AST Context Stats:\n");
1105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  fprintf(stderr, "  %d types total.\n", (int)Types.size());
1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
112f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  unsigned counts[] = {
113f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#define TYPE(Name, Parent) 0,
114f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#define ABSTRACT_TYPE(Name, Parent)
115f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/AST/TypeNodes.def"
11646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    0 // Extra
117f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  };
11846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
11946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Type *T = Types[i];
1212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    counts[(unsigned)T->getTypeClass()]++;
1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned Idx = 0;
1255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned TotalBytes = 0;
1265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define TYPE(Name, Parent)                                              \
1275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (counts[Idx])                                                      \
1285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
129f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
130f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  ++Idx;
131f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#define ABSTRACT_TYPE(Name, Parent)
132f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/AST/TypeNodes.def"
133f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
134f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
135116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch
1360529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  if (ExternalSource.get()) {
137f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    fprintf(stderr, "\n");
138f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    ExternalSource->PrintStats();
139f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
140f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
141f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
142f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
1430529e5d033099cbfc42635f6f6183833b09dff6eBen Murdochvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1440529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1450529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1460529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  Types.push_back(Ty);
1470529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch}
1480529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1490529e5d033099cbfc42635f6f6183833b09dff6eBen Murdochvoid ASTContext::InitBuiltinTypes() {
1500529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  assert(VoidTy.isNull() && "Context reinitialized?");
1510529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1520529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // C99 6.2.5p19.
1530529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(VoidTy,              BuiltinType::Void);
1540529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1550529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // C99 6.2.5p2.
156116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  InitBuiltinType(BoolTy,              BuiltinType::Bool);
157116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // C99 6.2.5p3.
15846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  if (LangOpts.CharIsSigned)
1590529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    InitBuiltinType(CharTy,            BuiltinType::Char_S);
1600529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  else
1610529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    InitBuiltinType(CharTy,            BuiltinType::Char_U);
1620529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // C99 6.2.5p4.
1630529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1640529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(ShortTy,             BuiltinType::Short);
1650529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(IntTy,               BuiltinType::Int);
1660529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(LongTy,              BuiltinType::Long);
1670529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1680529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1690529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // C99 6.2.5p6.
1700529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1710529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1720529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1730529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1740529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1750529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1760529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // C99 6.2.5p10.
1770529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(FloatTy,             BuiltinType::Float);
1780529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(DoubleTy,            BuiltinType::Double);
1790529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1800529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1810529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // GNU extension, 128-bit integers.
1820529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1830529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1840529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1850529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
1860529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    InitBuiltinType(WCharTy,           BuiltinType::WChar);
1870529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  else // C99
1880529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    WCharTy = getFromTargetType(Target.getWCharType());
1890529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1900529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1910529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1920529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  else // C99
1930529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    Char16Ty = getFromTargetType(Target.getChar16Type());
1940529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
1950529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1960529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1970529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  else // C99
1980529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    Char32Ty = getFromTargetType(Target.getChar32Type());
1990529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
2000529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  // Placeholder type for functions.
2015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
2021e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
2031320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci  // Placeholder type for type-dependent expressions whose type is
2045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // completely unknown. No code should ever check a type against
2055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // DependentTy and users should never see it; however, it is here to
2065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // help diagnose failures to properly check for type-dependent
2075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // expressions.
2085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
20946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
21046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // Placeholder type for C++0x auto declarations whose real type has
21146d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // not yet been deduced.
21246d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
21346d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
21446d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // C99 6.2.5p11.
21546d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  FloatComplexTy      = getComplexType(FloatTy);
21646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  DoubleComplexTy     = getComplexType(DoubleTy);
21746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  LongDoubleComplexTy = getComplexType(LongDoubleTy);
21846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
21946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  BuiltinVaListType = QualType();
22046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
22146d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
22246d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  ObjCIdTypedefType = QualType();
22346d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  ObjCClassTypedefType = QualType();
22446d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  ObjCSelTypedefType = QualType();
22546d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
2262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Builtin types for 'id', 'Class', and 'SEL'.
2272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
2285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
2295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
2305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
2312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCConstantStringType = QualType();
2325c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu
2335c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  // void * type
2345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  VoidPtrTy = getPointerType(VoidTy);
2355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
23646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // nullptr type (C++0x 2.14.7)
23746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
23846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)}
239f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)
2405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)MemberSpecializationInfo *
2415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
2425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(Var->isStaticDataMember() && "Not a static data member");
2432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
2445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = InstantiatedFromStaticDataMember.find(Var);
2455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Pos == InstantiatedFromStaticDataMember.end())
2465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
2475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return Pos->second;
2492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2504e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
251eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochvoid
2520529e5d033099cbfc42635f6f6183833b09dff6eBen MurdochASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
2530529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch                                                TemplateSpecializationKind TSK) {
2540529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  assert(Inst->isStaticDataMember() && "Not a static data member");
2550529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  assert(Tmpl->isStaticDataMember() && "Not a static data member");
2565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(!InstantiatedFromStaticDataMember[Inst] &&
2575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         "Already noted what static data member was instantiated from");
2585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InstantiatedFromStaticDataMember[Inst]
2595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
2605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
2615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)NamedDecl *
2635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
2645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
2652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = InstantiatedFromUsingDecl.find(UUD);
2665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Pos == InstantiatedFromUsingDecl.end())
2675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
2685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second;
2702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void
2732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
2745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert((isa<UsingDecl>(Pattern) ||
275a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)          isa<UnresolvedUsingValueDecl>(Pattern) ||
276a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
277a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)         "pattern decl is not a using decl");
278a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
279a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  InstantiatedFromUsingDecl[Inst] = Pattern;
2805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
281a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
282a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)UsingShadowDecl *
283a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
2845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
2855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = InstantiatedFromUsingShadowDecl.find(Inst);
2862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == InstantiatedFromUsingShadowDecl.end())
2872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
2882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return Pos->second;
2905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
29146d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
292a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void
293a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
294a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                               UsingShadowDecl *Pattern) {
2955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
2965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
297010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)}
298010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
299010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
300010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
301010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    = InstantiatedFromUnnamedFieldDecl.find(Field);
302010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
303a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return 0;
304a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
305a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return Pos->second;
3065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
307a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
308a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
309a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                                     FieldDecl *Tmpl) {
3105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
3115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
312f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
313010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)         "Already noted what unnamed field was instantiated from");
314010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
315c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
316c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
317c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
318c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)namespace {
319c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  class BeforeInTranslationUnit
320c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    : std::binary_function<SourceRange, SourceRange, bool> {
3212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    SourceManager *SourceMgr;
3222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  public:
3245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
3255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    bool operator()(SourceRange X, SourceRange Y) {
3275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
328a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    }
329a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  };
330e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch}
331e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch
3325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \brief Determine whether the given comment is a Doxygen-style comment.
333a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)///
334a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)/// \param Start the start of the comment text.
335a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)///
3365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \param End the end of the comment text.
3375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)///
3382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// \param Member whether we want to check whether this is a member comment
3392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
3405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// we only return true when we find a non-member comment.
3415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static bool
3425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
3432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                 bool Member = false) {
3442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const char *BufferStart
3452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
346a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
3475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
3485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (End - Start < 4)
350a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return false;
3515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(Start[0] == '/' && "Not a comment?");
353a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
354a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return false;
355a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
3565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return false;
3575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return (Start[3] == '<') == Member;
3592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
360a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
361a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)/// \brief Retrieve the comment associated with the given declaration, if
3625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// it has one.
3635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)const char *ASTContext::getCommentForDecl(const Decl *D) {
3642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!D)
365a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return 0;
366a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
367a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // Check whether we have cached a comment string for this declaration
368a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // already.
369a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  llvm::DenseMap<const Decl *, std::string>::iterator Pos
370a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    = DeclComments.find(D);
3710529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch  if (Pos != DeclComments.end())
372a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return Pos->second.c_str();
373a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
374a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // If we have an external AST source and have not yet loaded comments from
375a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // that source, do so now.
376a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (ExternalSource && !LoadedExternalComments) {
377a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    std::vector<SourceRange> LoadedComments;
378a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    ExternalSource->ReadComments(LoadedComments);
379a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
3802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!LoadedComments.empty())
3812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Comments.insert(Comments.begin(), LoadedComments.begin(),
3822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                      LoadedComments.end());
3832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    LoadedExternalComments = true;
3852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3860529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
3872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // If there are no comments anywhere, we won't find anything.
3882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Comments.empty())
389a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return 0;
390a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
3912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // If the declaration doesn't map directly to a location in a file, we
3922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // can't find the comment.
393a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SourceLocation DeclStartLoc = D->getLocStart();
394a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
3955d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    return 0;
3965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Find the comment that occurs just before this declaration.
3982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  std::vector<SourceRange>::iterator LastComment
39946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    = std::lower_bound(Comments.begin(), Comments.end(),
40046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)                       SourceRange(DeclStartLoc),
4010529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch                       BeforeInTranslationUnit(&SourceMgr));
4022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Decompose the location for the start of the declaration and find the
4045c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  // beginning of the file buffer.
4055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  std::pair<FileID, unsigned> DeclStartDecomp
4065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getDecomposedLoc(DeclStartLoc);
4075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const char *FileBufferStart
4085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
4095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
41046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // First check whether we have a comment for a member.
4117dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  if (LastComment != Comments.end() &&
4127dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
4137dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch      isDoxygenComment(SourceMgr, *LastComment, true)) {
4145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<FileID, unsigned> LastCommentEndDecomp
4155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
416f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
417f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
4185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
41946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)                                     LastCommentEndDecomp.second)) {
4205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // The Doxygen member comment comes after the declaration starts and
4215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // is on the same line and in the same file as the declaration. This
422f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      // is the comment we want.
423f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      std::string &Result = DeclComments[D];
424f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      Result.append(FileBufferStart +
4255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                      SourceMgr.getFileOffset(LastComment->getBegin()),
42646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)                    FileBufferStart + LastCommentEndDecomp.second + 1);
4275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      return Result.c_str();
4285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
4295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
4305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (LastComment == Comments.begin())
4325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
4335c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  --LastComment;
4345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Decompose the end of the comment.
4365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  std::pair<FileID, unsigned> LastCommentEndDecomp
4375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
438f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
439f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  // If the comment and the declaration aren't in the same file, then they
4405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // aren't related.
4415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
4425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
4435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Check that we actually have a Doxygen comment.
4455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (!isDoxygenComment(SourceMgr, *LastComment))
44646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    return 0;
44746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
4485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Compute the starting line for the declaration and for the end of the
4495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // comment (this is expensive).
4505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned DeclStartLine
4515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
4525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned CommentEndLine
4535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
4545c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu                              LastCommentEndDecomp.second);
4555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If the comment does not end on the line prior to the declaration, then
4575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // the comment is not associated with the declaration at all.
4585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (CommentEndLine + 1 != DeclStartLine)
4595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
4605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // We have a comment, but there may be more comments on the previous lines.
462116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Keep looking so long as the comments are still Doxygen comments and are
4631e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  // still adjacent.
4645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned ExpectedLine
4655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
4665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  std::vector<SourceRange>::iterator FirstComment = LastComment;
4675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  while (FirstComment != Comments.begin()) {
4685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Look at the previous comment
4695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    --FirstComment;
4705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<FileID, unsigned> Decomp
47146d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
47246d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
4735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If this previous comment is in a different file, we're done.
4745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (Decomp.first != DeclStartDecomp.first) {
4755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      ++FirstComment;
4765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
4775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
4785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4795c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu    // If this comment is not a Doxygen comment, we're done.
4805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
4815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      ++FirstComment;
4821e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)      break;
48346d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    }
4845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If the line number is not what we expected, we're done.
4865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
4875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (Line != ExpectedLine) {
4885c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu      ++FirstComment;
4895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
4905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
4915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Set the next expected line number.
493f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    ExpectedLine
494f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
4955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
4965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // The iterator range [FirstComment, LastComment] contains all of the
49846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  // BCPL comments that, together, are associated with this declaration.
4995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Form a single comment block string for this declaration that concatenates
5005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // all of these comments.
5015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  std::string &Result = DeclComments[D];
5025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  while (FirstComment != LastComment) {
5035c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu    std::pair<FileID, unsigned> DecompStart
5045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
5055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<FileID, unsigned> DecompEnd
5065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
5075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Result.append(FileBufferStart + DecompStart.second,
5081e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)                  FileBufferStart + DecompEnd.second + 1);
5095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ++FirstComment;
5105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
5115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
512116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch  // Append the last comment line.
5135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  Result.append(FileBufferStart +
5145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                  SourceMgr.getFileOffset(LastComment->getBegin()),
515116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch                FileBufferStart + LastCommentEndDecomp.second + 1);
5165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  return Result.c_str();
5175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
5185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
5205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//                         Type Sizing and Analysis
5215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
5225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
5245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// scalar floating point type.
525116680a4aac90f2aa7413d9095a592090648e557Ben Murdochconst llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
5265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const BuiltinType *BT = T->getAs<BuiltinType>();
5275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  assert(BT && "Not a floating point type!");
5285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  switch (BT->getKind()) {
5295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  default: assert(0 && "Not a floating point type!");
5305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  case BuiltinType::Float:      return Target.getFloatFormat();
5315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  case BuiltinType::Double:     return Target.getDoubleFormat();
5325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
5335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
534116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch}
5355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// getDeclAlign - Return a conservative estimate of the alignment of the
5375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// specified decl.  Note that bitfields do not have a valid alignment, so
5385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// this method will assert on them.
5395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// If @p RefAsPointee, references are treated like their underlying type
5405d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// (for alignof), else they're treated like pointers (for CodeGen).
5415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
5425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned Align = Target.getCharWidth();
54346d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
5445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
5455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = std::max(Align, AA->getMaxAlignment());
54646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
5475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
5485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    QualType T = VD->getType();
5495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
5505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (RefAsPointee)
5515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        T = RT->getPointeeType();
5525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      else
5535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        T = getPointerType(RT->getPointeeType());
554eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    }
5552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!T->isIncompleteType() && !T->isFunctionType()) {
5562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Incomplete or function types default to 1.
5575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
5585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        T = cast<ArrayType>(T)->getElementType();
5595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
5615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
5625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
5635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return CharUnits::fromQuantity(Align / Target.getCharWidth());
5655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
5665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// getTypeSize - Return the size of the specified type, in bits.  This method
5685c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu/// does not work on incomplete types.
5695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)///
5705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// FIXME: Pointers into different addr spaces could have different sizes and
5715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// alignment requirements: getPointerInfo should take an AddrSpace, this
5725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// should take a QualType, &c.
5735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)std::pair<uint64_t, unsigned>
5745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::getTypeInfo(const Type *T) {
5755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  uint64_t Width=0;
5765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned Align=8;
577f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  switch (T->getTypeClass()) {
5785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define TYPE(Class, Base)
5795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ABSTRACT_TYPE(Class, Base)
5805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define NON_CANONICAL_TYPE(Class, Base)
5812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/TypeNodes.def"
5835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    assert(false && "Should not see dependent types");
584f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)    break;
58546d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)
586f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)  case Type::FunctionNoProto:
5875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::FunctionProto:
5885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // GCC extension: alignof(function) = 32 bits
5895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = 0;
5905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = 32;
5915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
5925c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu
5935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::IncompleteArray:
5945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::VariableArray:
5955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = 0;
5965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
5975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
5985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::ConstantArray: {
6001e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
6010529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch
6020529e5d033099cbfc42635f6f6183833b09dff6eBen Murdoch    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
6035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = EltInfo.first*CAT->getSize().getZExtValue();
6045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = EltInfo.second;
60546d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    break;
60646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  }
6075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::ExtVector:
6085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Vector: {
6095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const VectorType *VT = cast<VectorType>(T);
6105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
6115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = EltInfo.first*VT->getNumElements();
6125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Width;
613eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    // If the alignment is not a power of 2, round up to the next power of 2.
6142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // This happens for non-power-of-2 length vectors.
6152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (VT->getNumElements() & (VT->getNumElements()-1)) {
6165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = llvm::NextPowerOf2(Align);
6172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = llvm::RoundUpToAlignment(Width, Align);
6185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
6195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
6205c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  }
6215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
6225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Builtin:
6235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    switch (cast<BuiltinType>(T)->getKind()) {
6245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    default: assert(0 && "Unknown builtin type!");
6255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Void:
6265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // GCC extension: alignof(void) = 8 bits.
6275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = 0;
628f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      Align = 8;
629f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      break;
6305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
6315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Bool:
6321e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)      Width = Target.getBoolWidth();
6335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getBoolAlign();
6345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Char_S:
6365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Char_U:
6375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::UChar:
6385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::SChar:
6395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getCharWidth();
6405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getCharAlign();
6415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::WChar:
6435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getWCharWidth();
6445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getWCharAlign();
6455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Char16:
647116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch      Width = Target.getChar16Width();
6485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getChar16Align();
64946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      break;
6505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Char32:
6515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getChar32Width();
6525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getChar32Align();
6535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::UShort:
6555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Short:
6565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getShortWidth();
6575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getShortAlign();
6585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::UInt:
6605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Int:
6615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getIntWidth();
6625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getIntAlign();
6635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::ULong:
6655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Long:
66646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      Width = Target.getLongWidth();
66746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      Align = Target.getLongAlign();
6685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::ULongLong:
6705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::LongLong:
6715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getLongLongWidth();
6725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getLongLongAlign();
6735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
674eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch    case BuiltinType::Int128:
6752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::UInt128:
6762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = 128;
6775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = 128; // int128_t is 128-bit aligned on all targets.
6782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
6795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Float:
6805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getFloatWidth();
6815c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu      Align = Target.getFloatAlign();
6825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Double:
6845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getDoubleWidth();
6855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getDoubleAlign();
6865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::LongDouble:
6885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getLongDoubleWidth();
6895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = Target.getLongDoubleAlign();
690a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)      break;
6915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::NullPtr:
6925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
6935d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      Align = Target.getPointerAlign(0); //   == sizeof(void*)
6945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
6955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
6965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
6975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::ObjCObjectPointer:
6985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Target.getPointerWidth(0);
6995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Target.getPointerAlign(0);
7005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::BlockPointer: {
7025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
7035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Target.getPointerWidth(AS);
7045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Target.getPointerAlign(AS);
7055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
707f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  case Type::LValueReference:
70846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  case Type::RValueReference: {
7095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // alignof and sizeof should never enter this code path here, so we go
710f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    // the pointer route.
711f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
7125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Target.getPointerWidth(AS);
7135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Target.getPointerAlign(AS);
7145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Pointer: {
7175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
7185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Target.getPointerWidth(AS);
7195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Target.getPointerAlign(AS);
7205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
72246d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)  case Type::MemberPointer: {
72346d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
7245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<uint64_t, unsigned> PtrDiffInfo =
7255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      getTypeInfo(getPointerDiffType());
7265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = PtrDiffInfo.first;
7275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (Pointee->isFunctionType())
7285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width *= 2;
7295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = PtrDiffInfo.second;
7305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Complex: {
7335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Complex types have the same alignment as their elements, but twice the
7345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // size.
7355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    std::pair<uint64_t, unsigned> EltInfo =
7365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      getTypeInfo(cast<ComplexType>(T)->getElementType());
7375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = EltInfo.first*2;
7385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = EltInfo.second;
7395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::ObjCInterface: {
7425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
7435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
7445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Layout.getSize();
7455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Align = Layout.getAlignment();
7465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
7475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::Record:
7495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Enum: {
7505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const TagType *TT = cast<TagType>(T);
7515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (TT->getDecl()->isInvalidDecl()) {
7535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Width = 1;
7545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = 1;
7555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
7565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
7575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (const EnumType *ET = dyn_cast<EnumType>(TT))
7595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      return getTypeInfo(ET->getDecl()->getIntegerType());
7602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const RecordType *RT = cast<RecordType>(TT);
7622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
7632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = Layout.getSize();
7642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = Layout.getAlignment();
7652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
7665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::SubstTemplateTypeParm:
7695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
7705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                       getReplacementType().getTypePtr());
7715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Elaborated:
7735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
7745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                         .getTypePtr());
7755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::Typedef: {
7775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
7787dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
779010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Align = std::max(Aligned->getMaxAlignment(),
7807dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch                       getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
7815d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
7827dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    } else
7837dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
7845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    break;
7857dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
7862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::TypeOfExpr:
7885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
7895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                         .getTypePtr());
790a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
7915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::TypeOf:
7925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
7935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
794c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  case Type::Decltype:
7957dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
7965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                        .getTypePtr());
7975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::QualifiedName:
7995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
8005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Type::TemplateSpecialization:
8025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    assert(getCanonicalType(T) != T &&
8035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)           "Cannot request the size of a dependent type");
8042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // FIXME: this is likely to be wrong once we support template
8055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // aliases, since a template alias could refer to a typedef that
8065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // has an __aligned__ attribute on it.
8075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getTypeInfo(getCanonicalType(T));
8085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
8095c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu
8105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
8115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return std::make_pair(Width, Align);
8125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
8135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// getTypeSizeInChars - Return the size of the specified type, in characters.
8155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// This method does not work on incomplete types.
8162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)CharUnits ASTContext::getTypeSizeInChars(QualType T) {
8175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
8185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
819c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
820eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdoch  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
8215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
8225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
8245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// characters. This method does not work on incomplete types.
8251e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)CharUnits ASTContext::getTypeAlignInChars(QualType T) {
8265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
8271e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)}
828c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
829c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
830c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
8315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
8335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// type for the current target in bits.  This can be different than the ABI
8345c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu/// alignment in cases where it is beneficial for performance to overalign
8355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// a data type.
8365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
8375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned ABIAlign = getTypeAlign(T);
8385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Double and long long should be naturally aligned if possible.
8405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (const ComplexType* CT = T->getAs<ComplexType>())
8415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    T = CT->getElementType().getTypePtr();
8421e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
8435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      T->isSpecificBuiltinType(BuiltinType::LongLong))
8445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return std::max(ABIAlign, (unsigned)getTypeSize(T));
8452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return ABIAlign;
847}
848
849static void CollectLocalObjCIvars(ASTContext *Ctx,
850                                  const ObjCInterfaceDecl *OI,
851                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
852  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
853       E = OI->ivar_end(); I != E; ++I) {
854    ObjCIvarDecl *IVDecl = *I;
855    if (!IVDecl->isInvalidDecl())
856      Fields.push_back(cast<FieldDecl>(IVDecl));
857  }
858}
859
860void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
861                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
862  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
863    CollectObjCIvars(SuperClass, Fields);
864  CollectLocalObjCIvars(this, OI, Fields);
865}
866
867/// ShallowCollectObjCIvars -
868/// Collect all ivars, including those synthesized, in the current class.
869///
870void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
871                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
872                                 bool CollectSynthesized) {
873  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
874         E = OI->ivar_end(); I != E; ++I) {
875     Ivars.push_back(*I);
876  }
877  if (CollectSynthesized)
878    CollectSynthesizedIvars(OI, Ivars);
879}
880
881void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
882                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
883  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
884       E = PD->prop_end(); I != E; ++I)
885    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
886      Ivars.push_back(Ivar);
887
888  // Also look into nested protocols.
889  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
890       E = PD->protocol_end(); P != E; ++P)
891    CollectProtocolSynthesizedIvars(*P, Ivars);
892}
893
894/// CollectSynthesizedIvars -
895/// This routine collect synthesized ivars for the designated class.
896///
897void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
898                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
899  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
900       E = OI->prop_end(); I != E; ++I) {
901    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
902      Ivars.push_back(Ivar);
903  }
904  // Also look into interface's protocol list for properties declared
905  // in the protocol and whose ivars are synthesized.
906  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
907       PE = OI->protocol_end(); P != PE; ++P) {
908    ObjCProtocolDecl *PD = (*P);
909    CollectProtocolSynthesizedIvars(PD, Ivars);
910  }
911}
912
913/// CollectInheritedProtocols - Collect all protocols in current class and
914/// those inherited by it.
915void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
916                          llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
917  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
918    for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
919         PE = OI->protocol_end(); P != PE; ++P) {
920      ObjCProtocolDecl *Proto = (*P);
921      Protocols.push_back(Proto);
922      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
923           PE = Proto->protocol_end(); P != PE; ++P)
924        CollectInheritedProtocols(*P, Protocols);
925      }
926
927    // Categories of this Interface.
928    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
929         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
930      CollectInheritedProtocols(CDeclChain, Protocols);
931    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
932      while (SD) {
933        CollectInheritedProtocols(SD, Protocols);
934        SD = SD->getSuperClass();
935      }
936    return;
937  }
938  if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
939    for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
940         PE = OC->protocol_end(); P != PE; ++P) {
941      ObjCProtocolDecl *Proto = (*P);
942      Protocols.push_back(Proto);
943      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
944           PE = Proto->protocol_end(); P != PE; ++P)
945        CollectInheritedProtocols(*P, Protocols);
946    }
947    return;
948  }
949  if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
950    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
951         PE = OP->protocol_end(); P != PE; ++P) {
952      ObjCProtocolDecl *Proto = (*P);
953      Protocols.push_back(Proto);
954      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955           PE = Proto->protocol_end(); P != PE; ++P)
956        CollectInheritedProtocols(*P, Protocols);
957    }
958    return;
959  }
960}
961
962unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
963  unsigned count = 0;
964  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
965       E = PD->prop_end(); I != E; ++I)
966    if ((*I)->getPropertyIvarDecl())
967      ++count;
968
969  // Also look into nested protocols.
970  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
971       E = PD->protocol_end(); P != E; ++P)
972    count += CountProtocolSynthesizedIvars(*P);
973  return count;
974}
975
976unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
977  unsigned count = 0;
978  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
979       E = OI->prop_end(); I != E; ++I) {
980    if ((*I)->getPropertyIvarDecl())
981      ++count;
982  }
983  // Also look into interface's protocol list for properties declared
984  // in the protocol and whose ivars are synthesized.
985  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
986       PE = OI->protocol_end(); P != PE; ++P) {
987    ObjCProtocolDecl *PD = (*P);
988    count += CountProtocolSynthesizedIvars(PD);
989  }
990  return count;
991}
992
993/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
994ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
995  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
996    I = ObjCImpls.find(D);
997  if (I != ObjCImpls.end())
998    return cast<ObjCImplementationDecl>(I->second);
999  return 0;
1000}
1001/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1002ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1003  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004    I = ObjCImpls.find(D);
1005  if (I != ObjCImpls.end())
1006    return cast<ObjCCategoryImplDecl>(I->second);
1007  return 0;
1008}
1009
1010/// \brief Set the implementation of ObjCInterfaceDecl.
1011void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1012                           ObjCImplementationDecl *ImplD) {
1013  assert(IFaceD && ImplD && "Passed null params");
1014  ObjCImpls[IFaceD] = ImplD;
1015}
1016/// \brief Set the implementation of ObjCCategoryDecl.
1017void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1018                           ObjCCategoryImplDecl *ImplD) {
1019  assert(CatD && ImplD && "Passed null params");
1020  ObjCImpls[CatD] = ImplD;
1021}
1022
1023/// \brief Allocate an uninitialized TypeSourceInfo.
1024///
1025/// The caller should initialize the memory held by TypeSourceInfo using
1026/// the TypeLoc wrappers.
1027///
1028/// \param T the type that will be the basis for type source info. This type
1029/// should refer to how the declarator was written in source code, not to
1030/// what type semantic analysis resolved the declarator to.
1031TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1032                                                 unsigned DataSize) {
1033  if (!DataSize)
1034    DataSize = TypeLoc::getFullDataSizeForType(T);
1035  else
1036    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1037           "incorrect data size provided to CreateTypeSourceInfo!");
1038
1039  TypeSourceInfo *TInfo =
1040    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1041  new (TInfo) TypeSourceInfo(T);
1042  return TInfo;
1043}
1044
1045TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1046                                                     SourceLocation L) {
1047  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1048  DI->getTypeLoc().initialize(L);
1049  return DI;
1050}
1051
1052/// getInterfaceLayoutImpl - Get or compute information about the
1053/// layout of the given interface.
1054///
1055/// \param Impl - If given, also include the layout of the interface's
1056/// implementation. This may differ by including synthesized ivars.
1057const ASTRecordLayout &
1058ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1059                          const ObjCImplementationDecl *Impl) {
1060  assert(!D->isForwardDecl() && "Invalid interface decl!");
1061
1062  // Look up this layout, if already laid out, return what we have.
1063  ObjCContainerDecl *Key =
1064    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1065  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1066    return *Entry;
1067
1068  // Add in synthesized ivar count if laying out an implementation.
1069  if (Impl) {
1070    unsigned SynthCount = CountSynthesizedIvars(D);
1071    // If there aren't any sythesized ivars then reuse the interface
1072    // entry. Note we can't cache this because we simply free all
1073    // entries later; however we shouldn't look up implementations
1074    // frequently.
1075    if (SynthCount == 0)
1076      return getObjCLayout(D, 0);
1077  }
1078
1079  const ASTRecordLayout *NewEntry =
1080    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1081  ObjCLayouts[Key] = NewEntry;
1082
1083  return *NewEntry;
1084}
1085
1086const ASTRecordLayout &
1087ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1088  return getObjCLayout(D, 0);
1089}
1090
1091const ASTRecordLayout &
1092ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1093  return getObjCLayout(D->getClassInterface(), D);
1094}
1095
1096/// getASTRecordLayout - Get or compute information about the layout of the
1097/// specified record (struct/union/class), which indicates its size and field
1098/// position information.
1099const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
1100  D = D->getDefinition(*this);
1101  assert(D && "Cannot get layout of forward declarations!");
1102
1103  // Look up this layout, if already laid out, return what we have.
1104  // Note that we can't save a reference to the entry because this function
1105  // is recursive.
1106  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
1107  if (Entry) return *Entry;
1108
1109  const ASTRecordLayout *NewEntry =
1110    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
1111  ASTRecordLayouts[D] = NewEntry;
1112
1113  return *NewEntry;
1114}
1115
1116const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1117  RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1118  assert(RD && "Cannot get key function for forward declarations!");
1119
1120  const CXXMethodDecl *&Entry = KeyFunctions[RD];
1121  if (!Entry)
1122    Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1123  else
1124    assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1125           "Key function changed!");
1126
1127  return Entry;
1128}
1129
1130//===----------------------------------------------------------------------===//
1131//                   Type creation/memoization methods
1132//===----------------------------------------------------------------------===//
1133
1134QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1135  unsigned Fast = Quals.getFastQualifiers();
1136  Quals.removeFastQualifiers();
1137
1138  // Check if we've already instantiated this type.
1139  llvm::FoldingSetNodeID ID;
1140  ExtQuals::Profile(ID, TypeNode, Quals);
1141  void *InsertPos = 0;
1142  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1143    assert(EQ->getQualifiers() == Quals);
1144    QualType T = QualType(EQ, Fast);
1145    return T;
1146  }
1147
1148  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1149  ExtQualNodes.InsertNode(New, InsertPos);
1150  QualType T = QualType(New, Fast);
1151  return T;
1152}
1153
1154QualType ASTContext::getVolatileType(QualType T) {
1155  QualType CanT = getCanonicalType(T);
1156  if (CanT.isVolatileQualified()) return T;
1157
1158  QualifierCollector Quals;
1159  const Type *TypeNode = Quals.strip(T);
1160  Quals.addVolatile();
1161
1162  return getExtQualType(TypeNode, Quals);
1163}
1164
1165QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1166  QualType CanT = getCanonicalType(T);
1167  if (CanT.getAddressSpace() == AddressSpace)
1168    return T;
1169
1170  // If we are composing extended qualifiers together, merge together
1171  // into one ExtQuals node.
1172  QualifierCollector Quals;
1173  const Type *TypeNode = Quals.strip(T);
1174
1175  // If this type already has an address space specified, it cannot get
1176  // another one.
1177  assert(!Quals.hasAddressSpace() &&
1178         "Type cannot be in multiple addr spaces!");
1179  Quals.addAddressSpace(AddressSpace);
1180
1181  return getExtQualType(TypeNode, Quals);
1182}
1183
1184QualType ASTContext::getObjCGCQualType(QualType T,
1185                                       Qualifiers::GC GCAttr) {
1186  QualType CanT = getCanonicalType(T);
1187  if (CanT.getObjCGCAttr() == GCAttr)
1188    return T;
1189
1190  if (T->isPointerType()) {
1191    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1192    if (Pointee->isAnyPointerType()) {
1193      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1194      return getPointerType(ResultType);
1195    }
1196  }
1197
1198  // If we are composing extended qualifiers together, merge together
1199  // into one ExtQuals node.
1200  QualifierCollector Quals;
1201  const Type *TypeNode = Quals.strip(T);
1202
1203  // If this type already has an ObjCGC specified, it cannot get
1204  // another one.
1205  assert(!Quals.hasObjCGCAttr() &&
1206         "Type cannot have multiple ObjCGCs!");
1207  Quals.addObjCGCAttr(GCAttr);
1208
1209  return getExtQualType(TypeNode, Quals);
1210}
1211
1212static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1213                                        bool AddNoReturn,
1214                                        CallingConv CallConv) {
1215  QualType ResultType;
1216  if (const PointerType *Pointer = T->getAs<PointerType>()) {
1217    QualType Pointee = Pointer->getPointeeType();
1218    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1219                                         CallConv);
1220    if (ResultType == Pointee)
1221      return T;
1222
1223    ResultType = Context.getPointerType(ResultType);
1224  } else if (const BlockPointerType *BlockPointer
1225                                              = T->getAs<BlockPointerType>()) {
1226    QualType Pointee = BlockPointer->getPointeeType();
1227    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1228                                         CallConv);
1229    if (ResultType == Pointee)
1230      return T;
1231
1232    ResultType = Context.getBlockPointerType(ResultType);
1233   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1234    if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
1235      return T;
1236
1237    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1238      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1239                                                  AddNoReturn, CallConv);
1240    } else {
1241      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
1242      ResultType
1243        = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1244                                  FPT->getNumArgs(), FPT->isVariadic(),
1245                                  FPT->getTypeQuals(),
1246                                  FPT->hasExceptionSpec(),
1247                                  FPT->hasAnyExceptionSpec(),
1248                                  FPT->getNumExceptions(),
1249                                  FPT->exception_begin(),
1250                                  AddNoReturn, CallConv);
1251    }
1252  } else
1253    return T;
1254
1255  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1256}
1257
1258QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1259  return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1260}
1261
1262QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1263  return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
1264}
1265
1266/// getComplexType - Return the uniqued reference to the type for a complex
1267/// number with the specified element type.
1268QualType ASTContext::getComplexType(QualType T) {
1269  // Unique pointers, to guarantee there is only one pointer of a particular
1270  // structure.
1271  llvm::FoldingSetNodeID ID;
1272  ComplexType::Profile(ID, T);
1273
1274  void *InsertPos = 0;
1275  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1276    return QualType(CT, 0);
1277
1278  // If the pointee type isn't canonical, this won't be a canonical type either,
1279  // so fill in the canonical type field.
1280  QualType Canonical;
1281  if (!T.isCanonical()) {
1282    Canonical = getComplexType(getCanonicalType(T));
1283
1284    // Get the new insert position for the node we care about.
1285    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1286    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1287  }
1288  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1289  Types.push_back(New);
1290  ComplexTypes.InsertNode(New, InsertPos);
1291  return QualType(New, 0);
1292}
1293
1294/// getPointerType - Return the uniqued reference to the type for a pointer to
1295/// the specified type.
1296QualType ASTContext::getPointerType(QualType T) {
1297  // Unique pointers, to guarantee there is only one pointer of a particular
1298  // structure.
1299  llvm::FoldingSetNodeID ID;
1300  PointerType::Profile(ID, T);
1301
1302  void *InsertPos = 0;
1303  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1304    return QualType(PT, 0);
1305
1306  // If the pointee type isn't canonical, this won't be a canonical type either,
1307  // so fill in the canonical type field.
1308  QualType Canonical;
1309  if (!T.isCanonical()) {
1310    Canonical = getPointerType(getCanonicalType(T));
1311
1312    // Get the new insert position for the node we care about.
1313    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1314    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1315  }
1316  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1317  Types.push_back(New);
1318  PointerTypes.InsertNode(New, InsertPos);
1319  return QualType(New, 0);
1320}
1321
1322/// getBlockPointerType - Return the uniqued reference to the type for
1323/// a pointer to the specified block.
1324QualType ASTContext::getBlockPointerType(QualType T) {
1325  assert(T->isFunctionType() && "block of function types only");
1326  // Unique pointers, to guarantee there is only one block of a particular
1327  // structure.
1328  llvm::FoldingSetNodeID ID;
1329  BlockPointerType::Profile(ID, T);
1330
1331  void *InsertPos = 0;
1332  if (BlockPointerType *PT =
1333        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1334    return QualType(PT, 0);
1335
1336  // If the block pointee type isn't canonical, this won't be a canonical
1337  // type either so fill in the canonical type field.
1338  QualType Canonical;
1339  if (!T.isCanonical()) {
1340    Canonical = getBlockPointerType(getCanonicalType(T));
1341
1342    // Get the new insert position for the node we care about.
1343    BlockPointerType *NewIP =
1344      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1345    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1346  }
1347  BlockPointerType *New
1348    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1349  Types.push_back(New);
1350  BlockPointerTypes.InsertNode(New, InsertPos);
1351  return QualType(New, 0);
1352}
1353
1354/// getLValueReferenceType - Return the uniqued reference to the type for an
1355/// lvalue reference to the specified type.
1356QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1357  // Unique pointers, to guarantee there is only one pointer of a particular
1358  // structure.
1359  llvm::FoldingSetNodeID ID;
1360  ReferenceType::Profile(ID, T, SpelledAsLValue);
1361
1362  void *InsertPos = 0;
1363  if (LValueReferenceType *RT =
1364        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1365    return QualType(RT, 0);
1366
1367  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1368
1369  // If the referencee type isn't canonical, this won't be a canonical type
1370  // either, so fill in the canonical type field.
1371  QualType Canonical;
1372  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1373    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1374    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1375
1376    // Get the new insert position for the node we care about.
1377    LValueReferenceType *NewIP =
1378      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1379    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1380  }
1381
1382  LValueReferenceType *New
1383    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1384                                                     SpelledAsLValue);
1385  Types.push_back(New);
1386  LValueReferenceTypes.InsertNode(New, InsertPos);
1387
1388  return QualType(New, 0);
1389}
1390
1391/// getRValueReferenceType - Return the uniqued reference to the type for an
1392/// rvalue reference to the specified type.
1393QualType ASTContext::getRValueReferenceType(QualType T) {
1394  // Unique pointers, to guarantee there is only one pointer of a particular
1395  // structure.
1396  llvm::FoldingSetNodeID ID;
1397  ReferenceType::Profile(ID, T, false);
1398
1399  void *InsertPos = 0;
1400  if (RValueReferenceType *RT =
1401        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1402    return QualType(RT, 0);
1403
1404  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1405
1406  // If the referencee type isn't canonical, this won't be a canonical type
1407  // either, so fill in the canonical type field.
1408  QualType Canonical;
1409  if (InnerRef || !T.isCanonical()) {
1410    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1411    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1412
1413    // Get the new insert position for the node we care about.
1414    RValueReferenceType *NewIP =
1415      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1416    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1417  }
1418
1419  RValueReferenceType *New
1420    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1421  Types.push_back(New);
1422  RValueReferenceTypes.InsertNode(New, InsertPos);
1423  return QualType(New, 0);
1424}
1425
1426/// getMemberPointerType - Return the uniqued reference to the type for a
1427/// member pointer to the specified type, in the specified class.
1428QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1429  // Unique pointers, to guarantee there is only one pointer of a particular
1430  // structure.
1431  llvm::FoldingSetNodeID ID;
1432  MemberPointerType::Profile(ID, T, Cls);
1433
1434  void *InsertPos = 0;
1435  if (MemberPointerType *PT =
1436      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1437    return QualType(PT, 0);
1438
1439  // If the pointee or class type isn't canonical, this won't be a canonical
1440  // type either, so fill in the canonical type field.
1441  QualType Canonical;
1442  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1443    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1444
1445    // Get the new insert position for the node we care about.
1446    MemberPointerType *NewIP =
1447      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1448    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1449  }
1450  MemberPointerType *New
1451    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1452  Types.push_back(New);
1453  MemberPointerTypes.InsertNode(New, InsertPos);
1454  return QualType(New, 0);
1455}
1456
1457/// getConstantArrayType - Return the unique reference to the type for an
1458/// array of the specified element type.
1459QualType ASTContext::getConstantArrayType(QualType EltTy,
1460                                          const llvm::APInt &ArySizeIn,
1461                                          ArrayType::ArraySizeModifier ASM,
1462                                          unsigned EltTypeQuals) {
1463  assert((EltTy->isDependentType() ||
1464          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1465         "Constant array of VLAs is illegal!");
1466
1467  // Convert the array size into a canonical width matching the pointer size for
1468  // the target.
1469  llvm::APInt ArySize(ArySizeIn);
1470  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1471
1472  llvm::FoldingSetNodeID ID;
1473  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1474
1475  void *InsertPos = 0;
1476  if (ConstantArrayType *ATP =
1477      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1478    return QualType(ATP, 0);
1479
1480  // If the element type isn't canonical, this won't be a canonical type either,
1481  // so fill in the canonical type field.
1482  QualType Canonical;
1483  if (!EltTy.isCanonical()) {
1484    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1485                                     ASM, EltTypeQuals);
1486    // Get the new insert position for the node we care about.
1487    ConstantArrayType *NewIP =
1488      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1489    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1490  }
1491
1492  ConstantArrayType *New = new(*this,TypeAlignment)
1493    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1494  ConstantArrayTypes.InsertNode(New, InsertPos);
1495  Types.push_back(New);
1496  return QualType(New, 0);
1497}
1498
1499/// getVariableArrayType - Returns a non-unique reference to the type for a
1500/// variable array of the specified element type.
1501QualType ASTContext::getVariableArrayType(QualType EltTy,
1502                                          Expr *NumElts,
1503                                          ArrayType::ArraySizeModifier ASM,
1504                                          unsigned EltTypeQuals,
1505                                          SourceRange Brackets) {
1506  // Since we don't unique expressions, it isn't possible to unique VLA's
1507  // that have an expression provided for their size.
1508
1509  VariableArrayType *New = new(*this, TypeAlignment)
1510    VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
1511
1512  VariableArrayTypes.push_back(New);
1513  Types.push_back(New);
1514  return QualType(New, 0);
1515}
1516
1517/// getDependentSizedArrayType - Returns a non-unique reference to
1518/// the type for a dependently-sized array of the specified element
1519/// type.
1520QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1521                                                Expr *NumElts,
1522                                                ArrayType::ArraySizeModifier ASM,
1523                                                unsigned EltTypeQuals,
1524                                                SourceRange Brackets) {
1525  assert((!NumElts || NumElts->isTypeDependent() ||
1526          NumElts->isValueDependent()) &&
1527         "Size must be type- or value-dependent!");
1528
1529  void *InsertPos = 0;
1530  DependentSizedArrayType *Canon = 0;
1531  llvm::FoldingSetNodeID ID;
1532
1533  if (NumElts) {
1534    // Dependently-sized array types that do not have a specified
1535    // number of elements will have their sizes deduced from an
1536    // initializer.
1537    DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1538                                     EltTypeQuals, NumElts);
1539
1540    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1541  }
1542
1543  DependentSizedArrayType *New;
1544  if (Canon) {
1545    // We already have a canonical version of this array type; use it as
1546    // the canonical type for a newly-built type.
1547    New = new (*this, TypeAlignment)
1548      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1549                              NumElts, ASM, EltTypeQuals, Brackets);
1550  } else {
1551    QualType CanonEltTy = getCanonicalType(EltTy);
1552    if (CanonEltTy == EltTy) {
1553      New = new (*this, TypeAlignment)
1554        DependentSizedArrayType(*this, EltTy, QualType(),
1555                                NumElts, ASM, EltTypeQuals, Brackets);
1556
1557      if (NumElts) {
1558        DependentSizedArrayType *CanonCheck
1559          = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1560        assert(!CanonCheck && "Dependent-sized canonical array type broken");
1561        (void)CanonCheck;
1562        DependentSizedArrayTypes.InsertNode(New, InsertPos);
1563      }
1564    } else {
1565      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1566                                                  ASM, EltTypeQuals,
1567                                                  SourceRange());
1568      New = new (*this, TypeAlignment)
1569        DependentSizedArrayType(*this, EltTy, Canon,
1570                                NumElts, ASM, EltTypeQuals, Brackets);
1571    }
1572  }
1573
1574  Types.push_back(New);
1575  return QualType(New, 0);
1576}
1577
1578QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1579                                            ArrayType::ArraySizeModifier ASM,
1580                                            unsigned EltTypeQuals) {
1581  llvm::FoldingSetNodeID ID;
1582  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1583
1584  void *InsertPos = 0;
1585  if (IncompleteArrayType *ATP =
1586       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1587    return QualType(ATP, 0);
1588
1589  // If the element type isn't canonical, this won't be a canonical type
1590  // either, so fill in the canonical type field.
1591  QualType Canonical;
1592
1593  if (!EltTy.isCanonical()) {
1594    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1595                                       ASM, EltTypeQuals);
1596
1597    // Get the new insert position for the node we care about.
1598    IncompleteArrayType *NewIP =
1599      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1600    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1601  }
1602
1603  IncompleteArrayType *New = new (*this, TypeAlignment)
1604    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1605
1606  IncompleteArrayTypes.InsertNode(New, InsertPos);
1607  Types.push_back(New);
1608  return QualType(New, 0);
1609}
1610
1611/// getVectorType - Return the unique reference to a vector type of
1612/// the specified element type and size. VectorType must be a built-in type.
1613QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1614                                   bool IsAltiVec, bool IsPixel) {
1615  BuiltinType *baseType;
1616
1617  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1618  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1619
1620  // Check if we've already instantiated a vector of this type.
1621  llvm::FoldingSetNodeID ID;
1622  VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1623    IsAltiVec, IsPixel);
1624  void *InsertPos = 0;
1625  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1626    return QualType(VTP, 0);
1627
1628  // If the element type isn't canonical, this won't be a canonical type either,
1629  // so fill in the canonical type field.
1630  QualType Canonical;
1631  if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1632    Canonical = getVectorType(getCanonicalType(vecType),
1633      NumElts, false, false);
1634
1635    // Get the new insert position for the node we care about.
1636    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1637    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1638  }
1639  VectorType *New = new (*this, TypeAlignment)
1640    VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
1641  VectorTypes.InsertNode(New, InsertPos);
1642  Types.push_back(New);
1643  return QualType(New, 0);
1644}
1645
1646/// getExtVectorType - Return the unique reference to an extended vector type of
1647/// the specified element type and size. VectorType must be a built-in type.
1648QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1649  BuiltinType *baseType;
1650
1651  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1652  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1653
1654  // Check if we've already instantiated a vector of this type.
1655  llvm::FoldingSetNodeID ID;
1656  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
1657  void *InsertPos = 0;
1658  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1659    return QualType(VTP, 0);
1660
1661  // If the element type isn't canonical, this won't be a canonical type either,
1662  // so fill in the canonical type field.
1663  QualType Canonical;
1664  if (!vecType.isCanonical()) {
1665    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1666
1667    // Get the new insert position for the node we care about.
1668    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1669    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1670  }
1671  ExtVectorType *New = new (*this, TypeAlignment)
1672    ExtVectorType(vecType, NumElts, Canonical);
1673  VectorTypes.InsertNode(New, InsertPos);
1674  Types.push_back(New);
1675  return QualType(New, 0);
1676}
1677
1678QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1679                                                    Expr *SizeExpr,
1680                                                    SourceLocation AttrLoc) {
1681  llvm::FoldingSetNodeID ID;
1682  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1683                                       SizeExpr);
1684
1685  void *InsertPos = 0;
1686  DependentSizedExtVectorType *Canon
1687    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1688  DependentSizedExtVectorType *New;
1689  if (Canon) {
1690    // We already have a canonical version of this array type; use it as
1691    // the canonical type for a newly-built type.
1692    New = new (*this, TypeAlignment)
1693      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1694                                  SizeExpr, AttrLoc);
1695  } else {
1696    QualType CanonVecTy = getCanonicalType(vecType);
1697    if (CanonVecTy == vecType) {
1698      New = new (*this, TypeAlignment)
1699        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1700                                    AttrLoc);
1701
1702      DependentSizedExtVectorType *CanonCheck
1703        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1704      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1705      (void)CanonCheck;
1706      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1707    } else {
1708      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1709                                                      SourceLocation());
1710      New = new (*this, TypeAlignment)
1711        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1712    }
1713  }
1714
1715  Types.push_back(New);
1716  return QualType(New, 0);
1717}
1718
1719/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1720///
1721QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1722                                            CallingConv CallConv) {
1723  // Unique functions, to guarantee there is only one function of a particular
1724  // structure.
1725  llvm::FoldingSetNodeID ID;
1726  FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
1727
1728  void *InsertPos = 0;
1729  if (FunctionNoProtoType *FT =
1730        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1731    return QualType(FT, 0);
1732
1733  QualType Canonical;
1734  if (!ResultTy.isCanonical() ||
1735      getCanonicalCallConv(CallConv) != CallConv) {
1736    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
1737                                       getCanonicalCallConv(CallConv));
1738
1739    // Get the new insert position for the node we care about.
1740    FunctionNoProtoType *NewIP =
1741      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1742    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1743  }
1744
1745  FunctionNoProtoType *New = new (*this, TypeAlignment)
1746    FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
1747  Types.push_back(New);
1748  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1749  return QualType(New, 0);
1750}
1751
1752/// getFunctionType - Return a normal function type with a typed argument
1753/// list.  isVariadic indicates whether the argument list includes '...'.
1754QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1755                                     unsigned NumArgs, bool isVariadic,
1756                                     unsigned TypeQuals, bool hasExceptionSpec,
1757                                     bool hasAnyExceptionSpec, unsigned NumExs,
1758                                     const QualType *ExArray, bool NoReturn,
1759                                     CallingConv CallConv) {
1760  // Unique functions, to guarantee there is only one function of a particular
1761  // structure.
1762  llvm::FoldingSetNodeID ID;
1763  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1764                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1765                             NumExs, ExArray, NoReturn, CallConv);
1766
1767  void *InsertPos = 0;
1768  if (FunctionProtoType *FTP =
1769        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1770    return QualType(FTP, 0);
1771
1772  // Determine whether the type being created is already canonical or not.
1773  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1774  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1775    if (!ArgArray[i].isCanonicalAsParam())
1776      isCanonical = false;
1777
1778  // If this type isn't canonical, get the canonical version of it.
1779  // The exception spec is not part of the canonical type.
1780  QualType Canonical;
1781  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1782    llvm::SmallVector<QualType, 16> CanonicalArgs;
1783    CanonicalArgs.reserve(NumArgs);
1784    for (unsigned i = 0; i != NumArgs; ++i)
1785      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1786
1787    Canonical = getFunctionType(getCanonicalType(ResultTy),
1788                                CanonicalArgs.data(), NumArgs,
1789                                isVariadic, TypeQuals, false,
1790                                false, 0, 0, NoReturn,
1791                                getCanonicalCallConv(CallConv));
1792
1793    // Get the new insert position for the node we care about.
1794    FunctionProtoType *NewIP =
1795      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1796    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1797  }
1798
1799  // FunctionProtoType objects are allocated with extra bytes after them
1800  // for two variable size arrays (for parameter and exception types) at the
1801  // end of them.
1802  FunctionProtoType *FTP =
1803    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1804                                 NumArgs*sizeof(QualType) +
1805                                 NumExs*sizeof(QualType), TypeAlignment);
1806  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1807                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1808                              ExArray, NumExs, Canonical, NoReturn, CallConv);
1809  Types.push_back(FTP);
1810  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1811  return QualType(FTP, 0);
1812}
1813
1814/// getTypeDeclType - Return the unique reference to the type for the
1815/// specified type declaration.
1816QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1817  assert(Decl && "Passed null for Decl param");
1818  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1819
1820  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1821    return getTypedefType(Typedef);
1822  else if (isa<TemplateTypeParmDecl>(Decl)) {
1823    assert(false && "Template type parameter types are always available.");
1824  } else if (ObjCInterfaceDecl *ObjCInterface
1825               = dyn_cast<ObjCInterfaceDecl>(Decl))
1826    return getObjCInterfaceType(ObjCInterface);
1827
1828  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1829    if (PrevDecl)
1830      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1831    else
1832      Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1833  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1834    if (PrevDecl)
1835      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1836    else
1837      Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1838  } else if (UnresolvedUsingTypenameDecl *Using =
1839               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1840    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1841  } else
1842    assert(false && "TypeDecl without a type?");
1843
1844  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1845  return QualType(Decl->TypeForDecl, 0);
1846}
1847
1848/// getTypedefType - Return the unique reference to the type for the
1849/// specified typename decl.
1850QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1851  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1852
1853  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1854  Decl->TypeForDecl = new(*this, TypeAlignment)
1855    TypedefType(Type::Typedef, Decl, Canonical);
1856  Types.push_back(Decl->TypeForDecl);
1857  return QualType(Decl->TypeForDecl, 0);
1858}
1859
1860/// \brief Retrieve a substitution-result type.
1861QualType
1862ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1863                                         QualType Replacement) {
1864  assert(Replacement.isCanonical()
1865         && "replacement types must always be canonical");
1866
1867  llvm::FoldingSetNodeID ID;
1868  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1869  void *InsertPos = 0;
1870  SubstTemplateTypeParmType *SubstParm
1871    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1872
1873  if (!SubstParm) {
1874    SubstParm = new (*this, TypeAlignment)
1875      SubstTemplateTypeParmType(Parm, Replacement);
1876    Types.push_back(SubstParm);
1877    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1878  }
1879
1880  return QualType(SubstParm, 0);
1881}
1882
1883/// \brief Retrieve the template type parameter type for a template
1884/// parameter or parameter pack with the given depth, index, and (optionally)
1885/// name.
1886QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1887                                             bool ParameterPack,
1888                                             IdentifierInfo *Name) {
1889  llvm::FoldingSetNodeID ID;
1890  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1891  void *InsertPos = 0;
1892  TemplateTypeParmType *TypeParm
1893    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1894
1895  if (TypeParm)
1896    return QualType(TypeParm, 0);
1897
1898  if (Name) {
1899    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1900    TypeParm = new (*this, TypeAlignment)
1901      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1902
1903    TemplateTypeParmType *TypeCheck
1904      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1905    assert(!TypeCheck && "Template type parameter canonical type broken");
1906    (void)TypeCheck;
1907  } else
1908    TypeParm = new (*this, TypeAlignment)
1909      TemplateTypeParmType(Depth, Index, ParameterPack);
1910
1911  Types.push_back(TypeParm);
1912  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1913
1914  return QualType(TypeParm, 0);
1915}
1916
1917QualType
1918ASTContext::getTemplateSpecializationType(TemplateName Template,
1919                                          const TemplateArgumentListInfo &Args,
1920                                          QualType Canon) {
1921  unsigned NumArgs = Args.size();
1922
1923  llvm::SmallVector<TemplateArgument, 4> ArgVec;
1924  ArgVec.reserve(NumArgs);
1925  for (unsigned i = 0; i != NumArgs; ++i)
1926    ArgVec.push_back(Args[i].getArgument());
1927
1928  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1929}
1930
1931QualType
1932ASTContext::getTemplateSpecializationType(TemplateName Template,
1933                                          const TemplateArgument *Args,
1934                                          unsigned NumArgs,
1935                                          QualType Canon) {
1936  if (!Canon.isNull())
1937    Canon = getCanonicalType(Canon);
1938  else {
1939    // Build the canonical template specialization type.
1940    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1941    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1942    CanonArgs.reserve(NumArgs);
1943    for (unsigned I = 0; I != NumArgs; ++I)
1944      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1945
1946    // Determine whether this canonical template specialization type already
1947    // exists.
1948    llvm::FoldingSetNodeID ID;
1949    TemplateSpecializationType::Profile(ID, CanonTemplate,
1950                                        CanonArgs.data(), NumArgs, *this);
1951
1952    void *InsertPos = 0;
1953    TemplateSpecializationType *Spec
1954      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1955
1956    if (!Spec) {
1957      // Allocate a new canonical template specialization type.
1958      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1959                            sizeof(TemplateArgument) * NumArgs),
1960                           TypeAlignment);
1961      Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
1962                                                  CanonArgs.data(), NumArgs,
1963                                                  Canon);
1964      Types.push_back(Spec);
1965      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1966    }
1967
1968    if (Canon.isNull())
1969      Canon = QualType(Spec, 0);
1970    assert(Canon->isDependentType() &&
1971           "Non-dependent template-id type must have a canonical type");
1972  }
1973
1974  // Allocate the (non-canonical) template specialization type, but don't
1975  // try to unique it: these types typically have location information that
1976  // we don't unique and don't want to lose.
1977  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1978                        sizeof(TemplateArgument) * NumArgs),
1979                       TypeAlignment);
1980  TemplateSpecializationType *Spec
1981    = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1982                                           Canon);
1983
1984  Types.push_back(Spec);
1985  return QualType(Spec, 0);
1986}
1987
1988QualType
1989ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1990                                 QualType NamedType) {
1991  llvm::FoldingSetNodeID ID;
1992  QualifiedNameType::Profile(ID, NNS, NamedType);
1993
1994  void *InsertPos = 0;
1995  QualifiedNameType *T
1996    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1997  if (T)
1998    return QualType(T, 0);
1999
2000  QualType Canon = NamedType;
2001  if (!Canon.isCanonical()) {
2002    Canon = getCanonicalType(NamedType);
2003    QualifiedNameType *CheckT
2004      = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2005    assert(!CheckT && "Qualified name canonical type broken");
2006    (void)CheckT;
2007  }
2008
2009  T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
2010  Types.push_back(T);
2011  QualifiedNameTypes.InsertNode(T, InsertPos);
2012  return QualType(T, 0);
2013}
2014
2015QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
2016                                     const IdentifierInfo *Name,
2017                                     QualType Canon) {
2018  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2019
2020  if (Canon.isNull()) {
2021    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2022    if (CanonNNS != NNS)
2023      Canon = getTypenameType(CanonNNS, Name);
2024  }
2025
2026  llvm::FoldingSetNodeID ID;
2027  TypenameType::Profile(ID, NNS, Name);
2028
2029  void *InsertPos = 0;
2030  TypenameType *T
2031    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2032  if (T)
2033    return QualType(T, 0);
2034
2035  T = new (*this) TypenameType(NNS, Name, Canon);
2036  Types.push_back(T);
2037  TypenameTypes.InsertNode(T, InsertPos);
2038  return QualType(T, 0);
2039}
2040
2041QualType
2042ASTContext::getTypenameType(NestedNameSpecifier *NNS,
2043                            const TemplateSpecializationType *TemplateId,
2044                            QualType Canon) {
2045  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2046
2047  llvm::FoldingSetNodeID ID;
2048  TypenameType::Profile(ID, NNS, TemplateId);
2049
2050  void *InsertPos = 0;
2051  TypenameType *T
2052    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2053  if (T)
2054    return QualType(T, 0);
2055
2056  if (Canon.isNull()) {
2057    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2058    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2059    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2060      const TemplateSpecializationType *CanonTemplateId
2061        = CanonType->getAs<TemplateSpecializationType>();
2062      assert(CanonTemplateId &&
2063             "Canonical type must also be a template specialization type");
2064      Canon = getTypenameType(CanonNNS, CanonTemplateId);
2065    }
2066
2067    TypenameType *CheckT
2068      = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2069    assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
2070  }
2071
2072  T = new (*this) TypenameType(NNS, TemplateId, Canon);
2073  Types.push_back(T);
2074  TypenameTypes.InsertNode(T, InsertPos);
2075  return QualType(T, 0);
2076}
2077
2078QualType
2079ASTContext::getElaboratedType(QualType UnderlyingType,
2080                              ElaboratedType::TagKind Tag) {
2081  llvm::FoldingSetNodeID ID;
2082  ElaboratedType::Profile(ID, UnderlyingType, Tag);
2083
2084  void *InsertPos = 0;
2085  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2086  if (T)
2087    return QualType(T, 0);
2088
2089  QualType Canon = UnderlyingType;
2090  if (!Canon.isCanonical()) {
2091    Canon = getCanonicalType(Canon);
2092    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2093    assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2094  }
2095
2096  T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2097  Types.push_back(T);
2098  ElaboratedTypes.InsertNode(T, InsertPos);
2099  return QualType(T, 0);
2100}
2101
2102/// CmpProtocolNames - Comparison predicate for sorting protocols
2103/// alphabetically.
2104static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2105                            const ObjCProtocolDecl *RHS) {
2106  return LHS->getDeclName() < RHS->getDeclName();
2107}
2108
2109static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2110                                unsigned NumProtocols) {
2111  if (NumProtocols == 0) return true;
2112
2113  for (unsigned i = 1; i != NumProtocols; ++i)
2114    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2115      return false;
2116  return true;
2117}
2118
2119static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2120                                   unsigned &NumProtocols) {
2121  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2122
2123  // Sort protocols, keyed by name.
2124  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2125
2126  // Remove duplicates.
2127  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2128  NumProtocols = ProtocolsEnd-Protocols;
2129}
2130
2131/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2132/// the given interface decl and the conforming protocol list.
2133QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
2134                                              ObjCProtocolDecl **Protocols,
2135                                              unsigned NumProtocols) {
2136  llvm::FoldingSetNodeID ID;
2137  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
2138
2139  void *InsertPos = 0;
2140  if (ObjCObjectPointerType *QT =
2141              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2142    return QualType(QT, 0);
2143
2144  // Sort the protocol list alphabetically to canonicalize it.
2145  QualType Canonical;
2146  if (!InterfaceT.isCanonical() ||
2147      !areSortedAndUniqued(Protocols, NumProtocols)) {
2148    if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2149      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2150      unsigned UniqueCount = NumProtocols;
2151
2152      std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2153      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2154
2155      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2156                                           &Sorted[0], UniqueCount);
2157    } else {
2158      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2159                                           Protocols, NumProtocols);
2160    }
2161
2162    // Regenerate InsertPos.
2163    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2164  }
2165
2166  // No match.
2167  unsigned Size = sizeof(ObjCObjectPointerType)
2168                + NumProtocols * sizeof(ObjCProtocolDecl *);
2169  void *Mem = Allocate(Size, TypeAlignment);
2170  ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2171                                                                 InterfaceT,
2172                                                                 Protocols,
2173                                                                 NumProtocols);
2174
2175  Types.push_back(QType);
2176  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2177  return QualType(QType, 0);
2178}
2179
2180/// getObjCInterfaceType - Return the unique reference to the type for the
2181/// specified ObjC interface decl. The list of protocols is optional.
2182QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2183                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
2184  llvm::FoldingSetNodeID ID;
2185  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
2186
2187  void *InsertPos = 0;
2188  if (ObjCInterfaceType *QT =
2189      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
2190    return QualType(QT, 0);
2191
2192  // Sort the protocol list alphabetically to canonicalize it.
2193  QualType Canonical;
2194  if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2195    llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2196    std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2197
2198    unsigned UniqueCount = NumProtocols;
2199    SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2200
2201    Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2202
2203    ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2204  }
2205
2206  unsigned Size = sizeof(ObjCInterfaceType)
2207    + NumProtocols * sizeof(ObjCProtocolDecl *);
2208  void *Mem = Allocate(Size, TypeAlignment);
2209  ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2210                                        const_cast<ObjCInterfaceDecl*>(Decl),
2211                                                         Protocols,
2212                                                         NumProtocols);
2213
2214  Types.push_back(QType);
2215  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
2216  return QualType(QType, 0);
2217}
2218
2219/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2220/// TypeOfExprType AST's (since expression's are never shared). For example,
2221/// multiple declarations that refer to "typeof(x)" all contain different
2222/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2223/// on canonical type's (which are always unique).
2224QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2225  TypeOfExprType *toe;
2226  if (tofExpr->isTypeDependent()) {
2227    llvm::FoldingSetNodeID ID;
2228    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2229
2230    void *InsertPos = 0;
2231    DependentTypeOfExprType *Canon
2232      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2233    if (Canon) {
2234      // We already have a "canonical" version of an identical, dependent
2235      // typeof(expr) type. Use that as our canonical type.
2236      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2237                                          QualType((TypeOfExprType*)Canon, 0));
2238    }
2239    else {
2240      // Build a new, canonical typeof(expr) type.
2241      Canon
2242        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2243      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2244      toe = Canon;
2245    }
2246  } else {
2247    QualType Canonical = getCanonicalType(tofExpr->getType());
2248    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2249  }
2250  Types.push_back(toe);
2251  return QualType(toe, 0);
2252}
2253
2254/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2255/// TypeOfType AST's. The only motivation to unique these nodes would be
2256/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2257/// an issue. This doesn't effect the type checker, since it operates
2258/// on canonical type's (which are always unique).
2259QualType ASTContext::getTypeOfType(QualType tofType) {
2260  QualType Canonical = getCanonicalType(tofType);
2261  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2262  Types.push_back(tot);
2263  return QualType(tot, 0);
2264}
2265
2266/// getDecltypeForExpr - Given an expr, will return the decltype for that
2267/// expression, according to the rules in C++0x [dcl.type.simple]p4
2268static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2269  if (e->isTypeDependent())
2270    return Context.DependentTy;
2271
2272  // If e is an id expression or a class member access, decltype(e) is defined
2273  // as the type of the entity named by e.
2274  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2275    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2276      return VD->getType();
2277  }
2278  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2279    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2280      return FD->getType();
2281  }
2282  // If e is a function call or an invocation of an overloaded operator,
2283  // (parentheses around e are ignored), decltype(e) is defined as the
2284  // return type of that function.
2285  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2286    return CE->getCallReturnType();
2287
2288  QualType T = e->getType();
2289
2290  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2291  // defined as T&, otherwise decltype(e) is defined as T.
2292  if (e->isLvalue(Context) == Expr::LV_Valid)
2293    T = Context.getLValueReferenceType(T);
2294
2295  return T;
2296}
2297
2298/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2299/// DecltypeType AST's. The only motivation to unique these nodes would be
2300/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2301/// an issue. This doesn't effect the type checker, since it operates
2302/// on canonical type's (which are always unique).
2303QualType ASTContext::getDecltypeType(Expr *e) {
2304  DecltypeType *dt;
2305  if (e->isTypeDependent()) {
2306    llvm::FoldingSetNodeID ID;
2307    DependentDecltypeType::Profile(ID, *this, e);
2308
2309    void *InsertPos = 0;
2310    DependentDecltypeType *Canon
2311      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2312    if (Canon) {
2313      // We already have a "canonical" version of an equivalent, dependent
2314      // decltype type. Use that as our canonical type.
2315      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2316                                       QualType((DecltypeType*)Canon, 0));
2317    }
2318    else {
2319      // Build a new, canonical typeof(expr) type.
2320      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2321      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2322      dt = Canon;
2323    }
2324  } else {
2325    QualType T = getDecltypeForExpr(e, *this);
2326    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2327  }
2328  Types.push_back(dt);
2329  return QualType(dt, 0);
2330}
2331
2332/// getTagDeclType - Return the unique reference to the type for the
2333/// specified TagDecl (struct/union/class/enum) decl.
2334QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2335  assert (Decl);
2336  // FIXME: What is the design on getTagDeclType when it requires casting
2337  // away const?  mutable?
2338  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2339}
2340
2341/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2342/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2343/// needs to agree with the definition in <stddef.h>.
2344CanQualType ASTContext::getSizeType() const {
2345  return getFromTargetType(Target.getSizeType());
2346}
2347
2348/// getSignedWCharType - Return the type of "signed wchar_t".
2349/// Used when in C++, as a GCC extension.
2350QualType ASTContext::getSignedWCharType() const {
2351  // FIXME: derive from "Target" ?
2352  return WCharTy;
2353}
2354
2355/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2356/// Used when in C++, as a GCC extension.
2357QualType ASTContext::getUnsignedWCharType() const {
2358  // FIXME: derive from "Target" ?
2359  return UnsignedIntTy;
2360}
2361
2362/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2363/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2364QualType ASTContext::getPointerDiffType() const {
2365  return getFromTargetType(Target.getPtrDiffType(0));
2366}
2367
2368//===----------------------------------------------------------------------===//
2369//                              Type Operators
2370//===----------------------------------------------------------------------===//
2371
2372CanQualType ASTContext::getCanonicalParamType(QualType T) {
2373  // Push qualifiers into arrays, and then discard any remaining
2374  // qualifiers.
2375  T = getCanonicalType(T);
2376  const Type *Ty = T.getTypePtr();
2377
2378  QualType Result;
2379  if (isa<ArrayType>(Ty)) {
2380    Result = getArrayDecayedType(QualType(Ty,0));
2381  } else if (isa<FunctionType>(Ty)) {
2382    Result = getPointerType(QualType(Ty, 0));
2383  } else {
2384    Result = QualType(Ty, 0);
2385  }
2386
2387  return CanQualType::CreateUnsafe(Result);
2388}
2389
2390/// getCanonicalType - Return the canonical (structural) type corresponding to
2391/// the specified potentially non-canonical type.  The non-canonical version
2392/// of a type may have many "decorated" versions of types.  Decorators can
2393/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2394/// to be free of any of these, allowing two canonical types to be compared
2395/// for exact equality with a simple pointer comparison.
2396CanQualType ASTContext::getCanonicalType(QualType T) {
2397  QualifierCollector Quals;
2398  const Type *Ptr = Quals.strip(T);
2399  QualType CanType = Ptr->getCanonicalTypeInternal();
2400
2401  // The canonical internal type will be the canonical type *except*
2402  // that we push type qualifiers down through array types.
2403
2404  // If there are no new qualifiers to push down, stop here.
2405  if (!Quals.hasQualifiers())
2406    return CanQualType::CreateUnsafe(CanType);
2407
2408  // If the type qualifiers are on an array type, get the canonical
2409  // type of the array with the qualifiers applied to the element
2410  // type.
2411  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2412  if (!AT)
2413    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2414
2415  // Get the canonical version of the element with the extra qualifiers on it.
2416  // This can recursively sink qualifiers through multiple levels of arrays.
2417  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2418  NewEltTy = getCanonicalType(NewEltTy);
2419
2420  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2421    return CanQualType::CreateUnsafe(
2422             getConstantArrayType(NewEltTy, CAT->getSize(),
2423                                  CAT->getSizeModifier(),
2424                                  CAT->getIndexTypeCVRQualifiers()));
2425  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2426    return CanQualType::CreateUnsafe(
2427             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2428                                    IAT->getIndexTypeCVRQualifiers()));
2429
2430  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2431    return CanQualType::CreateUnsafe(
2432             getDependentSizedArrayType(NewEltTy,
2433                                        DSAT->getSizeExpr() ?
2434                                          DSAT->getSizeExpr()->Retain() : 0,
2435                                        DSAT->getSizeModifier(),
2436                                        DSAT->getIndexTypeCVRQualifiers(),
2437                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2438
2439  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2440  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2441                                                        VAT->getSizeExpr() ?
2442                                              VAT->getSizeExpr()->Retain() : 0,
2443                                                        VAT->getSizeModifier(),
2444                                              VAT->getIndexTypeCVRQualifiers(),
2445                                                     VAT->getBracketsRange()));
2446}
2447
2448QualType ASTContext::getUnqualifiedArrayType(QualType T,
2449                                             Qualifiers &Quals) {
2450  Quals = T.getQualifiers();
2451  if (!isa<ArrayType>(T)) {
2452    return T.getUnqualifiedType();
2453  }
2454
2455  const ArrayType *AT = cast<ArrayType>(T);
2456  QualType Elt = AT->getElementType();
2457  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2458  if (Elt == UnqualElt)
2459    return T;
2460
2461  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2462    return getConstantArrayType(UnqualElt, CAT->getSize(),
2463                                CAT->getSizeModifier(), 0);
2464  }
2465
2466  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2467    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2468  }
2469
2470  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2471  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2472                                    DSAT->getSizeModifier(), 0,
2473                                    SourceRange());
2474}
2475
2476DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2477  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2478    return TD->getDeclName();
2479
2480  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2481    if (DTN->isIdentifier()) {
2482      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2483    } else {
2484      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2485    }
2486  }
2487
2488  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2489  assert(Storage);
2490  return (*Storage->begin())->getDeclName();
2491}
2492
2493TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2494  // If this template name refers to a template, the canonical
2495  // template name merely stores the template itself.
2496  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2497    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2498
2499  assert(!Name.getAsOverloadedTemplate());
2500
2501  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2502  assert(DTN && "Non-dependent template names must refer to template decls.");
2503  return DTN->CanonicalTemplateName;
2504}
2505
2506bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2507  X = getCanonicalTemplateName(X);
2508  Y = getCanonicalTemplateName(Y);
2509  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2510}
2511
2512TemplateArgument
2513ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2514  switch (Arg.getKind()) {
2515    case TemplateArgument::Null:
2516      return Arg;
2517
2518    case TemplateArgument::Expression:
2519      return Arg;
2520
2521    case TemplateArgument::Declaration:
2522      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2523
2524    case TemplateArgument::Template:
2525      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2526
2527    case TemplateArgument::Integral:
2528      return TemplateArgument(*Arg.getAsIntegral(),
2529                              getCanonicalType(Arg.getIntegralType()));
2530
2531    case TemplateArgument::Type:
2532      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2533
2534    case TemplateArgument::Pack: {
2535      // FIXME: Allocate in ASTContext
2536      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2537      unsigned Idx = 0;
2538      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2539                                        AEnd = Arg.pack_end();
2540           A != AEnd; (void)++A, ++Idx)
2541        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2542
2543      TemplateArgument Result;
2544      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2545      return Result;
2546    }
2547  }
2548
2549  // Silence GCC warning
2550  assert(false && "Unhandled template argument kind");
2551  return TemplateArgument();
2552}
2553
2554NestedNameSpecifier *
2555ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2556  if (!NNS)
2557    return 0;
2558
2559  switch (NNS->getKind()) {
2560  case NestedNameSpecifier::Identifier:
2561    // Canonicalize the prefix but keep the identifier the same.
2562    return NestedNameSpecifier::Create(*this,
2563                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2564                                       NNS->getAsIdentifier());
2565
2566  case NestedNameSpecifier::Namespace:
2567    // A namespace is canonical; build a nested-name-specifier with
2568    // this namespace and no prefix.
2569    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2570
2571  case NestedNameSpecifier::TypeSpec:
2572  case NestedNameSpecifier::TypeSpecWithTemplate: {
2573    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2574    return NestedNameSpecifier::Create(*this, 0,
2575                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2576                                       T.getTypePtr());
2577  }
2578
2579  case NestedNameSpecifier::Global:
2580    // The global specifier is canonical and unique.
2581    return NNS;
2582  }
2583
2584  // Required to silence a GCC warning
2585  return 0;
2586}
2587
2588
2589const ArrayType *ASTContext::getAsArrayType(QualType T) {
2590  // Handle the non-qualified case efficiently.
2591  if (!T.hasLocalQualifiers()) {
2592    // Handle the common positive case fast.
2593    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2594      return AT;
2595  }
2596
2597  // Handle the common negative case fast.
2598  QualType CType = T->getCanonicalTypeInternal();
2599  if (!isa<ArrayType>(CType))
2600    return 0;
2601
2602  // Apply any qualifiers from the array type to the element type.  This
2603  // implements C99 6.7.3p8: "If the specification of an array type includes
2604  // any type qualifiers, the element type is so qualified, not the array type."
2605
2606  // If we get here, we either have type qualifiers on the type, or we have
2607  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2608  // we must propagate them down into the element type.
2609
2610  QualifierCollector Qs;
2611  const Type *Ty = Qs.strip(T.getDesugaredType());
2612
2613  // If we have a simple case, just return now.
2614  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2615  if (ATy == 0 || Qs.empty())
2616    return ATy;
2617
2618  // Otherwise, we have an array and we have qualifiers on it.  Push the
2619  // qualifiers into the array element type and return a new array type.
2620  // Get the canonical version of the element with the extra qualifiers on it.
2621  // This can recursively sink qualifiers through multiple levels of arrays.
2622  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2623
2624  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2625    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2626                                                CAT->getSizeModifier(),
2627                                           CAT->getIndexTypeCVRQualifiers()));
2628  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2629    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2630                                                  IAT->getSizeModifier(),
2631                                           IAT->getIndexTypeCVRQualifiers()));
2632
2633  if (const DependentSizedArrayType *DSAT
2634        = dyn_cast<DependentSizedArrayType>(ATy))
2635    return cast<ArrayType>(
2636                     getDependentSizedArrayType(NewEltTy,
2637                                                DSAT->getSizeExpr() ?
2638                                              DSAT->getSizeExpr()->Retain() : 0,
2639                                                DSAT->getSizeModifier(),
2640                                              DSAT->getIndexTypeCVRQualifiers(),
2641                                                DSAT->getBracketsRange()));
2642
2643  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2644  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2645                                              VAT->getSizeExpr() ?
2646                                              VAT->getSizeExpr()->Retain() : 0,
2647                                              VAT->getSizeModifier(),
2648                                              VAT->getIndexTypeCVRQualifiers(),
2649                                              VAT->getBracketsRange()));
2650}
2651
2652
2653/// getArrayDecayedType - Return the properly qualified result of decaying the
2654/// specified array type to a pointer.  This operation is non-trivial when
2655/// handling typedefs etc.  The canonical type of "T" must be an array type,
2656/// this returns a pointer to a properly qualified element of the array.
2657///
2658/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2659QualType ASTContext::getArrayDecayedType(QualType Ty) {
2660  // Get the element type with 'getAsArrayType' so that we don't lose any
2661  // typedefs in the element type of the array.  This also handles propagation
2662  // of type qualifiers from the array type into the element type if present
2663  // (C99 6.7.3p8).
2664  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2665  assert(PrettyArrayType && "Not an array type!");
2666
2667  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2668
2669  // int x[restrict 4] ->  int *restrict
2670  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2671}
2672
2673QualType ASTContext::getBaseElementType(QualType QT) {
2674  QualifierCollector Qs;
2675  while (true) {
2676    const Type *UT = Qs.strip(QT);
2677    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2678      QT = AT->getElementType();
2679    } else {
2680      return Qs.apply(QT);
2681    }
2682  }
2683}
2684
2685QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2686  QualType ElemTy = AT->getElementType();
2687
2688  if (const ArrayType *AT = getAsArrayType(ElemTy))
2689    return getBaseElementType(AT);
2690
2691  return ElemTy;
2692}
2693
2694/// getConstantArrayElementCount - Returns number of constant array elements.
2695uint64_t
2696ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2697  uint64_t ElementCount = 1;
2698  do {
2699    ElementCount *= CA->getSize().getZExtValue();
2700    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2701  } while (CA);
2702  return ElementCount;
2703}
2704
2705/// getFloatingRank - Return a relative rank for floating point types.
2706/// This routine will assert if passed a built-in type that isn't a float.
2707static FloatingRank getFloatingRank(QualType T) {
2708  if (const ComplexType *CT = T->getAs<ComplexType>())
2709    return getFloatingRank(CT->getElementType());
2710
2711  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2712  switch (T->getAs<BuiltinType>()->getKind()) {
2713  default: assert(0 && "getFloatingRank(): not a floating type");
2714  case BuiltinType::Float:      return FloatRank;
2715  case BuiltinType::Double:     return DoubleRank;
2716  case BuiltinType::LongDouble: return LongDoubleRank;
2717  }
2718}
2719
2720/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2721/// point or a complex type (based on typeDomain/typeSize).
2722/// 'typeDomain' is a real floating point or complex type.
2723/// 'typeSize' is a real floating point or complex type.
2724QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2725                                                       QualType Domain) const {
2726  FloatingRank EltRank = getFloatingRank(Size);
2727  if (Domain->isComplexType()) {
2728    switch (EltRank) {
2729    default: assert(0 && "getFloatingRank(): illegal value for rank");
2730    case FloatRank:      return FloatComplexTy;
2731    case DoubleRank:     return DoubleComplexTy;
2732    case LongDoubleRank: return LongDoubleComplexTy;
2733    }
2734  }
2735
2736  assert(Domain->isRealFloatingType() && "Unknown domain!");
2737  switch (EltRank) {
2738  default: assert(0 && "getFloatingRank(): illegal value for rank");
2739  case FloatRank:      return FloatTy;
2740  case DoubleRank:     return DoubleTy;
2741  case LongDoubleRank: return LongDoubleTy;
2742  }
2743}
2744
2745/// getFloatingTypeOrder - Compare the rank of the two specified floating
2746/// point types, ignoring the domain of the type (i.e. 'double' ==
2747/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2748/// LHS < RHS, return -1.
2749int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2750  FloatingRank LHSR = getFloatingRank(LHS);
2751  FloatingRank RHSR = getFloatingRank(RHS);
2752
2753  if (LHSR == RHSR)
2754    return 0;
2755  if (LHSR > RHSR)
2756    return 1;
2757  return -1;
2758}
2759
2760/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2761/// routine will assert if passed a built-in type that isn't an integer or enum,
2762/// or if it is not canonicalized.
2763unsigned ASTContext::getIntegerRank(Type *T) {
2764  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2765  if (EnumType* ET = dyn_cast<EnumType>(T))
2766    T = ET->getDecl()->getPromotionType().getTypePtr();
2767
2768  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2769    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2770
2771  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2772    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2773
2774  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2775    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2776
2777  switch (cast<BuiltinType>(T)->getKind()) {
2778  default: assert(0 && "getIntegerRank(): not a built-in integer");
2779  case BuiltinType::Bool:
2780    return 1 + (getIntWidth(BoolTy) << 3);
2781  case BuiltinType::Char_S:
2782  case BuiltinType::Char_U:
2783  case BuiltinType::SChar:
2784  case BuiltinType::UChar:
2785    return 2 + (getIntWidth(CharTy) << 3);
2786  case BuiltinType::Short:
2787  case BuiltinType::UShort:
2788    return 3 + (getIntWidth(ShortTy) << 3);
2789  case BuiltinType::Int:
2790  case BuiltinType::UInt:
2791    return 4 + (getIntWidth(IntTy) << 3);
2792  case BuiltinType::Long:
2793  case BuiltinType::ULong:
2794    return 5 + (getIntWidth(LongTy) << 3);
2795  case BuiltinType::LongLong:
2796  case BuiltinType::ULongLong:
2797    return 6 + (getIntWidth(LongLongTy) << 3);
2798  case BuiltinType::Int128:
2799  case BuiltinType::UInt128:
2800    return 7 + (getIntWidth(Int128Ty) << 3);
2801  }
2802}
2803
2804/// \brief Whether this is a promotable bitfield reference according
2805/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2806///
2807/// \returns the type this bit-field will promote to, or NULL if no
2808/// promotion occurs.
2809QualType ASTContext::isPromotableBitField(Expr *E) {
2810  FieldDecl *Field = E->getBitField();
2811  if (!Field)
2812    return QualType();
2813
2814  QualType FT = Field->getType();
2815
2816  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2817  uint64_t BitWidth = BitWidthAP.getZExtValue();
2818  uint64_t IntSize = getTypeSize(IntTy);
2819  // GCC extension compatibility: if the bit-field size is less than or equal
2820  // to the size of int, it gets promoted no matter what its type is.
2821  // For instance, unsigned long bf : 4 gets promoted to signed int.
2822  if (BitWidth < IntSize)
2823    return IntTy;
2824
2825  if (BitWidth == IntSize)
2826    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2827
2828  // Types bigger than int are not subject to promotions, and therefore act
2829  // like the base type.
2830  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2831  // is ridiculous.
2832  return QualType();
2833}
2834
2835/// getPromotedIntegerType - Returns the type that Promotable will
2836/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2837/// integer type.
2838QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2839  assert(!Promotable.isNull());
2840  assert(Promotable->isPromotableIntegerType());
2841  if (const EnumType *ET = Promotable->getAs<EnumType>())
2842    return ET->getDecl()->getPromotionType();
2843  if (Promotable->isSignedIntegerType())
2844    return IntTy;
2845  uint64_t PromotableSize = getTypeSize(Promotable);
2846  uint64_t IntSize = getTypeSize(IntTy);
2847  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2848  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2849}
2850
2851/// getIntegerTypeOrder - Returns the highest ranked integer type:
2852/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2853/// LHS < RHS, return -1.
2854int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2855  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2856  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2857  if (LHSC == RHSC) return 0;
2858
2859  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2860  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2861
2862  unsigned LHSRank = getIntegerRank(LHSC);
2863  unsigned RHSRank = getIntegerRank(RHSC);
2864
2865  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2866    if (LHSRank == RHSRank) return 0;
2867    return LHSRank > RHSRank ? 1 : -1;
2868  }
2869
2870  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2871  if (LHSUnsigned) {
2872    // If the unsigned [LHS] type is larger, return it.
2873    if (LHSRank >= RHSRank)
2874      return 1;
2875
2876    // If the signed type can represent all values of the unsigned type, it
2877    // wins.  Because we are dealing with 2's complement and types that are
2878    // powers of two larger than each other, this is always safe.
2879    return -1;
2880  }
2881
2882  // If the unsigned [RHS] type is larger, return it.
2883  if (RHSRank >= LHSRank)
2884    return -1;
2885
2886  // If the signed type can represent all values of the unsigned type, it
2887  // wins.  Because we are dealing with 2's complement and types that are
2888  // powers of two larger than each other, this is always safe.
2889  return 1;
2890}
2891
2892static RecordDecl *
2893CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2894                 SourceLocation L, IdentifierInfo *Id) {
2895  if (Ctx.getLangOptions().CPlusPlus)
2896    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2897  else
2898    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2899}
2900
2901// getCFConstantStringType - Return the type used for constant CFStrings.
2902QualType ASTContext::getCFConstantStringType() {
2903  if (!CFConstantStringTypeDecl) {
2904    CFConstantStringTypeDecl =
2905      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2906                       &Idents.get("NSConstantString"));
2907    CFConstantStringTypeDecl->startDefinition();
2908
2909    QualType FieldTypes[4];
2910
2911    // const int *isa;
2912    FieldTypes[0] = getPointerType(IntTy.withConst());
2913    // int flags;
2914    FieldTypes[1] = IntTy;
2915    // const char *str;
2916    FieldTypes[2] = getPointerType(CharTy.withConst());
2917    // long length;
2918    FieldTypes[3] = LongTy;
2919
2920    // Create fields
2921    for (unsigned i = 0; i < 4; ++i) {
2922      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2923                                           SourceLocation(), 0,
2924                                           FieldTypes[i], /*TInfo=*/0,
2925                                           /*BitWidth=*/0,
2926                                           /*Mutable=*/false);
2927      CFConstantStringTypeDecl->addDecl(Field);
2928    }
2929
2930    CFConstantStringTypeDecl->completeDefinition(*this);
2931  }
2932
2933  return getTagDeclType(CFConstantStringTypeDecl);
2934}
2935
2936void ASTContext::setCFConstantStringType(QualType T) {
2937  const RecordType *Rec = T->getAs<RecordType>();
2938  assert(Rec && "Invalid CFConstantStringType");
2939  CFConstantStringTypeDecl = Rec->getDecl();
2940}
2941
2942QualType ASTContext::getObjCFastEnumerationStateType() {
2943  if (!ObjCFastEnumerationStateTypeDecl) {
2944    ObjCFastEnumerationStateTypeDecl =
2945      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2946                       &Idents.get("__objcFastEnumerationState"));
2947    ObjCFastEnumerationStateTypeDecl->startDefinition();
2948
2949    QualType FieldTypes[] = {
2950      UnsignedLongTy,
2951      getPointerType(ObjCIdTypedefType),
2952      getPointerType(UnsignedLongTy),
2953      getConstantArrayType(UnsignedLongTy,
2954                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2955    };
2956
2957    for (size_t i = 0; i < 4; ++i) {
2958      FieldDecl *Field = FieldDecl::Create(*this,
2959                                           ObjCFastEnumerationStateTypeDecl,
2960                                           SourceLocation(), 0,
2961                                           FieldTypes[i], /*TInfo=*/0,
2962                                           /*BitWidth=*/0,
2963                                           /*Mutable=*/false);
2964      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2965    }
2966
2967    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2968  }
2969
2970  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2971}
2972
2973QualType ASTContext::getBlockDescriptorType() {
2974  if (BlockDescriptorType)
2975    return getTagDeclType(BlockDescriptorType);
2976
2977  RecordDecl *T;
2978  // FIXME: Needs the FlagAppleBlock bit.
2979  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2980                       &Idents.get("__block_descriptor"));
2981  T->startDefinition();
2982
2983  QualType FieldTypes[] = {
2984    UnsignedLongTy,
2985    UnsignedLongTy,
2986  };
2987
2988  const char *FieldNames[] = {
2989    "reserved",
2990    "Size"
2991  };
2992
2993  for (size_t i = 0; i < 2; ++i) {
2994    FieldDecl *Field = FieldDecl::Create(*this,
2995                                         T,
2996                                         SourceLocation(),
2997                                         &Idents.get(FieldNames[i]),
2998                                         FieldTypes[i], /*TInfo=*/0,
2999                                         /*BitWidth=*/0,
3000                                         /*Mutable=*/false);
3001    T->addDecl(Field);
3002  }
3003
3004  T->completeDefinition(*this);
3005
3006  BlockDescriptorType = T;
3007
3008  return getTagDeclType(BlockDescriptorType);
3009}
3010
3011void ASTContext::setBlockDescriptorType(QualType T) {
3012  const RecordType *Rec = T->getAs<RecordType>();
3013  assert(Rec && "Invalid BlockDescriptorType");
3014  BlockDescriptorType = Rec->getDecl();
3015}
3016
3017QualType ASTContext::getBlockDescriptorExtendedType() {
3018  if (BlockDescriptorExtendedType)
3019    return getTagDeclType(BlockDescriptorExtendedType);
3020
3021  RecordDecl *T;
3022  // FIXME: Needs the FlagAppleBlock bit.
3023  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3024                       &Idents.get("__block_descriptor_withcopydispose"));
3025  T->startDefinition();
3026
3027  QualType FieldTypes[] = {
3028    UnsignedLongTy,
3029    UnsignedLongTy,
3030    getPointerType(VoidPtrTy),
3031    getPointerType(VoidPtrTy)
3032  };
3033
3034  const char *FieldNames[] = {
3035    "reserved",
3036    "Size",
3037    "CopyFuncPtr",
3038    "DestroyFuncPtr"
3039  };
3040
3041  for (size_t i = 0; i < 4; ++i) {
3042    FieldDecl *Field = FieldDecl::Create(*this,
3043                                         T,
3044                                         SourceLocation(),
3045                                         &Idents.get(FieldNames[i]),
3046                                         FieldTypes[i], /*TInfo=*/0,
3047                                         /*BitWidth=*/0,
3048                                         /*Mutable=*/false);
3049    T->addDecl(Field);
3050  }
3051
3052  T->completeDefinition(*this);
3053
3054  BlockDescriptorExtendedType = T;
3055
3056  return getTagDeclType(BlockDescriptorExtendedType);
3057}
3058
3059void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3060  const RecordType *Rec = T->getAs<RecordType>();
3061  assert(Rec && "Invalid BlockDescriptorType");
3062  BlockDescriptorExtendedType = Rec->getDecl();
3063}
3064
3065bool ASTContext::BlockRequiresCopying(QualType Ty) {
3066  if (Ty->isBlockPointerType())
3067    return true;
3068  if (isObjCNSObjectType(Ty))
3069    return true;
3070  if (Ty->isObjCObjectPointerType())
3071    return true;
3072  return false;
3073}
3074
3075QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3076  //  type = struct __Block_byref_1_X {
3077  //    void *__isa;
3078  //    struct __Block_byref_1_X *__forwarding;
3079  //    unsigned int __flags;
3080  //    unsigned int __size;
3081  //    void *__copy_helper;		// as needed
3082  //    void *__destroy_help		// as needed
3083  //    int X;
3084  //  } *
3085
3086  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3087
3088  // FIXME: Move up
3089  static unsigned int UniqueBlockByRefTypeID = 0;
3090  llvm::SmallString<36> Name;
3091  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3092                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3093  RecordDecl *T;
3094  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3095                       &Idents.get(Name.str()));
3096  T->startDefinition();
3097  QualType Int32Ty = IntTy;
3098  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3099  QualType FieldTypes[] = {
3100    getPointerType(VoidPtrTy),
3101    getPointerType(getTagDeclType(T)),
3102    Int32Ty,
3103    Int32Ty,
3104    getPointerType(VoidPtrTy),
3105    getPointerType(VoidPtrTy),
3106    Ty
3107  };
3108
3109  const char *FieldNames[] = {
3110    "__isa",
3111    "__forwarding",
3112    "__flags",
3113    "__size",
3114    "__copy_helper",
3115    "__destroy_helper",
3116    DeclName,
3117  };
3118
3119  for (size_t i = 0; i < 7; ++i) {
3120    if (!HasCopyAndDispose && i >=4 && i <= 5)
3121      continue;
3122    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3123                                         &Idents.get(FieldNames[i]),
3124                                         FieldTypes[i], /*TInfo=*/0,
3125                                         /*BitWidth=*/0, /*Mutable=*/false);
3126    T->addDecl(Field);
3127  }
3128
3129  T->completeDefinition(*this);
3130
3131  return getPointerType(getTagDeclType(T));
3132}
3133
3134
3135QualType ASTContext::getBlockParmType(
3136  bool BlockHasCopyDispose,
3137  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
3138  // FIXME: Move up
3139  static unsigned int UniqueBlockParmTypeID = 0;
3140  llvm::SmallString<36> Name;
3141  llvm::raw_svector_ostream(Name) << "__block_literal_"
3142                                  << ++UniqueBlockParmTypeID;
3143  RecordDecl *T;
3144  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3145                       &Idents.get(Name.str()));
3146  T->startDefinition();
3147  QualType FieldTypes[] = {
3148    getPointerType(VoidPtrTy),
3149    IntTy,
3150    IntTy,
3151    getPointerType(VoidPtrTy),
3152    (BlockHasCopyDispose ?
3153     getPointerType(getBlockDescriptorExtendedType()) :
3154     getPointerType(getBlockDescriptorType()))
3155  };
3156
3157  const char *FieldNames[] = {
3158    "__isa",
3159    "__flags",
3160    "__reserved",
3161    "__FuncPtr",
3162    "__descriptor"
3163  };
3164
3165  for (size_t i = 0; i < 5; ++i) {
3166    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3167                                         &Idents.get(FieldNames[i]),
3168                                         FieldTypes[i], /*TInfo=*/0,
3169                                         /*BitWidth=*/0, /*Mutable=*/false);
3170    T->addDecl(Field);
3171  }
3172
3173  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3174    const Expr *E = BlockDeclRefDecls[i];
3175    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3176    clang::IdentifierInfo *Name = 0;
3177    if (BDRE) {
3178      const ValueDecl *D = BDRE->getDecl();
3179      Name = &Idents.get(D->getName());
3180    }
3181    QualType FieldType = E->getType();
3182
3183    if (BDRE && BDRE->isByRef())
3184      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3185                                 FieldType);
3186
3187    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3188                                         Name, FieldType, /*TInfo=*/0,
3189                                         /*BitWidth=*/0, /*Mutable=*/false);
3190    T->addDecl(Field);
3191  }
3192
3193  T->completeDefinition(*this);
3194
3195  return getPointerType(getTagDeclType(T));
3196}
3197
3198void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3199  const RecordType *Rec = T->getAs<RecordType>();
3200  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3201  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3202}
3203
3204// This returns true if a type has been typedefed to BOOL:
3205// typedef <type> BOOL;
3206static bool isTypeTypedefedAsBOOL(QualType T) {
3207  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3208    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3209      return II->isStr("BOOL");
3210
3211  return false;
3212}
3213
3214/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3215/// purpose.
3216CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3217  CharUnits sz = getTypeSizeInChars(type);
3218
3219  // Make all integer and enum types at least as large as an int
3220  if (sz.isPositive() && type->isIntegralType())
3221    sz = std::max(sz, getTypeSizeInChars(IntTy));
3222  // Treat arrays as pointers, since that's how they're passed in.
3223  else if (type->isArrayType())
3224    sz = getTypeSizeInChars(VoidPtrTy);
3225  return sz;
3226}
3227
3228static inline
3229std::string charUnitsToString(const CharUnits &CU) {
3230  return llvm::itostr(CU.getQuantity());
3231}
3232
3233/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3234/// declaration.
3235void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3236                                             std::string& S) {
3237  const BlockDecl *Decl = Expr->getBlockDecl();
3238  QualType BlockTy =
3239      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3240  // Encode result type.
3241  getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3242  // Compute size of all parameters.
3243  // Start with computing size of a pointer in number of bytes.
3244  // FIXME: There might(should) be a better way of doing this computation!
3245  SourceLocation Loc;
3246  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3247  CharUnits ParmOffset = PtrSize;
3248  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3249       E = Decl->param_end(); PI != E; ++PI) {
3250    QualType PType = (*PI)->getType();
3251    CharUnits sz = getObjCEncodingTypeSize(PType);
3252    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3253    ParmOffset += sz;
3254  }
3255  // Size of the argument frame
3256  S += charUnitsToString(ParmOffset);
3257  // Block pointer and offset.
3258  S += "@?0";
3259  ParmOffset = PtrSize;
3260
3261  // Argument types.
3262  ParmOffset = PtrSize;
3263  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3264       Decl->param_end(); PI != E; ++PI) {
3265    ParmVarDecl *PVDecl = *PI;
3266    QualType PType = PVDecl->getOriginalType();
3267    if (const ArrayType *AT =
3268          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3269      // Use array's original type only if it has known number of
3270      // elements.
3271      if (!isa<ConstantArrayType>(AT))
3272        PType = PVDecl->getType();
3273    } else if (PType->isFunctionType())
3274      PType = PVDecl->getType();
3275    getObjCEncodingForType(PType, S);
3276    S += charUnitsToString(ParmOffset);
3277    ParmOffset += getObjCEncodingTypeSize(PType);
3278  }
3279}
3280
3281/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3282/// declaration.
3283void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3284                                              std::string& S) {
3285  // FIXME: This is not very efficient.
3286  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3287  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3288  // Encode result type.
3289  getObjCEncodingForType(Decl->getResultType(), S);
3290  // Compute size of all parameters.
3291  // Start with computing size of a pointer in number of bytes.
3292  // FIXME: There might(should) be a better way of doing this computation!
3293  SourceLocation Loc;
3294  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3295  // The first two arguments (self and _cmd) are pointers; account for
3296  // their size.
3297  CharUnits ParmOffset = 2 * PtrSize;
3298  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3299       E = Decl->param_end(); PI != E; ++PI) {
3300    QualType PType = (*PI)->getType();
3301    CharUnits sz = getObjCEncodingTypeSize(PType);
3302    assert (sz.isPositive() &&
3303        "getObjCEncodingForMethodDecl - Incomplete param type");
3304    ParmOffset += sz;
3305  }
3306  S += charUnitsToString(ParmOffset);
3307  S += "@0:";
3308  S += charUnitsToString(PtrSize);
3309
3310  // Argument types.
3311  ParmOffset = 2 * PtrSize;
3312  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3313       E = Decl->param_end(); PI != E; ++PI) {
3314    ParmVarDecl *PVDecl = *PI;
3315    QualType PType = PVDecl->getOriginalType();
3316    if (const ArrayType *AT =
3317          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3318      // Use array's original type only if it has known number of
3319      // elements.
3320      if (!isa<ConstantArrayType>(AT))
3321        PType = PVDecl->getType();
3322    } else if (PType->isFunctionType())
3323      PType = PVDecl->getType();
3324    // Process argument qualifiers for user supplied arguments; such as,
3325    // 'in', 'inout', etc.
3326    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3327    getObjCEncodingForType(PType, S);
3328    S += charUnitsToString(ParmOffset);
3329    ParmOffset += getObjCEncodingTypeSize(PType);
3330  }
3331}
3332
3333/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3334/// property declaration. If non-NULL, Container must be either an
3335/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3336/// NULL when getting encodings for protocol properties.
3337/// Property attributes are stored as a comma-delimited C string. The simple
3338/// attributes readonly and bycopy are encoded as single characters. The
3339/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3340/// encoded as single characters, followed by an identifier. Property types
3341/// are also encoded as a parametrized attribute. The characters used to encode
3342/// these attributes are defined by the following enumeration:
3343/// @code
3344/// enum PropertyAttributes {
3345/// kPropertyReadOnly = 'R',   // property is read-only.
3346/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3347/// kPropertyByref = '&',  // property is a reference to the value last assigned
3348/// kPropertyDynamic = 'D',    // property is dynamic
3349/// kPropertyGetter = 'G',     // followed by getter selector name
3350/// kPropertySetter = 'S',     // followed by setter selector name
3351/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3352/// kPropertyType = 't'              // followed by old-style type encoding.
3353/// kPropertyWeak = 'W'              // 'weak' property
3354/// kPropertyStrong = 'P'            // property GC'able
3355/// kPropertyNonAtomic = 'N'         // property non-atomic
3356/// };
3357/// @endcode
3358void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3359                                                const Decl *Container,
3360                                                std::string& S) {
3361  // Collect information from the property implementation decl(s).
3362  bool Dynamic = false;
3363  ObjCPropertyImplDecl *SynthesizePID = 0;
3364
3365  // FIXME: Duplicated code due to poor abstraction.
3366  if (Container) {
3367    if (const ObjCCategoryImplDecl *CID =
3368        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3369      for (ObjCCategoryImplDecl::propimpl_iterator
3370             i = CID->propimpl_begin(), e = CID->propimpl_end();
3371           i != e; ++i) {
3372        ObjCPropertyImplDecl *PID = *i;
3373        if (PID->getPropertyDecl() == PD) {
3374          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3375            Dynamic = true;
3376          } else {
3377            SynthesizePID = PID;
3378          }
3379        }
3380      }
3381    } else {
3382      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3383      for (ObjCCategoryImplDecl::propimpl_iterator
3384             i = OID->propimpl_begin(), e = OID->propimpl_end();
3385           i != e; ++i) {
3386        ObjCPropertyImplDecl *PID = *i;
3387        if (PID->getPropertyDecl() == PD) {
3388          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3389            Dynamic = true;
3390          } else {
3391            SynthesizePID = PID;
3392          }
3393        }
3394      }
3395    }
3396  }
3397
3398  // FIXME: This is not very efficient.
3399  S = "T";
3400
3401  // Encode result type.
3402  // GCC has some special rules regarding encoding of properties which
3403  // closely resembles encoding of ivars.
3404  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3405                             true /* outermost type */,
3406                             true /* encoding for property */);
3407
3408  if (PD->isReadOnly()) {
3409    S += ",R";
3410  } else {
3411    switch (PD->getSetterKind()) {
3412    case ObjCPropertyDecl::Assign: break;
3413    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3414    case ObjCPropertyDecl::Retain: S += ",&"; break;
3415    }
3416  }
3417
3418  // It really isn't clear at all what this means, since properties
3419  // are "dynamic by default".
3420  if (Dynamic)
3421    S += ",D";
3422
3423  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3424    S += ",N";
3425
3426  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3427    S += ",G";
3428    S += PD->getGetterName().getAsString();
3429  }
3430
3431  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3432    S += ",S";
3433    S += PD->getSetterName().getAsString();
3434  }
3435
3436  if (SynthesizePID) {
3437    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3438    S += ",V";
3439    S += OID->getNameAsString();
3440  }
3441
3442  // FIXME: OBJCGC: weak & strong
3443}
3444
3445/// getLegacyIntegralTypeEncoding -
3446/// Another legacy compatibility encoding: 32-bit longs are encoded as
3447/// 'l' or 'L' , but not always.  For typedefs, we need to use
3448/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3449///
3450void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3451  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3452    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3453      if (BT->getKind() == BuiltinType::ULong &&
3454          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3455        PointeeTy = UnsignedIntTy;
3456      else
3457        if (BT->getKind() == BuiltinType::Long &&
3458            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3459          PointeeTy = IntTy;
3460    }
3461  }
3462}
3463
3464void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3465                                        const FieldDecl *Field) {
3466  // We follow the behavior of gcc, expanding structures which are
3467  // directly pointed to, and expanding embedded structures. Note that
3468  // these rules are sufficient to prevent recursive encoding of the
3469  // same type.
3470  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3471                             true /* outermost type */);
3472}
3473
3474static void EncodeBitField(const ASTContext *Context, std::string& S,
3475                           const FieldDecl *FD) {
3476  const Expr *E = FD->getBitWidth();
3477  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3478  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3479  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3480  S += 'b';
3481  S += llvm::utostr(N);
3482}
3483
3484// FIXME: Use SmallString for accumulating string.
3485void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3486                                            bool ExpandPointedToStructures,
3487                                            bool ExpandStructures,
3488                                            const FieldDecl *FD,
3489                                            bool OutermostType,
3490                                            bool EncodingProperty) {
3491  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3492    if (FD && FD->isBitField())
3493      return EncodeBitField(this, S, FD);
3494    char encoding;
3495    switch (BT->getKind()) {
3496    default: assert(0 && "Unhandled builtin type kind");
3497    case BuiltinType::Void:       encoding = 'v'; break;
3498    case BuiltinType::Bool:       encoding = 'B'; break;
3499    case BuiltinType::Char_U:
3500    case BuiltinType::UChar:      encoding = 'C'; break;
3501    case BuiltinType::UShort:     encoding = 'S'; break;
3502    case BuiltinType::UInt:       encoding = 'I'; break;
3503    case BuiltinType::ULong:
3504        encoding =
3505          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3506        break;
3507    case BuiltinType::UInt128:    encoding = 'T'; break;
3508    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3509    case BuiltinType::Char_S:
3510    case BuiltinType::SChar:      encoding = 'c'; break;
3511    case BuiltinType::Short:      encoding = 's'; break;
3512    case BuiltinType::Int:        encoding = 'i'; break;
3513    case BuiltinType::Long:
3514      encoding =
3515        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3516      break;
3517    case BuiltinType::LongLong:   encoding = 'q'; break;
3518    case BuiltinType::Int128:     encoding = 't'; break;
3519    case BuiltinType::Float:      encoding = 'f'; break;
3520    case BuiltinType::Double:     encoding = 'd'; break;
3521    case BuiltinType::LongDouble: encoding = 'd'; break;
3522    }
3523
3524    S += encoding;
3525    return;
3526  }
3527
3528  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3529    S += 'j';
3530    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3531                               false);
3532    return;
3533  }
3534
3535  if (const PointerType *PT = T->getAs<PointerType>()) {
3536    if (PT->isObjCSelType()) {
3537      S += ':';
3538      return;
3539    }
3540    QualType PointeeTy = PT->getPointeeType();
3541
3542    bool isReadOnly = false;
3543    // For historical/compatibility reasons, the read-only qualifier of the
3544    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3545    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3546    // Also, do not emit the 'r' for anything but the outermost type!
3547    if (isa<TypedefType>(T.getTypePtr())) {
3548      if (OutermostType && T.isConstQualified()) {
3549        isReadOnly = true;
3550        S += 'r';
3551      }
3552    } else if (OutermostType) {
3553      QualType P = PointeeTy;
3554      while (P->getAs<PointerType>())
3555        P = P->getAs<PointerType>()->getPointeeType();
3556      if (P.isConstQualified()) {
3557        isReadOnly = true;
3558        S += 'r';
3559      }
3560    }
3561    if (isReadOnly) {
3562      // Another legacy compatibility encoding. Some ObjC qualifier and type
3563      // combinations need to be rearranged.
3564      // Rewrite "in const" from "nr" to "rn"
3565      const char * s = S.c_str();
3566      int len = S.length();
3567      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3568        std::string replace = "rn";
3569        S.replace(S.end()-2, S.end(), replace);
3570      }
3571    }
3572
3573    if (PointeeTy->isCharType()) {
3574      // char pointer types should be encoded as '*' unless it is a
3575      // type that has been typedef'd to 'BOOL'.
3576      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3577        S += '*';
3578        return;
3579      }
3580    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3581      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3582      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3583        S += '#';
3584        return;
3585      }
3586      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3587      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3588        S += '@';
3589        return;
3590      }
3591      // fall through...
3592    }
3593    S += '^';
3594    getLegacyIntegralTypeEncoding(PointeeTy);
3595
3596    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3597                               NULL);
3598    return;
3599  }
3600
3601  if (const ArrayType *AT =
3602      // Ignore type qualifiers etc.
3603        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3604    if (isa<IncompleteArrayType>(AT)) {
3605      // Incomplete arrays are encoded as a pointer to the array element.
3606      S += '^';
3607
3608      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3609                                 false, ExpandStructures, FD);
3610    } else {
3611      S += '[';
3612
3613      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3614        S += llvm::utostr(CAT->getSize().getZExtValue());
3615      else {
3616        //Variable length arrays are encoded as a regular array with 0 elements.
3617        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3618        S += '0';
3619      }
3620
3621      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3622                                 false, ExpandStructures, FD);
3623      S += ']';
3624    }
3625    return;
3626  }
3627
3628  if (T->getAs<FunctionType>()) {
3629    S += '?';
3630    return;
3631  }
3632
3633  if (const RecordType *RTy = T->getAs<RecordType>()) {
3634    RecordDecl *RDecl = RTy->getDecl();
3635    S += RDecl->isUnion() ? '(' : '{';
3636    // Anonymous structures print as '?'
3637    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3638      S += II->getName();
3639    } else {
3640      S += '?';
3641    }
3642    if (ExpandStructures) {
3643      S += '=';
3644      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3645                                   FieldEnd = RDecl->field_end();
3646           Field != FieldEnd; ++Field) {
3647        if (FD) {
3648          S += '"';
3649          S += Field->getNameAsString();
3650          S += '"';
3651        }
3652
3653        // Special case bit-fields.
3654        if (Field->isBitField()) {
3655          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3656                                     (*Field));
3657        } else {
3658          QualType qt = Field->getType();
3659          getLegacyIntegralTypeEncoding(qt);
3660          getObjCEncodingForTypeImpl(qt, S, false, true,
3661                                     FD);
3662        }
3663      }
3664    }
3665    S += RDecl->isUnion() ? ')' : '}';
3666    return;
3667  }
3668
3669  if (T->isEnumeralType()) {
3670    if (FD && FD->isBitField())
3671      EncodeBitField(this, S, FD);
3672    else
3673      S += 'i';
3674    return;
3675  }
3676
3677  if (T->isBlockPointerType()) {
3678    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3679    return;
3680  }
3681
3682  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3683    // @encode(class_name)
3684    ObjCInterfaceDecl *OI = OIT->getDecl();
3685    S += '{';
3686    const IdentifierInfo *II = OI->getIdentifier();
3687    S += II->getName();
3688    S += '=';
3689    llvm::SmallVector<FieldDecl*, 32> RecFields;
3690    CollectObjCIvars(OI, RecFields);
3691    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3692      if (RecFields[i]->isBitField())
3693        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3694                                   RecFields[i]);
3695      else
3696        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3697                                   FD);
3698    }
3699    S += '}';
3700    return;
3701  }
3702
3703  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3704    if (OPT->isObjCIdType()) {
3705      S += '@';
3706      return;
3707    }
3708
3709    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3710      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3711      // Since this is a binary compatibility issue, need to consult with runtime
3712      // folks. Fortunately, this is a *very* obsure construct.
3713      S += '#';
3714      return;
3715    }
3716
3717    if (OPT->isObjCQualifiedIdType()) {
3718      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3719                                 ExpandPointedToStructures,
3720                                 ExpandStructures, FD);
3721      if (FD || EncodingProperty) {
3722        // Note that we do extended encoding of protocol qualifer list
3723        // Only when doing ivar or property encoding.
3724        S += '"';
3725        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3726             E = OPT->qual_end(); I != E; ++I) {
3727          S += '<';
3728          S += (*I)->getNameAsString();
3729          S += '>';
3730        }
3731        S += '"';
3732      }
3733      return;
3734    }
3735
3736    QualType PointeeTy = OPT->getPointeeType();
3737    if (!EncodingProperty &&
3738        isa<TypedefType>(PointeeTy.getTypePtr())) {
3739      // Another historical/compatibility reason.
3740      // We encode the underlying type which comes out as
3741      // {...};
3742      S += '^';
3743      getObjCEncodingForTypeImpl(PointeeTy, S,
3744                                 false, ExpandPointedToStructures,
3745                                 NULL);
3746      return;
3747    }
3748
3749    S += '@';
3750    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3751      S += '"';
3752      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3753      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3754           E = OPT->qual_end(); I != E; ++I) {
3755        S += '<';
3756        S += (*I)->getNameAsString();
3757        S += '>';
3758      }
3759      S += '"';
3760    }
3761    return;
3762  }
3763
3764  assert(0 && "@encode for type not implemented!");
3765}
3766
3767void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3768                                                 std::string& S) const {
3769  if (QT & Decl::OBJC_TQ_In)
3770    S += 'n';
3771  if (QT & Decl::OBJC_TQ_Inout)
3772    S += 'N';
3773  if (QT & Decl::OBJC_TQ_Out)
3774    S += 'o';
3775  if (QT & Decl::OBJC_TQ_Bycopy)
3776    S += 'O';
3777  if (QT & Decl::OBJC_TQ_Byref)
3778    S += 'R';
3779  if (QT & Decl::OBJC_TQ_Oneway)
3780    S += 'V';
3781}
3782
3783void ASTContext::setBuiltinVaListType(QualType T) {
3784  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3785
3786  BuiltinVaListType = T;
3787}
3788
3789void ASTContext::setObjCIdType(QualType T) {
3790  ObjCIdTypedefType = T;
3791}
3792
3793void ASTContext::setObjCSelType(QualType T) {
3794  ObjCSelTypedefType = T;
3795}
3796
3797void ASTContext::setObjCProtoType(QualType QT) {
3798  ObjCProtoType = QT;
3799}
3800
3801void ASTContext::setObjCClassType(QualType T) {
3802  ObjCClassTypedefType = T;
3803}
3804
3805void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3806  assert(ObjCConstantStringType.isNull() &&
3807         "'NSConstantString' type already set!");
3808
3809  ObjCConstantStringType = getObjCInterfaceType(Decl);
3810}
3811
3812/// \brief Retrieve the template name that corresponds to a non-empty
3813/// lookup.
3814TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3815                                                   UnresolvedSetIterator End) {
3816  unsigned size = End - Begin;
3817  assert(size > 1 && "set is not overloaded!");
3818
3819  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3820                          size * sizeof(FunctionTemplateDecl*));
3821  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3822
3823  NamedDecl **Storage = OT->getStorage();
3824  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3825    NamedDecl *D = *I;
3826    assert(isa<FunctionTemplateDecl>(D) ||
3827           (isa<UsingShadowDecl>(D) &&
3828            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3829    *Storage++ = D;
3830  }
3831
3832  return TemplateName(OT);
3833}
3834
3835/// \brief Retrieve the template name that represents a qualified
3836/// template name such as \c std::vector.
3837TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3838                                                  bool TemplateKeyword,
3839                                                  TemplateDecl *Template) {
3840  // FIXME: Canonicalization?
3841  llvm::FoldingSetNodeID ID;
3842  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3843
3844  void *InsertPos = 0;
3845  QualifiedTemplateName *QTN =
3846    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3847  if (!QTN) {
3848    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3849    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3850  }
3851
3852  return TemplateName(QTN);
3853}
3854
3855/// \brief Retrieve the template name that represents a dependent
3856/// template name such as \c MetaFun::template apply.
3857TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3858                                                  const IdentifierInfo *Name) {
3859  assert((!NNS || NNS->isDependent()) &&
3860         "Nested name specifier must be dependent");
3861
3862  llvm::FoldingSetNodeID ID;
3863  DependentTemplateName::Profile(ID, NNS, Name);
3864
3865  void *InsertPos = 0;
3866  DependentTemplateName *QTN =
3867    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3868
3869  if (QTN)
3870    return TemplateName(QTN);
3871
3872  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3873  if (CanonNNS == NNS) {
3874    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3875  } else {
3876    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3877    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3878    DependentTemplateName *CheckQTN =
3879      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3880    assert(!CheckQTN && "Dependent type name canonicalization broken");
3881    (void)CheckQTN;
3882  }
3883
3884  DependentTemplateNames.InsertNode(QTN, InsertPos);
3885  return TemplateName(QTN);
3886}
3887
3888/// \brief Retrieve the template name that represents a dependent
3889/// template name such as \c MetaFun::template operator+.
3890TemplateName
3891ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3892                                     OverloadedOperatorKind Operator) {
3893  assert((!NNS || NNS->isDependent()) &&
3894         "Nested name specifier must be dependent");
3895
3896  llvm::FoldingSetNodeID ID;
3897  DependentTemplateName::Profile(ID, NNS, Operator);
3898
3899  void *InsertPos = 0;
3900  DependentTemplateName *QTN
3901    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3902
3903  if (QTN)
3904    return TemplateName(QTN);
3905
3906  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3907  if (CanonNNS == NNS) {
3908    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3909  } else {
3910    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3911    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3912
3913    DependentTemplateName *CheckQTN
3914      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3915    assert(!CheckQTN && "Dependent template name canonicalization broken");
3916    (void)CheckQTN;
3917  }
3918
3919  DependentTemplateNames.InsertNode(QTN, InsertPos);
3920  return TemplateName(QTN);
3921}
3922
3923/// getFromTargetType - Given one of the integer types provided by
3924/// TargetInfo, produce the corresponding type. The unsigned @p Type
3925/// is actually a value of type @c TargetInfo::IntType.
3926CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3927  switch (Type) {
3928  case TargetInfo::NoInt: return CanQualType();
3929  case TargetInfo::SignedShort: return ShortTy;
3930  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3931  case TargetInfo::SignedInt: return IntTy;
3932  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3933  case TargetInfo::SignedLong: return LongTy;
3934  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3935  case TargetInfo::SignedLongLong: return LongLongTy;
3936  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3937  }
3938
3939  assert(false && "Unhandled TargetInfo::IntType value");
3940  return CanQualType();
3941}
3942
3943//===----------------------------------------------------------------------===//
3944//                        Type Predicates.
3945//===----------------------------------------------------------------------===//
3946
3947/// isObjCNSObjectType - Return true if this is an NSObject object using
3948/// NSObject attribute on a c-style pointer type.
3949/// FIXME - Make it work directly on types.
3950/// FIXME: Move to Type.
3951///
3952bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3953  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3954    if (TypedefDecl *TD = TDT->getDecl())
3955      if (TD->getAttr<ObjCNSObjectAttr>())
3956        return true;
3957  }
3958  return false;
3959}
3960
3961/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3962/// garbage collection attribute.
3963///
3964Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3965  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3966  if (getLangOptions().ObjC1 &&
3967      getLangOptions().getGCMode() != LangOptions::NonGC) {
3968    GCAttrs = Ty.getObjCGCAttr();
3969    // Default behavious under objective-c's gc is for objective-c pointers
3970    // (or pointers to them) be treated as though they were declared
3971    // as __strong.
3972    if (GCAttrs == Qualifiers::GCNone) {
3973      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3974        GCAttrs = Qualifiers::Strong;
3975      else if (Ty->isPointerType())
3976        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3977    }
3978    // Non-pointers have none gc'able attribute regardless of the attribute
3979    // set on them.
3980    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3981      return Qualifiers::GCNone;
3982  }
3983  return GCAttrs;
3984}
3985
3986//===----------------------------------------------------------------------===//
3987//                        Type Compatibility Testing
3988//===----------------------------------------------------------------------===//
3989
3990/// areCompatVectorTypes - Return true if the two specified vector types are
3991/// compatible.
3992static bool areCompatVectorTypes(const VectorType *LHS,
3993                                 const VectorType *RHS) {
3994  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3995  return LHS->getElementType() == RHS->getElementType() &&
3996         LHS->getNumElements() == RHS->getNumElements();
3997}
3998
3999//===----------------------------------------------------------------------===//
4000// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4001//===----------------------------------------------------------------------===//
4002
4003/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4004/// inheritance hierarchy of 'rProto'.
4005bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4006                                                ObjCProtocolDecl *rProto) {
4007  if (lProto == rProto)
4008    return true;
4009  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4010       E = rProto->protocol_end(); PI != E; ++PI)
4011    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4012      return true;
4013  return false;
4014}
4015
4016/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4017/// return true if lhs's protocols conform to rhs's protocol; false
4018/// otherwise.
4019bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4020  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4021    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4022  return false;
4023}
4024
4025/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4026/// ObjCQualifiedIDType.
4027bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4028                                                   bool compare) {
4029  // Allow id<P..> and an 'id' or void* type in all cases.
4030  if (lhs->isVoidPointerType() ||
4031      lhs->isObjCIdType() || lhs->isObjCClassType())
4032    return true;
4033  else if (rhs->isVoidPointerType() ||
4034           rhs->isObjCIdType() || rhs->isObjCClassType())
4035    return true;
4036
4037  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4038    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4039
4040    if (!rhsOPT) return false;
4041
4042    if (rhsOPT->qual_empty()) {
4043      // If the RHS is a unqualified interface pointer "NSString*",
4044      // make sure we check the class hierarchy.
4045      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4046        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4047             E = lhsQID->qual_end(); I != E; ++I) {
4048          // when comparing an id<P> on lhs with a static type on rhs,
4049          // see if static class implements all of id's protocols, directly or
4050          // through its super class and categories.
4051          if (!rhsID->ClassImplementsProtocol(*I, true))
4052            return false;
4053        }
4054      }
4055      // If there are no qualifiers and no interface, we have an 'id'.
4056      return true;
4057    }
4058    // Both the right and left sides have qualifiers.
4059    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4060         E = lhsQID->qual_end(); I != E; ++I) {
4061      ObjCProtocolDecl *lhsProto = *I;
4062      bool match = false;
4063
4064      // when comparing an id<P> on lhs with a static type on rhs,
4065      // see if static class implements all of id's protocols, directly or
4066      // through its super class and categories.
4067      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4068           E = rhsOPT->qual_end(); J != E; ++J) {
4069        ObjCProtocolDecl *rhsProto = *J;
4070        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4071            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4072          match = true;
4073          break;
4074        }
4075      }
4076      // If the RHS is a qualified interface pointer "NSString<P>*",
4077      // make sure we check the class hierarchy.
4078      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4079        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4080             E = lhsQID->qual_end(); I != E; ++I) {
4081          // when comparing an id<P> on lhs with a static type on rhs,
4082          // see if static class implements all of id's protocols, directly or
4083          // through its super class and categories.
4084          if (rhsID->ClassImplementsProtocol(*I, true)) {
4085            match = true;
4086            break;
4087          }
4088        }
4089      }
4090      if (!match)
4091        return false;
4092    }
4093
4094    return true;
4095  }
4096
4097  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4098  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4099
4100  if (const ObjCObjectPointerType *lhsOPT =
4101        lhs->getAsObjCInterfacePointerType()) {
4102    if (lhsOPT->qual_empty()) {
4103      bool match = false;
4104      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4105        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4106             E = rhsQID->qual_end(); I != E; ++I) {
4107          // when comparing an id<P> on lhs with a static type on rhs,
4108          // see if static class implements all of id's protocols, directly or
4109          // through its super class and categories.
4110          if (lhsID->ClassImplementsProtocol(*I, true)) {
4111            match = true;
4112            break;
4113          }
4114        }
4115        if (!match)
4116          return false;
4117      }
4118      return true;
4119    }
4120    // Both the right and left sides have qualifiers.
4121    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4122         E = lhsOPT->qual_end(); I != E; ++I) {
4123      ObjCProtocolDecl *lhsProto = *I;
4124      bool match = false;
4125
4126      // when comparing an id<P> on lhs with a static type on rhs,
4127      // see if static class implements all of id's protocols, directly or
4128      // through its super class and categories.
4129      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4130           E = rhsQID->qual_end(); J != E; ++J) {
4131        ObjCProtocolDecl *rhsProto = *J;
4132        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4133            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4134          match = true;
4135          break;
4136        }
4137      }
4138      if (!match)
4139        return false;
4140    }
4141    return true;
4142  }
4143  return false;
4144}
4145
4146/// canAssignObjCInterfaces - Return true if the two interface types are
4147/// compatible for assignment from RHS to LHS.  This handles validation of any
4148/// protocol qualifiers on the LHS or RHS.
4149///
4150bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4151                                         const ObjCObjectPointerType *RHSOPT) {
4152  // If either type represents the built-in 'id' or 'Class' types, return true.
4153  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4154    return true;
4155
4156  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4157    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4158                                             QualType(RHSOPT,0),
4159                                             false);
4160
4161  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4162  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4163  if (LHS && RHS) // We have 2 user-defined types.
4164    return canAssignObjCInterfaces(LHS, RHS);
4165
4166  return false;
4167}
4168
4169/// getIntersectionOfProtocols - This routine finds the intersection of set
4170/// of protocols inherited from two distinct objective-c pointer objects.
4171/// It is used to build composite qualifier list of the composite type of
4172/// the conditional expression involving two objective-c pointer objects.
4173static
4174void getIntersectionOfProtocols(ASTContext &Context,
4175                                const ObjCObjectPointerType *LHSOPT,
4176                                const ObjCObjectPointerType *RHSOPT,
4177      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4178
4179  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4180  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4181
4182  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4183  unsigned LHSNumProtocols = LHS->getNumProtocols();
4184  if (LHSNumProtocols > 0)
4185    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4186  else {
4187    llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4188     Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4189    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4190                                LHSInheritedProtocols.end());
4191  }
4192
4193  unsigned RHSNumProtocols = RHS->getNumProtocols();
4194  if (RHSNumProtocols > 0) {
4195    ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4196    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4197      if (InheritedProtocolSet.count(RHSProtocols[i]))
4198        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4199  }
4200  else {
4201    llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4202    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4203    // FIXME. This may cause duplication of protocols in the list, but should
4204    // be harmless.
4205    for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4206      if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4207        IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4208  }
4209}
4210
4211/// areCommonBaseCompatible - Returns common base class of the two classes if
4212/// one found. Note that this is O'2 algorithm. But it will be called as the
4213/// last type comparison in a ?-exp of ObjC pointer types before a
4214/// warning is issued. So, its invokation is extremely rare.
4215QualType ASTContext::areCommonBaseCompatible(
4216                                          const ObjCObjectPointerType *LHSOPT,
4217                                          const ObjCObjectPointerType *RHSOPT) {
4218  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4219  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4220  if (!LHS || !RHS)
4221    return QualType();
4222
4223  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4224    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4225    LHS = LHSTy->getAs<ObjCInterfaceType>();
4226    if (canAssignObjCInterfaces(LHS, RHS)) {
4227      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4228      getIntersectionOfProtocols(*this,
4229                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4230      if (IntersectionOfProtocols.empty())
4231        LHSTy = getObjCObjectPointerType(LHSTy);
4232      else
4233        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4234                                                IntersectionOfProtocols.size());
4235      return LHSTy;
4236    }
4237  }
4238
4239  return QualType();
4240}
4241
4242bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4243                                         const ObjCInterfaceType *RHS) {
4244  // Verify that the base decls are compatible: the RHS must be a subclass of
4245  // the LHS.
4246  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4247    return false;
4248
4249  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4250  // protocol qualified at all, then we are good.
4251  if (LHS->getNumProtocols() == 0)
4252    return true;
4253
4254  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4255  // isn't a superset.
4256  if (RHS->getNumProtocols() == 0)
4257    return true;  // FIXME: should return false!
4258
4259  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4260                                        LHSPE = LHS->qual_end();
4261       LHSPI != LHSPE; LHSPI++) {
4262    bool RHSImplementsProtocol = false;
4263
4264    // If the RHS doesn't implement the protocol on the left, the types
4265    // are incompatible.
4266    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4267                                          RHSPE = RHS->qual_end();
4268         RHSPI != RHSPE; RHSPI++) {
4269      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4270        RHSImplementsProtocol = true;
4271        break;
4272      }
4273    }
4274    // FIXME: For better diagnostics, consider passing back the protocol name.
4275    if (!RHSImplementsProtocol)
4276      return false;
4277  }
4278  // The RHS implements all protocols listed on the LHS.
4279  return true;
4280}
4281
4282bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4283  // get the "pointed to" types
4284  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4285  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4286
4287  if (!LHSOPT || !RHSOPT)
4288    return false;
4289
4290  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4291         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4292}
4293
4294/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4295/// both shall have the identically qualified version of a compatible type.
4296/// C99 6.2.7p1: Two types have compatible types if their types are the
4297/// same. See 6.7.[2,3,5] for additional rules.
4298bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4299  if (getLangOptions().CPlusPlus)
4300    return hasSameType(LHS, RHS);
4301
4302  return !mergeTypes(LHS, RHS).isNull();
4303}
4304
4305QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
4306  const FunctionType *lbase = lhs->getAs<FunctionType>();
4307  const FunctionType *rbase = rhs->getAs<FunctionType>();
4308  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4309  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4310  bool allLTypes = true;
4311  bool allRTypes = true;
4312
4313  // Check return type
4314  QualType LRES = lbase->getResultType();
4315  QualType RRES = rbase->getResultType();
4316  Qualifiers::GC GC_L = LRES.getObjCGCAttr();
4317  Qualifiers::GC GC_R = RRES.getObjCGCAttr();
4318  // __weak/__strong attribute on one function/block return type but
4319  // not the other is OK.
4320  if (GC_L != GC_R) {
4321    if (GC_R == Qualifiers::GCNone)
4322      RRES = getObjCGCQualType(RRES, GC_L);
4323    else if (GC_L == Qualifiers::GCNone)
4324      LRES = getObjCGCQualType(LRES, GC_R);
4325  }
4326
4327  QualType retType = mergeTypes(LRES, RRES);
4328  if (retType.isNull()) return QualType();
4329  if (getCanonicalType(retType) != getCanonicalType(LRES))
4330    allLTypes = false;
4331  if (getCanonicalType(retType) != getCanonicalType(RRES))
4332    allRTypes = false;
4333  // FIXME: double check this
4334  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4335  if (NoReturn != lbase->getNoReturnAttr())
4336    allLTypes = false;
4337  if (NoReturn != rbase->getNoReturnAttr())
4338    allRTypes = false;
4339  CallingConv lcc = lbase->getCallConv();
4340  CallingConv rcc = rbase->getCallConv();
4341  // Compatible functions must have compatible calling conventions
4342  if (!isSameCallConv(lcc, rcc))
4343    return QualType();
4344
4345  if (lproto && rproto) { // two C99 style function prototypes
4346    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4347           "C++ shouldn't be here");
4348    unsigned lproto_nargs = lproto->getNumArgs();
4349    unsigned rproto_nargs = rproto->getNumArgs();
4350
4351    // Compatible functions must have the same number of arguments
4352    if (lproto_nargs != rproto_nargs)
4353      return QualType();
4354
4355    // Variadic and non-variadic functions aren't compatible
4356    if (lproto->isVariadic() != rproto->isVariadic())
4357      return QualType();
4358
4359    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4360      return QualType();
4361
4362    // Check argument compatibility
4363    llvm::SmallVector<QualType, 10> types;
4364    for (unsigned i = 0; i < lproto_nargs; i++) {
4365      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4366      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4367      QualType argtype = mergeTypes(largtype, rargtype);
4368      if (argtype.isNull()) return QualType();
4369      types.push_back(argtype);
4370      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4371        allLTypes = false;
4372      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4373        allRTypes = false;
4374    }
4375    if (allLTypes) return lhs;
4376    if (allRTypes) return rhs;
4377    return getFunctionType(retType, types.begin(), types.size(),
4378                           lproto->isVariadic(), lproto->getTypeQuals(),
4379                           NoReturn, lcc);
4380  }
4381
4382  if (lproto) allRTypes = false;
4383  if (rproto) allLTypes = false;
4384
4385  const FunctionProtoType *proto = lproto ? lproto : rproto;
4386  if (proto) {
4387    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4388    if (proto->isVariadic()) return QualType();
4389    // Check that the types are compatible with the types that
4390    // would result from default argument promotions (C99 6.7.5.3p15).
4391    // The only types actually affected are promotable integer
4392    // types and floats, which would be passed as a different
4393    // type depending on whether the prototype is visible.
4394    unsigned proto_nargs = proto->getNumArgs();
4395    for (unsigned i = 0; i < proto_nargs; ++i) {
4396      QualType argTy = proto->getArgType(i);
4397
4398      // Look at the promotion type of enum types, since that is the type used
4399      // to pass enum values.
4400      if (const EnumType *Enum = argTy->getAs<EnumType>())
4401        argTy = Enum->getDecl()->getPromotionType();
4402
4403      if (argTy->isPromotableIntegerType() ||
4404          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4405        return QualType();
4406    }
4407
4408    if (allLTypes) return lhs;
4409    if (allRTypes) return rhs;
4410    return getFunctionType(retType, proto->arg_type_begin(),
4411                           proto->getNumArgs(), proto->isVariadic(),
4412                           proto->getTypeQuals(), NoReturn, lcc);
4413  }
4414
4415  if (allLTypes) return lhs;
4416  if (allRTypes) return rhs;
4417  return getFunctionNoProtoType(retType, NoReturn, lcc);
4418}
4419
4420QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
4421  // C++ [expr]: If an expression initially has the type "reference to T", the
4422  // type is adjusted to "T" prior to any further analysis, the expression
4423  // designates the object or function denoted by the reference, and the
4424  // expression is an lvalue unless the reference is an rvalue reference and
4425  // the expression is a function call (possibly inside parentheses).
4426  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4427  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4428
4429  QualType LHSCan = getCanonicalType(LHS),
4430           RHSCan = getCanonicalType(RHS);
4431
4432  // If two types are identical, they are compatible.
4433  if (LHSCan == RHSCan)
4434    return LHS;
4435
4436  // If the qualifiers are different, the types aren't compatible... mostly.
4437  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4438  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4439  if (LQuals != RQuals) {
4440    // If any of these qualifiers are different, we have a type
4441    // mismatch.
4442    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4443        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4444      return QualType();
4445
4446    // Exactly one GC qualifier difference is allowed: __strong is
4447    // okay if the other type has no GC qualifier but is an Objective
4448    // C object pointer (i.e. implicitly strong by default).  We fix
4449    // this by pretending that the unqualified type was actually
4450    // qualified __strong.
4451    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4452    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4453    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4454
4455    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4456      return QualType();
4457
4458    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4459      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4460    }
4461    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4462      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4463    }
4464    return QualType();
4465  }
4466
4467  // Okay, qualifiers are equal.
4468
4469  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4470  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4471
4472  // We want to consider the two function types to be the same for these
4473  // comparisons, just force one to the other.
4474  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4475  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4476
4477  // Same as above for arrays
4478  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4479    LHSClass = Type::ConstantArray;
4480  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4481    RHSClass = Type::ConstantArray;
4482
4483  // Canonicalize ExtVector -> Vector.
4484  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4485  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4486
4487  // If the canonical type classes don't match.
4488  if (LHSClass != RHSClass) {
4489    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4490    // a signed integer type, or an unsigned integer type.
4491    // Compatibility is based on the underlying type, not the promotion
4492    // type.
4493    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4494      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4495        return RHS;
4496    }
4497    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4498      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4499        return LHS;
4500    }
4501
4502    return QualType();
4503  }
4504
4505  // The canonical type classes match.
4506  switch (LHSClass) {
4507#define TYPE(Class, Base)
4508#define ABSTRACT_TYPE(Class, Base)
4509#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4510#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4511#include "clang/AST/TypeNodes.def"
4512    assert(false && "Non-canonical and dependent types shouldn't get here");
4513    return QualType();
4514
4515  case Type::LValueReference:
4516  case Type::RValueReference:
4517  case Type::MemberPointer:
4518    assert(false && "C++ should never be in mergeTypes");
4519    return QualType();
4520
4521  case Type::IncompleteArray:
4522  case Type::VariableArray:
4523  case Type::FunctionProto:
4524  case Type::ExtVector:
4525    assert(false && "Types are eliminated above");
4526    return QualType();
4527
4528  case Type::Pointer:
4529  {
4530    // Merge two pointer types, while trying to preserve typedef info
4531    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4532    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4533    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4534    if (ResultType.isNull()) return QualType();
4535    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4536      return LHS;
4537    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4538      return RHS;
4539    return getPointerType(ResultType);
4540  }
4541  case Type::BlockPointer:
4542  {
4543    // Merge two block pointer types, while trying to preserve typedef info
4544    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4545    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4546    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4547    if (ResultType.isNull()) return QualType();
4548    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4549      return LHS;
4550    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4551      return RHS;
4552    return getBlockPointerType(ResultType);
4553  }
4554  case Type::ConstantArray:
4555  {
4556    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4557    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4558    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4559      return QualType();
4560
4561    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4562    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4563    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4564    if (ResultType.isNull()) return QualType();
4565    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4566      return LHS;
4567    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4568      return RHS;
4569    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4570                                          ArrayType::ArraySizeModifier(), 0);
4571    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4572                                          ArrayType::ArraySizeModifier(), 0);
4573    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4574    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4575    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4576      return LHS;
4577    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4578      return RHS;
4579    if (LVAT) {
4580      // FIXME: This isn't correct! But tricky to implement because
4581      // the array's size has to be the size of LHS, but the type
4582      // has to be different.
4583      return LHS;
4584    }
4585    if (RVAT) {
4586      // FIXME: This isn't correct! But tricky to implement because
4587      // the array's size has to be the size of RHS, but the type
4588      // has to be different.
4589      return RHS;
4590    }
4591    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4592    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4593    return getIncompleteArrayType(ResultType,
4594                                  ArrayType::ArraySizeModifier(), 0);
4595  }
4596  case Type::FunctionNoProto:
4597    return mergeFunctionTypes(LHS, RHS);
4598  case Type::Record:
4599  case Type::Enum:
4600    return QualType();
4601  case Type::Builtin:
4602    // Only exactly equal builtin types are compatible, which is tested above.
4603    return QualType();
4604  case Type::Complex:
4605    // Distinct complex types are incompatible.
4606    return QualType();
4607  case Type::Vector:
4608    // FIXME: The merged type should be an ExtVector!
4609    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4610      return LHS;
4611    return QualType();
4612  case Type::ObjCInterface: {
4613    // Check if the interfaces are assignment compatible.
4614    // FIXME: This should be type compatibility, e.g. whether
4615    // "LHS x; RHS x;" at global scope is legal.
4616    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4617    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4618    if (LHSIface && RHSIface &&
4619        canAssignObjCInterfaces(LHSIface, RHSIface))
4620      return LHS;
4621
4622    return QualType();
4623  }
4624  case Type::ObjCObjectPointer: {
4625    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4626                                RHS->getAs<ObjCObjectPointerType>()))
4627      return LHS;
4628
4629    return QualType();
4630  }
4631  case Type::TemplateSpecialization:
4632    assert(false && "Dependent types have no size");
4633    break;
4634  }
4635
4636  return QualType();
4637}
4638
4639//===----------------------------------------------------------------------===//
4640//                         Integer Predicates
4641//===----------------------------------------------------------------------===//
4642
4643unsigned ASTContext::getIntWidth(QualType T) {
4644  if (T->isBooleanType())
4645    return 1;
4646  if (EnumType *ET = dyn_cast<EnumType>(T))
4647    T = ET->getDecl()->getIntegerType();
4648  // For builtin types, just use the standard type sizing method
4649  return (unsigned)getTypeSize(T);
4650}
4651
4652QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4653  assert(T->isSignedIntegerType() && "Unexpected type");
4654
4655  // Turn <4 x signed int> -> <4 x unsigned int>
4656  if (const VectorType *VTy = T->getAs<VectorType>())
4657    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4658             VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
4659
4660  // For enums, we return the unsigned version of the base type.
4661  if (const EnumType *ETy = T->getAs<EnumType>())
4662    T = ETy->getDecl()->getIntegerType();
4663
4664  const BuiltinType *BTy = T->getAs<BuiltinType>();
4665  assert(BTy && "Unexpected signed integer type");
4666  switch (BTy->getKind()) {
4667  case BuiltinType::Char_S:
4668  case BuiltinType::SChar:
4669    return UnsignedCharTy;
4670  case BuiltinType::Short:
4671    return UnsignedShortTy;
4672  case BuiltinType::Int:
4673    return UnsignedIntTy;
4674  case BuiltinType::Long:
4675    return UnsignedLongTy;
4676  case BuiltinType::LongLong:
4677    return UnsignedLongLongTy;
4678  case BuiltinType::Int128:
4679    return UnsignedInt128Ty;
4680  default:
4681    assert(0 && "Unexpected signed integer type");
4682    return QualType();
4683  }
4684}
4685
4686ExternalASTSource::~ExternalASTSource() { }
4687
4688void ExternalASTSource::PrintStats() { }
4689
4690
4691//===----------------------------------------------------------------------===//
4692//                          Builtin Type Computation
4693//===----------------------------------------------------------------------===//
4694
4695/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4696/// pointer over the consumed characters.  This returns the resultant type.
4697static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4698                                  ASTContext::GetBuiltinTypeError &Error,
4699                                  bool AllowTypeModifiers = true) {
4700  // Modifiers.
4701  int HowLong = 0;
4702  bool Signed = false, Unsigned = false;
4703
4704  // Read the modifiers first.
4705  bool Done = false;
4706  while (!Done) {
4707    switch (*Str++) {
4708    default: Done = true; --Str; break;
4709    case 'S':
4710      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4711      assert(!Signed && "Can't use 'S' modifier multiple times!");
4712      Signed = true;
4713      break;
4714    case 'U':
4715      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4716      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4717      Unsigned = true;
4718      break;
4719    case 'L':
4720      assert(HowLong <= 2 && "Can't have LLLL modifier");
4721      ++HowLong;
4722      break;
4723    }
4724  }
4725
4726  QualType Type;
4727
4728  // Read the base type.
4729  switch (*Str++) {
4730  default: assert(0 && "Unknown builtin type letter!");
4731  case 'v':
4732    assert(HowLong == 0 && !Signed && !Unsigned &&
4733           "Bad modifiers used with 'v'!");
4734    Type = Context.VoidTy;
4735    break;
4736  case 'f':
4737    assert(HowLong == 0 && !Signed && !Unsigned &&
4738           "Bad modifiers used with 'f'!");
4739    Type = Context.FloatTy;
4740    break;
4741  case 'd':
4742    assert(HowLong < 2 && !Signed && !Unsigned &&
4743           "Bad modifiers used with 'd'!");
4744    if (HowLong)
4745      Type = Context.LongDoubleTy;
4746    else
4747      Type = Context.DoubleTy;
4748    break;
4749  case 's':
4750    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4751    if (Unsigned)
4752      Type = Context.UnsignedShortTy;
4753    else
4754      Type = Context.ShortTy;
4755    break;
4756  case 'i':
4757    if (HowLong == 3)
4758      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4759    else if (HowLong == 2)
4760      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4761    else if (HowLong == 1)
4762      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4763    else
4764      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4765    break;
4766  case 'c':
4767    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4768    if (Signed)
4769      Type = Context.SignedCharTy;
4770    else if (Unsigned)
4771      Type = Context.UnsignedCharTy;
4772    else
4773      Type = Context.CharTy;
4774    break;
4775  case 'b': // boolean
4776    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4777    Type = Context.BoolTy;
4778    break;
4779  case 'z':  // size_t.
4780    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4781    Type = Context.getSizeType();
4782    break;
4783  case 'F':
4784    Type = Context.getCFConstantStringType();
4785    break;
4786  case 'a':
4787    Type = Context.getBuiltinVaListType();
4788    assert(!Type.isNull() && "builtin va list type not initialized!");
4789    break;
4790  case 'A':
4791    // This is a "reference" to a va_list; however, what exactly
4792    // this means depends on how va_list is defined. There are two
4793    // different kinds of va_list: ones passed by value, and ones
4794    // passed by reference.  An example of a by-value va_list is
4795    // x86, where va_list is a char*. An example of by-ref va_list
4796    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4797    // we want this argument to be a char*&; for x86-64, we want
4798    // it to be a __va_list_tag*.
4799    Type = Context.getBuiltinVaListType();
4800    assert(!Type.isNull() && "builtin va list type not initialized!");
4801    if (Type->isArrayType()) {
4802      Type = Context.getArrayDecayedType(Type);
4803    } else {
4804      Type = Context.getLValueReferenceType(Type);
4805    }
4806    break;
4807  case 'V': {
4808    char *End;
4809    unsigned NumElements = strtoul(Str, &End, 10);
4810    assert(End != Str && "Missing vector size");
4811
4812    Str = End;
4813
4814    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4815    // FIXME: Don't know what to do about AltiVec.
4816    Type = Context.getVectorType(ElementType, NumElements, false, false);
4817    break;
4818  }
4819  case 'X': {
4820    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4821    Type = Context.getComplexType(ElementType);
4822    break;
4823  }
4824  case 'P':
4825    Type = Context.getFILEType();
4826    if (Type.isNull()) {
4827      Error = ASTContext::GE_Missing_stdio;
4828      return QualType();
4829    }
4830    break;
4831  case 'J':
4832    if (Signed)
4833      Type = Context.getsigjmp_bufType();
4834    else
4835      Type = Context.getjmp_bufType();
4836
4837    if (Type.isNull()) {
4838      Error = ASTContext::GE_Missing_setjmp;
4839      return QualType();
4840    }
4841    break;
4842  }
4843
4844  if (!AllowTypeModifiers)
4845    return Type;
4846
4847  Done = false;
4848  while (!Done) {
4849    switch (*Str++) {
4850      default: Done = true; --Str; break;
4851      case '*':
4852        Type = Context.getPointerType(Type);
4853        break;
4854      case '&':
4855        Type = Context.getLValueReferenceType(Type);
4856        break;
4857      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4858      case 'C':
4859        Type = Type.withConst();
4860        break;
4861      case 'D':
4862        Type = Context.getVolatileType(Type);
4863        break;
4864    }
4865  }
4866
4867  return Type;
4868}
4869
4870/// GetBuiltinType - Return the type for the specified builtin.
4871QualType ASTContext::GetBuiltinType(unsigned id,
4872                                    GetBuiltinTypeError &Error) {
4873  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4874
4875  llvm::SmallVector<QualType, 8> ArgTypes;
4876
4877  Error = GE_None;
4878  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4879  if (Error != GE_None)
4880    return QualType();
4881  while (TypeStr[0] && TypeStr[0] != '.') {
4882    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4883    if (Error != GE_None)
4884      return QualType();
4885
4886    // Do array -> pointer decay.  The builtin should use the decayed type.
4887    if (Ty->isArrayType())
4888      Ty = getArrayDecayedType(Ty);
4889
4890    ArgTypes.push_back(Ty);
4891  }
4892
4893  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4894         "'.' should only occur at end of builtin type list!");
4895
4896  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4897  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4898    return getFunctionNoProtoType(ResType);
4899  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4900                         TypeStr[0] == '.', 0);
4901}
4902
4903QualType
4904ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4905  // Perform the usual unary conversions. We do this early so that
4906  // integral promotions to "int" can allow us to exit early, in the
4907  // lhs == rhs check. Also, for conversion purposes, we ignore any
4908  // qualifiers.  For example, "const float" and "float" are
4909  // equivalent.
4910  if (lhs->isPromotableIntegerType())
4911    lhs = getPromotedIntegerType(lhs);
4912  else
4913    lhs = lhs.getUnqualifiedType();
4914  if (rhs->isPromotableIntegerType())
4915    rhs = getPromotedIntegerType(rhs);
4916  else
4917    rhs = rhs.getUnqualifiedType();
4918
4919  // If both types are identical, no conversion is needed.
4920  if (lhs == rhs)
4921    return lhs;
4922
4923  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4924  // The caller can deal with this (e.g. pointer + int).
4925  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4926    return lhs;
4927
4928  // At this point, we have two different arithmetic types.
4929
4930  // Handle complex types first (C99 6.3.1.8p1).
4931  if (lhs->isComplexType() || rhs->isComplexType()) {
4932    // if we have an integer operand, the result is the complex type.
4933    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4934      // convert the rhs to the lhs complex type.
4935      return lhs;
4936    }
4937    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4938      // convert the lhs to the rhs complex type.
4939      return rhs;
4940    }
4941    // This handles complex/complex, complex/float, or float/complex.
4942    // When both operands are complex, the shorter operand is converted to the
4943    // type of the longer, and that is the type of the result. This corresponds
4944    // to what is done when combining two real floating-point operands.
4945    // The fun begins when size promotion occur across type domains.
4946    // From H&S 6.3.4: When one operand is complex and the other is a real
4947    // floating-point type, the less precise type is converted, within it's
4948    // real or complex domain, to the precision of the other type. For example,
4949    // when combining a "long double" with a "double _Complex", the
4950    // "double _Complex" is promoted to "long double _Complex".
4951    int result = getFloatingTypeOrder(lhs, rhs);
4952
4953    if (result > 0) { // The left side is bigger, convert rhs.
4954      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4955    } else if (result < 0) { // The right side is bigger, convert lhs.
4956      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4957    }
4958    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4959    // domains match. This is a requirement for our implementation, C99
4960    // does not require this promotion.
4961    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4962      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4963        return rhs;
4964      } else { // handle "_Complex double, double".
4965        return lhs;
4966      }
4967    }
4968    return lhs; // The domain/size match exactly.
4969  }
4970  // Now handle "real" floating types (i.e. float, double, long double).
4971  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4972    // if we have an integer operand, the result is the real floating type.
4973    if (rhs->isIntegerType()) {
4974      // convert rhs to the lhs floating point type.
4975      return lhs;
4976    }
4977    if (rhs->isComplexIntegerType()) {
4978      // convert rhs to the complex floating point type.
4979      return getComplexType(lhs);
4980    }
4981    if (lhs->isIntegerType()) {
4982      // convert lhs to the rhs floating point type.
4983      return rhs;
4984    }
4985    if (lhs->isComplexIntegerType()) {
4986      // convert lhs to the complex floating point type.
4987      return getComplexType(rhs);
4988    }
4989    // We have two real floating types, float/complex combos were handled above.
4990    // Convert the smaller operand to the bigger result.
4991    int result = getFloatingTypeOrder(lhs, rhs);
4992    if (result > 0) // convert the rhs
4993      return lhs;
4994    assert(result < 0 && "illegal float comparison");
4995    return rhs;   // convert the lhs
4996  }
4997  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4998    // Handle GCC complex int extension.
4999    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5000    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5001
5002    if (lhsComplexInt && rhsComplexInt) {
5003      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5004                              rhsComplexInt->getElementType()) >= 0)
5005        return lhs; // convert the rhs
5006      return rhs;
5007    } else if (lhsComplexInt && rhs->isIntegerType()) {
5008      // convert the rhs to the lhs complex type.
5009      return lhs;
5010    } else if (rhsComplexInt && lhs->isIntegerType()) {
5011      // convert the lhs to the rhs complex type.
5012      return rhs;
5013    }
5014  }
5015  // Finally, we have two differing integer types.
5016  // The rules for this case are in C99 6.3.1.8
5017  int compare = getIntegerTypeOrder(lhs, rhs);
5018  bool lhsSigned = lhs->isSignedIntegerType(),
5019       rhsSigned = rhs->isSignedIntegerType();
5020  QualType destType;
5021  if (lhsSigned == rhsSigned) {
5022    // Same signedness; use the higher-ranked type
5023    destType = compare >= 0 ? lhs : rhs;
5024  } else if (compare != (lhsSigned ? 1 : -1)) {
5025    // The unsigned type has greater than or equal rank to the
5026    // signed type, so use the unsigned type
5027    destType = lhsSigned ? rhs : lhs;
5028  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5029    // The two types are different widths; if we are here, that
5030    // means the signed type is larger than the unsigned type, so
5031    // use the signed type.
5032    destType = lhsSigned ? lhs : rhs;
5033  } else {
5034    // The signed type is higher-ranked than the unsigned type,
5035    // but isn't actually any bigger (like unsigned int and long
5036    // on most 32-bit systems).  Use the unsigned type corresponding
5037    // to the signed type.
5038    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5039  }
5040  return destType;
5041}
5042